text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def needs_fixed_byte(self, byte, value):
"""
:return: None
"""
assert isinstance(byte, int)
assert isinstance(value, int)
assert byte >= 0 and value >= 0
assert byte <= 0xff and value <= 0xff
if byte != value:
self.parser_error("expect... | [
"def",
"needs_fixed_byte",
"(",
"self",
",",
"byte",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"byte",
",",
"int",
")",
"assert",
"isinstance",
"(",
"value",
",",
"int",
")",
"assert",
"byte",
">=",
"0",
"and",
"value",
">=",
"0",
"assert",
... | 35.4 | 0.008264 |
def to_kana(text):
"""
Use MeCab to turn any text into its phonetic spelling, as katakana
separated by spaces.
"""
records = MECAB.analyze(text)
kana = []
for record in records:
if record.pronunciation:
kana.append(record.pronunciation)
elif record.reading:
... | [
"def",
"to_kana",
"(",
"text",
")",
":",
"records",
"=",
"MECAB",
".",
"analyze",
"(",
"text",
")",
"kana",
"=",
"[",
"]",
"for",
"record",
"in",
"records",
":",
"if",
"record",
".",
"pronunciation",
":",
"kana",
".",
"append",
"(",
"record",
".",
... | 29 | 0.002227 |
def execute(self, input_data):
''' Execute method '''
# Grab the raw bytes of the sample
raw_bytes = input_data['sample']['raw_bytes']
# Spin up the rekall session and render components
session = MemSession(raw_bytes)
renderer = WorkbenchRenderer(session=session)
... | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"# Grab the raw bytes of the sample",
"raw_bytes",
"=",
"input_data",
"[",
"'sample'",
"]",
"[",
"'raw_bytes'",
"]",
"# Spin up the rekall session and render components",
"session",
"=",
"MemSession",
"(",
"raw... | 30.5 | 0.004545 |
def detectWindowsMobile(self):
"""Return detection of Windows Mobile
Detects if the current browser is a Windows Mobile device.
Excludes Windows Phone 7 devices.
Focuses on Windows Mobile 6.xx and earlier.
"""
#Exclude new Windows Phone.
if self.detectWindowsPhon... | [
"def",
"detectWindowsMobile",
"(",
"self",
")",
":",
"#Exclude new Windows Phone.",
"if",
"self",
".",
"detectWindowsPhone",
"(",
")",
":",
"return",
"False",
"#Most devices use 'Windows CE', but some report 'iemobile'",
"# and some older ones report as 'PIE' for Pocket IE.",
"#... | 44.428571 | 0.004721 |
def device_removed(self, device):
"""Show removal notification for specified device object."""
if not self._mounter.is_handleable(device):
return
device_file = device.device_presentation
if (device.is_drive or device.is_toplevel) and device_file:
self._show_notifi... | [
"def",
"device_removed",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"device_file",
"=",
"device",
".",
"device_presentation",
"if",
"(",
"device",
".",
"is_drive",
"o... | 45.272727 | 0.003937 |
def main():
"""Mainloop for the application"""
logging.basicConfig(level=logging.INFO)
app = RunSnakeRunApp(0)
app.MainLoop() | [
"def",
"main",
"(",
")",
":",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
")",
"app",
"=",
"RunSnakeRunApp",
"(",
"0",
")",
"app",
".",
"MainLoop",
"(",
")"
] | 27.4 | 0.007092 |
def background_estimator(bdata):
"""Estimate the background in a 2D array"""
crowded = False
std = numpy.std(bdata)
std0 = std
mean = bdata.mean()
while True:
prep = len(bdata)
numpy.clip(bdata, mean - 3 * std, mean + 3 * std, out=bdata)
if prep == len(bdata):
... | [
"def",
"background_estimator",
"(",
"bdata",
")",
":",
"crowded",
"=",
"False",
"std",
"=",
"numpy",
".",
"std",
"(",
"bdata",
")",
"std0",
"=",
"std",
"mean",
"=",
"bdata",
".",
"mean",
"(",
")",
"while",
"True",
":",
"prep",
"=",
"len",
"(",
"bda... | 24.76 | 0.001555 |
def get_trip_counts_per_day(self):
"""
Get trip counts per day between the start and end day of the feed.
Returns
-------
trip_counts : pandas.DataFrame
Has columns "date_str" (dtype str) "trip_counts" (dtype int)
"""
query = "SELECT date, count(*) AS... | [
"def",
"get_trip_counts_per_day",
"(",
"self",
")",
":",
"query",
"=",
"\"SELECT date, count(*) AS number_of_trips FROM day_trips GROUP BY date\"",
"# this yields the actual data",
"trip_counts_per_day",
"=",
"pd",
".",
"read_sql_query",
"(",
"query",
",",
"self",
".",
"conn"... | 46.27027 | 0.003432 |
def model_function(self, model_name, version, func_name):
"""Return the model-specific caching function."""
assert func_name in ('serializer', 'loader', 'invalidator')
name = "%s_%s_%s" % (model_name.lower(), version, func_name)
return getattr(self, name) | [
"def",
"model_function",
"(",
"self",
",",
"model_name",
",",
"version",
",",
"func_name",
")",
":",
"assert",
"func_name",
"in",
"(",
"'serializer'",
",",
"'loader'",
",",
"'invalidator'",
")",
"name",
"=",
"\"%s_%s_%s\"",
"%",
"(",
"model_name",
".",
"lowe... | 56.6 | 0.006969 |
def is_username(string, minlen=1, maxlen=15):
""" Determines whether the @string pattern is username-like
@string: #str being tested
@minlen: minimum required username length
@maxlen: maximum username length
-> #bool
"""
if string:
string = string.strip()
ret... | [
"def",
"is_username",
"(",
"string",
",",
"minlen",
"=",
"1",
",",
"maxlen",
"=",
"15",
")",
":",
"if",
"string",
":",
"string",
"=",
"string",
".",
"strip",
"(",
")",
"return",
"username_re",
".",
"match",
"(",
"string",
")",
"and",
"(",
"minlen",
... | 32.75 | 0.002475 |
def _set_priority_tag_enable(self, v, load=False):
"""
Setter method for priority_tag_enable, mapped from YANG variable /interface/port_channel/priority_tag_enable (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_priority_tag_enable is considered as a private
... | [
"def",
"_set_priority_tag_enable",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",... | 81.545455 | 0.00551 |
def _load_templates(self, config):
""" load templates
@dict: configuration of ldapcherry
"""
# definition of the template directory
self.template_dir = self._get_param(
'resources',
'templates.dir',
config
)
cherrypy.log.err... | [
"def",
"_load_templates",
"(",
"self",
",",
"config",
")",
":",
"# definition of the template directory",
"self",
".",
"template_dir",
"=",
"self",
".",
"_get_param",
"(",
"'resources'",
",",
"'templates.dir'",
",",
"config",
")",
"cherrypy",
".",
"log",
".",
"e... | 37.964286 | 0.001835 |
def destroy(self):
"""
Destroy the consumer group.
"""
resp = {}
for key in self.keys:
resp[key] = self.database.xgroup_destroy(key, self.name)
return resp | [
"def",
"destroy",
"(",
"self",
")",
":",
"resp",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"keys",
":",
"resp",
"[",
"key",
"]",
"=",
"self",
".",
"database",
".",
"xgroup_destroy",
"(",
"key",
",",
"self",
".",
"name",
")",
"return",
"resp... | 26 | 0.009302 |
def jsonable(self, *args, **options):
"""
return a public version of this instance that can be jsonified
Note that this does not return _id, _created, _updated, the reason why is
because lots of times you have a different name for _id (like if it is a
user object, then you migh... | [
"def",
"jsonable",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"d",
"=",
"{",
"}",
"for",
"field_name",
",",
"field",
"in",
"self",
".",
"schema",
".",
"normal_fields",
".",
"items",
"(",
")",
":",
"field_val",
"=",
"getattr"... | 45 | 0.009326 |
def getrange(self):
"""Retrieve the dataset min and max values.
Args::
no argument
Returns::
(min, max) tuple (attribute 'valid_range')
Note that those are the values as stored
by the 'setrange' method. 'getrange' does *NOT* compute the
min ... | [
"def",
"getrange",
"(",
"self",
")",
":",
"# Obtain SDS data type.",
"try",
":",
"sds_name",
",",
"rank",
",",
"dim_sizes",
",",
"data_type",
",",
"n_attrs",
"=",
"self",
".",
"info",
"(",
")",
"except",
"HDF4Error",
":",
"raise",
"HDF4Error",
"(",
"'getra... | 31.686747 | 0.001844 |
def features(self):
"""Returns a list of the J-Link embedded features.
Args:
self (JLink): the ``JLink`` instance
Returns:
A list of strings, each a feature. Example:
``[ 'RDI', 'FlashBP', 'FlashDL', 'JFlash', 'GDB' ]``
"""
buf = (ctypes.c_char * ... | [
"def",
"features",
"(",
"self",
")",
":",
"buf",
"=",
"(",
"ctypes",
".",
"c_char",
"*",
"self",
".",
"MAX_BUF_SIZE",
")",
"(",
")",
"self",
".",
"_dll",
".",
"JLINKARM_GetFeatureString",
"(",
"buf",
")",
"result",
"=",
"ctypes",
".",
"string_at",
"(",... | 28.833333 | 0.003731 |
def gridsearch_color_plot(model, x_param, y_param, X=None, y=None, ax=None,
**kwargs):
"""Quick method:
Create a color plot showing the best grid search scores across two
parameters.
This helper function is a quick wrapper to utilize GridSearchColorPlot
for one-off analysi... | [
"def",
"gridsearch_color_plot",
"(",
"model",
",",
"x_param",
",",
"y_param",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Instantiate the visualizer",
"visualizer",
"=",
"GridSearchColorPlot",
... | 32.107143 | 0.00054 |
def unhandled(self, key):
"""Handle other keyboard actions not handled by the ListBox widget.
"""
self.key = key
self.size = self.tui.get_cols_rows()
if self.search is True:
if self.enter is False and self.no_matches is False:
if len(key) == 1 and key... | [
"def",
"unhandled",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"key",
"=",
"key",
"self",
".",
"size",
"=",
"self",
".",
"tui",
".",
"get_cols_rows",
"(",
")",
"if",
"self",
".",
"search",
"is",
"True",
":",
"if",
"self",
".",
"enter",
"is",... | 35.909091 | 0.002466 |
def get_dimension(self, dataset, dimension):
"""The method is getting information about dimension with items"""
path = '/api/1.0/meta/dataset/{}/dimension/{}'
return self._api_get(definition.Dimension, path.format(dataset, dimension)) | [
"def",
"get_dimension",
"(",
"self",
",",
"dataset",
",",
"dimension",
")",
":",
"path",
"=",
"'/api/1.0/meta/dataset/{}/dimension/{}'",
"return",
"self",
".",
"_api_get",
"(",
"definition",
".",
"Dimension",
",",
"path",
".",
"format",
"(",
"dataset",
",",
"d... | 51.8 | 0.011407 |
def string_get(self, ypos, xpos, length):
"""
Get a string of `length` at screen co-ordinates `ypos`/`xpos`
Co-ordinates are 1 based, as listed in the status area of the
terminal.
"""
# the screen's co-ordinates are 1 based, but the command is 0 based
... | [
"def",
"string_get",
"(",
"self",
",",
"ypos",
",",
"xpos",
",",
"length",
")",
":",
"# the screen's co-ordinates are 1 based, but the command is 0 based",
"xpos",
"-=",
"1",
"ypos",
"-=",
"1",
"cmd",
"=",
"self",
".",
"exec_command",
"(",
"\"Ascii({0},{1},{2})\"",
... | 38.125 | 0.0032 |
def login(self, username, password, disableautosave=True, print_response=True):
"""
:param username:
:param password:
:param disableautosave: boolean
:param print_response: print log if required
:return: status code, response data
"""
if type(username) != ... | [
"def",
"login",
"(",
"self",
",",
"username",
",",
"password",
",",
"disableautosave",
"=",
"True",
",",
"print_response",
"=",
"True",
")",
":",
"if",
"type",
"(",
"username",
")",
"!=",
"str",
":",
"return",
"False",
",",
"\"Username must be string\"",
"... | 38.535714 | 0.004521 |
def readGlobalFile(self, fileStoreID, userPath=None, cache=True, mutable=False, symlink=False):
"""
Makes the file associated with fileStoreID available locally. If mutable is True,
then a copy of the file will be created locally so that the original is not modified
and does not change t... | [
"def",
"readGlobalFile",
"(",
"self",
",",
"fileStoreID",
",",
"userPath",
"=",
"None",
",",
"cache",
"=",
"True",
",",
"mutable",
"=",
"False",
",",
"symlink",
"=",
"False",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | 61.526316 | 0.01011 |
def paste_mashes(sketches, pasted_mash, force = False):
"""
Combine mash files into single sketch
Input:
sketches <list[str]> -- paths to sketch files
pasted_mash <str> -- path to output mash file
force <boolean> -- force overwrite of all mash file
"""
if os.path.isf... | [
"def",
"paste_mashes",
"(",
"sketches",
",",
"pasted_mash",
",",
"force",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"pasted_mash",
")",
":",
"if",
"force",
":",
"subprocess",
".",
"Popen",
"(",
"[",
"'rm'",
",",
"pasted_mash"... | 33.421053 | 0.004594 |
def learn(network, env, seed=None, nsteps=20, total_timesteps=int(80e6), q_coef=0.5, ent_coef=0.01,
max_grad_norm=10, lr=7e-4, lrschedule='linear', rprop_epsilon=1e-5, rprop_alpha=0.99, gamma=0.99,
log_interval=100, buffer_size=50000, replay_ratio=4, replay_start=10000, c=10.0,
trust_regio... | [
"def",
"learn",
"(",
"network",
",",
"env",
",",
"seed",
"=",
"None",
",",
"nsteps",
"=",
"20",
",",
"total_timesteps",
"=",
"int",
"(",
"80e6",
")",
",",
"q_coef",
"=",
"0.5",
",",
"ent_coef",
"=",
"0.01",
",",
"max_grad_norm",
"=",
"10",
",",
"lr... | 56.134615 | 0.006396 |
def check_differences(self):
""" In-depth check of mail differences.
Compare all mails of the duplicate set with each other, both in size
and content. Raise an error if we're not within the limits imposed by
the threshold setting.
"""
logger.info("Check that mail differe... | [
"def",
"check_differences",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Check that mail differences are within the limits.\"",
")",
"if",
"self",
".",
"conf",
".",
"size_threshold",
"<",
"0",
":",
"logger",
".",
"info",
"(",
"\"Skip checking for size diffe... | 46.833333 | 0.001162 |
def z_angle_rotate(xy, theta):
"""
Rotated the input vector or set of vectors `xy` by the angle `theta`.
Parameters
----------
xy : array_like
The vector or array of vectors to transform. Must have shape
"""
xy = np.array(xy).T
theta = np.array(theta).T
out = np.zeros_lik... | [
"def",
"z_angle_rotate",
"(",
"xy",
",",
"theta",
")",
":",
"xy",
"=",
"np",
".",
"array",
"(",
"xy",
")",
".",
"T",
"theta",
"=",
"np",
".",
"array",
"(",
"theta",
")",
".",
"T",
"out",
"=",
"np",
".",
"zeros_like",
"(",
"xy",
")",
"out",
"[... | 24.157895 | 0.014675 |
def font_to_wx_font(font):
"""
Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings
"""
if font is None:
return ''
if type(font) is str:
_font = ... | [
"def",
"font_to_wx_font",
"(",
"font",
")",
":",
"if",
"font",
"is",
"None",
":",
"return",
"''",
"if",
"type",
"(",
"font",
")",
"is",
"str",
":",
"_font",
"=",
"font",
".",
"split",
"(",
"' '",
")",
"else",
":",
"_font",
"=",
"font",
"name",
"=... | 25.419355 | 0.003667 |
def filter_cols(model, *filtered_columns):
"""Return columnsnames for a model except named ones.
Useful for defer() for example to retain only columns of interest
"""
m = sa.orm.class_mapper(model)
return list(
{p.key for p in m.iterate_properties if hasattr(p, "columns")}.difference(
... | [
"def",
"filter_cols",
"(",
"model",
",",
"*",
"filtered_columns",
")",
":",
"m",
"=",
"sa",
".",
"orm",
".",
"class_mapper",
"(",
"model",
")",
"return",
"list",
"(",
"{",
"p",
".",
"key",
"for",
"p",
"in",
"m",
".",
"iterate_properties",
"if",
"hasa... | 31.727273 | 0.005571 |
def set_dimensions(self, variables, unlimited_dims=None):
"""
This provides a centralized method to set the dimensions on the data
store.
Parameters
----------
variables : dict-like
Dictionary of key/value (variable name / xr.Variable) pairs
unlimited... | [
"def",
"set_dimensions",
"(",
"self",
",",
"variables",
",",
"unlimited_dims",
"=",
"None",
")",
":",
"if",
"unlimited_dims",
"is",
"None",
":",
"unlimited_dims",
"=",
"set",
"(",
")",
"existing_dims",
"=",
"self",
".",
"get_dimensions",
"(",
")",
"dims",
... | 36.9375 | 0.001649 |
def _sendReset(self, sequenceId=0):
"""
Sends a reset signal to the network.
"""
for col in xrange(self.numColumns):
self.sensorInputs[col].addResetToQueue(sequenceId)
self.externalInputs[col].addResetToQueue(sequenceId)
self.network.run(1) | [
"def",
"_sendReset",
"(",
"self",
",",
"sequenceId",
"=",
"0",
")",
":",
"for",
"col",
"in",
"xrange",
"(",
"self",
".",
"numColumns",
")",
":",
"self",
".",
"sensorInputs",
"[",
"col",
"]",
".",
"addResetToQueue",
"(",
"sequenceId",
")",
"self",
".",
... | 33.125 | 0.011029 |
def Update(self, data):
"""Updates the PMF with new data.
data: string cookie type
"""
for hypo in self.Values():
like = self.Likelihood(data, hypo)
self.Mult(hypo, like)
self.Normalize() | [
"def",
"Update",
"(",
"self",
",",
"data",
")",
":",
"for",
"hypo",
"in",
"self",
".",
"Values",
"(",
")",
":",
"like",
"=",
"self",
".",
"Likelihood",
"(",
"data",
",",
"hypo",
")",
"self",
".",
"Mult",
"(",
"hypo",
",",
"like",
")",
"self",
"... | 30.5 | 0.007968 |
def results(self, trial_ids):
"""
Accepts a sequence of trial ids and returns a pandas dataframe
with the schema
trial_id, iteration?, *metric_schema_union
where iteration is an optional column that specifies the iteration
when a user logged a metric, if the user suppli... | [
"def",
"results",
"(",
"self",
",",
"trial_ids",
")",
":",
"metadata_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"log_dir",
",",
"constants",
".",
"METADATA_FOLDER",
")",
"dfs",
"=",
"[",
"]",
"# TODO: various file-creation corner cases lik... | 49.928571 | 0.001404 |
def reporter(gc_dict, contig_dist_dict, longest_contig_dict, genome_length_dict, num_contigs_dict, n50_dict, n75_dict,
n90_dict, l50_dict, l75_dict, l90_dict, orf_dist_dict, genus_dict, sequencepath):
"""
Create a report of all the extracted features
:param gc_dict: dictionary of strain name: G... | [
"def",
"reporter",
"(",
"gc_dict",
",",
"contig_dist_dict",
",",
"longest_contig_dict",
",",
"genome_length_dict",
",",
"num_contigs_dict",
",",
"n50_dict",
",",
"n75_dict",
",",
"n90_dict",
",",
"l50_dict",
",",
"l75_dict",
",",
"l90_dict",
",",
"orf_dist_dict",
... | 61.267857 | 0.002869 |
def calculate_one_hot_encoder_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, 1] ---> [N, C']
C' is the total number of categorical values.
'''
check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
if operator.inputs[0].type.shape[1] ... | [
"def",
"calculate_one_hot_encoder_output_shapes",
"(",
"operator",
")",
":",
"check_input_and_output_numbers",
"(",
"operator",
",",
"input_count_range",
"=",
"1",
",",
"output_count_range",
"=",
"1",
")",
"if",
"operator",
".",
"inputs",
"[",
"0",
"]",
".",
"type... | 45.92 | 0.005973 |
def random_forest(self):
""" Random Forest.
This function runs random forest and stores the,
1. Model
2. Model name
3. Max score
4. Metrics
"""
model = RandomForestRegressor(random_state=42)
scores = []
kfold = KFold(n_splits=self.cv, s... | [
"def",
"random_forest",
"(",
"self",
")",
":",
"model",
"=",
"RandomForestRegressor",
"(",
"random_state",
"=",
"42",
")",
"scores",
"=",
"[",
"]",
"kfold",
"=",
"KFold",
"(",
"n_splits",
"=",
"self",
".",
"cv",
",",
"shuffle",
"=",
"True",
",",
"rando... | 38.444444 | 0.006579 |
def SeqN(n, *inner_rules, **kwargs):
"""
A rule that accepts a sequence of tokens satisfying ``rules`` and returns
the value returned by rule number ``n``, or None if the first rule was not satisfied.
"""
@action(Seq(*inner_rules), loc=kwargs.get("loc", None))
def rule(parser, *values):
... | [
"def",
"SeqN",
"(",
"n",
",",
"*",
"inner_rules",
",",
"*",
"*",
"kwargs",
")",
":",
"@",
"action",
"(",
"Seq",
"(",
"*",
"inner_rules",
")",
",",
"loc",
"=",
"kwargs",
".",
"get",
"(",
"\"loc\"",
",",
"None",
")",
")",
"def",
"rule",
"(",
"par... | 38.222222 | 0.005682 |
def compress_js(self, paths, templates=None, **kwargs):
"""Concatenate and compress JS files"""
js = self.concatenate(paths)
if templates:
js = js + self.compile_templates(templates)
if not settings.DISABLE_WRAPPER:
js = settings.JS_WRAPPER % js
compress... | [
"def",
"compress_js",
"(",
"self",
",",
"paths",
",",
"templates",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"js",
"=",
"self",
".",
"concatenate",
"(",
"paths",
")",
"if",
"templates",
":",
"js",
"=",
"js",
"+",
"self",
".",
"compile_templates... | 32.142857 | 0.00432 |
def format(self, formatter, subset=None):
"""
Format the text display value of cells.
.. versionadded:: 0.18.0
Parameters
----------
formatter : str, callable, or dict
subset : IndexSlice
An argument to ``DataFrame.loc`` that restricts which elements... | [
"def",
"format",
"(",
"self",
",",
"formatter",
",",
"subset",
"=",
"None",
")",
":",
"if",
"subset",
"is",
"None",
":",
"row_locs",
"=",
"range",
"(",
"len",
"(",
"self",
".",
"data",
")",
")",
"col_locs",
"=",
"range",
"(",
"len",
"(",
"self",
... | 33.890625 | 0.000896 |
def generate(self):
"""
Generate all output types and write to disk.
"""
logger.info('Generating graphs')
self._generate_graph(
'by-version',
'Downloads by Version',
self._stats.per_version_data,
'Version'
)
self._ge... | [
"def",
"generate",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Generating graphs'",
")",
"self",
".",
"_generate_graph",
"(",
"'by-version'",
",",
"'Downloads by Version'",
",",
"self",
".",
"_stats",
".",
"per_version_data",
",",
"'Version'",
")",
"s... | 31.816667 | 0.001016 |
def from_dir(dirpath: Path, feat_type: str) -> None:
""" Performs feature extraction from the WAV files in a directory.
Args:
dirpath: A `Path` to the directory where the WAV files reside.
feat_type: The type of features that are being used.
"""
logger.info("Extracting features from di... | [
"def",
"from_dir",
"(",
"dirpath",
":",
"Path",
",",
"feat_type",
":",
"str",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"\"Extracting features from directory {}\"",
".",
"format",
"(",
"dirpath",
")",
")",
"dirname",
"=",
"str",
"(",
"dirpath",
"... | 38.508772 | 0.001777 |
def seek( self, offset, whence=0 ):
"""
Move the file pointer to a particular offset.
"""
# Determine absolute target position
if whence == 0:
target_pos = offset
elif whence == 1:
target_pos = self.file_pos + offset
elif whence == 2:
... | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"0",
")",
":",
"# Determine absolute target position",
"if",
"whence",
"==",
"0",
":",
"target_pos",
"=",
"offset",
"elif",
"whence",
"==",
"1",
":",
"target_pos",
"=",
"self",
".",
"file_pos",... | 36.130435 | 0.008206 |
def generator_family(cls):
""" :meth:`.WHashGeneratorProto.generator_family` implementation
"""
if cls.__generator_family__ is not None:
if isinstance(cls.__generator_family__, str) is False:
raise TypeError('"__generator_class__" if defined must be a str instance')
if cls.__generator_family__ is not N... | [
"def",
"generator_family",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__generator_family__",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"cls",
".",
"__generator_family__",
",",
"str",
")",
"is",
"False",
":",
"raise",
"TypeError",
"(",
"'\"__generator_... | 39.888889 | 0.024523 |
async def execute(self, query: str, *args, timeout: float=None) -> str:
"""Execute an SQL command (or commands).
Pool performs this operation using one of its connections. Other than
that, it behaves identically to
:meth:`Connection.execute() <connection.Connection.execute>`.
... | [
"async",
"def",
"execute",
"(",
"self",
",",
"query",
":",
"str",
",",
"*",
"args",
",",
"timeout",
":",
"float",
"=",
"None",
")",
"->",
"str",
":",
"async",
"with",
"self",
".",
"acquire",
"(",
")",
"as",
"con",
":",
"return",
"await",
"con",
"... | 41.454545 | 0.008584 |
def name(self):
"""Instance name."""
return ffi.string(lib.EnvGetInstanceName(self._env, self._ist)).decode() | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"ffi",
".",
"string",
"(",
"lib",
".",
"EnvGetInstanceName",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_ist",
")",
")",
".",
"decode",
"(",
")"
] | 41 | 0.024 |
def cbday_roll(self):
"""
Define default roll function to be called in apply method.
"""
cbday = CustomBusinessDay(n=self.n, normalize=False, **self.kwds)
if self._prefix.endswith('S'):
# MonthBegin
roll_func = cbday.rollforward
else:
... | [
"def",
"cbday_roll",
"(",
"self",
")",
":",
"cbday",
"=",
"CustomBusinessDay",
"(",
"n",
"=",
"self",
".",
"n",
",",
"normalize",
"=",
"False",
",",
"*",
"*",
"self",
".",
"kwds",
")",
"if",
"self",
".",
"_prefix",
".",
"endswith",
"(",
"'S'",
")",... | 29.384615 | 0.005076 |
def parse_pattern(s):
"""Parse a string such as 'foo/bar/*.py'
Assumes is_pattern(s) has been called and returned True
1. directory to process
2. pattern to match"""
if '{' in s:
return None, None # Unsupported by fnmatch
if s and s[0] == '~':
s = os.path.expanduser(s)
parts... | [
"def",
"parse_pattern",
"(",
"s",
")",
":",
"if",
"'{'",
"in",
"s",
":",
"return",
"None",
",",
"None",
"# Unsupported by fnmatch",
"if",
"s",
"and",
"s",
"[",
"0",
"]",
"==",
"'~'",
":",
"s",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"s",
... | 33.24 | 0.002339 |
def _timestamp_query_param_from_json(value, field):
"""Coerce 'value' to a datetime, if set or not nullable.
Args:
value (str): The timestamp.
field (.SchemaField): The field corresponding to the value.
Returns:
Optional[datetime.datetime]: The parsed datetime object from
`... | [
"def",
"_timestamp_query_param_from_json",
"(",
"value",
",",
"field",
")",
":",
"if",
"_not_null",
"(",
"value",
",",
"field",
")",
":",
"# Canonical formats for timestamps in BigQuery are flexible. See:",
"# g.co/cloud/bigquery/docs/reference/standard-sql/data-types#timestamp-typ... | 36.848485 | 0.002404 |
def __setup_fileserver(self):
'''
Set the local file objects from the file server interface
'''
# Avoid circular import
import salt.fileserver
self.fs_ = salt.fileserver.Fileserver(self.opts)
self._serve_file = self.fs_.serve_file
self._file_find = self.fs... | [
"def",
"__setup_fileserver",
"(",
"self",
")",
":",
"# Avoid circular import",
"import",
"salt",
".",
"fileserver",
"self",
".",
"fs_",
"=",
"salt",
".",
"fileserver",
".",
"Fileserver",
"(",
"self",
".",
"opts",
")",
"self",
".",
"_serve_file",
"=",
"self",... | 42.125 | 0.002903 |
def max(self, axis=None, keepdims=False):
"""
Return the maximum of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
keepdims : boo... | [
"def",
"max",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"False",
")",
":",
"from",
"numpy",
"import",
"maximum",
"return",
"self",
".",
"_stat",
"(",
"axis",
",",
"func",
"=",
"maximum",
",",
"keepdims",
"=",
"keepdims",
")"
] | 33.8 | 0.003839 |
def set_calibration(self, attenuations, freqs, frange, calname):
"""See :meth:`AbstractAcquisitionRunner<sparkle.run.abstract_acquisition.AbstractAcquisitionRunner.set_calibration>`"""
self._stimulus.setCalibration(attenuations, freqs, frange) | [
"def",
"set_calibration",
"(",
"self",
",",
"attenuations",
",",
"freqs",
",",
"frange",
",",
"calname",
")",
":",
"self",
".",
"_stimulus",
".",
"setCalibration",
"(",
"attenuations",
",",
"freqs",
",",
"frange",
")"
] | 85.666667 | 0.011583 |
def change_name(self, new_name):
"""Change the name of the shell, possibly updating the maximum name
length"""
if not new_name:
name = self.hostname
else:
name = new_name.decode()
self.display_name = display_names.change(
self.display_name, nam... | [
"def",
"change_name",
"(",
"self",
",",
"new_name",
")",
":",
"if",
"not",
"new_name",
":",
"name",
"=",
"self",
".",
"hostname",
"else",
":",
"name",
"=",
"new_name",
".",
"decode",
"(",
")",
"self",
".",
"display_name",
"=",
"display_names",
".",
"ch... | 34.888889 | 0.006211 |
def _update_modifier_key(self, orig_key, dep_key):
"""Update a key based on the dataset it will modified (dep).
Typical use case is requesting a modified dataset (orig_key). This
modified dataset most likely depends on a less-modified
dataset (dep_key). The less-modified dataset must co... | [
"def",
"_update_modifier_key",
"(",
"self",
",",
"orig_key",
",",
"dep_key",
")",
":",
"orig_dict",
"=",
"orig_key",
".",
"_asdict",
"(",
")",
"dep_dict",
"=",
"dep_key",
".",
"_asdict",
"(",
")",
"# don't change the modifiers",
"for",
"k",
"in",
"DATASET_KEYS... | 48.1 | 0.002039 |
def deep_update_dict(default, options):
"""
Updates the values in a nested dict, while unspecified values will remain
unchanged
"""
for key in options.keys():
default_setting = default.get(key)
new_setting = options.get(key)
if isinstance(default_setting, dict):
d... | [
"def",
"deep_update_dict",
"(",
"default",
",",
"options",
")",
":",
"for",
"key",
"in",
"options",
".",
"keys",
"(",
")",
":",
"default_setting",
"=",
"default",
".",
"get",
"(",
"key",
")",
"new_setting",
"=",
"options",
".",
"get",
"(",
"key",
")",
... | 33.916667 | 0.002392 |
def swipe(self):
'''
Perform swipe action. if device platform greater than API 18, percent can be used and value between 0 and 1
Usages:
d().swipe.right()
d().swipe.left(steps=10)
d().swipe.up(steps=10)
d().swipe.down()
d().swipe("right", steps=20)
... | [
"def",
"swipe",
"(",
"self",
")",
":",
"@",
"param_to_property",
"(",
"direction",
"=",
"[",
"\"up\"",
",",
"\"down\"",
",",
"\"right\"",
",",
"\"left\"",
"]",
")",
"def",
"_swipe",
"(",
"direction",
"=",
"\"left\"",
",",
"steps",
"=",
"10",
",",
"perc... | 39.666667 | 0.005472 |
def hexists(self, name, key):
"""
Returns ``True`` if the field exists, ``False`` otherwise.
:param name: str the name of the redis key
:param key: the member of the hash
:return: Future()
"""
with self.pipe as pipe:
return pipe.hexists(self.redis... | [
"def",
"hexists",
"(",
"self",
",",
"name",
",",
"key",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"hexists",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"self",
".",
"memberparse",
".",
"encode",
"("... | 34.818182 | 0.005089 |
def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't star... | [
"def",
"CheckSpacing",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"nesting_state",
",",
"error",
")",
":",
"# Don't use \"elided\" lines here, otherwise we can't check commented lines.",
"# Don't want to use \"raw\" either, because we don't want to check inside C++11",
... | 45.285714 | 0.009775 |
def OnToggleTool(self, event):
"""Tool event handler"""
config["check_spelling"] = str(event.IsChecked())
toggle_id = self.parent.menubar.FindMenuItem(_("View"),
_("Check spelling"))
if toggle_id != -1:
# Check may fail if... | [
"def",
"OnToggleTool",
"(",
"self",
",",
"event",
")",
":",
"config",
"[",
"\"check_spelling\"",
"]",
"=",
"str",
"(",
"event",
".",
"IsChecked",
"(",
")",
")",
"toggle_id",
"=",
"self",
".",
"parent",
".",
"menubar",
".",
"FindMenuItem",
"(",
"_",
"("... | 38.133333 | 0.003413 |
def _render_config(cls, dest, template_name, template_args):
"""
Renders and writes a template_name to a dest given some template_args.
This is for platform-specific configurations
"""
template_args = template_args.copy()
# Substitute values here
pyversion = tem... | [
"def",
"_render_config",
"(",
"cls",
",",
"dest",
",",
"template_name",
",",
"template_args",
")",
":",
"template_args",
"=",
"template_args",
".",
"copy",
"(",
")",
"# Substitute values here",
"pyversion",
"=",
"template_args",
"[",
"'pyversion'",
"]",
"template_... | 36.066667 | 0.003604 |
def _sync_dir(self):
"""Traverse the local folder structure and remote peers.
This is the core algorithm that generates calls to self.sync_XXX()
handler methods.
_sync_dir() is called by self.run().
"""
local_entries = self.local.get_dir()
# Convert into a dict {... | [
"def",
"_sync_dir",
"(",
"self",
")",
":",
"local_entries",
"=",
"self",
".",
"local",
".",
"get_dir",
"(",
")",
"# Convert into a dict {name: FileEntry, ...}",
"local_entry_map",
"=",
"dict",
"(",
"map",
"(",
"lambda",
"e",
":",
"(",
"e",
".",
"name",
",",
... | 39.918699 | 0.001192 |
def apply(
self,
docs=None,
split=0,
train=False,
lfs=None,
clear=True,
parallelism=None,
progress_bar=True,
):
"""Apply the labels of the specified candidates based on the provided LFs.
:param docs: If provided, apply the LFs to all t... | [
"def",
"apply",
"(",
"self",
",",
"docs",
"=",
"None",
",",
"split",
"=",
"0",
",",
"train",
"=",
"False",
",",
"lfs",
"=",
"None",
",",
"clear",
"=",
"True",
",",
"parallelism",
"=",
"None",
",",
"progress_bar",
"=",
"True",
",",
")",
":",
"if",... | 36.026667 | 0.001441 |
def generation_plot(file, errorbars=True):
"""Plot the results of the algorithm using generation statistics.
This function creates a plot of the generation fitness statistics
(best, worst, median, and average). This function requires the
matplotlib library.
.. note::
This fun... | [
"def",
"generation_plot",
"(",
"file",
",",
"errorbars",
"=",
"True",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"matplotlib",
".",
"font_manager",
"generation",
"=",
"[",
"]",
"psize",
"=",
"[",
"]",
"worst",
"=",
"[",
"]",
... | 32.970149 | 0.008791 |
def last_item(array):
"""Returns the last item of an array in a list or an empty list."""
if array.size == 0:
# work around for https://github.com/numpy/numpy/issues/5195
return []
indexer = (slice(-1, None),) * array.ndim
return np.ravel(array[indexer]).tolist() | [
"def",
"last_item",
"(",
"array",
")",
":",
"if",
"array",
".",
"size",
"==",
"0",
":",
"# work around for https://github.com/numpy/numpy/issues/5195",
"return",
"[",
"]",
"indexer",
"=",
"(",
"slice",
"(",
"-",
"1",
",",
"None",
")",
",",
")",
"*",
"array... | 36.125 | 0.003378 |
def _set_mem_list(self, v, load=False):
"""
Setter method for mem_list, mapped from YANG variable /mem_state/mem_list (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mem_list is considered as a private
method. Backends looking to populate this variable sh... | [
"def",
"_set_mem_list",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base"... | 71.875 | 0.006293 |
def platform_mapped(func):
"""Decorates functions for lookups within a config.platform_map dictionary.
The first level key is mapped to the func.__name__ of the decorated function.
Regular expressions are used on the second level key, values.
Note that there is no guaranteed order within the dictionary... | [
"def",
"platform_mapped",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Since platform is being used within config lazy import config to prevent",
"# circular dependencies",
"from",
"rez",
".",
"config",
"import",
"conf... | 35.589744 | 0.00561 |
def do_mkdir(self, line):
"""mkdir DIRECTORY...
Creates one or more directories.
"""
args = self.line_to_args(line)
for filename in args:
filename = resolve_path(filename)
if not mkdir(filename):
print_err('Unable to create %s' % filena... | [
"def",
"do_mkdir",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"self",
".",
"line_to_args",
"(",
"line",
")",
"for",
"filename",
"in",
"args",
":",
"filename",
"=",
"resolve_path",
"(",
"filename",
")",
"if",
"not",
"mkdir",
"(",
"filename",
")",
... | 31.4 | 0.006192 |
def add_suspect(self, case_obj, variant_obj):
"""Link a suspect to a case."""
new_suspect = Suspect(case=case_obj, variant_id=variant_obj.variant_id,
name=variant_obj.display_name)
self.session.add(new_suspect)
self.save()
return new_suspect | [
"def",
"add_suspect",
"(",
"self",
",",
"case_obj",
",",
"variant_obj",
")",
":",
"new_suspect",
"=",
"Suspect",
"(",
"case",
"=",
"case_obj",
",",
"variant_id",
"=",
"variant_obj",
".",
"variant_id",
",",
"name",
"=",
"variant_obj",
".",
"display_name",
")"... | 43.571429 | 0.006431 |
def _parse_settings_bond_2(opts, iface, bond_def):
'''
Filters given options and outputs valid settings for bond2.
If an option has a value that is not expected, this
function will log what the Interface, Setting and what it was
expecting.
'''
bond = {'mode': '2'}
valid = ['list of ips... | [
"def",
"_parse_settings_bond_2",
"(",
"opts",
",",
"iface",
",",
"bond_def",
")",
":",
"bond",
"=",
"{",
"'mode'",
":",
"'2'",
"}",
"valid",
"=",
"[",
"'list of ips (up to 16)'",
"]",
"if",
"'arp_ip_target'",
"in",
"opts",
":",
"if",
"isinstance",
"(",
"op... | 37.333333 | 0.00116 |
def close(self):
"""
Call :func:`os.close` on :attr:`fd` if it is not :data:`None`,
then set it to :data:`None`.
"""
if not self.closed:
_vv and IOLOG.debug('%r.close()', self)
self.closed = True
os.close(self.fd) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"closed",
":",
"_vv",
"and",
"IOLOG",
".",
"debug",
"(",
"'%r.close()'",
",",
"self",
")",
"self",
".",
"closed",
"=",
"True",
"os",
".",
"close",
"(",
"self",
".",
"fd",
")"
] | 31.222222 | 0.00692 |
def tag_builder(parser, token, cls, flow_type):
"""Helper function handling flow form tags."""
tokens = token.split_contents()
tokens_num = len(tokens)
if tokens_num == 1 or (tokens_num == 3 and tokens[1] == 'for'):
flow_name = None
if tokens_num == 3:
flow_name = tokens[2]
... | [
"def",
"tag_builder",
"(",
"parser",
",",
"token",
",",
"cls",
",",
"flow_type",
")",
":",
"tokens",
"=",
"token",
".",
"split_contents",
"(",
")",
"tokens_num",
"=",
"len",
"(",
"tokens",
")",
"if",
"tokens_num",
"==",
"1",
"or",
"(",
"tokens_num",
"=... | 40.4 | 0.003226 |
def _create_hstore_required(self, table_name, field, key):
"""Creates a REQUIRED CONSTRAINT for the specified hstore key."""
name = self._required_constraint_name(
table_name, field, key)
sql = self.sql_hstore_required_create.format(
name=self.quote_name(name),
... | [
"def",
"_create_hstore_required",
"(",
"self",
",",
"table_name",
",",
"field",
",",
"key",
")",
":",
"name",
"=",
"self",
".",
"_required_constraint_name",
"(",
"table_name",
",",
"field",
",",
"key",
")",
"sql",
"=",
"self",
".",
"sql_hstore_required_create"... | 34.692308 | 0.00432 |
def _map_in_out(self, inside_var_name):
"""Return the external name of a variable mapped from inside."""
for out_name, in_name in self.outside_name_map.items():
if inside_var_name == in_name:
return out_name
return None | [
"def",
"_map_in_out",
"(",
"self",
",",
"inside_var_name",
")",
":",
"for",
"out_name",
",",
"in_name",
"in",
"self",
".",
"outside_name_map",
".",
"items",
"(",
")",
":",
"if",
"inside_var_name",
"==",
"in_name",
":",
"return",
"out_name",
"return",
"None"
... | 44.333333 | 0.00738 |
def get(self):
'''
:return:
'''
cluster = self.get_argument("cluster")
environ = self.get_argument("environ")
topology = self.get_argument("topology")
component = self.get_argument("component", default=None)
metric = self.get_argument("metric")
instances = self.get_argument("instance... | [
"def",
"get",
"(",
"self",
")",
":",
"cluster",
"=",
"self",
".",
"get_argument",
"(",
"\"cluster\"",
")",
"environ",
"=",
"self",
".",
"get_argument",
"(",
"\"environ\"",
")",
"topology",
"=",
"self",
".",
"get_argument",
"(",
"\"topology\"",
")",
"compon... | 35.90625 | 0.005085 |
def get_login_password(site_name="github.com",
netrc_file="~/.netrc",
git_credential_file="~/.git-credentials"):
"""Read a .netrc file and return login/password for LWN."""
try:
n = netrc.netrc(os.path.expanduser(netrc_file))
except OSError:
pass... | [
"def",
"get_login_password",
"(",
"site_name",
"=",
"\"github.com\"",
",",
"netrc_file",
"=",
"\"~/.netrc\"",
",",
"git_credential_file",
"=",
"\"~/.git-credentials\"",
")",
":",
"try",
":",
"n",
"=",
"netrc",
".",
"netrc",
"(",
"os",
".",
"path",
".",
"expand... | 34.173913 | 0.001238 |
def _chk_fields(field_data, field_formatter):
"""Check that expected fields are present."""
if len(field_data) == len(field_formatter):
return
len_dat = len(field_data)
len_fmt = len(field_formatter)
msg = [
"FIELD DATA({d}) != FORMATTER({f})".format(d=len... | [
"def",
"_chk_fields",
"(",
"field_data",
",",
"field_formatter",
")",
":",
"if",
"len",
"(",
"field_data",
")",
"==",
"len",
"(",
"field_formatter",
")",
":",
"return",
"len_dat",
"=",
"len",
"(",
"field_data",
")",
"len_fmt",
"=",
"len",
"(",
"field_forma... | 44.909091 | 0.003968 |
def predict(self, x):
"""
Make prediction recursively. Use both the samples inside the current
node and the statistics inherited from parent.
"""
if self._is_leaf():
d1 = self.predict_initialize['count_dict']
d2 = count_dict(self.Y)
for key, va... | [
"def",
"predict",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"_is_leaf",
"(",
")",
":",
"d1",
"=",
"self",
".",
"predict_initialize",
"[",
"'count_dict'",
"]",
"d2",
"=",
"count_dict",
"(",
"self",
".",
"Y",
")",
"for",
"key",
",",
"value"... | 33.368421 | 0.003067 |
def reset(self):
"""Reset StackInABox to a like-new state."""
logger.debug('StackInABox({0}): Resetting...'
.format(self.__id))
for k, v in six.iteritems(self.services):
matcher, service = v
logger.debug('StackInABox({0}): Resetting Service {1}'
... | [
"def",
"reset",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'StackInABox({0}): Resetting...'",
".",
"format",
"(",
"self",
".",
"__id",
")",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"services",
")",
":",
"m... | 35.8 | 0.00363 |
def tree(alias, title='', items=None, **kwargs):
"""Dynamically creates and returns a sitetree.
:param str|unicode alias:
:param str|unicode title:
:param iterable items: dynamic sitetree items objects created by `item` function.
:param kwargs: Additional arguments to pass to tree item initializer.... | [
"def",
"tree",
"(",
"alias",
",",
"title",
"=",
"''",
",",
"items",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"tree_obj",
"=",
"get_tree_model",
"(",
")",
"(",
"alias",
"=",
"alias",
",",
"title",
"=",
"title",
",",
"*",
"*",
"kwargs",
")",... | 33.28 | 0.003505 |
def main_composite(kind, toolkits=None, name=None):
"""Wrap a main composite invocation as a `Topology`.
Provides a bridge between an SPL application (main composite)
and a `Topology`. Create a `Topology` that contains just
the invocation of the main composite defined by `kind`.
The returned `To... | [
"def",
"main_composite",
"(",
"kind",
",",
"toolkits",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"'::'",
"in",
"kind",
":",
"ns",
",",
"name",
"=",
"kind",
".",
"rsplit",
"(",
"'::'",
",",
"1",
")",
"ns",
"+=",
"'._spl'",
"else",
":"... | 38.921053 | 0.002639 |
def quintic_bucket_warp(x, n, l1, l2, l3, x0, w1, w2, w3):
"""Warps the length scale with a piecewise quintic "bucket" shape.
Parameters
----------
x : float or array-like of float
Locations to evaluate length scale at.
n : non-negative int
Derivative order to evaluate. Only first d... | [
"def",
"quintic_bucket_warp",
"(",
"x",
",",
"n",
",",
"l1",
",",
"l2",
",",
"l3",
",",
"x0",
",",
"w1",
",",
"w2",
",",
"w3",
")",
":",
"x1",
"=",
"x0",
"-",
"w2",
"/",
"2.0",
"-",
"w1",
"/",
"2.0",
"x2",
"=",
"x0",
"+",
"w2",
"/",
"2.0"... | 36.125 | 0.000842 |
def clean_int(v):
"""Remove commas from a float"""
if v is None or not str(v).strip():
return None
return int(str(v).replace(',', '')) | [
"def",
"clean_int",
"(",
"v",
")",
":",
"if",
"v",
"is",
"None",
"or",
"not",
"str",
"(",
"v",
")",
".",
"strip",
"(",
")",
":",
"return",
"None",
"return",
"int",
"(",
"str",
"(",
"v",
")",
".",
"replace",
"(",
"','",
",",
"''",
")",
")"
] | 21.428571 | 0.00641 |
def process_args(args):
"""Processes passed arguments."""
passed_args = args
if isinstance(args, argparse.Namespace):
passed_args = vars(passed_args)
elif hasattr(args, "to_dict"):
passed_args = passed_args.to_dict()
return Box(passed_args, frozen_box=True, default_box=True) | [
"def",
"process_args",
"(",
"args",
")",
":",
"passed_args",
"=",
"args",
"if",
"isinstance",
"(",
"args",
",",
"argparse",
".",
"Namespace",
")",
":",
"passed_args",
"=",
"vars",
"(",
"passed_args",
")",
"elif",
"hasattr",
"(",
"args",
",",
"\"to_dict\"",... | 33.777778 | 0.003205 |
def to_dict(self):
"""Converts this embed object into a dict."""
# add in the raw data into the dict
result = {
key[1:]: getattr(self, key)
for key in self.__slots__
if key[0] == '_' and hasattr(self, key)
}
# deal with basic conven... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"# add in the raw data into the dict\r",
"result",
"=",
"{",
"key",
"[",
"1",
":",
"]",
":",
"getattr",
"(",
"self",
",",
"key",
")",
"for",
"key",
"in",
"self",
".",
"__slots__",
"if",
"key",
"[",
"0",
"]",
"... | 24.904762 | 0.00184 |
def _organize_lanes(info_iter, barcode_ids):
"""Organize flat lane information into nested YAML structure.
"""
all_lanes = []
for (fcid, lane, sampleref), info in itertools.groupby(info_iter, lambda x: (x[0], x[1], x[1])):
info = list(info)
cur_lane = dict(flowcell_id=fcid, lane=lane, ge... | [
"def",
"_organize_lanes",
"(",
"info_iter",
",",
"barcode_ids",
")",
":",
"all_lanes",
"=",
"[",
"]",
"for",
"(",
"fcid",
",",
"lane",
",",
"sampleref",
")",
",",
"info",
"in",
"itertools",
".",
"groupby",
"(",
"info_iter",
",",
"lambda",
"x",
":",
"("... | 46.904762 | 0.00398 |
def manifest_download(self):
'''download manifest files'''
if self.downloaders_lock.acquire(False):
if len(self.downloaders):
# there already exist downloader threads
self.downloaders_lock.release()
return
for url in ['http://firmw... | [
"def",
"manifest_download",
"(",
"self",
")",
":",
"if",
"self",
".",
"downloaders_lock",
".",
"acquire",
"(",
"False",
")",
":",
"if",
"len",
"(",
"self",
".",
"downloaders",
")",
":",
"# there already exist downloader threads",
"self",
".",
"downloaders_lock",... | 46 | 0.003995 |
def _get_process_mapping():
"""Select a way to obtain process information from the system.
* `/proc` is used if supported.
* The system `ps` utility is used as a fallback option.
"""
for impl in (proc, ps):
try:
mapping = impl.get_process_mapping()
except EnvironmentErro... | [
"def",
"_get_process_mapping",
"(",
")",
":",
"for",
"impl",
"in",
"(",
"proc",
",",
"ps",
")",
":",
"try",
":",
"mapping",
"=",
"impl",
".",
"get_process_mapping",
"(",
")",
"except",
"EnvironmentError",
":",
"continue",
"return",
"mapping",
"raise",
"She... | 33.384615 | 0.002242 |
def children(self, alias, bank_id):
"""
URL for getting or setting child relationships for the specified bank
:param alias:
:param bank_id:
:return:
"""
return self._root + self._safe_alias(alias) + '/child/ids/' + str(bank_id) | [
"def",
"children",
"(",
"self",
",",
"alias",
",",
"bank_id",
")",
":",
"return",
"self",
".",
"_root",
"+",
"self",
".",
"_safe_alias",
"(",
"alias",
")",
"+",
"'/child/ids/'",
"+",
"str",
"(",
"bank_id",
")"
] | 34.5 | 0.010601 |
def transformBy(self, matrix, origin=None):
"""
Transform the object.
>>> obj.transformBy((0.5, 0, 0, 2.0, 10, 0))
>>> obj.transformBy((0.5, 0, 0, 2.0, 10, 0), origin=(500, 500))
**matrix** must be a :ref:`type-transformation`.
**origin** defines the point at wi... | [
"def",
"transformBy",
"(",
"self",
",",
"matrix",
",",
"origin",
"=",
"None",
")",
":",
"matrix",
"=",
"normalizers",
".",
"normalizeTransformationMatrix",
"(",
"matrix",
")",
"if",
"origin",
"is",
"None",
":",
"origin",
"=",
"(",
"0",
",",
"0",
")",
"... | 37.291667 | 0.002179 |
def clean(self):
"""
Get rid of stale connections.
"""
# Note that we do not close the connection here -- somebody
# may still be reading from it.
while len(self.queue) > 0 and self._pair_stale(self.queue[0]):
self.queue.pop(0) | [
"def",
"clean",
"(",
"self",
")",
":",
"# Note that we do not close the connection here -- somebody",
"# may still be reading from it.",
"while",
"len",
"(",
"self",
".",
"queue",
")",
">",
"0",
"and",
"self",
".",
"_pair_stale",
"(",
"self",
".",
"queue",
"[",
"0... | 35 | 0.006969 |
def almost_eq(arr1, arr2, thresh=1E-11, ret_error=False):
""" checks if floating point number are equal to a threshold
"""
error = np.abs(arr1 - arr2)
passed = error < thresh
if ret_error:
return passed, error
return passed | [
"def",
"almost_eq",
"(",
"arr1",
",",
"arr2",
",",
"thresh",
"=",
"1E-11",
",",
"ret_error",
"=",
"False",
")",
":",
"error",
"=",
"np",
".",
"abs",
"(",
"arr1",
"-",
"arr2",
")",
"passed",
"=",
"error",
"<",
"thresh",
"if",
"ret_error",
":",
"retu... | 31 | 0.003922 |
def revise_paragraph_classification(paragraphs, max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT):
"""
Context-sensitive paragraph classification. Assumes that classify_pragraphs
has already been called.
"""
# copy classes
for paragraph in paragraphs:
paragraph.class_type = paragraph.cf... | [
"def",
"revise_paragraph_classification",
"(",
"paragraphs",
",",
"max_heading_distance",
"=",
"MAX_HEADING_DISTANCE_DEFAULT",
")",
":",
"# copy classes",
"for",
"paragraph",
"in",
"paragraphs",
":",
"paragraph",
".",
"class_type",
"=",
"paragraph",
".",
"cf_class",
"# ... | 39.38806 | 0.003327 |
def next_index(self) -> int:
"""Get a random index."""
return bisect.bisect_right(self.totals, random.random() * self.total) | [
"def",
"next_index",
"(",
"self",
")",
"->",
"int",
":",
"return",
"bisect",
".",
"bisect_right",
"(",
"self",
".",
"totals",
",",
"random",
".",
"random",
"(",
")",
"*",
"self",
".",
"total",
")"
] | 46 | 0.014286 |
def get_attribute_by_id(attr_id, **kwargs):
"""
Get a specific attribute by its ID.
"""
try:
attr_i = db.DBSession.query(Attr).filter(Attr.id==attr_id).one()
return attr_i
except NoResultFound:
return None | [
"def",
"get_attribute_by_id",
"(",
"attr_id",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"attr_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Attr",
")",
".",
"filter",
"(",
"Attr",
".",
"id",
"==",
"attr_id",
")",
".",
"one",
"(",
")",
... | 24.5 | 0.007874 |
def _set_seed(self):
""" Set random seed for numpy and tensorflow packages """
if self.flags['SEED'] is not None:
tf.set_random_seed(self.flags['SEED'])
np.random.seed(self.flags['SEED']) | [
"def",
"_set_seed",
"(",
"self",
")",
":",
"if",
"self",
".",
"flags",
"[",
"'SEED'",
"]",
"is",
"not",
"None",
":",
"tf",
".",
"set_random_seed",
"(",
"self",
".",
"flags",
"[",
"'SEED'",
"]",
")",
"np",
".",
"random",
".",
"seed",
"(",
"self",
... | 44.6 | 0.008811 |
def remove_hooks(scrub_sys_modules=False):
"""
This function removes the import hook from sys.meta_path.
"""
if PY3:
return
flog.debug('Uninstalling hooks ...')
# Loop backwards, so deleting items keeps the ordering:
for i, hook in list(enumerate(sys.meta_path))[::-1]:
if has... | [
"def",
"remove_hooks",
"(",
"scrub_sys_modules",
"=",
"False",
")",
":",
"if",
"PY3",
":",
"return",
"flog",
".",
"debug",
"(",
"'Uninstalling hooks ...'",
")",
"# Loop backwards, so deleting items keeps the ordering:",
"for",
"i",
",",
"hook",
"in",
"list",
"(",
... | 36.611111 | 0.001479 |
def send(self, node_id, request, wakeup=True):
"""Send a request to a specific node. Bytes are placed on an
internal per-connection send-queue. Actual network I/O will be
triggered in a subsequent call to .poll()
Arguments:
node_id (int): destination node
request... | [
"def",
"send",
"(",
"self",
",",
"node_id",
",",
"request",
",",
"wakeup",
"=",
"True",
")",
":",
"conn",
"=",
"self",
".",
"_conns",
".",
"get",
"(",
"node_id",
")",
"if",
"not",
"conn",
"or",
"not",
"self",
".",
"_can_send_request",
"(",
"node_id",... | 37.181818 | 0.001589 |
def monthly(date=datetime.date.today()):
"""
Take a date object and return the first day of the month.
"""
return datetime.date(date.year, date.month, 1) | [
"def",
"monthly",
"(",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
":",
"return",
"datetime",
".",
"date",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"1",
")"
] | 33 | 0.005917 |
def add_attribute_group_items(attributegroupitems, **kwargs):
"""
Populate attribute groups with items.
** attributegroupitems : a list of items, of the form:
```{
'attr_id' : X,
'group_id' : Y,
'network_id' : Z,
... | [
"def",
"add_attribute_group_items",
"(",
"attributegroupitems",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"if",
"not",
"isinstance",
"(",
"attributegroupitems",
",",
"list",
")",
":",
"raise",
"HydraError",... | 41.436364 | 0.007499 |
def parse_reply(self, data):
"""Deserializes and validates a response.
Called by the client to reconstruct the serialized :py:class:`JSONRPCResponse`.
:param bytes data: The data stream received by the transport layer containing the
serialized request.
:return: A reconstruc... | [
"def",
"parse_reply",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"data",
"=",
"data",
".",
"decode",
"(",
")",
"try",
":",
"rep",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"except",
"Exception",
... | 34.480769 | 0.003796 |
def get_state_data(cls, entity):
"""
Returns the state data for the given entity.
This also works for unmanaged entities.
"""
attrs = get_domain_class_attribute_iterator(type(entity))
return dict([(attr,
get_nested_attribute(entity, attr.entity_attr... | [
"def",
"get_state_data",
"(",
"cls",
",",
"entity",
")",
":",
"attrs",
"=",
"get_domain_class_attribute_iterator",
"(",
"type",
"(",
"entity",
")",
")",
"return",
"dict",
"(",
"[",
"(",
"attr",
",",
"get_nested_attribute",
"(",
"entity",
",",
"attr",
".",
... | 36.909091 | 0.007212 |
def calc_gs_kappa(b, ne, delta, sinth, nu):
"""Calculate the gyrosynchrotron absorption coefficient κ_ν.
This is Dulk (1985) equation 36, which is a fitting function assuming a
power-law electron population. Arguments are:
b
Magnetic field strength in Gauss
ne
The density of electrons ... | [
"def",
"calc_gs_kappa",
"(",
"b",
",",
"ne",
",",
"delta",
",",
"sinth",
",",
"nu",
")",
":",
"s",
"=",
"nu",
"/",
"calc_nu_b",
"(",
"b",
")",
"return",
"(",
"ne",
"/",
"b",
"*",
"1.4e-9",
"*",
"10",
"**",
"(",
"-",
"0.22",
"*",
"delta",
")",... | 38.4375 | 0.004758 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.