text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def do_sing(self, arg):
"""Sing a colorful song."""
color_escape = COLORS.get(self.songcolor, Fore.RESET)
self.poutput(arg, color=color_escape) | [
"def",
"do_sing",
"(",
"self",
",",
"arg",
")",
":",
"color_escape",
"=",
"COLORS",
".",
"get",
"(",
"self",
".",
"songcolor",
",",
"Fore",
".",
"RESET",
")",
"self",
".",
"poutput",
"(",
"arg",
",",
"color",
"=",
"color_escape",
")"
] | 41 | 10.75 |
def mouseMoveEvent(self, e):
"""
Extends mouseMoveEvent to display a pointing hand cursor when the
mouse cursor is over a file location
"""
super(PyInteractiveConsole, self).mouseMoveEvent(e)
cursor = self.cursorForPosition(e.pos())
assert isinstance(cursor, QtGui... | [
"def",
"mouseMoveEvent",
"(",
"self",
",",
"e",
")",
":",
"super",
"(",
"PyInteractiveConsole",
",",
"self",
")",
".",
"mouseMoveEvent",
"(",
"e",
")",
"cursor",
"=",
"self",
".",
"cursorForPosition",
"(",
"e",
".",
"pos",
"(",
")",
")",
"assert",
"isi... | 46.941176 | 15.529412 |
def vmdk_to_ami(args):
"""
Calls methods to perform vmdk import
:param args:
:return:
"""
aws_importer = AWSUtilities.AWSUtils(args.directory, args.aws_profile, args.s3_bucket,
args.aws_regions, args.ami_name, args.vmdk_upload_file)
aws_importer.impor... | [
"def",
"vmdk_to_ami",
"(",
"args",
")",
":",
"aws_importer",
"=",
"AWSUtilities",
".",
"AWSUtils",
"(",
"args",
".",
"directory",
",",
"args",
".",
"aws_profile",
",",
"args",
".",
"s3_bucket",
",",
"args",
".",
"aws_regions",
",",
"args",
".",
"ami_name",... | 35.555556 | 20.666667 |
def create_geotiff(name, Array, driver, ndv, xsize, ysize, geot, projection, datatype, band=1):
'''
Creates new geotiff from array
'''
if isinstance(datatype, np.int) == False:
if datatype.startswith('gdal.GDT_') == False:
datatype = eval('gdal.GDT_'+datatype)
newfilename = name+... | [
"def",
"create_geotiff",
"(",
"name",
",",
"Array",
",",
"driver",
",",
"ndv",
",",
"xsize",
",",
"ysize",
",",
"geot",
",",
"projection",
",",
"datatype",
",",
"band",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"datatype",
",",
"np",
".",
"int",
... | 39 | 16.157895 |
def get_provider():
"""Return an instance of the BLE provider for the current platform."""
global _provider
# Set the provider based on the current platform.
if _provider is None:
if sys.platform.startswith('linux'):
# Linux platform
from .bluez_dbus.provider import Bluez... | [
"def",
"get_provider",
"(",
")",
":",
"global",
"_provider",
"# Set the provider based on the current platform.",
"if",
"_provider",
"is",
"None",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'linux'",
")",
":",
"# Linux platform",
"from",
".",
"blu... | 42.647059 | 16.411765 |
def plot(self, attribute=None, ax=None, **kwargs):
"""
Plot the rose diagram.
Parameters
----------
attribute : (n,) ndarray, optional
Variable to specify colors of the colorbars.
ax : Matplotlib Axes instance, optional
If given, the figure will b... | [
"def",
"plot",
"(",
"self",
",",
"attribute",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"splot",
".",
"giddy",
"import",
"dynamic_lisa_rose",
"fig",
",",
"ax",
"=",
"dynamic_lisa_rose",
"(",
"self",
",",
"attribute... | 35.107143 | 17.821429 |
def alpha_(self,x):
""" Create a mappable function alpha to apply to each xmin in a list of xmins.
This is essentially the slow version of fplfit/cplfit, though I bet it could
be speeded up with a clever use of parellel_map. Not intended to be used by users."""
def alpha(xmin,x=x):
... | [
"def",
"alpha_",
"(",
"self",
",",
"x",
")",
":",
"def",
"alpha",
"(",
"xmin",
",",
"x",
"=",
"x",
")",
":",
"\"\"\"\n given a sorted data set and a minimum, returns power law MLE fit\n data is passed as a keyword parameter so that it can be vectorized\n ... | 46.611111 | 16.277778 |
def split_string(self, string, splitter='.', allow_empty=True):
"""Split the string with respect of quotes"""
i = 0
rv = []
need_split = False
while i < len(string):
m = re.compile(_KEY_NAME).match(string, i)
if not need_split and m:
i = m.... | [
"def",
"split_string",
"(",
"self",
",",
"string",
",",
"splitter",
"=",
"'.'",
",",
"allow_empty",
"=",
"True",
")",
":",
"i",
"=",
"0",
"rv",
"=",
"[",
"]",
"need_split",
"=",
"False",
"while",
"i",
"<",
"len",
"(",
"string",
")",
":",
"m",
"="... | 39 | 12.777778 |
def ConsumeInt32(self):
"""Consumes a signed 32bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If a signed 32bit integer couldn't be consumed.
"""
try:
result = ParseInteger(self.token, is_signed=True, is_long=False)
except ValueError as e:
raise se... | [
"def",
"ConsumeInt32",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"ParseInteger",
"(",
"self",
".",
"token",
",",
"is_signed",
"=",
"True",
",",
"is_long",
"=",
"False",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"self",
".",
"_ParseE... | 24.466667 | 21.066667 |
def _format_results(_keywords, combined_keywords, split, scores):
"""
:param keywords:dict of keywords:scores
:param combined_keywords:list of word/s
"""
combined_keywords.sort(key=lambda w: _get_average_score(w, _keywords), reverse=True)
if scores:
return [(word, _get_average_score(word... | [
"def",
"_format_results",
"(",
"_keywords",
",",
"combined_keywords",
",",
"split",
",",
"scores",
")",
":",
"combined_keywords",
".",
"sort",
"(",
"key",
"=",
"lambda",
"w",
":",
"_get_average_score",
"(",
"w",
",",
"_keywords",
")",
",",
"reverse",
"=",
... | 40.090909 | 17.363636 |
def total_cycles(self) -> int:
"""The number of total number of cycles in the structure."""
return sum((int(re.sub(r'\D', '', op)) for op in self.tokens)) | [
"def",
"total_cycles",
"(",
"self",
")",
"->",
"int",
":",
"return",
"sum",
"(",
"(",
"int",
"(",
"re",
".",
"sub",
"(",
"r'\\D'",
",",
"''",
",",
"op",
")",
")",
"for",
"op",
"in",
"self",
".",
"tokens",
")",
")"
] | 56 | 13.333333 |
def select_mask(cls, dataset, selection):
"""
Given a Dataset object and a dictionary with dimension keys and
selection keys (i.e tuple ranges, slices, sets, lists or literals)
return a boolean mask over the rows in the Dataset object that
have been selected.
"""
... | [
"def",
"select_mask",
"(",
"cls",
",",
"dataset",
",",
"selection",
")",
":",
"select_mask",
"=",
"None",
"for",
"dim",
",",
"k",
"in",
"selection",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"k",
",",
"tuple",
")",
":",
"k",
"=",
"slice... | 38.585366 | 9.170732 |
def set_header_info(self, r_free, r_work, resolution, title,
deposition_date, release_date, experimental_methods):
"""Sets the header information.
:param r_free: the measured R-Free for the structure
:param r_work: the measure R-Work for the structure
:param resol... | [
"def",
"set_header_info",
"(",
"self",
",",
"r_free",
",",
"r_work",
",",
"resolution",
",",
"title",
",",
"deposition_date",
",",
"release_date",
",",
"experimental_methods",
")",
":",
"raise",
"NotImplementedError"
] | 55.083333 | 18.75 |
def macros_attachment_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros#create-unassociated-macro-attachment"
api_path = "/api/v2/macros/attachments.json"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"macros_attachment_create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/macros/attachments.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
"data",
... | 68.75 | 28.75 |
def require(self, key):
"""
Raises an exception if value for ``key`` is empty.
"""
value = self.get(key)
if not value:
raise ValueError('"{}" is empty.'.format(key))
return value | [
"def",
"require",
"(",
"self",
",",
"key",
")",
":",
"value",
"=",
"self",
".",
"get",
"(",
"key",
")",
"if",
"not",
"value",
":",
"raise",
"ValueError",
"(",
"'\"{}\" is empty.'",
".",
"format",
"(",
"key",
")",
")",
"return",
"value"
] | 28.875 | 12.875 |
def add_toolbars_to_menu(self, menu_title, actions):
"""Add toolbars to a menu."""
# Six is the position of the view menu in menus list
# that you can find in plugins/editor.py setup_other_windows.
view_menu = self.menus[6]
if actions == self.toolbars and view_menu:
... | [
"def",
"add_toolbars_to_menu",
"(",
"self",
",",
"menu_title",
",",
"actions",
")",
":",
"# Six is the position of the view menu in menus list\r",
"# that you can find in plugins/editor.py setup_other_windows.\r",
"view_menu",
"=",
"self",
".",
"menus",
"[",
"6",
"]",
"if",
... | 46.454545 | 10.272727 |
def maxsize(self, size):
"""Resize the cache, evicting the oldest items if necessary."""
if size < 0:
raise ValueError('maxsize must be non-negative')
with self._lock:
self._enforce_size_limit(size)
self._maxsize = size | [
"def",
"maxsize",
"(",
"self",
",",
"size",
")",
":",
"if",
"size",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'maxsize must be non-negative'",
")",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_enforce_size_limit",
"(",
"size",
")",
"self",
".",
"_... | 39 | 11.714286 |
def get_scheduler_location(self, topologyName, callback=None):
""" get scheduler location """
isWatching = False
# Temp dict used to return result
# if callback is not provided.
ret = {
"result": None
}
if callback:
isWatching = True
else:
def callback(data):
... | [
"def",
"get_scheduler_location",
"(",
"self",
",",
"topologyName",
",",
"callback",
"=",
"None",
")",
":",
"isWatching",
"=",
"False",
"# Temp dict used to return result",
"# if callback is not provided.",
"ret",
"=",
"{",
"\"result\"",
":",
"None",
"}",
"if",
"call... | 24.619048 | 20.428571 |
def getWindowRect(self, hwnd):
""" Returns a rect (x,y,w,h) for the specified window's area """
rect = ctypes.wintypes.RECT()
if ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rect)):
x1 = rect.left
y1 = rect.top
x2 = rect.right
y2 = rect.bo... | [
"def",
"getWindowRect",
"(",
"self",
",",
"hwnd",
")",
":",
"rect",
"=",
"ctypes",
".",
"wintypes",
".",
"RECT",
"(",
")",
"if",
"ctypes",
".",
"windll",
".",
"user32",
".",
"GetWindowRect",
"(",
"hwnd",
",",
"ctypes",
".",
"byref",
"(",
"rect",
")",... | 37.7 | 12.1 |
def topsDF(symbols=None, token='', version=''):
'''TOPS provides IEX’s aggregated best quoted bid and offer position in near real time for all securities on IEX’s displayed limit order book.
TOPS is ideal for developers needing both quote and trade data.
https://iexcloud.io/docs/api/#tops
Args:
... | [
"def",
"topsDF",
"(",
"symbols",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"df",
"=",
"pd",
".",
"io",
".",
"json",
".",
"json_normalize",
"(",
"tops",
"(",
"symbols",
",",
"token",
",",
"version",
")",
")",
"_toD... | 32.722222 | 25.833333 |
def _bind(self):
"""
Create CloudWatch Connection
"""
self.log.debug(
"CloudWatch: Attempting to connect to CloudWatch at Region: %s",
self.region)
try:
self.connection = boto.ec2.cloudwatch.connect_to_region(
self.region)
... | [
"def",
"_bind",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"CloudWatch: Attempting to connect to CloudWatch at Region: %s\"",
",",
"self",
".",
"region",
")",
"try",
":",
"self",
".",
"connection",
"=",
"boto",
".",
"ec2",
".",
"cloudwatch... | 35.125 | 19.125 |
def group_keys_by_replica(session, keyspace, table, keys):
"""
Returns a :class:`dict` with the keys grouped per host. This can be
used to more accurately group by IN clause or to batch the keys per host.
If a valid replica is not found for a particular key it will be grouped under
:class:`~.NO_VAL... | [
"def",
"group_keys_by_replica",
"(",
"session",
",",
"keyspace",
",",
"table",
",",
"keys",
")",
":",
"cluster",
"=",
"session",
".",
"cluster",
"partition_keys",
"=",
"cluster",
".",
"metadata",
".",
"keyspaces",
"[",
"keyspace",
"]",
".",
"tables",
"[",
... | 42.227273 | 24.590909 |
def delete_direct(self, addresses):
"""Called in the context manager's delete method to either
mark an entry for deletion , or create a new future and immediately
set it for deletion in the future.
Args:
address_list (list of str): The unique full addresses.
Raises:... | [
"def",
"delete_direct",
"(",
"self",
",",
"addresses",
")",
":",
"with",
"self",
".",
"_lock",
":",
"for",
"address",
"in",
"addresses",
":",
"self",
".",
"_validate_write",
"(",
"address",
")",
"if",
"address",
"in",
"self",
".",
"_state",
":",
"self",
... | 34.285714 | 15.761905 |
def serialize(self, private=True):
"""Serialize this key.
:param private: Whether or not the serialized key should contain
private information. Set to False for a public-only representation
that cannot spend funds but can create children. You want
private=False if yo... | [
"def",
"serialize",
"(",
"self",
",",
"private",
"=",
"True",
")",
":",
"if",
"private",
"and",
"not",
"self",
".",
"private_key",
":",
"raise",
"ValueError",
"(",
"\"Cannot serialize a public key as private\"",
")",
"if",
"private",
":",
"network_version",
"=",... | 42.882353 | 18.558824 |
def convert_to_crash_data(raw_crash, processed_crash):
"""
Takes a raw crash and a processed crash (these are Socorro-centric
data structures) and converts them to a crash data structure used
by signature generation.
:arg raw_crash: raw crash data from Socorro
:arg processed_crash: processed cr... | [
"def",
"convert_to_crash_data",
"(",
"raw_crash",
",",
"processed_crash",
")",
":",
"# We want to generate fresh signatures, so we remove the \"normalized\" field",
"# from stack frames from the processed crash because this is essentially",
"# cached data from previous processing",
"for",
"t... | 37.362319 | 28.811594 |
def listen(self):
"""Self-host using 'bind' and 'port' from the WSGI config group."""
msgtmpl = (u'Serving on host %(host)s:%(port)s')
host = CONF.wsgi.wsgi_host
port = CONF.wsgi.wsgi_port
LOG.info(msgtmpl,
{'host': host, 'port': port})
server_cls = self... | [
"def",
"listen",
"(",
"self",
")",
":",
"msgtmpl",
"=",
"(",
"u'Serving on host %(host)s:%(port)s'",
")",
"host",
"=",
"CONF",
".",
"wsgi",
".",
"wsgi_host",
"port",
"=",
"CONF",
".",
"wsgi",
".",
"wsgi_port",
"LOG",
".",
"info",
"(",
"msgtmpl",
",",
"{"... | 40.071429 | 12 |
def properties_for_args(cls, arg_names='_arg_names'):
"""For a class with an attribute `arg_names` containing a list of names,
add a property for every name in that list.
It is assumed that there is an instance attribute ``self._<arg_name>``,
which is returned by the `arg_name` property. The decorator... | [
"def",
"properties_for_args",
"(",
"cls",
",",
"arg_names",
"=",
"'_arg_names'",
")",
":",
"from",
"qnet",
".",
"algebra",
".",
"core",
".",
"scalar_algebra",
"import",
"Scalar",
"scalar_args",
"=",
"False",
"if",
"hasattr",
"(",
"cls",
",",
"'_scalar_args'",
... | 39.241379 | 14.241379 |
def set_value(value_proto, value, exclude_from_indexes=None):
"""Set the corresponding datastore.Value _value field for the given arg.
Args:
value_proto: datastore.Value proto message.
value: python object or datastore.Value. (unicode value will set a
datastore string value, str value will set a bl... | [
"def",
"set_value",
"(",
"value_proto",
",",
"value",
",",
"exclude_from_indexes",
"=",
"None",
")",
":",
"value_proto",
".",
"Clear",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"sub_value",
"in",
... | 37.282609 | 15.652174 |
def find_home_directory():
"""
Look up the home directory of the effective user id.
:returns: The pathname of the home directory (a string).
.. note:: On Windows this uses the ``%APPDATA%`` environment variable (if
available) and otherwise falls back to ``~/Application Data``.
"""
... | [
"def",
"find_home_directory",
"(",
")",
":",
"if",
"WINDOWS",
":",
"directory",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'APPDATA'",
")",
"if",
"not",
"directory",
":",
"directory",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"r'~\\Application Data... | 37.52381 | 21.142857 |
def from_segwizard(source, gpstype=LIGOTimeGPS, strict=True):
"""Read segments from a segwizard format file into a `SegmentList`
Parameters
----------
source : `file`, `str`
An open file, or file path, from which to read
gpstype : `type`, optional
The numeric type to which to cast ... | [
"def",
"from_segwizard",
"(",
"source",
",",
"gpstype",
"=",
"LIGOTimeGPS",
",",
"strict",
"=",
"True",
")",
":",
"# read file path",
"if",
"isinstance",
"(",
"source",
",",
"string_types",
")",
":",
"with",
"open",
"(",
"source",
",",
"'r'",
")",
"as",
... | 30.795455 | 20.090909 |
def render(self):
""" Returns generated html code.
"""
with codecs.open(self.template_file, encoding=self.encoding) as template_src:
template = jinja2.Template(template_src.read())
slides = self.fetch_contents(self.source)
context = self.get_template_vars(slides)
... | [
"def",
"render",
"(",
"self",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"self",
".",
"template_file",
",",
"encoding",
"=",
"self",
".",
"encoding",
")",
"as",
"template_src",
":",
"template",
"=",
"jinja2",
".",
"Template",
"(",
"template_src",
".",... | 42.733333 | 23.688889 |
def get_sample_name_from_vcf_header_lines(header_lines):
'''Given a list of header lines (made by either
vcf_file_to_dict() or vcf_file_to_list()),
returns the sample name. Assumes only one sample
in the file.
Raises error if badly formatted #CHROM line.
Returns None if no #CHROM line found'''
... | [
"def",
"get_sample_name_from_vcf_header_lines",
"(",
"header_lines",
")",
":",
"# We want the #CHROM line, which should be the last line",
"# of the header",
"for",
"line",
"in",
"reversed",
"(",
"header_lines",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'#CHROM'",
... | 45.861111 | 27.805556 |
def set_values(self, values):
"""
Set multiple Visual properties at once.
:param values:
:return:
"""
if values is None:
raise ValueError('Values are required.')
new_values = []
for vp in values.keys():
new_val = {
... | [
"def",
"set_values",
"(",
"self",
",",
"values",
")",
":",
"if",
"values",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Values are required.'",
")",
"new_values",
"=",
"[",
"]",
"for",
"vp",
"in",
"values",
".",
"keys",
"(",
")",
":",
"new_val",
"=... | 25.842105 | 16.894737 |
def getPointsForInterpolation(self,EndOfPrdvP,aNrmNow):
'''
Find endogenous interpolation points for each asset point and each
discrete preference shock.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
aNrmNow : np.... | [
"def",
"getPointsForInterpolation",
"(",
"self",
",",
"EndOfPrdvP",
",",
"aNrmNow",
")",
":",
"c_base",
"=",
"self",
".",
"uPinv",
"(",
"EndOfPrdvP",
")",
"PrefShkCount",
"=",
"self",
".",
"PrefShkVals",
".",
"size",
"PrefShk_temp",
"=",
"np",
".",
"tile",
... | 43.0625 | 23.125 |
def get_last_thread(self):
"""
Return the last modified thread
"""
cache_key = '_get_last_thread_cache'
if not hasattr(self, cache_key):
item = None
res = self.thread_set.filter(visible=True).order_by('-modified')[0:1]
if len(res)>0:
... | [
"def",
"get_last_thread",
"(",
"self",
")",
":",
"cache_key",
"=",
"'_get_last_thread_cache'",
"if",
"not",
"hasattr",
"(",
"self",
",",
"cache_key",
")",
":",
"item",
"=",
"None",
"res",
"=",
"self",
".",
"thread_set",
".",
"filter",
"(",
"visible",
"=",
... | 34.333333 | 8.666667 |
def _default_next_char(particle):
"""
Default next character implementation - linear progression through
each character.
"""
return particle.chars[
(len(particle.chars) - 1) * particle.time // particle.life_time] | [
"def",
"_default_next_char",
"(",
"particle",
")",
":",
"return",
"particle",
".",
"chars",
"[",
"(",
"len",
"(",
"particle",
".",
"chars",
")",
"-",
"1",
")",
"*",
"particle",
".",
"time",
"//",
"particle",
".",
"life_time",
"]"
] | 36.857143 | 14.857143 |
def _storestr(ins):
""" Stores a string value into a memory address.
It copies content of 2nd operand (string), into 1st, reallocating
dynamic memory for the 1st str. These instruction DOES ALLOW
inmediate strings for the 2nd parameter, starting with '#'.
Must prepend '#' (immediate sigil) to 1st o... | [
"def",
"_storestr",
"(",
"ins",
")",
":",
"op1",
"=",
"ins",
".",
"quad",
"[",
"1",
"]",
"indirect",
"=",
"op1",
"[",
"0",
"]",
"==",
"'*'",
"if",
"indirect",
":",
"op1",
"=",
"op1",
"[",
"1",
":",
"]",
"immediate",
"=",
"op1",
"[",
"0",
"]",... | 29.483871 | 20.935484 |
def groups_create(self, name, **kwargs):
"""Creates a new private group, optionally including users, only if you’re part of the group."""
return self.__call_api_post('groups.create', name=name, kwargs=kwargs) | [
"def",
"groups_create",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'groups.create'",
",",
"name",
"=",
"name",
",",
"kwargs",
"=",
"kwargs",
")"
] | 74 | 12.666667 |
def _ReadFileHeader(self, file_object):
"""Reads the file header.
Args:
file_object (file): file-like object.
Returns:
keychain_file_header: file header.
Raises:
ParseError: if the file header cannot be read.
"""
data_type_map = self._GetDataTypeMap('keychain_file_header')
... | [
"def",
"_ReadFileHeader",
"(",
"self",
",",
"file_object",
")",
":",
"data_type_map",
"=",
"self",
".",
"_GetDataTypeMap",
"(",
"'keychain_file_header'",
")",
"file_header",
",",
"_",
"=",
"self",
".",
"_ReadStructureFromFileObject",
"(",
"file_object",
",",
"0",
... | 31.615385 | 23.230769 |
def get_3d_markers(self, component_info=None, data=None, component_position=None):
"""Get 3D markers."""
return self._get_3d_markers(
RT3DMarkerPosition, component_info, data, component_position
) | [
"def",
"get_3d_markers",
"(",
"self",
",",
"component_info",
"=",
"None",
",",
"data",
"=",
"None",
",",
"component_position",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_3d_markers",
"(",
"RT3DMarkerPosition",
",",
"component_info",
",",
"data",
",",
... | 45.6 | 21.8 |
def _dispatch_event(self, event, data=None):
"""Dispatches the event and executes any associated callbacks.
Note: To prevent the app from crashing due to callback errors. We
catch all exceptions and send all data to the logger.
Args:
event (str): The type of event. e.g. 'bo... | [
"def",
"_dispatch_event",
"(",
"self",
",",
"event",
",",
"data",
"=",
"None",
")",
":",
"for",
"callback",
"in",
"self",
".",
"_callbacks",
"[",
"event",
"]",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Running %s callbacks for event: '%s'\"",
",",
... | 38.282051 | 18.358974 |
def all(self):
"""
Returns entire table as a DataFrame. This is executing:
SELECT
*
FROM
<name_of_the_table>
Examples
--------
>>> from db import DemoDB
>>> db = DemoDB()
>>> len(db.tables.Track.all())
... | [
"def",
"all",
"(",
"self",
")",
":",
"q",
"=",
"self",
".",
"_query_templates",
"[",
"'table'",
"]",
"[",
"'all'",
"]",
".",
"format",
"(",
"schema",
"=",
"self",
".",
"schema",
",",
"table",
"=",
"self",
".",
"name",
")",
"return",
"pd",
".",
"r... | 27.6 | 18.7 |
def hash(self):
'''
:rtype: int
:return: hash of the container
'''
hashed = super(TakeFrom, self).hash()
return khash(hashed, self.min_elements, self.max_elements, self.seed) | [
"def",
"hash",
"(",
"self",
")",
":",
"hashed",
"=",
"super",
"(",
"TakeFrom",
",",
"self",
")",
".",
"hash",
"(",
")",
"return",
"khash",
"(",
"hashed",
",",
"self",
".",
"min_elements",
",",
"self",
".",
"max_elements",
",",
"self",
".",
"seed",
... | 30.857143 | 21.142857 |
def _filter(self, commands, parser):
""" Filter DATA/SIZE commands that are overridden by a
SIZE command.
"""
resized = set()
commands2 = []
for command in reversed(commands):
if command[0] == 'SHADERS':
convert = parser.convert_shaders()
... | [
"def",
"_filter",
"(",
"self",
",",
"commands",
",",
"parser",
")",
":",
"resized",
"=",
"set",
"(",
")",
"commands2",
"=",
"[",
"]",
"for",
"command",
"in",
"reversed",
"(",
"commands",
")",
":",
"if",
"command",
"[",
"0",
"]",
"==",
"'SHADERS'",
... | 39.526316 | 8.210526 |
def apply(self, *args: Any, **kwargs: Any) -> Any:
"""Called by workers to run the wrapped function.
You may call it yourself if you want to run the task in current process
without sending to the queue.
If task has a `retry` property it will be retried on failure.
If task has a... | [
"def",
"apply",
"(",
"self",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Any",
":",
"def",
"send_signal",
"(",
"sig",
":",
"Signal",
",",
"*",
"*",
"extra",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"... | 37.282051 | 19.487179 |
def delete_topic(self, topic):
"""Delete a topic."""
nsq.assert_valid_topic_name(topic)
return self._request('POST', '/topic/delete', fields={'topic': topic}) | [
"def",
"delete_topic",
"(",
"self",
",",
"topic",
")",
":",
"nsq",
".",
"assert_valid_topic_name",
"(",
"topic",
")",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'/topic/delete'",
",",
"fields",
"=",
"{",
"'topic'",
":",
"topic",
"}",
")"
] | 44.75 | 12.5 |
def execute_finder(self, manager, package_name):
""" Execute finder script within the temporary venv context. """
filename = '{env_path}/results.json'.format(env_path=manager.env_path)
subprocess.call([
manager.venv_python, self._finder_path, package_name, filename
])
... | [
"def",
"execute_finder",
"(",
"self",
",",
"manager",
",",
"package_name",
")",
":",
"filename",
"=",
"'{env_path}/results.json'",
".",
"format",
"(",
"env_path",
"=",
"manager",
".",
"env_path",
")",
"subprocess",
".",
"call",
"(",
"[",
"manager",
".",
"ven... | 42.7 | 17.5 |
def session(self) -> str:
""" Generate a session(authorization Bearer) JWT token """
session_jwt = None
self.user = self.user_model.where_username(self.username)
if self.user is None:
return None
self.user.updated() # update timestamp on user access
if... | [
"def",
"session",
"(",
"self",
")",
"->",
"str",
":",
"session_jwt",
"=",
"None",
"self",
".",
"user",
"=",
"self",
".",
"user_model",
".",
"where_username",
"(",
"self",
".",
"username",
")",
"if",
"self",
".",
"user",
"is",
"None",
":",
"return",
"... | 45.352941 | 16.617647 |
def gp_datdir(initial, topN):
"""example for plotting from a text file via numpy.loadtxt
1. prepare input/output directories
2. load the data into an OrderedDict() [adjust axes units]
3. sort countries from highest to lowest population
4. select the <topN> most populated countries
5. call ccsgp.make_plot w... | [
"def",
"gp_datdir",
"(",
"initial",
",",
"topN",
")",
":",
"# prepare input/output directories",
"inDir",
",",
"outDir",
"=",
"getWorkDirs",
"(",
")",
"initial",
"=",
"initial",
".",
"capitalize",
"(",
")",
"inDir",
"=",
"os",
".",
"path",
".",
"join",
"("... | 36.478873 | 18.070423 |
def _make_unique_title(self, title):
"""Make the title unique.
Adds a counter to the title to prevent duplicates.
Prior to IDA 6.8, two graphs with the same title could crash IDA.
This has been fixed (https://www.hex-rays.com/products/ida/6.8/index.shtml).
The code will not cha... | [
"def",
"_make_unique_title",
"(",
"self",
",",
"title",
")",
":",
"unique_title",
"=",
"title",
"for",
"counter",
"in",
"itertools",
".",
"count",
"(",
")",
":",
"unique_title",
"=",
"\"{}-{}\"",
".",
"format",
"(",
"title",
",",
"counter",
")",
"if",
"n... | 34.666667 | 21 |
def authenticate(self, request, email=None, password=None, username=None):
"""
Attempt to authenticate a set of credentials.
Args:
request:
The request associated with the authentication attempt.
email:
The user's email address.
... | [
"def",
"authenticate",
"(",
"self",
",",
"request",
",",
"email",
"=",
"None",
",",
"password",
"=",
"None",
",",
"username",
"=",
"None",
")",
":",
"email",
"=",
"email",
"or",
"username",
"try",
":",
"email_instance",
"=",
"models",
".",
"EmailAddress"... | 29.6 | 20.742857 |
def insert_user_data(host_name, client_name, client_pass, user_twitter_id, topic_to_score):
"""
Inserts topic/score data for a user to a PServer client.
Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted.
- client_name: The PServer client na... | [
"def",
"insert_user_data",
"(",
"host_name",
",",
"client_name",
",",
"client_pass",
",",
"user_twitter_id",
",",
"topic_to_score",
")",
":",
"# Construct values.",
"values",
"=",
"\"usr=\"",
"+",
"str",
"(",
"user_twitter_id",
")",
"for",
"topic",
",",
"score",
... | 38.333333 | 21.666667 |
def remove_handler(self, handler):
"""
Remove a handler from the list.
handler - The handler (as returned by add_handler) to remove.
Returns True on success, False otherwise.
"""
try:
self._events[handler.type].remove(handler)
return True
... | [
"def",
"remove_handler",
"(",
"self",
",",
"handler",
")",
":",
"try",
":",
"self",
".",
"_events",
"[",
"handler",
".",
"type",
"]",
".",
"remove",
"(",
"handler",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False"
] | 27.076923 | 16.461538 |
def skos_hierarchical(rdf, narrower=True):
"""Infer skos:broader/skos:narrower (S25) but only keep skos:narrower on request.
:param bool narrower: If set to False, skos:narrower will not be added,
but rather removed.
"""
if narrower:
for s, o in rdf.subject_objects(SKOS.broader):
... | [
"def",
"skos_hierarchical",
"(",
"rdf",
",",
"narrower",
"=",
"True",
")",
":",
"if",
"narrower",
":",
"for",
"s",
",",
"o",
"in",
"rdf",
".",
"subject_objects",
"(",
"SKOS",
".",
"broader",
")",
":",
"rdf",
".",
"add",
"(",
"(",
"o",
",",
"SKOS",
... | 38.846154 | 12.692308 |
def statistics(self):
"""
Access the statistics
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsList
:rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics.TaskQueueStatisticsList
"""
if self._statis... | [
"def",
"statistics",
"(",
"self",
")",
":",
"if",
"self",
".",
"_statistics",
"is",
"None",
":",
"self",
".",
"_statistics",
"=",
"TaskQueueStatisticsList",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_s... | 40.714286 | 22 |
def configure_client(
cls, address: Union[str, Tuple[str, int], Path] = 'localhost', port: int = 6379,
db: int = 0, password: str = None, ssl: Union[bool, str, SSLContext] = False,
**client_args) -> Dict[str, Any]:
"""
Configure a Redis client.
:param address... | [
"def",
"configure_client",
"(",
"cls",
",",
"address",
":",
"Union",
"[",
"str",
",",
"Tuple",
"[",
"str",
",",
"int",
"]",
",",
"Path",
"]",
"=",
"'localhost'",
",",
"port",
":",
"int",
"=",
"6379",
",",
"db",
":",
"int",
"=",
"0",
",",
"passwor... | 41.294118 | 20.176471 |
def histogram(values, bins=10, vrange=None, title="", c="g", corner=1, lines=True):
"""
Build a 2D histogram from a list of values in n bins.
Use *vrange* to restrict the range of the histogram.
Use *corner* to assign its position:
- 1, topleft,
- 2, topright,
- 3, bottomleft,
... | [
"def",
"histogram",
"(",
"values",
",",
"bins",
"=",
"10",
",",
"vrange",
"=",
"None",
",",
"title",
"=",
"\"\"",
",",
"c",
"=",
"\"g\"",
",",
"corner",
"=",
"1",
",",
"lines",
"=",
"True",
")",
":",
"fs",
",",
"edges",
"=",
"np",
".",
"histogr... | 30.842105 | 18.526316 |
def get_font(self, bold, oblique):
"""
Get the font based on bold and italic flags.
"""
if bold and oblique:
return self.fonts['BOLDITALIC']
elif bold:
return self.fonts['BOLD']
elif oblique:
return self.fonts['ITALIC']
else:
... | [
"def",
"get_font",
"(",
"self",
",",
"bold",
",",
"oblique",
")",
":",
"if",
"bold",
"and",
"oblique",
":",
"return",
"self",
".",
"fonts",
"[",
"'BOLDITALIC'",
"]",
"elif",
"bold",
":",
"return",
"self",
".",
"fonts",
"[",
"'BOLD'",
"]",
"elif",
"ob... | 28.833333 | 8.833333 |
def spc_helper(egg, match='exact', distance='euclidean',
features=None):
"""
Computes probability of a word being recalled (in the appropriate recall list), given its presentation position
Parameters
----------
egg : quail.Egg
Data to analyze
match : str (exact, best or ... | [
"def",
"spc_helper",
"(",
"egg",
",",
"match",
"=",
"'exact'",
",",
"distance",
"=",
"'euclidean'",
",",
"features",
"=",
"None",
")",
":",
"def",
"spc",
"(",
"lst",
")",
":",
"d",
"=",
"np",
".",
"zeros_like",
"(",
"egg",
".",
"pres",
".",
"values... | 35.4375 | 24.979167 |
def register(cls, range_mixin):
"""
Decorator for registering range set mixins for global use. This works
the same as :meth:`~spans.settypes.MetaRangeSet.add`
:param range_mixin: A :class:`~spans.types.Range` mixin class to
to register a decorated range set m... | [
"def",
"register",
"(",
"cls",
",",
"range_mixin",
")",
":",
"def",
"decorator",
"(",
"range_set_mixin",
")",
":",
"cls",
".",
"add",
"(",
"range_mixin",
",",
"range_set_mixin",
")",
"return",
"range_set_mixin",
"return",
"decorator"
] | 39.071429 | 19.214286 |
def add_prompt(self, prompt, echo=True):
"""
Add a prompt to this query. The prompt should be a (reasonably short)
string. Multiple prompts can be added to the same query.
:param str prompt: the user prompt
:param bool echo:
``True`` (default) if the user's respons... | [
"def",
"add_prompt",
"(",
"self",
",",
"prompt",
",",
"echo",
"=",
"True",
")",
":",
"self",
".",
"prompts",
".",
"append",
"(",
"(",
"prompt",
",",
"echo",
")",
")"
] | 40.181818 | 15.454545 |
def get_last_config_update_time_for_xpaths_output_last_config_update_time_for_xpaths_xpath_string(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_last_config_update_time_for_xpaths = ET.Element("get_last_config_update_time_for_xpaths")
config = get_l... | [
"def",
"get_last_config_update_time_for_xpaths_output_last_config_update_time_for_xpaths_xpath_string",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_last_config_update_time_for_xpaths",
"=",
"ET",
".",
"... | 58.615385 | 29.615385 |
def convert_matmul(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert matmul layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary wi... | [
"def",
"convert_matmul",
"(",
"params",
",",
"w_name",
",",
"scope_name",
",",
"inputs",
",",
"layers",
",",
"weights",
",",
"names",
")",
":",
"print",
"(",
"'Converting matmul ...'",
")",
"if",
"names",
"==",
"'short'",
":",
"tf_name",
"=",
"'MMUL'",
"+"... | 31.68 | 20.4 |
def id(self, obj):
"""
The method is to be used to assign an integer variable ID for a
given new object. If the object already has an ID, no new ID is
created and the old one is returned instead.
An object can be anything. In some cases it is convenient to use
... | [
"def",
"id",
"(",
"self",
",",
"obj",
")",
":",
"vid",
"=",
"self",
".",
"obj2id",
"[",
"obj",
"]",
"if",
"vid",
"not",
"in",
"self",
".",
"id2obj",
":",
"self",
".",
"id2obj",
"[",
"vid",
"]",
"=",
"obj",
"return",
"vid"
] | 28.354167 | 22.854167 |
def resolveSystem(self, sysID):
"""Try to lookup the catalog resource for a system ID """
ret = libxml2mod.xmlACatalogResolveSystem(self._o, sysID)
return ret | [
"def",
"resolveSystem",
"(",
"self",
",",
"sysID",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlACatalogResolveSystem",
"(",
"self",
".",
"_o",
",",
"sysID",
")",
"return",
"ret"
] | 44.75 | 14 |
def deleted(self, key, value):
"""Populate the ``deleted`` key.
Also populates the ``stub`` key through side effects.
"""
def _is_deleted(value):
return force_single_element(value.get('c', '')).upper() == 'DELETED'
def _is_stub(value):
return not (force_single_element(value.get('a'... | [
"def",
"deleted",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"def",
"_is_deleted",
"(",
"value",
")",
":",
"return",
"force_single_element",
"(",
"value",
".",
"get",
"(",
"'c'",
",",
"''",
")",
")",
".",
"upper",
"(",
")",
"==",
"'DELETED'",
... | 28.45 | 20.6 |
def logevents(self):
"""Iterator yielding all logevents from groups dictionary."""
for key in self.groups:
for logevent in self.groups[key]:
yield logevent | [
"def",
"logevents",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"groups",
":",
"for",
"logevent",
"in",
"self",
".",
"groups",
"[",
"key",
"]",
":",
"yield",
"logevent"
] | 39 | 8.8 |
def rCopy(d, f=identityConversion, discardNoneKeys=True, deepCopy=True):
"""Recursively copies a dict and returns the result.
Args:
d: The dict to copy.
f: A function to apply to values when copying that takes the value and the
list of keys from the root of the dict to the value and returns a value... | [
"def",
"rCopy",
"(",
"d",
",",
"f",
"=",
"identityConversion",
",",
"discardNoneKeys",
"=",
"True",
",",
"deepCopy",
"=",
"True",
")",
":",
"# Optionally deep copy the dict.",
"if",
"deepCopy",
":",
"d",
"=",
"copy",
".",
"deepcopy",
"(",
"d",
")",
"newDic... | 33.970588 | 21.352941 |
def save_image(img, fname):
"""Save an image.
Parameters
----------
img : `PIL.Image`
Image to save.
fname : `str`
File path.
"""
_, ext = os.path.splitext(fname)
ext = ext[1:] or 'png'
with open(fname, 'wb') as fp:
img.save(fp, ext) | [
"def",
"save_image",
"(",
"img",
",",
"fname",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fname",
")",
"ext",
"=",
"ext",
"[",
"1",
":",
"]",
"or",
"'png'",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
... | 20.071429 | 16.214286 |
def get_methods_descriptor(self, class_name, method_name):
"""
Return the specific methods of the class
:param class_name: the class name of the method
:type class_name: string
:param method_name: the name of the method
:type method_name: string
:rtype: None or ... | [
"def",
"get_methods_descriptor",
"(",
"self",
",",
"class_name",
",",
"method_name",
")",
":",
"l",
"=",
"[",
"]",
"for",
"i",
"in",
"self",
".",
"get_classes",
"(",
")",
":",
"if",
"i",
".",
"get_name",
"(",
")",
"==",
"class_name",
":",
"for",
"j",... | 30.947368 | 14.421053 |
def create_framework(
bundles,
properties=None,
auto_start=False,
wait_for_stop=False,
auto_delete=False,
):
# type: (Union[list, tuple], dict, bool, bool, bool) -> Framework
"""
Creates a Pelix framework, installs the given bundles and returns its
instance reference.
If *auto_st... | [
"def",
"create_framework",
"(",
"bundles",
",",
"properties",
"=",
"None",
",",
"auto_start",
"=",
"False",
",",
"wait_for_stop",
"=",
"False",
",",
"auto_delete",
"=",
"False",
",",
")",
":",
"# type: (Union[list, tuple], dict, bool, bool, bool) -> Framework",
"# Tes... | 36.35 | 19.016667 |
def get_context_data(cls, instance):
'''
Generate a Context Parameters object based on the instance's
configuration.
We do not use the hlapi currently, but the rfc3413.oneliner.cmdgen
accepts Context Engine Id (always None for now) and Context Name parameters.
'''
... | [
"def",
"get_context_data",
"(",
"cls",
",",
"instance",
")",
":",
"context_engine_id",
"=",
"None",
"context_name",
"=",
"''",
"if",
"\"user\"",
"in",
"instance",
":",
"if",
"'context_engine_id'",
"in",
"instance",
":",
"context_engine_id",
"=",
"OctetString",
"... | 36.722222 | 22.611111 |
def read_method(self):
"""
Read a method from the peer.
"""
self._next_method()
m = self.queue.get()
if isinstance(m, Exception):
raise m
return m | [
"def",
"read_method",
"(",
"self",
")",
":",
"self",
".",
"_next_method",
"(",
")",
"m",
"=",
"self",
".",
"queue",
".",
"get",
"(",
")",
"if",
"isinstance",
"(",
"m",
",",
"Exception",
")",
":",
"raise",
"m",
"return",
"m"
] | 20.6 | 13.6 |
def read_chunks(stream, block_size=2**10):
"""
Given a byte stream with reader, yield chunks of block_size
until the stream is consusmed.
"""
while True:
chunk = stream.read(block_size)
if not chunk:
break
yield chunk | [
"def",
"read_chunks",
"(",
"stream",
",",
"block_size",
"=",
"2",
"**",
"10",
")",
":",
"while",
"True",
":",
"chunk",
"=",
"stream",
".",
"read",
"(",
"block_size",
")",
"if",
"not",
"chunk",
":",
"break",
"yield",
"chunk"
] | 26.4 | 12 |
def extract(self, file_path):
"""
Extract a tar file at the specified file path.
"""
import tarfile
print('Extracting {}'.format(file_path))
if not os.path.exists(self.extracted_data_directory):
os.makedirs(self.extracted_data_directory)
def track_p... | [
"def",
"extract",
"(",
"self",
",",
"file_path",
")",
":",
"import",
"tarfile",
"print",
"(",
"'Extracting {}'",
".",
"format",
"(",
"file_path",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"extracted_data_directory",
")",
... | 31.826087 | 22.086957 |
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
... | [
"def",
"refund_transaction",
"(",
"self",
",",
"transactionid",
"=",
"None",
",",
"payerid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# This line seems like a complete waste of time... kwargs should not",
"# be populated",
"if",
"(",
"transactionid",
"is",
"No... | 35.763158 | 17.894737 |
def is_list_of_list_of_states(self, arg):
"""
A list of list of states example -
[[('x1', 'easy'), ('x2', 'hard')], [('x1', 'hard'), ('x2', 'medium')]]
Returns
-------
True, if arg is a list of list of states else False.
"""
if arg is None:
r... | [
"def",
"is_list_of_list_of_states",
"(",
"self",
",",
"arg",
")",
":",
"if",
"arg",
"is",
"None",
":",
"return",
"False",
"return",
"all",
"(",
"[",
"isinstance",
"(",
"arg",
",",
"list",
")",
",",
"all",
"(",
"isinstance",
"(",
"i",
",",
"list",
")"... | 33 | 18.6 |
def nworker(data, smpchunk, tests):
""" The workhorse function. Not numba. """
## tell engines to limit threads
#numba.config.NUMBA_DEFAULT_NUM_THREADS = 1
## open the seqarray view, the modified array is in bootsarr
with h5py.File(data.database.input, 'r') as io5:
seqview = io5["b... | [
"def",
"nworker",
"(",
"data",
",",
"smpchunk",
",",
"tests",
")",
":",
"## tell engines to limit threads",
"#numba.config.NUMBA_DEFAULT_NUM_THREADS = 1",
"## open the seqarray view, the modified array is in bootsarr",
"with",
"h5py",
".",
"File",
"(",
"data",
".",
"database"... | 38.2 | 20.022222 |
def _resetSelection(self, moveToTop=False):
""" Reset selection.
If moveToTop is True - move cursor to the top position
"""
ancor, pos = self._qpart.selectedPosition
dst = min(ancor, pos) if moveToTop else pos
self._qpart.cursorPosition = dst | [
"def",
"_resetSelection",
"(",
"self",
",",
"moveToTop",
"=",
"False",
")",
":",
"ancor",
",",
"pos",
"=",
"self",
".",
"_qpart",
".",
"selectedPosition",
"dst",
"=",
"min",
"(",
"ancor",
",",
"pos",
")",
"if",
"moveToTop",
"else",
"pos",
"self",
".",
... | 40.571429 | 6.428571 |
def _prepare_method(self, pandas_func, **kwargs):
"""Prepares methods given various metadata.
Args:
pandas_func: The function to prepare.
Returns
Helper function which handles potential transpose.
"""
if self._is_transposed:
def helper(df, in... | [
"def",
"_prepare_method",
"(",
"self",
",",
"pandas_func",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_is_transposed",
":",
"def",
"helper",
"(",
"df",
",",
"internal_indices",
"=",
"[",
"]",
")",
":",
"if",
"len",
"(",
"internal_indices",
... | 32.76 | 19.64 |
def get(value: str) -> 'Protocol':
"""
Return enum instance corresponding to input version value ('RsaVerificationKey2018' etc.)
"""
for pktype in PublicKeyType:
if value in (pktype.ver_type, pktype.authn_type):
return pktype
return None | [
"def",
"get",
"(",
"value",
":",
"str",
")",
"->",
"'Protocol'",
":",
"for",
"pktype",
"in",
"PublicKeyType",
":",
"if",
"value",
"in",
"(",
"pktype",
".",
"ver_type",
",",
"pktype",
".",
"authn_type",
")",
":",
"return",
"pktype",
"return",
"None"
] | 33.111111 | 17.777778 |
def is_comment(self):
'''Return True if the first non-empty cell starts with "#"'''
for cell in self[:]:
if cell == "":
continue
# this is the first non-empty cell. Check whether it is
# a comment or not.
if cell.lstrip().startswith("#"):... | [
"def",
"is_comment",
"(",
"self",
")",
":",
"for",
"cell",
"in",
"self",
"[",
":",
"]",
":",
"if",
"cell",
"==",
"\"\"",
":",
"continue",
"# this is the first non-empty cell. Check whether it is",
"# a comment or not.",
"if",
"cell",
".",
"lstrip",
"(",
")",
"... | 28.785714 | 19.928571 |
def make_request(name, params=None, version="V001", key=None, api_type="web",
fetcher=get_page, base=None, language="en_us"):
"""
Make an API request
"""
params = params or {}
params["key"] = key or API_KEY
params["language"] = language
if not params["key"]:
raise ... | [
"def",
"make_request",
"(",
"name",
",",
"params",
"=",
"None",
",",
"version",
"=",
"\"V001\"",
",",
"key",
"=",
"None",
",",
"api_type",
"=",
"\"web\"",
",",
"fetcher",
"=",
"get_page",
",",
"base",
"=",
"None",
",",
"language",
"=",
"\"en_us\"",
")"... | 30.666667 | 21.333333 |
def release(self, sim_size):
"""
The memory release primitive for this heap implementation. Decreases the position of the break to deallocate
space. Guards against releasing beyond the initial heap base.
:param sim_size: a size specifying how much to decrease the break pointer by (may b... | [
"def",
"release",
"(",
"self",
",",
"sim_size",
")",
":",
"requested",
"=",
"self",
".",
"_conc_alloc_size",
"(",
"sim_size",
")",
"used",
"=",
"self",
".",
"heap_location",
"-",
"self",
".",
"heap_base",
"released",
"=",
"requested",
"if",
"requested",
"<... | 54.583333 | 28.416667 |
def get_ldap_groups(self):
"""Retrieve groups from LDAP server."""
if (not self.conf_LDAP_SYNC_GROUP):
return (None, None)
uri_groups_server, groups = self.ldap_search(self.conf_LDAP_SYNC_GROUP_FILTER, self.conf_LDAP_SYNC_GROUP_ATTRIBUTES.keys(), self.conf_LDAP_SYNC_GROUP_INCREMENTAL... | [
"def",
"get_ldap_groups",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"conf_LDAP_SYNC_GROUP",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"uri_groups_server",
",",
"groups",
"=",
"self",
".",
"ldap_search",
"(",
"self",
".",
"conf_LDAP_SYN... | 71.857143 | 37.428571 |
def save(self, model, path=''):
"""Save the file model and return the model with no content."""
path = path.strip('/')
if 'type' not in model:
raise web.HTTPError(400, u'No file type provided')
if 'content' not in model and model['type'] != 'directory':
raise web... | [
"def",
"save",
"(",
"self",
",",
"model",
",",
"path",
"=",
"''",
")",
":",
"path",
"=",
"path",
".",
"strip",
"(",
"'/'",
")",
"if",
"'type'",
"not",
"in",
"model",
":",
"raise",
"web",
".",
"HTTPError",
"(",
"400",
",",
"u'No file type provided'",
... | 40.909091 | 20.287879 |
def create_zone(self, zone, serial=None):
"""Create a zone for the specified zone.
:param zone: the zone name to create
:param serial: serial value on the zone (default: strftime(%Y%m%d01))
"""
return self.service.createObject({
'name': zone,
'serial': s... | [
"def",
"create_zone",
"(",
"self",
",",
"zone",
",",
"serial",
"=",
"None",
")",
":",
"return",
"self",
".",
"service",
".",
"createObject",
"(",
"{",
"'name'",
":",
"zone",
",",
"'serial'",
":",
"serial",
"or",
"time",
".",
"strftime",
"(",
"'%Y%m%d01... | 34.636364 | 14.727273 |
def search(self, **kwargs):
"""
Method to search object group permissions based on extends search.
:param search: Dict containing QuerySets to find object group permissions.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields t... | [
"def",
"search",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"ApiObjectGroupPermission",
",",
"self",
")",
".",
"get",
"(",
"self",
".",
"prepare_url",
"(",
"'api/v3/object-group-perm/'",
",",
"kwargs",
")",
")"
] | 53.642857 | 31.071429 |
def reset_catalog():
'''
.. versionadded:: 2016.3.0
Reset the Software Update Catalog to the default.
:return: True if successful, False if not
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' softwareupdates.reset_catalog
'''
# This command always returns an erro... | [
"def",
"reset_catalog",
"(",
")",
":",
"# This command always returns an error code, though it completes",
"# successfully. Success will be determined by making sure get_catalog",
"# returns 'Default'",
"cmd",
"=",
"[",
"'softwareupdate'",
",",
"'--clear-catalog'",
"]",
"try",
":",
... | 24.153846 | 24.153846 |
def order_items(self, item_ids, assessment_id):
"""Sequences existing items in an assessment.
arg: item_ids (osid.id.Id[]): the ``Id`` of the ``Items``
arg: assessment_id (osid.id.Id): the ``Id`` of the
``Assessment``
raise: NotFound - ``assessment_id`` is not fou... | [
"def",
"order_items",
"(",
"self",
",",
"item_ids",
",",
"assessment_id",
")",
":",
"if",
"assessment_id",
".",
"get_identifier_namespace",
"(",
")",
"!=",
"'assessment.Assessment'",
":",
"raise",
"errors",
".",
"InvalidArgument",
"self",
".",
"_part_item_design_ses... | 49.444444 | 22.111111 |
def _normalize_group_dns(self, group_dns):
"""
Converts one or more group DNs to an LDAPGroupQuery.
group_dns may be a string, a non-empty list or tuple of strings, or an
LDAPGroupQuery. The result will be an LDAPGroupQuery. A list or tuple
will be joined with the | operator.
... | [
"def",
"_normalize_group_dns",
"(",
"self",
",",
"group_dns",
")",
":",
"if",
"isinstance",
"(",
"group_dns",
",",
"LDAPGroupQuery",
")",
":",
"query",
"=",
"group_dns",
"elif",
"isinstance",
"(",
"group_dns",
",",
"str",
")",
":",
"query",
"=",
"LDAPGroupQu... | 36.947368 | 18.842105 |
def convert_to_dataset_file_metadata(self, file_data, path):
""" convert a set of file_data to a metadata file at path
Parameters
==========
file_data: a dictionary of file data to write to file
path: the path to write the metadata to
"""
as_metad... | [
"def",
"convert_to_dataset_file_metadata",
"(",
"self",
",",
"file_data",
",",
"path",
")",
":",
"as_metadata",
"=",
"{",
"'path'",
":",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"file_data",
"[",
"'name'",
"]",
")",
",",
"'description'",
":",
"f... | 30.961538 | 16.192308 |
def yearly(self):
"""
Access the yearly
:returns: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList
:rtype: twilio.rest.api.v2010.account.usage.record.yearly.YearlyList
"""
if self._yearly is None:
self._yearly = YearlyList(self._version, account_s... | [
"def",
"yearly",
"(",
"self",
")",
":",
"if",
"self",
".",
"_yearly",
"is",
"None",
":",
"self",
".",
"_yearly",
"=",
"YearlyList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")",
... | 37.4 | 23 |
def __reflect(self):
"""Reflect metadata
"""
def only(name, _):
return self.__only(name) and self.__mapper.restore_bucket(name) is not None
self.__metadata.reflect(only=only) | [
"def",
"__reflect",
"(",
"self",
")",
":",
"def",
"only",
"(",
"name",
",",
"_",
")",
":",
"return",
"self",
".",
"__only",
"(",
"name",
")",
"and",
"self",
".",
"__mapper",
".",
"restore_bucket",
"(",
"name",
")",
"is",
"not",
"None",
"self",
".",... | 26.625 | 20.375 |
def random_ascii_words(lang='en', wordlist='best', nwords=5,
bits_per_word=12):
"""
Returns a string of random, space separated, ASCII words.
These words are of the given language and from the given wordlist.
There will be `nwords` words in the string.
`bits_per_word` determ... | [
"def",
"random_ascii_words",
"(",
"lang",
"=",
"'en'",
",",
"wordlist",
"=",
"'best'",
",",
"nwords",
"=",
"5",
",",
"bits_per_word",
"=",
"12",
")",
":",
"return",
"random_words",
"(",
"lang",
",",
"wordlist",
",",
"nwords",
",",
"bits_per_word",
",",
"... | 42.692308 | 20.230769 |
def set_mode_apm(self, mode, custom_mode = 0, custom_sub_mode = 0):
'''enter arbitrary mode'''
if isinstance(mode, str):
mode_map = self.mode_mapping()
if mode_map is None or mode not in mode_map:
print("Unknown mode '%s'" % mode)
return
... | [
"def",
"set_mode_apm",
"(",
"self",
",",
"mode",
",",
"custom_mode",
"=",
"0",
",",
"custom_sub_mode",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"mode",
",",
"str",
")",
":",
"mode_map",
"=",
"self",
".",
"mode_mapping",
"(",
")",
"if",
"mode_map",
... | 45.833333 | 12.833333 |
def run_init_tables(*args):
'''
Run to init tables.
'''
print('--')
create_table(TabPost)
create_table(TabTag)
create_table(TabMember)
create_table(TabWiki)
create_table(TabLink)
create_table(TabEntity)
create_table(TabPostHist)
create_table(TabWikiHist)
create_table... | [
"def",
"run_init_tables",
"(",
"*",
"args",
")",
":",
"print",
"(",
"'--'",
")",
"create_table",
"(",
"TabPost",
")",
"create_table",
"(",
"TabTag",
")",
"create_table",
"(",
"TabMember",
")",
"create_table",
"(",
"TabWiki",
")",
"create_table",
"(",
"TabLin... | 23.666667 | 16.333333 |
def set_cookie_prefix(self, cookie_prefix=None):
"""Set a random cookie prefix unless one is specified.
In order to run multiple demonstration auth services on the
same server we need to have different cookie names for each
auth domain. Unless cookie_prefix is set, generate a random
... | [
"def",
"set_cookie_prefix",
"(",
"self",
",",
"cookie_prefix",
"=",
"None",
")",
":",
"if",
"(",
"cookie_prefix",
"is",
"None",
")",
":",
"self",
".",
"cookie_prefix",
"=",
"\"%06d_\"",
"%",
"int",
"(",
"random",
".",
"random",
"(",
")",
"*",
"1000000",
... | 41.75 | 19 |
def _calc_distortion(self):
"""Calculates the distortion value of the current clusters
"""
m = self._X.shape[0]
self.distortion = 1/m * sum(
linalg.norm(self._X[i, :] - self.centroids[self.clusters[i]])**2 for i in range(m)
)
return self.distortion | [
"def",
"_calc_distortion",
"(",
"self",
")",
":",
"m",
"=",
"self",
".",
"_X",
".",
"shape",
"[",
"0",
"]",
"self",
".",
"distortion",
"=",
"1",
"/",
"m",
"*",
"sum",
"(",
"linalg",
".",
"norm",
"(",
"self",
".",
"_X",
"[",
"i",
",",
":",
"]"... | 37.625 | 15.5 |
def _set_ruleaction(self, v, load=False):
"""
Setter method for ruleaction, mapped from YANG variable /rbridge_id/maps/policy/ruleaction (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ruleaction is considered as a private
method. Backends looking to populate ... | [
"def",
"_set_ruleaction",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | 116.818182 | 56.045455 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.