text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_rec_column_descr(self, colnum, vstorage):
"""
Get a descriptor entry for the specified column.
parameters
----------
colnum: integer
The column number, 0 offset
vstorage: string
See docs in read_columns
"""
npy_type, isvar,... | [
"def",
"get_rec_column_descr",
"(",
"self",
",",
"colnum",
",",
"vstorage",
")",
":",
"npy_type",
",",
"isvar",
",",
"istbit",
"=",
"self",
".",
"_get_tbl_numpy_dtype",
"(",
"colnum",
")",
"name",
"=",
"self",
".",
"_info",
"[",
"'colinfo'",
"]",
"[",
"c... | 39.431034 | 16.810345 |
def get(self, receiver_id=None, event_id=None):
"""Handle GET request."""
event = self._get_event(receiver_id, event_id)
return make_response(event) | [
"def",
"get",
"(",
"self",
",",
"receiver_id",
"=",
"None",
",",
"event_id",
"=",
"None",
")",
":",
"event",
"=",
"self",
".",
"_get_event",
"(",
"receiver_id",
",",
"event_id",
")",
"return",
"make_response",
"(",
"event",
")"
] | 42.25 | 6.5 |
def new_job_file(frontier, job_conf_file):
'''Returns new Job.'''
logging.info("loading %s", job_conf_file)
with open(job_conf_file) as f:
job_conf = yaml.safe_load(f)
return new_job(frontier, job_conf) | [
"def",
"new_job_file",
"(",
"frontier",
",",
"job_conf_file",
")",
":",
"logging",
".",
"info",
"(",
"\"loading %s\"",
",",
"job_conf_file",
")",
"with",
"open",
"(",
"job_conf_file",
")",
"as",
"f",
":",
"job_conf",
"=",
"yaml",
".",
"safe_load",
"(",
"f"... | 37.5 | 5.5 |
def __neighbor_indexes_points(self, optic_object):
"""!
@brief Return neighbors of the specified object in case of sequence of points.
@param[in] optic_object (optics_descriptor): Object for which neighbors should be returned in line with connectivity radius.
@return (list) List ... | [
"def",
"__neighbor_indexes_points",
"(",
"self",
",",
"optic_object",
")",
":",
"kdnodes",
"=",
"self",
".",
"__kdtree",
".",
"find_nearest_dist_nodes",
"(",
"self",
".",
"__sample_pointer",
"[",
"optic_object",
".",
"index_object",
"]",
",",
"self",
".",
"__eps... | 55.333333 | 39.416667 |
def get_current_async():
"""Return a reference to the currently executing Async job object
or None if not in an Async job.
"""
local_context = _local.get_local_context()
if local_context._executing_async:
return local_context._executing_async[-1]
raise errors.NotInContextError('Not in ... | [
"def",
"get_current_async",
"(",
")",
":",
"local_context",
"=",
"_local",
".",
"get_local_context",
"(",
")",
"if",
"local_context",
".",
"_executing_async",
":",
"return",
"local_context",
".",
"_executing_async",
"[",
"-",
"1",
"]",
"raise",
"errors",
".",
... | 33.4 | 14.4 |
def attack_batch(self, imgs, labs):
"""
Run the attack on a batch of instance and labels.
"""
def compare(x, y):
if not isinstance(x, (float, int, np.int64)):
x = np.copy(x)
if self.TARGETED:
x[y] -= self.CONFIDENCE
else:
x[y] += self.CONFIDENCE
... | [
"def",
"attack_batch",
"(",
"self",
",",
"imgs",
",",
"labs",
")",
":",
"def",
"compare",
"(",
"x",
",",
"y",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"(",
"float",
",",
"int",
",",
"np",
".",
"int64",
")",
")",
":",
"x",
"=",
"np"... | 34.934959 | 17.552846 |
def viterbi_decode(tag_sequence: torch.Tensor,
transition_matrix: torch.Tensor,
tag_observations: Optional[List[int]] = None):
"""
Perform Viterbi decoding in log space over a sequence given a transition matrix
specifying pairwise (transition) potentials between tags an... | [
"def",
"viterbi_decode",
"(",
"tag_sequence",
":",
"torch",
".",
"Tensor",
",",
"transition_matrix",
":",
"torch",
".",
"Tensor",
",",
"tag_observations",
":",
"Optional",
"[",
"List",
"[",
"int",
"]",
"]",
"=",
"None",
")",
":",
"sequence_length",
",",
"n... | 46.464286 | 22.607143 |
def image_search(auth=None, **kwargs):
'''
Search for images
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_search name=image1
salt '*' glanceng.image_search
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.search_images(**k... | [
"def",
"image_search",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"search_images",
"(",
"*",
"... | 22.357143 | 19.071429 |
def open(self):
"""
Calls SetupDiGetClassDevs to obtain a handle to an opaque device
information set that describes the device interfaces supported by all
the USB collections currently installed in the system. The
application should specify DIGCF.PRESENT and DIGCF.INTERFACED... | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"h_info",
"=",
"SetupDiGetClassDevs",
"(",
"byref",
"(",
"self",
".",
"guid",
")",
",",
"None",
",",
"None",
",",
"(",
"DIGCF",
".",
"PRESENT",
"|",
"DIGCF",
".",
"DEVICEINTERFACE",
")",
")",
"return... | 46 | 23.5 |
def load_off(file_obj, **kwargs):
"""
Load an OFF file into the kwargs for a Trimesh constructor
Parameters
----------
file_obj : file object
Contains an OFF file
Returns
----------
loaded : dict
kwargs for Trimesh constructor
"""
header_string =... | [
"def",
"load_off",
"(",
"file_obj",
",",
"*",
"*",
"kwargs",
")",
":",
"header_string",
"=",
"file_obj",
".",
"readline",
"(",
")",
"if",
"hasattr",
"(",
"header_string",
",",
"'decode'",
")",
":",
"header_string",
"=",
"header_string",
".",
"decode",
"(",... | 29.422222 | 16.488889 |
def set_breakpoints(self, breakpoints):
"""Set breakpoints"""
self.clear_breakpoints()
for line_number, condition in breakpoints:
self.toogle_breakpoint(line_number, condition)
self.breakpoints = self.get_breakpoints() | [
"def",
"set_breakpoints",
"(",
"self",
",",
"breakpoints",
")",
":",
"self",
".",
"clear_breakpoints",
"(",
")",
"for",
"line_number",
",",
"condition",
"in",
"breakpoints",
":",
"self",
".",
"toogle_breakpoint",
"(",
"line_number",
",",
"condition",
")",
"sel... | 42.833333 | 7.666667 |
def generate_code_verifier(n_bytes=64):
"""
source: https://github.com/openstack/deb-python-oauth2client
Generates a 'code_verifier' as described in section 4.1 of RFC 7636.
This is a 'high-entropy cryptographic random string' that will be
impractical for an attacker to guess.
Args:
n_by... | [
"def",
"generate_code_verifier",
"(",
"n_bytes",
"=",
"64",
")",
":",
"verifier",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"os",
".",
"urandom",
"(",
"n_bytes",
")",
")",
".",
"rstrip",
"(",
"b'='",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"# https:... | 40.458333 | 19.208333 |
def unwrap_single(self):
"""
Unwrap the single Result item. Call this from single-operation
methods to return the actual result
:return: The actual result
"""
try:
return next(self.itervalues())
except AttributeError:
return next(iter(self.... | [
"def",
"unwrap_single",
"(",
"self",
")",
":",
"try",
":",
"return",
"next",
"(",
"self",
".",
"itervalues",
"(",
")",
")",
"except",
"AttributeError",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"values",
"(",
")",
")",
")"
] | 32.1 | 9.9 |
def command(self, rs_id, command, *args):
"""Call a ReplicaSet method."""
rs = self._storage[rs_id]
try:
return getattr(rs, command)(*args)
except AttributeError:
raise ValueError("Cannot issue the command %r to ReplicaSet %s"
% (comma... | [
"def",
"command",
"(",
"self",
",",
"rs_id",
",",
"command",
",",
"*",
"args",
")",
":",
"rs",
"=",
"self",
".",
"_storage",
"[",
"rs_id",
"]",
"try",
":",
"return",
"getattr",
"(",
"rs",
",",
"command",
")",
"(",
"*",
"args",
")",
"except",
"Att... | 40.5 | 11.875 |
def to_list_of(self, state):
# type: (S) -> List[B]
'''Returns a list of all the foci within `state`.
Requires kind Fold. This method will raise TypeError if the
optic has no way to get any foci.
'''
if not self._is_kind(Fold):
raise TypeError('Must be an ins... | [
"def",
"to_list_of",
"(",
"self",
",",
"state",
")",
":",
"# type: (S) -> List[B]",
"if",
"not",
"self",
".",
"_is_kind",
"(",
"Fold",
")",
":",
"raise",
"TypeError",
"(",
"'Must be an instance of Fold to .to_list_of()'",
")",
"pure",
"=",
"lambda",
"a",
":",
... | 35.846154 | 18.461538 |
def p_declarations(self, p):
"""declarations : declarations declaration
| declaration"""
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
elif n == 2:
p[0] = [p[1]] | [
"def",
"p_declarations",
"(",
"self",
",",
"p",
")",
":",
"n",
"=",
"len",
"(",
"p",
")",
"if",
"n",
"==",
"3",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"[",
"p",
"[",
"2",
"]",
"]",
"elif",
"n",
"==",
"2",
":",
"p",
"["... | 28.875 | 12.375 |
def parse_sidebar(self, media_page):
"""Parses the DOM and returns media attributes in the sidebar.
:type media_page: :class:`bs4.BeautifulSoup`
:param media_page: MAL media page's DOM
:rtype: dict
:return: media attributes.
:raises: InvalidMediaError, MalformedMediaPageError
"""
med... | [
"def",
"parse_sidebar",
"(",
"self",
",",
"media_page",
")",
":",
"media_info",
"=",
"{",
"}",
"# if MAL says the series doesn't exist, raise an InvalidMediaError.",
"error_tag",
"=",
"media_page",
".",
"find",
"(",
"u'div'",
",",
"{",
"'class'",
":",
"'badresult'",
... | 37.119205 | 25.430464 |
def get_queryset_filters(self, query):
"""
Return the filtered queryset
"""
conditions = Q()
for field_name in self.fields:
conditions |= Q(**{
self._construct_qs_filter(field_name): query
})
return conditions | [
"def",
"get_queryset_filters",
"(",
"self",
",",
"query",
")",
":",
"conditions",
"=",
"Q",
"(",
")",
"for",
"field_name",
"in",
"self",
".",
"fields",
":",
"conditions",
"|=",
"Q",
"(",
"*",
"*",
"{",
"self",
".",
"_construct_qs_filter",
"(",
"field_nam... | 28.8 | 9.4 |
def _os_walk(directory, recurse=True, **kwargs):
"""
Work like os.walk but if recurse is False just list current directory
"""
if recurse:
for root, dirs, files in os.walk(directory, **kwargs):
yield root, dirs, files
else:
files = []
for filename in os.listdir(di... | [
"def",
"_os_walk",
"(",
"directory",
",",
"recurse",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"recurse",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
",",
"*",
"*",
"kwargs",
")",
":",
"yi... | 35.153846 | 14.230769 |
def delete(self):
"""
Destructor.
"""
if self.glucose:
pysolvers.glucose3_del(self.glucose)
self.glucose = None
if self.prfile:
self.prfile.close() | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"glucose",
":",
"pysolvers",
".",
"glucose3_del",
"(",
"self",
".",
"glucose",
")",
"self",
".",
"glucose",
"=",
"None",
"if",
"self",
".",
"prfile",
":",
"self",
".",
"prfile",
".",
"close",... | 20.636364 | 15.545455 |
def _inferSchema(self, rdd, samplingRatio=None, names=None):
"""
Infer schema from an RDD of Row or tuple.
:param rdd: an RDD of Row or tuple
:param samplingRatio: sampling ratio, or no sampling (default)
:return: :class:`pyspark.sql.types.StructType`
"""
first =... | [
"def",
"_inferSchema",
"(",
"self",
",",
"rdd",
",",
"samplingRatio",
"=",
"None",
",",
"names",
"=",
"None",
")",
":",
"first",
"=",
"rdd",
".",
"first",
"(",
")",
"if",
"not",
"first",
":",
"raise",
"ValueError",
"(",
"\"The first row in RDD is empty, \"... | 43.741935 | 19.225806 |
def pushtx(tx_hex, coin_symbol='btc', api_key=None):
'''
Takes a signed transaction hex binary (and coin_symbol) and broadcasts it to the bitcoin network.
'''
assert is_valid_coin_symbol(coin_symbol)
assert api_key, 'api_key required'
url = _get_pushtx_url(coin_symbol=coin_symbol)
logger.... | [
"def",
"pushtx",
"(",
"tx_hex",
",",
"coin_symbol",
"=",
"'btc'",
",",
"api_key",
"=",
"None",
")",
":",
"assert",
"is_valid_coin_symbol",
"(",
"coin_symbol",
")",
"assert",
"api_key",
",",
"'api_key required'",
"url",
"=",
"_get_pushtx_url",
"(",
"coin_symbol",... | 27.555556 | 28 |
def logger_initial_config(service_name=None,
log_level=None,
logger_format=None,
logger_date_format=None):
'''Set initial logging configurations.
:param service_name: Name of the service
:type logger: String
:param log_level... | [
"def",
"logger_initial_config",
"(",
"service_name",
"=",
"None",
",",
"log_level",
"=",
"None",
",",
"logger_format",
"=",
"None",
",",
"logger_date_format",
"=",
"None",
")",
":",
"if",
"not",
"log_level",
":",
"log_level",
"=",
"os",
".",
"getenv",
"(",
... | 32.852941 | 20.029412 |
def nodes(self, type=None, failed=False, participant_id=None):
"""Get nodes in the network.
type specifies the type of Node. Failed can be "all", False
(default) or True. If a participant_id is passed only
nodes with that participant_id will be returned.
"""
if type is N... | [
"def",
"nodes",
"(",
"self",
",",
"type",
"=",
"None",
",",
"failed",
"=",
"False",
",",
"participant_id",
"=",
"None",
")",
":",
"if",
"type",
"is",
"None",
":",
"type",
"=",
"Node",
"if",
"not",
"issubclass",
"(",
"type",
",",
"Node",
")",
":",
... | 38.633333 | 21.2 |
def get_contour_pd_plot(self):
"""
Plot a contour phase diagram plot, where phase triangles are colored
according to degree of instability by interpolation. Currently only
works for 3-component phase diagrams.
Returns:
A matplotlib plot object.
"""
fr... | [
"def",
"get_contour_pd_plot",
"(",
"self",
")",
":",
"from",
"scipy",
"import",
"interpolate",
"from",
"matplotlib",
"import",
"cm",
"pd",
"=",
"self",
".",
"_pd",
"entries",
"=",
"pd",
".",
"qhull_entries",
"data",
"=",
"np",
".",
"array",
"(",
"pd",
".... | 31.6 | 17.142857 |
def _stream(self):
"""execute subprocess with timeout
Usage::
>>> with cmd_proc.run_with_timeout() as cmd_proc:
... stdout, stderr = cmd_proc.communicate()
...
>>> assert cmd_proc.proc.return_code == 0, "proc exec failed"
"""
timer =... | [
"def",
"_stream",
"(",
"self",
")",
":",
"timer",
"=",
"None",
"try",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"self",
".",
"cmd",
",",
"cwd",
"=",
"self",
".",
"cwd",
",",
"env",
"=",
"self",
".",
"env",
",",
"stdout",
"=",
"subprocess... | 28.333333 | 18.222222 |
def logged(level=logging.DEBUG):
"""
Useful logging decorator. If a method is logged, the beginning and end of
the method call will be logged at a pre-specified level.
Args:
level: Level to log method at. Defaults to DEBUG.
"""
def wrap(f):
_logger = logging.getLogger("{}.{}".fo... | [
"def",
"logged",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"_logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"{}.{}\"",
".",
"format",
"(",
"f",
".",
"__module__",
",",
"f",
".",
"__name__",
")",
")"... | 36.761905 | 23.238095 |
def request(method, url, **kwargs):
"""same as requests/requests/api.py request(...)"""
time_before_request = time()
# session start
session = SessionSinglePool()
# proxies
kwargs['proxies'] = settings['outgoing'].get('proxies') or None
# timeout
if 'timeout' in kwargs:
timeou... | [
"def",
"request",
"(",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"time_before_request",
"=",
"time",
"(",
")",
"# session start",
"session",
"=",
"SessionSinglePool",
"(",
")",
"# proxies",
"kwargs",
"[",
"'proxies'",
"]",
"=",
"settings",
"... | 29.74359 | 21.410256 |
def custom_handler(self, glade, function_name, widget_name, str1, str2, int1, int2):
"""
Generic handler for creating custom widgets, internally used to
enable custom widgets (custom widgets of glade).
The custom widgets have a creation function specified in design time.
Those c... | [
"def",
"custom_handler",
"(",
"self",
",",
"glade",
",",
"function_name",
",",
"widget_name",
",",
"str1",
",",
"str2",
",",
"int1",
",",
"int2",
")",
":",
"try",
":",
"handler",
"=",
"getattr",
"(",
"self",
",",
"function_name",
")",
"return",
"handler"... | 43.75 | 24.15 |
def _create_db(self):
"""Creates a new databae or opens a connection to an existing one.
.. note::
You can't share sqlite3 connections between threads (by default)
hence we setup the db here. It has the upside of running async.
"""
log.debug("Creating sqlite data... | [
"def",
"_create_db",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Creating sqlite database\"",
")",
"self",
".",
"_conn",
"=",
"sqlite3",
".",
"connect",
"(",
"self",
".",
"_db_filename",
")",
"# create table structure",
"self",
".",
"_conn",
".",
"cu... | 32 | 19.692308 |
def _find_vm(name, data, quiet=False):
'''
Scan the query data for the named VM
'''
for hv_ in data:
# Check if data is a dict, and not '"virt.full_info" is not available.'
if not isinstance(data[hv_], dict):
continue
if name in data[hv_].get('vm_info', {}):
... | [
"def",
"_find_vm",
"(",
"name",
",",
"data",
",",
"quiet",
"=",
"False",
")",
":",
"for",
"hv_",
"in",
"data",
":",
"# Check if data is a dict, and not '\"virt.full_info\" is not available.'",
"if",
"not",
"isinstance",
"(",
"data",
"[",
"hv_",
"]",
",",
"dict",... | 36.5 | 20.5 |
def get_client_settings_config_file(**kwargs): # pylint: disable=inconsistent-return-statements
"""Retrieve client settings from the possible config file locations.
:param \\*\\*kwargs: Arguments that are passed into the client instance
"""
config_files = ['/etc/softlayer.conf', '~/.softlayer']
... | [
"def",
"get_client_settings_config_file",
"(",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=inconsistent-return-statements",
"config_files",
"=",
"[",
"'/etc/softlayer.conf'",
",",
"'~/.softlayer'",
"]",
"if",
"kwargs",
".",
"get",
"(",
"'config_file'",
")",
":",
... | 39.576923 | 20.615385 |
def _wrap_paginated_response(cls, request, response, controls, data,
head=None):
"""Builds the metadata for a pagingated response and wraps everying in
a JSON encoded web.Response
"""
paging_response = response['paging']
if head is None:
... | [
"def",
"_wrap_paginated_response",
"(",
"cls",
",",
"request",
",",
"response",
",",
"controls",
",",
"data",
",",
"head",
"=",
"None",
")",
":",
"paging_response",
"=",
"response",
"[",
"'paging'",
"]",
"if",
"head",
"is",
"None",
":",
"head",
"=",
"res... | 32.446809 | 14.510638 |
async def start(self, **kwargs):
"""Start the pairing server and publish service."""
zeroconf = kwargs['zeroconf']
self._name = kwargs['name']
self._pairing_guid = kwargs.get('pairing_guid', None) or \
self._generate_random_guid()
self._web_server = web.Server(self.h... | [
"async",
"def",
"start",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"zeroconf",
"=",
"kwargs",
"[",
"'zeroconf'",
"]",
"self",
".",
"_name",
"=",
"kwargs",
"[",
"'name'",
"]",
"self",
".",
"_pairing_guid",
"=",
"kwargs",
".",
"get",
"(",
"'pairi... | 44.4375 | 20.25 |
def get_yaml_schema(self):
"""GetYamlSchema.
[Preview API]
:rtype: object
"""
response = self._send(http_method='GET',
location_id='1f9990b9-1dba-441f-9c2e-6485888c42b6',
version='5.1-preview.1')
return self._des... | [
"def",
"get_yaml_schema",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'GET'",
",",
"location_id",
"=",
"'1f9990b9-1dba-441f-9c2e-6485888c42b6'",
",",
"version",
"=",
"'5.1-preview.1'",
")",
"return",
"self",
".",
"_des... | 37.777778 | 14 |
def _remlogic_time(time_cell, date):
"""Reads RemLogic time string to datetime
Parameters
----------
time_cell : str
entire time cell from text file
date : datetime
start date from text file
Returns
-------
datetime
date and time
"""
stage_st... | [
"def",
"_remlogic_time",
"(",
"time_cell",
",",
"date",
")",
":",
"stage_start_time",
"=",
"datetime",
".",
"strptime",
"(",
"time_cell",
"[",
"-",
"8",
":",
"]",
",",
"'%I:%M:%S'",
")",
"start",
"=",
"datetime",
".",
"combine",
"(",
"date",
".",
"date",... | 25.192308 | 18.576923 |
def CopyToDateTimeString(self):
"""Copies the POSIX timestamp to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.######" or
None if the timestamp is missing.
"""
if (self._timestamp is None or self._timestamp < self._INT64_MIN or
self... | [
"def",
"CopyToDateTimeString",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_timestamp",
"is",
"None",
"or",
"self",
".",
"_timestamp",
"<",
"self",
".",
"_INT64_MIN",
"or",
"self",
".",
"_timestamp",
">",
"self",
".",
"_INT64_MAX",
")",
":",
"return"... | 34.583333 | 19 |
def get_command(self, ctx, cmd_name):
"""Get command for click."""
path = "%s.%s" % (__name__, cmd_name)
path = path.replace("-", "_")
module = importlib.import_module(path)
return getattr(module, 'cli') | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
":",
"path",
"=",
"\"%s.%s\"",
"%",
"(",
"__name__",
",",
"cmd_name",
")",
"path",
"=",
"path",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
"module",
"=",
"importlib",
".",
"im... | 39.666667 | 3.333333 |
def cons(collection, value):
"""Extends a collection with a value."""
if isinstance(value, collections.Mapping):
if collection is None:
collection = {}
collection.update(**value)
elif isinstance(value, six.string_types):
if collection is None:
collection = []... | [
"def",
"cons",
"(",
"collection",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Mapping",
")",
":",
"if",
"collection",
"is",
"None",
":",
"collection",
"=",
"{",
"}",
"collection",
".",
"update",
"(",
"*",
"*",
... | 26.086957 | 15.826087 |
def stop_stack(awsclient, stack_name, use_suspend=False):
"""Stop an existing stack on AWS cloud.
:param awsclient:
:param stack_name:
:param use_suspend: use suspend and resume on the autoscaling group
:return: exit_code
"""
exit_code = 0
# check for DisableStop
#disable_stop = co... | [
"def",
"stop_stack",
"(",
"awsclient",
",",
"stack_name",
",",
"use_suspend",
"=",
"False",
")",
":",
"exit_code",
"=",
"0",
"# check for DisableStop",
"#disable_stop = conf.get('deployment', {}).get('DisableStop', False)",
"#if disable_stop:",
"# log.warn('\\'DisableStop\\' i... | 40.948276 | 22 |
def checkResponse(request):
'''
Returns if a request has an okay error code, otherwise raises InvalidRequest.
'''
# Check the status code of the returned request
if str(request.status_code)[0] not in ['2', '3']:
w = str(request.text).split('\\r')[0][2:]
r... | [
"def",
"checkResponse",
"(",
"request",
")",
":",
"# Check the status code of the returned request",
"if",
"str",
"(",
"request",
".",
"status_code",
")",
"[",
"0",
"]",
"not",
"in",
"[",
"'2'",
",",
"'3'",
"]",
":",
"w",
"=",
"str",
"(",
"request",
".",
... | 34.8 | 23.2 |
def call(__self, __obj, *args, **kwargs):
"""Call the callable with the arguments and keyword arguments
provided but inject the active context or environment as first
argument if the callable is a :func:`contextfunction` or
:func:`environmentfunction`.
"""
if __debug__:
... | [
"def",
"call",
"(",
"__self",
",",
"__obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"__debug__",
":",
"__traceback_hide__",
"=",
"True",
"if",
"isinstance",
"(",
"__obj",
",",
"_context_function_types",
")",
":",
"if",
"getattr",
"(",
... | 46.625 | 10.375 |
def set_all_requested_intervals(self, requested_intervals):
"""
Sets the requested intervals for all workflow
:param requested_intervals: The requested intervals
:return: None
:type requested_intervals: TimeIntervals
"""
for workflow_id in self.workflows:
... | [
"def",
"set_all_requested_intervals",
"(",
"self",
",",
"requested_intervals",
")",
":",
"for",
"workflow_id",
"in",
"self",
".",
"workflows",
":",
"if",
"self",
".",
"workflows",
"[",
"workflow_id",
"]",
".",
"online",
":",
"self",
".",
"workflows",
"[",
"w... | 43.9 | 13.5 |
def _find_own_cgroups():
"""
For all subsystems, return the information in which (sub-)cgroup this process is in.
(Each process is in exactly cgroup in each hierarchy.)
@return a generator of tuples (subsystem, cgroup)
"""
try:
with open('/proc/self/cgroup', 'rt') as ownCgroupsFile:
... | [
"def",
"_find_own_cgroups",
"(",
")",
":",
"try",
":",
"with",
"open",
"(",
"'/proc/self/cgroup'",
",",
"'rt'",
")",
"as",
"ownCgroupsFile",
":",
"for",
"cgroup",
"in",
"_parse_proc_pid_cgroup",
"(",
"ownCgroupsFile",
")",
":",
"yield",
"cgroup",
"except",
"IO... | 39.833333 | 18.833333 |
def _scalar2array(d):
"""Convert a dictionary with scalar elements and string indices '_1234'
to a dictionary of arrays. Unspecified entries are np.nan."""
da = {}
for k, v in d.items():
if '_' not in k:
da[k] = v
else:
name = ''.join(k.split('_')[:-1])
... | [
"def",
"_scalar2array",
"(",
"d",
")",
":",
"da",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"'_'",
"not",
"in",
"k",
":",
"da",
"[",
"k",
"]",
"=",
"v",
"else",
":",
"name",
"=",
"''",
".",
"join",... | 35.588235 | 13.823529 |
def to_list(self):
"""
To a list of dicts (each dict is an instances)
"""
ret = []
for instance in self.instances:
ret.append(instance.to_dict())
return ret | [
"def",
"to_list",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"instance",
"in",
"self",
".",
"instances",
":",
"ret",
".",
"append",
"(",
"instance",
".",
"to_dict",
"(",
")",
")",
"return",
"ret"
] | 26.125 | 10.625 |
async def extended_analog(self, pin, data):
"""
This method will send an extended-data analog write command to the
selected pin.
:param pin: 0 - 127
:param data: 0 - 0xfffff
:returns: No return value
"""
analog_data = [pin, data & 0x7f, (data >> 7) & 0x... | [
"async",
"def",
"extended_analog",
"(",
"self",
",",
"pin",
",",
"data",
")",
":",
"analog_data",
"=",
"[",
"pin",
",",
"data",
"&",
"0x7f",
",",
"(",
"data",
">>",
"7",
")",
"&",
"0x7f",
",",
"(",
"data",
">>",
"14",
")",
"&",
"0x7f",
"]",
"aw... | 31.538462 | 21.692308 |
def fit(self, X, y, **kwargs):
"""
Fits the estimator to calculate feature correlation to
dependent variable.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m features
y : ndarray or Series of length n
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_create_labels_for_features",
"(",
"X",
")",
"self",
".",
"_select_features_to_plot",
"(",
"X",
")",
"# Calculate Features correlation with target variable",
"if",
... | 30.916667 | 20.5 |
def _load(self, exit_on_failure):
"""One you have added all your configuration data (Section, Element,
...) you need to load data from the config file."""
# pylint: disable-msg=W0621
log = logging.getLogger('argtoolbox')
discoveredFileList = []
if self.config_file:
... | [
"def",
"_load",
"(",
"self",
",",
"exit_on_failure",
")",
":",
"# pylint: disable-msg=W0621",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'argtoolbox'",
")",
"discoveredFileList",
"=",
"[",
"]",
"if",
"self",
".",
"config_file",
":",
"if",
"isinstance",
"("... | 42.068182 | 16.772727 |
def get_lowest_probable_prepared_certificate_in_view(
self, view_no) -> Optional[int]:
"""
Return lowest pp_seq_no of the view for which can be prepared but
choose from unprocessed PRE-PREPAREs and PREPAREs.
"""
# TODO: Naive implementation, dont need to iterate over ... | [
"def",
"get_lowest_probable_prepared_certificate_in_view",
"(",
"self",
",",
"view_no",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"# TODO: Naive implementation, dont need to iterate over the complete",
"# data structures, fix this later",
"seq_no_pp",
"=",
"SortedList",
"(",
... | 36.269231 | 18.346154 |
def delete(self, key, sort_key):
primary_key = key
key = self.prefixed('{}:{}'.format(key, sort_key))
""" Delete an element in dictionary """
self.logger.debug('Storage - delete {}'.format(key))
if sort_key is not None:
self.cache[self.prefixed(primary_key)].remove(so... | [
"def",
"delete",
"(",
"self",
",",
"key",
",",
"sort_key",
")",
":",
"primary_key",
"=",
"key",
"key",
"=",
"self",
".",
"prefixed",
"(",
"'{}:{}'",
".",
"format",
"(",
"key",
",",
"sort_key",
")",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'S... | 42.214286 | 13.857143 |
def _get_src_path_line_nodes_jacoco(self, xml_document, src_path):
"""
Return a list of nodes containing line information for `src_path`
in `xml_document`.
If file is not present in `xml_document`, return None
"""
files = []
packages = [pkg for pkg in xml_docume... | [
"def",
"_get_src_path_line_nodes_jacoco",
"(",
"self",
",",
"xml_document",
",",
"src_path",
")",
":",
"files",
"=",
"[",
"]",
"packages",
"=",
"[",
"pkg",
"for",
"pkg",
"in",
"xml_document",
".",
"findall",
"(",
"\".//package\"",
")",
"]",
"for",
"pkg",
"... | 35.782609 | 20.478261 |
def most_recent_year():
"""
This year, if it's December.
The most recent year, otherwise.
Note: Advent of Code started in 2015
"""
aoc_now = datetime.datetime.now(tz=AOC_TZ)
year = aoc_now.year
if aoc_now.month < 12:
year -= 1
if year < 2015:
raise AocdError("Time tra... | [
"def",
"most_recent_year",
"(",
")",
":",
"aoc_now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"tz",
"=",
"AOC_TZ",
")",
"year",
"=",
"aoc_now",
".",
"year",
"if",
"aoc_now",
".",
"month",
"<",
"12",
":",
"year",
"-=",
"1",
"if",
"year",
"... | 26.692308 | 11.615385 |
def serialize_footer(signer):
"""Uses the signer object which has been used to sign the message to generate
the signature, then serializes that signature.
:param signer: Cryptographic signer object
:type signer: aws_encryption_sdk.internal.crypto.Signer
:returns: Serialized footer
:rtype: bytes... | [
"def",
"serialize_footer",
"(",
"signer",
")",
":",
"footer",
"=",
"b\"\"",
"if",
"signer",
"is",
"not",
"None",
":",
"signature",
"=",
"signer",
".",
"finalize",
"(",
")",
"footer",
"=",
"struct",
".",
"pack",
"(",
"\">H{sig_len}s\"",
".",
"format",
"("... | 37 | 17.428571 |
def _get_privacy(self, table_name):
"""gets current privacy of a table"""
ds_manager = DatasetManager(self.auth_client)
try:
dataset = ds_manager.get(table_name)
return dataset.privacy.lower()
except NotFoundException:
return None | [
"def",
"_get_privacy",
"(",
"self",
",",
"table_name",
")",
":",
"ds_manager",
"=",
"DatasetManager",
"(",
"self",
".",
"auth_client",
")",
"try",
":",
"dataset",
"=",
"ds_manager",
".",
"get",
"(",
"table_name",
")",
"return",
"dataset",
".",
"privacy",
"... | 36.375 | 10 |
def git(ctx, url, private, sync): # pylint:disable=assign-to-new-keyword
"""Set/Sync git repo on this project.
Uses [Caching](/references/polyaxon-cli/#caching)
Example:
\b
```bash
$ polyaxon project git --url=https://github.com/polyaxon/polyaxon-quick-start
```
\b
```bash
$... | [
"def",
"git",
"(",
"ctx",
",",
"url",
",",
"private",
",",
"sync",
")",
":",
"# pylint:disable=assign-to-new-keyword",
"user",
",",
"project_name",
"=",
"get_project_or_local",
"(",
"ctx",
".",
"obj",
".",
"get",
"(",
"'project'",
")",
")",
"def",
"git_set_u... | 35.470588 | 31.196078 |
def token_list_width(tokenlist):
"""
Return the character width of this token list.
(Take double width characters into account.)
:param tokenlist: List of (token, text) or (token, text, mouse_handler)
tuples.
"""
ZeroWidthEscape = Token.ZeroWidthEscape
return sum(get_c... | [
"def",
"token_list_width",
"(",
"tokenlist",
")",
":",
"ZeroWidthEscape",
"=",
"Token",
".",
"ZeroWidthEscape",
"return",
"sum",
"(",
"get_cwidth",
"(",
"c",
")",
"for",
"item",
"in",
"tokenlist",
"for",
"c",
"in",
"item",
"[",
"1",
"]",
"if",
"item",
"[... | 38.9 | 17.3 |
def toXMLname(string):
"""Convert string to a XML name."""
if string.find(':') != -1 :
(prefix, localname) = string.split(':',1)
else:
prefix = None
localname = string
T = unicode(localname)
N = len(localname)
X = [];
for i in range(N) :
if i< N-1 and T[... | [
"def",
"toXMLname",
"(",
"string",
")",
":",
"if",
"string",
".",
"find",
"(",
"':'",
")",
"!=",
"-",
"1",
":",
"(",
"prefix",
",",
"localname",
")",
"=",
"string",
".",
"split",
"(",
"':'",
",",
"1",
")",
"else",
":",
"prefix",
"=",
"None",
"l... | 29.642857 | 16.892857 |
def open(self, inp, opts={}):
"""Use this to set where to read from.
Set opts['try_lineedit'] if you want this input to interact
with GNU-like readline library. By default, we will assume to
try importing and using readline. If readline is not
importable, line editing is not ava... | [
"def",
"open",
"(",
"self",
",",
"inp",
",",
"opts",
"=",
"{",
"}",
")",
":",
"get_option",
"=",
"lambda",
"key",
":",
"Mmisc",
".",
"option_set",
"(",
"opts",
",",
"key",
",",
"self",
".",
"DEFAULT_OPEN_READ_OPTS",
")",
"if",
"(",
"isinstance",
"(",... | 43.911765 | 19.117647 |
def main(self) -> None:
"""
Main entry point. Runs :func:`service`.
"""
# Actual main service code.
try:
self.service()
except Exception as e:
self.error("Unexpected exception: {e}\n{t}".format(
e=e, t=traceback.format_exc())) | [
"def",
"main",
"(",
"self",
")",
"->",
"None",
":",
"# Actual main service code.",
"try",
":",
"self",
".",
"service",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"error",
"(",
"\"Unexpected exception: {e}\\n{t}\"",
".",
"format",
"(",
"e",... | 30.5 | 11.1 |
def put_value(self, value, timeout=None):
"""Put a value to the Attribute and wait for completion"""
self._context.put(self._data.path + ["value"], value, timeout=timeout) | [
"def",
"put_value",
"(",
"self",
",",
"value",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_context",
".",
"put",
"(",
"self",
".",
"_data",
".",
"path",
"+",
"[",
"\"value\"",
"]",
",",
"value",
",",
"timeout",
"=",
"timeout",
")"
] | 61.666667 | 13 |
def iter_annotation_values(graph, annotation: str) -> Iterable[str]:
"""Iterate over all of the values for an annotation used in the graph.
:param pybel.BELGraph graph: A BEL graph
:param str annotation: The annotation to grab
"""
return (
value
for _, _, data in graph.edges(data=Tr... | [
"def",
"iter_annotation_values",
"(",
"graph",
",",
"annotation",
":",
"str",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"return",
"(",
"value",
"for",
"_",
",",
"_",
",",
"data",
"in",
"graph",
".",
"edges",
"(",
"data",
"=",
"True",
")",
"if",
... | 34.833333 | 16.416667 |
def experiments_fmri_create(self, experiment_id, filename):
"""Create functional data object from given file and associate the
object with the specified experiment.
Parameters
----------
experiment_id : string
Unique experiment identifier
filename : File-type... | [
"def",
"experiments_fmri_create",
"(",
"self",
",",
"experiment_id",
",",
"filename",
")",
":",
"# Get the experiment to ensure that it exist before we even create the",
"# functional data object",
"experiment",
"=",
"self",
".",
"experiments_get",
"(",
"experiment_id",
")",
... | 40.555556 | 18.305556 |
def target_to_ipv4_long(target):
""" Attempt to return a IPv4 long-range list from a target string. """
splitted = target.split('-')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET, splitted[0])
end_packed = inet_pton(socket.AF_INET, splitted[1])
... | [
"def",
"target_to_ipv4_long",
"(",
"target",
")",
":",
"splitted",
"=",
"target",
".",
"split",
"(",
"'-'",
")",
"if",
"len",
"(",
"splitted",
")",
"!=",
"2",
":",
"return",
"None",
"try",
":",
"start_packed",
"=",
"inet_pton",
"(",
"socket",
".",
"AF_... | 32.928571 | 17.357143 |
def meta_features_path(self, path):
"""Returns path for meta-features
Args:
path (str): Absolute/local path of xcessiv folder
"""
return os.path.join(
path,
app.config['XCESSIV_META_FEATURES_FOLDER'],
str(self.id)
)... | [
"def",
"meta_features_path",
"(",
"self",
",",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"app",
".",
"config",
"[",
"'XCESSIV_META_FEATURES_FOLDER'",
"]",
",",
"str",
"(",
"self",
".",
"id",
")",
")",
"+",
"'.npy'"
] | 29 | 15.727273 |
def preprocess(options):
assert options.bfile!=None, 'Please specify a bfile.'
""" computing the covariance matrix """
if options.compute_cov:
assert options.bfile!=None, 'Please specify a bfile.'
assert options.cfile is not None, 'Specify covariance matrix basename'
print('Computing ... | [
"def",
"preprocess",
"(",
"options",
")",
":",
"assert",
"options",
".",
"bfile",
"!=",
"None",
",",
"'Please specify a bfile.'",
"if",
"options",
".",
"compute_cov",
":",
"assert",
"options",
".",
"bfile",
"!=",
"None",
",",
"'Please specify a bfile.'",
"assert... | 41.397436 | 18.512821 |
def _unpack_token_compact(token):
"""
Unpack a compact-form serialized JWT.
Returns (header, payload, signature, signing_input) on success
Raises DecodeError on bad input
"""
if isinstance(token, (str, unicode)):
token = token.encode('utf-8')
try:
signing_input, crypto_segme... | [
"def",
"_unpack_token_compact",
"(",
"token",
")",
":",
"if",
"isinstance",
"(",
"token",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"token",
"=",
"token",
".",
"encode",
"(",
"'utf-8'",
")",
"try",
":",
"signing_input",
",",
"crypto_segment",
"=",
... | 31.818182 | 19.454545 |
def voice(self):
"""tuple. contain text and lang code
"""
dbid = self.lldb.dbid
text, lang = self._voiceoverdb.get_text_lang(dbid)
return text, lang | [
"def",
"voice",
"(",
"self",
")",
":",
"dbid",
"=",
"self",
".",
"lldb",
".",
"dbid",
"text",
",",
"lang",
"=",
"self",
".",
"_voiceoverdb",
".",
"get_text_lang",
"(",
"dbid",
")",
"return",
"text",
",",
"lang"
] | 30.5 | 11.333333 |
def clean(self):
"""
Pass the provided username and password to the active
authentication backends and verify the user account is
not disabled. If authentication succeeds, the ``User`` object
is assigned to the form so it can be accessed in the view.
"""
username ... | [
"def",
"clean",
"(",
"self",
")",
":",
"username",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'username'",
")",
"password",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'password'",
")",
"if",
"username",
"and",
"password",
":",
"try",
... | 44.793103 | 22.241379 |
def _set_route_source(self, v, load=False):
"""
Setter method for route_source, mapped from YANG variable /rbridge_id/route_map/content/match/ipv6/route_source (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_route_source is considered as a private
method.... | [
"def",
"_set_route_source",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | 71.125 | 34.416667 |
def main():
"""
Example application that opens a serial device and prints messages to the terminal.
"""
try:
# Retrieve the specified serial device.
device = AlarmDecoder(SerialDevice(interface=SERIAL_DEVICE))
# Set up an event handler and open the device
device.on_messa... | [
"def",
"main",
"(",
")",
":",
"try",
":",
"# Retrieve the specified serial device.",
"device",
"=",
"AlarmDecoder",
"(",
"SerialDevice",
"(",
"interface",
"=",
"SERIAL_DEVICE",
")",
")",
"# Set up an event handler and open the device",
"device",
".",
"on_message",
"+=",... | 31.894737 | 19.894737 |
def create_tag(self, tag_name):
"""
Create a new tag based on the working tree's revision.
:param tag_name: The name of the tag to create (a string).
"""
# Make sure the local repository exists and supports a working tree.
self.create()
self.ensure_working_tree()... | [
"def",
"create_tag",
"(",
"self",
",",
"tag_name",
")",
":",
"# Make sure the local repository exists and supports a working tree.",
"self",
".",
"create",
"(",
")",
"self",
".",
"ensure_working_tree",
"(",
")",
"# Create the new tag in the local repository.",
"logger",
"."... | 43.083333 | 20.25 |
def do_status(self, args):
'''print the number of work units in an existing work spec'''
work_spec_name = self._get_work_spec_name(args)
status = self.task_master.status(work_spec_name)
self.stdout.write(json.dumps(status, indent=4, sort_keys=True) +
'\n') | [
"def",
"do_status",
"(",
"self",
",",
"args",
")",
":",
"work_spec_name",
"=",
"self",
".",
"_get_work_spec_name",
"(",
"args",
")",
"status",
"=",
"self",
".",
"task_master",
".",
"status",
"(",
"work_spec_name",
")",
"self",
".",
"stdout",
".",
"write",
... | 51.5 | 19.166667 |
def create_database(self):
""" Create postgres database. """
self.print_message("Creating database '%s'" % self.databases['destination']['name'])
self.export_pgpassword('destination')
args = [
"createdb",
self.databases['destination']['name'],
]
ar... | [
"def",
"create_database",
"(",
"self",
")",
":",
"self",
".",
"print_message",
"(",
"\"Creating database '%s'\"",
"%",
"self",
".",
"databases",
"[",
"'destination'",
"]",
"[",
"'name'",
"]",
")",
"self",
".",
"export_pgpassword",
"(",
"'destination'",
")",
"a... | 41.461538 | 16 |
def load_foundation_sample_data(fd):
"""
Sample data for the Foundation object
:param fd: Foundation Object
:return:
"""
# foundation
fd.width = 16.0 # m
fd.length = 18.0 # m
fd.depth = 0.0 # m
fd.mass = 0.0 | [
"def",
"load_foundation_sample_data",
"(",
"fd",
")",
":",
"# foundation",
"fd",
".",
"width",
"=",
"16.0",
"# m",
"fd",
".",
"length",
"=",
"18.0",
"# m",
"fd",
".",
"depth",
"=",
"0.0",
"# m",
"fd",
".",
"mass",
"=",
"0.0"
] | 21.818182 | 12.363636 |
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
... | [
"def",
"_delete_handler",
"(",
"self",
",",
"handler_class",
")",
":",
"to_remove",
"=",
"self",
".",
"_get_handler",
"(",
"handler_class",
")",
"if",
"not",
"to_remove",
":",
"logging",
".",
"warning",
"(",
"'Error we should have an element to remove'",
")",
"els... | 43.75 | 12.25 |
def unselectRow(self, row):
'Unselect given row, return True if selected; else return False. O(log n)'
if id(row) in self._selectedRows:
del self._selectedRows[id(row)]
return True
else:
return False | [
"def",
"unselectRow",
"(",
"self",
",",
"row",
")",
":",
"if",
"id",
"(",
"row",
")",
"in",
"self",
".",
"_selectedRows",
":",
"del",
"self",
".",
"_selectedRows",
"[",
"id",
"(",
"row",
")",
"]",
"return",
"True",
"else",
":",
"return",
"False"
] | 36.142857 | 17 |
def get_details(self, obj):
""" return detail url """
return reverse('api_user_social_links_detail',
args=[obj.user.username, obj.pk],
request=self.context.get('request'),
format=self.context.get('format')) | [
"def",
"get_details",
"(",
"self",
",",
"obj",
")",
":",
"return",
"reverse",
"(",
"'api_user_social_links_detail'",
",",
"args",
"=",
"[",
"obj",
".",
"user",
".",
"username",
",",
"obj",
".",
"pk",
"]",
",",
"request",
"=",
"self",
".",
"context",
".... | 47.666667 | 13.166667 |
def delete(adapter, case_obj, update=False, existing_case=False):
"""Delete a case and all of it's variants from the database.
Args:
adapter: Connection to database
case_obj(models.Case)
update(bool): If we are in the middle of an update
existing_case(models.Case): If someth... | [
"def",
"delete",
"(",
"adapter",
",",
"case_obj",
",",
"update",
"=",
"False",
",",
"existing_case",
"=",
"False",
")",
":",
"# This will overwrite the updated case with the previous one",
"if",
"update",
":",
"adapter",
".",
"add_case",
"(",
"existing_case",
")",
... | 32 | 17.551724 |
def get_tok(self, tok):
'''
Return the name associated with the token, or False if the token is
not valid
'''
tdata = self.tokens["{0}.get_token".format(self.opts['eauth_tokens'])](self.opts, tok)
if not tdata:
return {}
rm_tok = False
if 'exp... | [
"def",
"get_tok",
"(",
"self",
",",
"tok",
")",
":",
"tdata",
"=",
"self",
".",
"tokens",
"[",
"\"{0}.get_token\"",
".",
"format",
"(",
"self",
".",
"opts",
"[",
"'eauth_tokens'",
"]",
")",
"]",
"(",
"self",
".",
"opts",
",",
"tok",
")",
"if",
"not... | 28.157895 | 22.263158 |
def build_D3bubbleChart(old, MAX_DEPTH, level=1, toplayer=None):
"""
Similar to standar d3, but nodes with children need to be duplicated otherwise they are
not depicted explicitly but just color coded
"name": "all",
"children": [
{"name": "Biological Science", "size": 9000},
{"name": "Biological Sci... | [
"def",
"build_D3bubbleChart",
"(",
"old",
",",
"MAX_DEPTH",
",",
"level",
"=",
"1",
",",
"toplayer",
"=",
"None",
")",
":",
"out",
"=",
"[",
"]",
"if",
"not",
"old",
":",
"old",
"=",
"toplayer",
"for",
"x",
"in",
"old",
":",
"d",
"=",
"{",
"}",
... | 35.705882 | 18.27451 |
def _perform_type_validation(self, path, typ, value, results):
"""
Validates a given value to match specified type.
The type can be defined as a Schema, type, a type name or [[TypeCode]].
When type is a Schema, it executes validation recursively against that Schema.
:param path:... | [
"def",
"_perform_type_validation",
"(",
"self",
",",
"path",
",",
"typ",
",",
"value",
",",
"results",
")",
":",
"# If type it not defined then skip",
"if",
"typ",
"==",
"None",
":",
"return",
"# Perform validation against schema",
"if",
"isinstance",
"(",
"typ",
... | 31.212766 | 21.085106 |
def get_structure_seqs(self, model):
"""Gather chain sequences and store in their corresponding ``ChainProp`` objects in the ``chains`` attribute.
Args:
model (Model): Biopython Model object of the structure you would like to parse
"""
# Don't overwrite existing ChainProp ... | [
"def",
"get_structure_seqs",
"(",
"self",
",",
"model",
")",
":",
"# Don't overwrite existing ChainProp objects",
"dont_overwrite",
"=",
"[",
"]",
"chains",
"=",
"list",
"(",
"model",
".",
"get_chains",
"(",
")",
")",
"for",
"x",
"in",
"chains",
":",
"if",
"... | 42.035714 | 20.821429 |
def create_local_copy(self, effects=None, store=None):
"""Creates a Local File Copy on Uploadcare Storage.
Args:
- effects:
Adds CDN image effects. If ``self.default_effects`` property
is set effects will be combined with default effects.
- store:... | [
"def",
"create_local_copy",
"(",
"self",
",",
"effects",
"=",
"None",
",",
"store",
"=",
"None",
")",
":",
"effects",
"=",
"self",
".",
"_build_effects",
"(",
"effects",
")",
"store",
"=",
"store",
"or",
"''",
"data",
"=",
"{",
"'source'",
":",
"self",... | 37.142857 | 20.761905 |
def get_zone(self, id=None, name=None):
""" Get zone object by name or id.
"""
log.info("Picking zone: %s (%s)" % (name, id))
return self.zones[id or name] | [
"def",
"get_zone",
"(",
"self",
",",
"id",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"Picking zone: %s (%s)\"",
"%",
"(",
"name",
",",
"id",
")",
")",
"return",
"self",
".",
"zones",
"[",
"id",
"or",
"name",
"]"
] | 36.6 | 3.6 |
def peng_float(snum):
r"""
Return floating point equivalent of a number represented in engineering notation.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: string
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation fo... | [
"def",
"peng_float",
"(",
"snum",
")",
":",
"# This can be coded as peng_mant(snum)*(peng_power(snum)[1]), but the",
"# \"function unrolling\" is about 4x faster",
"snum",
"=",
"snum",
".",
"rstrip",
"(",
")",
"power",
"=",
"_SUFFIX_POWER_DICT",
"[",
"\" \"",
"if",
"snum",
... | 29.321429 | 23.785714 |
def translate(self, frame=0):
'''Returns a Fasta sequence, translated into amino acids. Starts translating from 'frame', where frame expected to be 0,1 or 2'''
return Fasta(self.id, ''.join([genetic_codes.codes[genetic_code].get(self.seq[x:x+3].upper(), 'X') for x in range(frame, len(self)-1-frame, 3)])... | [
"def",
"translate",
"(",
"self",
",",
"frame",
"=",
"0",
")",
":",
"return",
"Fasta",
"(",
"self",
".",
"id",
",",
"''",
".",
"join",
"(",
"[",
"genetic_codes",
".",
"codes",
"[",
"genetic_code",
"]",
".",
"get",
"(",
"self",
".",
"seq",
"[",
"x"... | 106.333333 | 73.666667 |
def update_child_calls(self):
"""Replace child nodes on original function call with their partials"""
for node in filter(lambda n: len(n.arg_name), self.child_list):
self.data["bound_args"].arguments[node.arg_name] = node.partial()
self.updated = True | [
"def",
"update_child_calls",
"(",
"self",
")",
":",
"for",
"node",
"in",
"filter",
"(",
"lambda",
"n",
":",
"len",
"(",
"n",
".",
"arg_name",
")",
",",
"self",
".",
"child_list",
")",
":",
"self",
".",
"data",
"[",
"\"bound_args\"",
"]",
".",
"argume... | 47.166667 | 22 |
def threw(cls, spy, error_type=None):
"""
Checking the inspector is raised error_type
Args: SinonSpy, Exception (defaut: None)
"""
cls.__is_spy(spy)
if not (spy.threw(error_type)):
raise cls.failException(cls.message) | [
"def",
"threw",
"(",
"cls",
",",
"spy",
",",
"error_type",
"=",
"None",
")",
":",
"cls",
".",
"__is_spy",
"(",
"spy",
")",
"if",
"not",
"(",
"spy",
".",
"threw",
"(",
"error_type",
")",
")",
":",
"raise",
"cls",
".",
"failException",
"(",
"cls",
... | 33.75 | 5.75 |
def SignalAbort(self):
"""Signals the process to abort."""
self._abort = True
if self._foreman_status_wait_event:
self._foreman_status_wait_event.set()
if self._analysis_mediator:
self._analysis_mediator.SignalAbort() | [
"def",
"SignalAbort",
"(",
"self",
")",
":",
"self",
".",
"_abort",
"=",
"True",
"if",
"self",
".",
"_foreman_status_wait_event",
":",
"self",
".",
"_foreman_status_wait_event",
".",
"set",
"(",
")",
"if",
"self",
".",
"_analysis_mediator",
":",
"self",
".",... | 34.142857 | 7.428571 |
def ensemble_mean_std_max_min(ens):
"""Calculate ensemble statistics between a results from an ensemble of climate simulations
Returns a dataset containing ensemble mean, standard-deviation,
minimum and maximum for input climate simulations.
Parameters
----------
ens : Ensemble dataset (see xc... | [
"def",
"ensemble_mean_std_max_min",
"(",
"ens",
")",
":",
"dsOut",
"=",
"ens",
".",
"drop",
"(",
"ens",
".",
"data_vars",
")",
"for",
"v",
"in",
"ens",
".",
"data_vars",
":",
"dsOut",
"[",
"v",
"+",
"'_mean'",
"]",
"=",
"ens",
"[",
"v",
"]",
".",
... | 33.341463 | 20.341463 |
def reset(self):
'''
Reset Stan model and all tracked distributions and parameters.
'''
self.parameters = []
self.transformed_parameters = []
self.expressions = []
self.data = []
self.transformed_data = []
self.X = {}
self.model = []
... | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"parameters",
"=",
"[",
"]",
"self",
".",
"transformed_parameters",
"=",
"[",
"]",
"self",
".",
"expressions",
"=",
"[",
"]",
"self",
".",
"data",
"=",
"[",
"]",
"self",
".",
"transformed_data",
"="... | 34.722222 | 17.611111 |
def _remote_methodcall(id, method_name, *args, **kwargs):
"""(Executed on remote engine) convert Ids to real objects, call method """
obj = distob.engine[id]
nargs = []
for a in args:
if isinstance(a, Id):
nargs.append(distob.engine[a])
elif (isinstance(a, collections.Sequenc... | [
"def",
"_remote_methodcall",
"(",
"id",
",",
"method_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"distob",
".",
"engine",
"[",
"id",
"]",
"nargs",
"=",
"[",
"]",
"for",
"a",
"in",
"args",
":",
"if",
"isinstance",
"(",
... | 40.529412 | 15.029412 |
def from_timeseries(ts1, ts2, stride, fftlength=None, overlap=None,
window=None, nproc=1, **kwargs):
"""Calculate the coherence `Spectrogram` between two `TimeSeries`.
Parameters
----------
timeseries : :class:`~gwpy.timeseries.TimeSeries`
input time-series to process.
s... | [
"def",
"from_timeseries",
"(",
"ts1",
",",
"ts2",
",",
"stride",
",",
"fftlength",
"=",
"None",
",",
"overlap",
"=",
"None",
",",
"window",
"=",
"None",
",",
"nproc",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"# format FFT parameters",
"if",
"fftlen... | 33.987654 | 19.432099 |
def river_flow(self, source, world, river_list, lake_list):
"""simulate fluid dynamics by using starting point and flowing to the
lowest available point"""
current_location = source
path = [source]
# start the flow
while True:
x, y = current_location
... | [
"def",
"river_flow",
"(",
"self",
",",
"source",
",",
"world",
",",
"river_list",
",",
"lake_list",
")",
":",
"current_location",
"=",
"source",
"path",
"=",
"[",
"source",
"]",
"# start the flow",
"while",
"True",
":",
"x",
",",
"y",
"=",
"current_locatio... | 42.5 | 18.627273 |
def _stable_names(self):
'''
This private method extracts the element names from stable_el.
Note that stable_names is a misnomer as stable_el also contains
unstable element names with a number 999 for the *stable* mass
numbers. (?!??)
'''
stable_names=[]
... | [
"def",
"_stable_names",
"(",
"self",
")",
":",
"stable_names",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"stable_el",
")",
")",
":",
"stable_names",
".",
"append",
"(",
"self",
".",
"stable_el",
"[",
"i",
"]",
"[",
"0"... | 36.5 | 21.5 |
def stage_redis(self, variable, data):
"""Stage data in Redis.
Args:
variable (str): The Redis variable name.
data (dict|list|str): The data to store in Redis.
"""
if isinstance(data, int):
data = str(data)
# handle binary
if variable.... | [
"def",
"stage_redis",
"(",
"self",
",",
"variable",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"data",
"=",
"str",
"(",
"data",
")",
"# handle binary",
"if",
"variable",
".",
"endswith",
"(",
"'Binary'",
")",
":",
"... | 38.294118 | 14.176471 |
def _xy2hash(x, y, dim):
"""Convert (x, y) to hashcode.
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
Pure python implementation.
Parameters:
x: int x value of point [0, dim) in dim x dim coord system
y: int ... | [
"def",
"_xy2hash",
"(",
"x",
",",
"y",
",",
"dim",
")",
":",
"d",
"=",
"0",
"lvl",
"=",
"dim",
">>",
"1",
"while",
"(",
"lvl",
">",
"0",
")",
":",
"rx",
"=",
"int",
"(",
"(",
"x",
"&",
"lvl",
")",
">",
"0",
")",
"ry",
"=",
"int",
"(",
... | 29.923077 | 21.192308 |
def export(id, local=False, scrub_pii=False):
"""Export data from an experiment."""
print("Preparing to export the data...")
if local:
db_uri = db.db_url
else:
db_uri = HerokuApp(id).db_uri
# Create the data package if it doesn't already exist.
subdata_path = os.path.join("dat... | [
"def",
"export",
"(",
"id",
",",
"local",
"=",
"False",
",",
"scrub_pii",
"=",
"False",
")",
":",
"print",
"(",
"\"Preparing to export the data...\"",
")",
"if",
"local",
":",
"db_uri",
"=",
"db",
".",
"db_url",
"else",
":",
"db_uri",
"=",
"HerokuApp",
"... | 26.87931 | 21.965517 |
def SetCredentials(api_username,api_passwd):
"""Establish API username and password associated with APIv2 commands."""
global V2_API_USERNAME
global V2_API_PASSWD
global _V2_ENABLED
_V2_ENABLED = True
V2_API_USERNAME = api_username
V2_API_PASSWD = api_passwd | [
"def",
"SetCredentials",
"(",
"api_username",
",",
"api_passwd",
")",
":",
"global",
"V2_API_USERNAME",
"global",
"V2_API_PASSWD",
"global",
"_V2_ENABLED",
"_V2_ENABLED",
"=",
"True",
"V2_API_USERNAME",
"=",
"api_username",
"V2_API_PASSWD",
"=",
"api_passwd"
] | 32.25 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.