text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def remove_class(text):
"""
Remove the CLASS from each DNS record, if present.
The only class that gets used today (for all intents
and purposes) is 'IN'.
"""
# see RFC 1035 for list of classes
lines = text.split("\n")
ret = []
for line in lines:
tokens = tokenize_line(line)... | [
"def",
"remove_class",
"(",
"text",
")",
":",
"# see RFC 1035 for list of classes",
"lines",
"=",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
"ret",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"tokens",
"=",
"tokenize_line",
"(",
"line",
")",
"tokens_... | 26.115385 | 0.00142 |
def estimator_values_df(run_list, estimator_list, **kwargs):
"""Get a dataframe of estimator values.
NB when parallelised the results will not be produced in order (so results
from some run number will not nessesarily correspond to that number run in
run_list).
Parameters
----------
run_li... | [
"def",
"estimator_values_df",
"(",
"run_list",
",",
"estimator_list",
",",
"*",
"*",
"kwargs",
")",
":",
"estimator_names",
"=",
"kwargs",
".",
"pop",
"(",
"'estimator_names'",
",",
"[",
"'est_'",
"+",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"("... | 36.893617 | 0.000562 |
def _AddInitMethod(message_descriptor, cls):
"""Adds an __init__ method to cls."""
def _GetIntegerEnumValue(enum_type, value):
"""Convert a string or integer enum value to an integer.
If the value is a string, it is converted to the enum value in
enum_type with the same name. If the value is not a st... | [
"def",
"_AddInitMethod",
"(",
"message_descriptor",
",",
"cls",
")",
":",
"def",
"_GetIntegerEnumValue",
"(",
"enum_type",
",",
"value",
")",
":",
"\"\"\"Convert a string or integer enum value to an integer.\n\n If the value is a string, it is converted to the enum value in\n e... | 39.231707 | 0.008793 |
def safe_path(path, replacement="_"):
"""
Replace unsafe path characters with underscores. Do NOT use this
with existing paths that cannot be modified, this to to help generate
new, clean paths.
Supports windows and *nix systems.
:param path: path as a string
:param replacement: character ... | [
"def",
"safe_path",
"(",
"path",
",",
"replacement",
"=",
"\"_\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"path must be a string\"",
")",
"if",
"os",
".",
"sep",
"not",
"in",
"path",
":",
"r... | 37.864865 | 0.000696 |
def rebuild(self, scene=None):
"""
This method is where you will rebuild the geometry and \
data for a node.
:param scene <QGraphicsScene> || None
:return <bool> success
"""
rect = QRectF(0, 0, self.minimumWidth(), self.minimumHeig... | [
"def",
"rebuild",
"(",
"self",
",",
"scene",
"=",
"None",
")",
":",
"rect",
"=",
"QRectF",
"(",
"0",
",",
"0",
",",
"self",
".",
"minimumWidth",
"(",
")",
",",
"self",
".",
"minimumHeight",
"(",
")",
")",
"self",
".",
"setRect",
"(",
"rect",
")",... | 29.857143 | 0.009281 |
def entities(self):
"""
Access the entities
:returns: twilio.rest.authy.v1.service.entity.EntityList
:rtype: twilio.rest.authy.v1.service.entity.EntityList
"""
if self._entities is None:
self._entities = EntityList(self._version, service_sid=self._solution['s... | [
"def",
"entities",
"(",
"self",
")",
":",
"if",
"self",
".",
"_entities",
"is",
"None",
":",
"self",
".",
"_entities",
"=",
"EntityList",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
")",
"r... | 34.8 | 0.008403 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self,
'customization_id') and self.customization_id is not None:
_dict['customization_id'] = self.customization_id
if hasattr(self, 'name') and self.name is no... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'customization_id'",
")",
"and",
"self",
".",
"customization_id",
"is",
"not",
"None",
":",
"_dict",
"[",
"'customization_id'",
"]",
"=",
"self",
".",
... | 51.333333 | 0.001821 |
def video_pos(self):
"""
Returns:
(int, int, int, int): Video spatial position (x1, y1, x2, y2) where (x1, y1) is top left,
and (x2, y2) is bottom right. All values in px.
"""
position_string = self._player_interface.VideoPos(ObjectPath('/not... | [
"def",
"video_pos",
"(",
"self",
")",
":",
"position_string",
"=",
"self",
".",
"_player_interface",
".",
"VideoPos",
"(",
"ObjectPath",
"(",
"'/not/used'",
")",
")",
"return",
"list",
"(",
"map",
"(",
"int",
",",
"position_string",
".",
"split",
"(",
"\" ... | 47.375 | 0.012953 |
def execute_insert_no_results(self, sock_info, run, op_id, acknowledged):
"""Execute insert, returning no results.
"""
command = SON([('insert', self.collection.name),
('ordered', self.ordered)])
concern = {'w': int(self.ordered)}
command['writeConcern'] = ... | [
"def",
"execute_insert_no_results",
"(",
"self",
",",
"sock_info",
",",
"run",
",",
"op_id",
",",
"acknowledged",
")",
":",
"command",
"=",
"SON",
"(",
"[",
"(",
"'insert'",
",",
"self",
".",
"collection",
".",
"name",
")",
",",
"(",
"'ordered'",
",",
... | 47.882353 | 0.00241 |
def save_file_data(self, path):
""" Implements the abstract method of the ExternalEditor class.
"""
try:
# just create file with empty text first; this command also creates the whole path to the file
filesystem.write_file(os.path.join(path, storage.SCRIPT_FILE), "", creat... | [
"def",
"save_file_data",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"# just create file with empty text first; this command also creates the whole path to the file",
"filesystem",
".",
"write_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"storage",
... | 65.181818 | 0.008253 |
async def get_deals(self, **params):
"""Receives all users deals
Accepts:
- buyer public key
"""
if params.get("message"):
params = json.loads(params.get("message", "{}"))
if not params:
return {"error":400, "reason":"Missed required fields"}
buyer = params.get("buyer")
if not buyer:
retur... | [
"async",
"def",
"get_deals",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"if",
"params",
".",
"get",
"(",
"\"message\"",
")",
":",
"params",
"=",
"json",
".",
"loads",
"(",
"params",
".",
"get",
"(",
"\"message\"",
",",
"\"{}\"",
")",
")",
"if"... | 27.291667 | 0.042773 |
def switch(self):
"""Switch to the hub.
This method pauses the current fiber and runs the event loop. The
caller should ensure that it has set up appropriate callbacks so that
it will get scheduled again, preferably using :class:`switch_back`. In
this case then return value of t... | [
"def",
"switch",
"(",
"self",
")",
":",
"if",
"self",
".",
"_loop",
"is",
"None",
"or",
"not",
"self",
".",
"is_alive",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'hub is closed/dead'",
")",
"elif",
"fibers",
".",
"current",
"(",
")",
"is",
"self",
... | 52.4 | 0.001874 |
def _agent_registration(self):
"""Register this agent with the server.
This method registers the cfg agent with the neutron server so hosting
devices can be assigned to it. In case the server is not ready to
accept registration (it sends a False) then we retry registration
for `... | [
"def",
"_agent_registration",
"(",
"self",
")",
":",
"for",
"attempts",
"in",
"range",
"(",
"MAX_REGISTRATION_ATTEMPTS",
")",
":",
"context",
"=",
"bc",
".",
"context",
".",
"get_admin_context_without_session",
"(",
")",
"self",
".",
"send_agent_report",
"(",
"s... | 52.864865 | 0.001004 |
def authorize(self, cidr_ip=None, ec2_group=None):
"""
Add a new rule to this DBSecurity group.
You need to pass in either a CIDR block to authorize or
and EC2 SecurityGroup.
@type cidr_ip: string
@param cidr_ip: A valid CIDR IP range to authorize
@type ec2_grou... | [
"def",
"authorize",
"(",
"self",
",",
"cidr_ip",
"=",
"None",
",",
"ec2_group",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"ec2_group",
",",
"SecurityGroup",
")",
":",
"group_name",
"=",
"ec2_group",
".",
"name",
"group_owner_id",
"=",
"ec2_group",
".... | 38 | 0.002139 |
def set_ghost_status(self, ghost_status):
"""
Sets ghost RAM status
:param ghost_status: state flag indicating status
0 => Do not use IOS ghosting
1 => This is a ghost instance
2 => Use an existing ghost instance
"""
yield from self._hypervisor.send('vm ... | [
"def",
"set_ghost_status",
"(",
"self",
",",
"ghost_status",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm set_ghost_status \"{name}\" {ghost_status}'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"_name",
",",
"ghost_status",
"... | 49.823529 | 0.008111 |
def parse(self, character_page):
"""Parses the DOM and returns character attributes in the main-content area.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL character page's DOM
:rtype: dict
:return: Character attributes.
"""
character_info = self.parse_sideba... | [
"def",
"parse",
"(",
"self",
",",
"character_page",
")",
":",
"character_info",
"=",
"self",
".",
"parse_sidebar",
"(",
"character_page",
")",
"second_col",
"=",
"character_page",
".",
"find",
"(",
"u'div'",
",",
"{",
"'id'",
":",
"'content'",
"}",
")",
".... | 34.153846 | 0.014448 |
def _thread_main(self):
"""The entry point for the worker thread.
Pulls pending log entries off the queue and writes them in batches to
the Cloud Logger.
"""
_LOGGER.debug("Background thread started.")
quit_ = False
while True:
batch = self._cloud_lo... | [
"def",
"_thread_main",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Background thread started.\"",
")",
"quit_",
"=",
"False",
"while",
"True",
":",
"batch",
"=",
"self",
".",
"_cloud_logger",
".",
"batch",
"(",
")",
"items",
"=",
"_get_many",
"... | 30 | 0.001899 |
def get_nonzero_random_bytes(length, rnd=default_crypto_random):
'''
Accumulate random bit string and remove \0 bytes until the needed length
is obtained.
'''
result = []
i = 0
while i < length:
rnd = rnd.getrandbits(12*length)
s = i2osp(rnd, 3*length)
s = s.rep... | [
"def",
"get_nonzero_random_bytes",
"(",
"length",
",",
"rnd",
"=",
"default_crypto_random",
")",
":",
"result",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"length",
":",
"rnd",
"=",
"rnd",
".",
"getrandbits",
"(",
"12",
"*",
"length",
")",
"s",
... | 29 | 0.002387 |
def is_first_instance_k8s(current_pod_name=None):
"""
Returns True if the current pod is the first replica in Kubernetes cluster.
"""
current_pod_name = current_pod_name or os.environ.get('POD_NAME')
if not current_pod_name:
raise StackInterrogationException('Pod name not known')
namesp... | [
"def",
"is_first_instance_k8s",
"(",
"current_pod_name",
"=",
"None",
")",
":",
"current_pod_name",
"=",
"current_pod_name",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"'POD_NAME'",
")",
"if",
"not",
"current_pod_name",
":",
"raise",
"StackInterrogationException",... | 39.956522 | 0.002125 |
def start(self):
"""
Starts the session.
Starting the session will actually get the API key of the current user
"""
if NURESTSession.session_stack:
bambou_logger.critical("Starting a session inside a with statement is not supported.")
raise Excep... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"NURESTSession",
".",
"session_stack",
":",
"bambou_logger",
".",
"critical",
"(",
"\"Starting a session inside a with statement is not supported.\"",
")",
"raise",
"Exception",
"(",
"\"Starting a session inside a with statement is... | 31.333333 | 0.010331 |
def add_beacon(self, name, beacon_data):
'''
Add a beacon item
'''
data = {}
data[name] = beacon_data
if name in self._get_beacons(include_opts=False):
comment = 'Cannot update beacon item {0}, ' \
'because it is configured in pillar.'.... | [
"def",
"add_beacon",
"(",
"self",
",",
"name",
",",
"beacon_data",
")",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"name",
"]",
"=",
"beacon_data",
"if",
"name",
"in",
"self",
".",
"_get_beacons",
"(",
"include_opts",
"=",
"False",
")",
":",
"comment",
... | 36.464286 | 0.001908 |
def run_scan_command(
self,
server_info: ServerConnectivityInfo,
scan_command: PluginScanCommand
) -> PluginScanResult:
"""Run a single scan command against a server; will block until the scan command has been completed.
Args:
server_info: The server'... | [
"def",
"run_scan_command",
"(",
"self",
",",
"server_info",
":",
"ServerConnectivityInfo",
",",
"scan_command",
":",
"PluginScanCommand",
")",
"->",
"PluginScanResult",
":",
"plugin_class",
"=",
"self",
".",
"_plugins_repository",
".",
"get_plugin_class_for_command",
"(... | 47.210526 | 0.008743 |
def init_board(self):
"""Init a valid board by given settings.
Parameters
----------
mine_map : numpy.ndarray
the map that defines the mine
0 is empty, 1 is mine
info_map : numpy.ndarray
the map that presents to gamer
0-8 is number... | [
"def",
"init_board",
"(",
"self",
")",
":",
"self",
".",
"mine_map",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"board_height",
",",
"self",
".",
"board_width",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"idx_list",
"=",
"np",
".",
"rand... | 34.586207 | 0.00194 |
def mime_type(self, category=None):
"""
:param category: application|audio|image|message|model|multipart|text|video
"""
category = category if category else self.random_element(
list(self.mime_types.keys()))
return self.random_element(self.mime_types[category]) | [
"def",
"mime_type",
"(",
"self",
",",
"category",
"=",
"None",
")",
":",
"category",
"=",
"category",
"if",
"category",
"else",
"self",
".",
"random_element",
"(",
"list",
"(",
"self",
".",
"mime_types",
".",
"keys",
"(",
")",
")",
")",
"return",
"self... | 43.857143 | 0.009585 |
def should_update(stack):
"""Tests whether a stack should be submitted for updates to CF.
Args:
stack (:class:`stacker.stack.Stack`): The stack object to check.
Returns:
bool: If the stack should be updated, return True.
"""
if stack.locked:
if not stack.force:
... | [
"def",
"should_update",
"(",
"stack",
")",
":",
"if",
"stack",
".",
"locked",
":",
"if",
"not",
"stack",
".",
"force",
":",
"logger",
".",
"debug",
"(",
"\"Stack %s locked and not in --force list. \"",
"\"Refusing to update.\"",
",",
"stack",
".",
"name",
")",
... | 30.684211 | 0.001664 |
def get_item(self, **kwargs):
""" Reload context on each access. """
self.reload_context(es_based=False, **kwargs)
return super(ItemSubresourceBaseView, self).get_item(**kwargs) | [
"def",
"get_item",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"reload_context",
"(",
"es_based",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"return",
"super",
"(",
"ItemSubresourceBaseView",
",",
"self",
")",
".",
"get_item",
"(",
"*... | 49.5 | 0.00995 |
def loggable(obj):
"""Return "True" if the obj implements the minimum Logger API
required by the 'trace' decorator.
"""
if isinstance(obj, logging.Logger):
return True
else:
return (inspect.isclass(obj)
and inspect.ismethod(getattr(obj, 'debug', None))
... | [
"def",
"loggable",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"logging",
".",
"Logger",
")",
":",
"return",
"True",
"else",
":",
"return",
"(",
"inspect",
".",
"isclass",
"(",
"obj",
")",
"and",
"inspect",
".",
"ismethod",
"(",
"getat... | 39.727273 | 0.002237 |
def silhouette_score(self, data, metric='euclidean', sample_size=None, random_state=None, **kwds):
"""
Computes the mean Silhouette Coefficient of all samples (implicit evaluation)
:param data: The data that the clusters are generated from
:param metric: the pairwise distance metric
... | [
"def",
"silhouette_score",
"(",
"self",
",",
"data",
",",
"metric",
"=",
"'euclidean'",
",",
"sample_size",
"=",
"None",
",",
"random_state",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"silhouette_score",
"(",
"data",
",",
"self",
".",
"get_... | 63.25 | 0.01039 |
def register(self, schema):
"""Register input schema class.
When registering a schema, all inner schemas are registered as well.
:param Schema schema: schema to register.
:return: old registered schema.
:rtype: type
"""
result = None
uuid = schema.uuid
... | [
"def",
"register",
"(",
"self",
",",
"schema",
")",
":",
"result",
"=",
"None",
"uuid",
"=",
"schema",
".",
"uuid",
"if",
"uuid",
"in",
"self",
".",
"_schbyuuid",
":",
"result",
"=",
"self",
".",
"_schbyuuid",
"[",
"uuid",
"]",
"if",
"result",
"!=",
... | 24.09375 | 0.002494 |
def build_header(
filename, disposition='attachment', filename_compat=None
):
"""Generate a Content-Disposition header for a given filename.
For legacy clients that don't understand the filename* parameter,
a filename_compat value may be given.
It should either be ascii-only (recommended) or iso-88... | [
"def",
"build_header",
"(",
"filename",
",",
"disposition",
"=",
"'attachment'",
",",
"filename_compat",
"=",
"None",
")",
":",
"# While this method exists, it could also sanitize the filename",
"# by rejecting slashes or other weirdness that might upset a receiver.",
"if",
"dispos... | 39.375 | 0.000442 |
def correct(self, text: str, srctext=None) -> str:
"""Automatically apply suggestions to the text."""
return correct(text, self.check(text, srctext)) | [
"def",
"correct",
"(",
"self",
",",
"text",
":",
"str",
",",
"srctext",
"=",
"None",
")",
"->",
"str",
":",
"return",
"correct",
"(",
"text",
",",
"self",
".",
"check",
"(",
"text",
",",
"srctext",
")",
")"
] | 54.333333 | 0.012121 |
def build_geometry_by_shape(
feed: "Feed",
shape_ids: Optional[List[str]] = None,
*,
use_utm: bool = False,
) -> Dict:
"""
Return a dictionary with structure shape_id -> Shapely LineString
of shape.
Parameters
----------
feed : Feed
shape_ids : list
IDs of shapes in ... | [
"def",
"build_geometry_by_shape",
"(",
"feed",
":",
"\"Feed\"",
",",
"shape_ids",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"*",
",",
"use_utm",
":",
"bool",
"=",
"False",
",",
")",
"->",
"Dict",
":",
"if",
"feed",
".",
... | 28.701754 | 0.000591 |
def urlencode(data):
"""A version of `urllib.urlencode` that isn't insane.
This only cares that `data` is an iterable of iterables. Each sub-iterable
must be of overall length 2, i.e. a name/value pair.
Unicode strings will be encoded to UTF-8. This is what Django expects; see
`smart_text` in the ... | [
"def",
"urlencode",
"(",
"data",
")",
":",
"def",
"dec",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"bytes",
")",
":",
"string",
"=",
"string",
".",
"decode",
"(",
"\"utf-8\"",
")",
"return",
"quote_plus",
"(",
"string",
")",
"r... | 33.352941 | 0.001715 |
def purge (self,
strategy = "klogn",
keep = None,
deleteNonSnapshots = False,
**kwargs):
"""Purge snapshot directory of snapshots according to some strategy,
preserving ... | [
"def",
"purge",
"(",
"self",
",",
"strategy",
"=",
"\"klogn\"",
",",
"keep",
"=",
"None",
",",
"deleteNonSnapshots",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"(",
"isinstance",
"(",
"keep",
",",
"(",
"list",
",",
"set",
")",
")",
... | 38.891892 | 0.046102 |
def createMCMC(config,srcfile,section='source',samples=None):
""" Create an MCMC instance """
source = ugali.analysis.source.Source()
source.load(srcfile,section=section)
loglike = ugali.analysis.loglike.createLoglike(config,source)
mcmc = MCMC(config,loglike)
if samples is not None:
m... | [
"def",
"createMCMC",
"(",
"config",
",",
"srcfile",
",",
"section",
"=",
"'source'",
",",
"samples",
"=",
"None",
")",
":",
"source",
"=",
"ugali",
".",
"analysis",
".",
"source",
".",
"Source",
"(",
")",
"source",
".",
"load",
"(",
"srcfile",
",",
"... | 29.25 | 0.019337 |
def _parse_frange_part(frange):
"""
Internal method: parse a discrete frame range part.
Args:
frange (str): single part of a frame range as a string
(ie "1-100x5")
Returns:
tuple: (start, end, modifier, chunk)
Raises:
:class:... | [
"def",
"_parse_frange_part",
"(",
"frange",
")",
":",
"match",
"=",
"FRANGE_RE",
".",
"match",
"(",
"frange",
")",
"if",
"not",
"match",
":",
"msg",
"=",
"'Could not parse \"{0}\": did not match {1}'",
"raise",
"ParseException",
"(",
"msg",
".",
"format",
"(",
... | 35.575758 | 0.001658 |
def pick_trust_for_twisted(netloc, possible):
"""
Pick the right "trust roots" (certificate authority certificates) for the
given server and return it in the form Twisted wants.
Kubernetes certificates are often self-signed or otherwise exist outside
of the typical certificate authority cartel syst... | [
"def",
"pick_trust_for_twisted",
"(",
"netloc",
",",
"possible",
")",
":",
"try",
":",
"trust_cert",
"=",
"possible",
"[",
"netloc",
"]",
"except",
"KeyError",
":",
"return",
"None",
"cert",
"=",
"ssl",
".",
"Certificate",
".",
"load",
"(",
"trust_cert",
"... | 40.875 | 0.000996 |
def approve(ctx, _spender='address', _value='uint256', returns=STATUS):
""" Standardized Contract API:
function approve(address _spender, uint256 _value) returns (bool success)
"""
ctx.allowances[ctx.msg_sender][_spender] += _value
ctx.Approval(ctx.msg_sender, _spender, _value)
... | [
"def",
"approve",
"(",
"ctx",
",",
"_spender",
"=",
"'address'",
",",
"_value",
"=",
"'uint256'",
",",
"returns",
"=",
"STATUS",
")",
":",
"ctx",
".",
"allowances",
"[",
"ctx",
".",
"msg_sender",
"]",
"[",
"_spender",
"]",
"+=",
"_value",
"ctx",
".",
... | 47.142857 | 0.008929 |
def __write_text(self, outfile):
"""
Write text information into file
This method should be called only from ``write_idat`` method
or chunk order will be ruined.
"""
for k, v in self.text.items():
if not isinstance(v, bytes):
try:
... | [
"def",
"__write_text",
"(",
"self",
",",
"outfile",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"text",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"bytes",
")",
":",
"try",
":",
"international",
"=",
"False",
"v... | 37.423077 | 0.002004 |
def rebalance(self):
"""The genetic rebalancing algorithm runs for a fixed number of
generations. Each generation has two phases: exploration and pruning.
In exploration, a large set of possible states are found by randomly
applying assignment changes to the existing states. In pruning, ... | [
"def",
"rebalance",
"(",
"self",
")",
":",
"if",
"self",
".",
"args",
".",
"num_gens",
"<",
"self",
".",
"args",
".",
"max_partition_movements",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"num-gens ({num_gens}) is less than max-partition-movements\"",
"\" ({m... | 42.134831 | 0.001042 |
def get_url_directory_string(url):
"""
Determines the url's directory string.
:param str url: the url to extract the directory string from
:return str: the directory string on the server
"""
domain = UrlExtractor.get_allowed_domain(url)
splitted_url = url.split(... | [
"def",
"get_url_directory_string",
"(",
"url",
")",
":",
"domain",
"=",
"UrlExtractor",
".",
"get_allowed_domain",
"(",
"url",
")",
"splitted_url",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"# the following commented list comprehension could replace",
"# the following ... | 38.708333 | 0.002101 |
def get_cached_parent_for_taxon(self, child_taxon):
"""If the taxa are being cached, this call will create a the lineage "spike" for taxon child_taxon
Expecting child_taxon to have a non-empty _taxonomic_lineage with response dicts that can create
an ancestral TaxonWrapper.
"""
... | [
"def",
"get_cached_parent_for_taxon",
"(",
"self",
",",
"child_taxon",
")",
":",
"if",
"self",
".",
"_ott_id2taxon",
"is",
"None",
":",
"resp",
"=",
"child_taxon",
".",
"_taxonomic_lineage",
"[",
"0",
"]",
"tl",
"=",
"child_taxon",
".",
"_taxonomic_lineage",
"... | 47.545455 | 0.002498 |
def send(self, email, body):
"""Send email."""
print('Connecting server {0}:{1} with {2}:{3}'.format(
self._host, self._port, self._login, self._password))
print('Sending "{0}" to "{1}"'.format(body, email)) | [
"def",
"send",
"(",
"self",
",",
"email",
",",
"body",
")",
":",
"print",
"(",
"'Connecting server {0}:{1} with {2}:{3}'",
".",
"format",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_port",
",",
"self",
".",
"_login",
",",
"self",
".",
"_password",
")"... | 47.8 | 0.00823 |
def process_mgi_relationship_transgene_genes(self, limit=None):
"""
Here, we have the relationship between MGI transgene alleles,
and the non-mouse gene ids that are part of them.
We augment the allele with the transgene parts.
:param limit:
:return:
"""
... | [
"def",
"process_mgi_relationship_transgene_genes",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"if",
"self",
".",
"test_mode",
":",
"graph",
"=",
"self",
".",
"testgraph",
"else",
":",
"graph",
"=",
"self",
".",
"graph",
"LOG",
".",
"info",
"(",
"\... | 38.333333 | 0.002355 |
def get_curve_name(self, ecdh=False):
"""Return correct curve name for device operations."""
if ecdh:
return formats.get_ecdh_curve_name(self.curve_name)
else:
return self.curve_name | [
"def",
"get_curve_name",
"(",
"self",
",",
"ecdh",
"=",
"False",
")",
":",
"if",
"ecdh",
":",
"return",
"formats",
".",
"get_ecdh_curve_name",
"(",
"self",
".",
"curve_name",
")",
"else",
":",
"return",
"self",
".",
"curve_name"
] | 37.5 | 0.008696 |
def setdefault (self, key, def_val=None):
"""Update key usage if found and return value, else set and return
default."""
if key in self:
return self[key]
self[key] = def_val
return def_val | [
"def",
"setdefault",
"(",
"self",
",",
"key",
",",
"def_val",
"=",
"None",
")",
":",
"if",
"key",
"in",
"self",
":",
"return",
"self",
"[",
"key",
"]",
"self",
"[",
"key",
"]",
"=",
"def_val",
"return",
"def_val"
] | 33.428571 | 0.0125 |
def managed(name,
value=None,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Manage a memcached key.
name
The key to manage
value
The value to set for that key
hos... | [
"def",
"managed",
"(",
"name",
",",
"value",
"=",
"None",
",",
"host",
"=",
"DEFAULT_HOST",
",",
"port",
"=",
"DEFAULT_PORT",
",",
"time",
"=",
"DEFAULT_TIME",
",",
"min_compress_len",
"=",
"DEFAULT_MIN_COMPRESS_LEN",
")",
":",
"ret",
"=",
"{",
"'name'",
"... | 25.867647 | 0.001095 |
def setattr(self, name, value):
# type: (Any, Any, Any) -> Any
'''Takes an object, a string, and a value and produces a new object
that is a copy of the original but with the attribute called ``name``
set to ``value``.
The following equality should hold for your definition:
.. code-block:: pyt... | [
"def",
"setattr",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"# type: (Any, Any, Any) -> Any",
"try",
":",
"self",
".",
"_lens_setattr",
"except",
"AttributeError",
":",
"selfcopy",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"builtin_setattr",
"(",
"... | 36.057143 | 0.000772 |
def starmap(source, func, ordered=True, task_limit=None):
"""Apply a given function to the unpacked elements of
an asynchronous sequence.
Each element is unpacked before applying the function.
The given function can either be synchronous or asynchronous.
The results can either be returned in or ou... | [
"def",
"starmap",
"(",
"source",
",",
"func",
",",
"ordered",
"=",
"True",
",",
"task_limit",
"=",
"None",
")",
":",
"if",
"asyncio",
".",
"iscoroutinefunction",
"(",
"func",
")",
":",
"async",
"def",
"starfunc",
"(",
"args",
")",
":",
"return",
"await... | 41.26087 | 0.00103 |
def as_issue(self):
"""
:calls: `GET /repos/:owner/:repo/issues/:number <http://developer.github.com/v3/issues>`_
:rtype: :class:`github.Issue.Issue`
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.issue_url
)
return gi... | [
"def",
"as_issue",
"(",
"self",
")",
":",
"headers",
",",
"data",
"=",
"self",
".",
"_requester",
".",
"requestJsonAndCheck",
"(",
"\"GET\"",
",",
"self",
".",
"issue_url",
")",
"return",
"github",
".",
"Issue",
".",
"Issue",
"(",
"self",
".",
"_requeste... | 37.5 | 0.010417 |
def getSizeFromPage(rh, page):
"""
Convert a size value from page to a number with a magnitude appended.
Input:
Request Handle
Size in page
Output:
Converted value with a magnitude
"""
rh.printSysLog("Enter generalUtils.getSizeFromPage")
bSize = float(page) * 4096
... | [
"def",
"getSizeFromPage",
"(",
"rh",
",",
"page",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter generalUtils.getSizeFromPage\"",
")",
"bSize",
"=",
"float",
"(",
"page",
")",
"*",
"4096",
"mSize",
"=",
"cvtToMag",
"(",
"rh",
",",
"bSize",
")",
"rh",
... | 23.555556 | 0.002268 |
def change_size_for_active_pane(self, up=0, right=0, down=0, left=0):
"""
Increase the size of the current pane in any of the four directions.
"""
child = self.active_pane
self.change_size_for_pane(child, up=up, right=right, down=down, left=left) | [
"def",
"change_size_for_active_pane",
"(",
"self",
",",
"up",
"=",
"0",
",",
"right",
"=",
"0",
",",
"down",
"=",
"0",
",",
"left",
"=",
"0",
")",
":",
"child",
"=",
"self",
".",
"active_pane",
"self",
".",
"change_size_for_pane",
"(",
"child",
",",
... | 46.833333 | 0.01049 |
def verify_password(password, password_hash):
"""Returns ``True`` if the password matches the supplied hash.
:param password: A plaintext password to verify
:param password_hash: The expected hash value of the password
(usually from your database)
"""
if use_double_hash(pa... | [
"def",
"verify_password",
"(",
"password",
",",
"password_hash",
")",
":",
"if",
"use_double_hash",
"(",
"password_hash",
")",
":",
"password",
"=",
"get_hmac",
"(",
"password",
")",
"return",
"_pwd_context",
".",
"verify",
"(",
"password",
",",
"password_hash",... | 38 | 0.002336 |
def v1_folder_list(request, kvlclient):
'''Retrieves a list of folders for the current user.
The route for this endpoint is: ``GET /dossier/v1/folder``.
(Temporarily, the "current user" can be set via the
``annotator_id`` query parameter.)
The payload returned is a list of folder identifiers.
... | [
"def",
"v1_folder_list",
"(",
"request",
",",
"kvlclient",
")",
":",
"return",
"sorted",
"(",
"imap",
"(",
"attrgetter",
"(",
"'name'",
")",
",",
"ifilter",
"(",
"lambda",
"it",
":",
"it",
".",
"is_folder",
"(",
")",
",",
"new_folders",
"(",
"kvlclient",... | 37.615385 | 0.001996 |
def inverse(self, rhov, time_derivative=False):
r"""Fold a vector into a matrix.
The input of this function can be a numpy array or a sympy Matrix.
If the input is understood to represent the time derivative of a
density matrix, then the flag time_derivative must be set to True.
... | [
"def",
"inverse",
"(",
"self",
",",
"rhov",
",",
"time_derivative",
"=",
"False",
")",
":",
"Ne",
"=",
"self",
".",
"Ne",
"Nrho",
"=",
"self",
".",
"Nrho",
"IJ",
"=",
"self",
".",
"IJ",
"if",
"isinstance",
"(",
"rhov",
",",
"np",
".",
"ndarray",
... | 32.666667 | 0.000825 |
def rta_len(self, value):
"""Length setter."""
self.bytearray[self._get_slicers(0)] = bytearray(c_ushort(value or 0)) | [
"def",
"rta_len",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"bytearray",
"[",
"self",
".",
"_get_slicers",
"(",
"0",
")",
"]",
"=",
"bytearray",
"(",
"c_ushort",
"(",
"value",
"or",
"0",
")",
")"
] | 43.666667 | 0.015038 |
def _lits(lexer, varname, nvars):
"""Return a tuple of DIMACS CNF clause literals."""
tok = _expect_token(lexer, {OP_not, IntegerToken})
if isinstance(tok, IntegerToken) and tok.value == 0:
return tuple()
else:
if isinstance(tok, OP_not):
neg = True
tok = _expect_... | [
"def",
"_lits",
"(",
"lexer",
",",
"varname",
",",
"nvars",
")",
":",
"tok",
"=",
"_expect_token",
"(",
"lexer",
",",
"{",
"OP_not",
",",
"IntegerToken",
"}",
")",
"if",
"isinstance",
"(",
"tok",
",",
"IntegerToken",
")",
"and",
"tok",
".",
"value",
... | 30.772727 | 0.001433 |
def calibrate(self, counts, calibration, channel):
"""Perform calibration"""
# Convert 16bit counts from netCDF4 file to the original 10bit
# GVAR counts by dividing by 32. See [FAQ].
counts = counts / 32.
coefs = CALIB_COEFS[self.platform_name][channel]
if calibration =... | [
"def",
"calibrate",
"(",
"self",
",",
"counts",
",",
"calibration",
",",
"channel",
")",
":",
"# Convert 16bit counts from netCDF4 file to the original 10bit",
"# GVAR counts by dividing by 32. See [FAQ].",
"counts",
"=",
"counts",
"/",
"32.",
"coefs",
"=",
"CALIB_COEFS",
... | 45.285714 | 0.00206 |
def write_to_socket(self, frame_data):
"""Write data to the socket.
:param str frame_data:
:return:
"""
self._wr_lock.acquire()
try:
total_bytes_written = 0
bytes_to_send = len(frame_data)
while total_bytes_written < bytes_to_send:
... | [
"def",
"write_to_socket",
"(",
"self",
",",
"frame_data",
")",
":",
"self",
".",
"_wr_lock",
".",
"acquire",
"(",
")",
"try",
":",
"total_bytes_written",
"=",
"0",
"bytes_to_send",
"=",
"len",
"(",
"frame_data",
")",
"while",
"total_bytes_written",
"<",
"byt... | 37.103448 | 0.001812 |
def printPi(self):
"""
Prints all states state and their steady state probabilities.
Not recommended for large state spaces.
"""
assert self.pi is not None, "Calculate pi before calling printPi()"
assert len(self.mapping)>0, "printPi() can only be used in combination with... | [
"def",
"printPi",
"(",
"self",
")",
":",
"assert",
"self",
".",
"pi",
"is",
"not",
"None",
",",
"\"Calculate pi before calling printPi()\"",
"assert",
"len",
"(",
"self",
".",
"mapping",
")",
">",
"0",
",",
"\"printPi() can only be used in combination with the direc... | 53.888889 | 0.014199 |
def commit(filename):
"""Commit (git) a specified file
This method does the same than a ::
$ git commit -a "message"
Keyword Arguments:
:filename: (str) -- name of the file to commit
Returns:
<nothing>
"""
try:
repo = Repo()
# gitcmd = repo.git
... | [
"def",
"commit",
"(",
"filename",
")",
":",
"try",
":",
"repo",
"=",
"Repo",
"(",
")",
"# gitcmd = repo.git",
"# gitcmd.commit(filename)",
"index",
"=",
"repo",
".",
"index",
"index",
".",
"commit",
"(",
"\"Updated file: {0}\"",
".",
"format",
"(",
"filename",... | 23.571429 | 0.001942 |
def extract_ngram_filter(pos_seq, regex=SimpleNP, minlen=1, maxlen=8):
"""The "FilterFSA" method in Handler et al. 2016.
Returns token position spans of valid ngrams."""
ss = coarse_tag_str(pos_seq)
def gen():
for s in xrange(len(ss)):
for n in xrange(minlen, 1 + min(maxlen, len(ss) - s)):
e = s + n
s... | [
"def",
"extract_ngram_filter",
"(",
"pos_seq",
",",
"regex",
"=",
"SimpleNP",
",",
"minlen",
"=",
"1",
",",
"maxlen",
"=",
"8",
")",
":",
"ss",
"=",
"coarse_tag_str",
"(",
"pos_seq",
")",
"def",
"gen",
"(",
")",
":",
"for",
"s",
"in",
"xrange",
"(",
... | 28.5 | 0.029126 |
def create_services_from_endpoint(url, catalog, greedy_opt=True):
"""
Generate service/services from an endpoint.
WMS, WMTS, TMS endpoints correspond to a single service.
ESRI, CSW endpoints corrispond to many services.
:return: imported, message
"""
# this variable will collect any excepti... | [
"def",
"create_services_from_endpoint",
"(",
"url",
",",
"catalog",
",",
"greedy_opt",
"=",
"True",
")",
":",
"# this variable will collect any exception message during the routine.",
"# will be used in the last step to send a message if \"detected\" var is False.",
"messages",
"=",
... | 39.46371 | 0.001993 |
def start_namespace(self, prefix, uri):
""" Declare a namespace prefix
Use prefix=None to set the default namespace.
"""
self._g.startPrefixMapping(prefix, uri)
self._ns[prefix] = uri | [
"def",
"start_namespace",
"(",
"self",
",",
"prefix",
",",
"uri",
")",
":",
"self",
".",
"_g",
".",
"startPrefixMapping",
"(",
"prefix",
",",
"uri",
")",
"self",
".",
"_ns",
"[",
"prefix",
"]",
"=",
"uri"
] | 31.142857 | 0.008929 |
def serialiseString(self, s):
"""
Similar to L{writeString} but does not encode a type byte.
"""
if type(s) is unicode:
s = self.context.getBytesForString(s)
l = len(s)
if l > 0xffff:
self.stream.write_ulong(l)
else:
self.stre... | [
"def",
"serialiseString",
"(",
"self",
",",
"s",
")",
":",
"if",
"type",
"(",
"s",
")",
"is",
"unicode",
":",
"s",
"=",
"self",
".",
"context",
".",
"getBytesForString",
"(",
"s",
")",
"l",
"=",
"len",
"(",
"s",
")",
"if",
"l",
">",
"0xffff",
"... | 23.6 | 0.008152 |
def rmtree_errorhandler(func, path, exc_info):
"""On Windows, the files in .svn are read-only, so when rmtree() tries to
remove them, an exception is thrown. We catch that here, remove the
read-only attribute, and hopefully continue without problems."""
exctype, value = exc_info[:2]
# On Python 2.4... | [
"def",
"rmtree_errorhandler",
"(",
"func",
",",
"path",
",",
"exc_info",
")",
":",
"exctype",
",",
"value",
"=",
"exc_info",
"[",
":",
"2",
"]",
"# On Python 2.4, it will be OSError number 13",
"# On all more recent Pythons, it'll be WindowsError number 5",
"if",
"not",
... | 46.705882 | 0.001235 |
def check_cousins(self, individual_1_id, individual_2_id):
"""
Check if two family members are cousins.
If two individuals share any grandparents they are cousins.
Arguments:
individual_1_id (str): The id of an individual
individual_2_id (str): ... | [
"def",
"check_cousins",
"(",
"self",
",",
"individual_1_id",
",",
"individual_2_id",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Checking if {0} and {1} are cousins\"",
".",
"format",
"(",
"individual_1_id",
",",
"individual_2_id",
")",
")",
"#TODO check ... | 32.380952 | 0.014286 |
def use_comparative_book_view(self):
"""Pass through to provider CommentBookSession.use_comparative_book_view"""
self._book_view = COMPARATIVE
# self._get_provider_session('comment_book_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
... | [
"def",
"use_comparative_book_view",
"(",
"self",
")",
":",
"self",
".",
"_book_view",
"=",
"COMPARATIVE",
"# self._get_provider_session('comment_book_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessions",
"(",
")",
":"... | 47.555556 | 0.009174 |
def process_string(self,string):
'''Searches the string (or list of strings) for an action word (a :class:`Concept` that has and ``action`` attached
to it), then calls the appropriate function with a dictionary of the identified words (according to ``vocab``).
For examples, see ``demo.p... | [
"def",
"process_string",
"(",
"self",
",",
"string",
")",
":",
"item_list",
"=",
"self",
".",
"parse_string",
"(",
"string",
")",
"for",
"item",
"in",
"item_list",
":",
"if",
"len",
"(",
"item",
")",
">",
"0",
"and",
"'concept'",
"in",
"dir",
"(",
"i... | 57.5 | 0.013699 |
def from_mime(cls, message, manager):
"""
Instantiates ``Email`` instance from ``MIMEText`` instance.
:param message: ``email.mime.text.MIMEText`` instance.
:param manager: :py:class:`EmailManager` instance.
:return: :py:class:`Email`
"""
text, html, attachments ... | [
"def",
"from_mime",
"(",
"cls",
",",
"message",
",",
"manager",
")",
":",
"text",
",",
"html",
",",
"attachments",
"=",
"deconstruct_multipart",
"(",
"message",
")",
"subject",
"=",
"prepare_header",
"(",
"message",
"[",
"\"Subject\"",
"]",
")",
"sender",
... | 33.448276 | 0.002004 |
def export_complex_gateway_info(node_params, output_element):
"""
Adds ComplexGateway node attributes to exported XML element
:param node_params: dictionary with given complex gateway parameters,
:param output_element: object representing BPMN XML 'complexGateway' element.
"""
... | [
"def",
"export_complex_gateway_info",
"(",
"node_params",
",",
"output_element",
")",
":",
"output_element",
".",
"set",
"(",
"consts",
".",
"Consts",
".",
"gateway_direction",
",",
"node_params",
"[",
"consts",
".",
"Consts",
".",
"gateway_direction",
"]",
")",
... | 60.5 | 0.009772 |
def make_conditional(
self, request_or_environ, accept_ranges=False, complete_length=None
):
"""Make the response conditional to the request. This method works
best if an etag was defined for the response already. The `add_etag`
method can be used to do that. If called without eta... | [
"def",
"make_conditional",
"(",
"self",
",",
"request_or_environ",
",",
"accept_ranges",
"=",
"False",
",",
"complete_length",
"=",
"None",
")",
":",
"environ",
"=",
"_get_environ",
"(",
"request_or_environ",
")",
"if",
"environ",
"[",
"\"REQUEST_METHOD\"",
"]",
... | 51.014925 | 0.001435 |
def compute_correction_factors(data, true_conductivity, elem_file, elec_file):
"""Compute correction factors for 2D rhizotron geometries, following
Weigand and Kemna, 2017, Biogeosciences
https://doi.org/10.5194/bg-14-921-2017
Parameters
----------
data : :py:class:`pandas.DataFrame`
m... | [
"def",
"compute_correction_factors",
"(",
"data",
",",
"true_conductivity",
",",
"elem_file",
",",
"elec_file",
")",
":",
"settings",
"=",
"{",
"'rho'",
":",
"100",
",",
"'pha'",
":",
"0",
",",
"'elem'",
":",
"'elem.dat'",
",",
"'elec'",
":",
"'elec.dat'",
... | 26.960784 | 0.000702 |
def quaternion_slerp(a, b, t):
"""Spherical linear interpolation for unit quaternions.
This is based on the implementation in the gl-matrix package:
https://github.com/toji/gl-matrix
"""
if a is None:
a = unit_quaternion()
if b is None:
b = unit_quaternion()
# calc cosine
... | [
"def",
"quaternion_slerp",
"(",
"a",
",",
"b",
",",
"t",
")",
":",
"if",
"a",
"is",
"None",
":",
"a",
"=",
"unit_quaternion",
"(",
")",
"if",
"b",
"is",
"None",
":",
"b",
"=",
"unit_quaternion",
"(",
")",
"# calc cosine",
"cosom",
"=",
"np",
".",
... | 28.533333 | 0.00113 |
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if m.get_type() == 'SERIAL_CONTROL':
data = m.data[:m.count]
s = ''.join(str(chr(x)) for x in data)
sys.stdout.write(s) | [
"def",
"mavlink_packet",
"(",
"self",
",",
"m",
")",
":",
"if",
"m",
".",
"get_type",
"(",
")",
"==",
"'SERIAL_CONTROL'",
":",
"data",
"=",
"m",
".",
"data",
"[",
":",
"m",
".",
"count",
"]",
"s",
"=",
"''",
".",
"join",
"(",
"str",
"(",
"chr",... | 39.166667 | 0.008333 |
def run(self, input_func=_stdin_):
"""Run the sections."""
# reset question count
self.qcount = 1
for section_name in self.survey:
self.run_section(section_name, input_func) | [
"def",
"run",
"(",
"self",
",",
"input_func",
"=",
"_stdin_",
")",
":",
"# reset question count",
"self",
".",
"qcount",
"=",
"1",
"for",
"section_name",
"in",
"self",
".",
"survey",
":",
"self",
".",
"run_section",
"(",
"section_name",
",",
"input_func",
... | 35.333333 | 0.009217 |
def is_timeout(self):
'''
Check if the lapse between initialization and now is more than ``self.timeout``.
'''
lapse = datetime.datetime.now() - self.init_time
return lapse > datetime.timedelta(seconds=self.timeout) | [
"def",
"is_timeout",
"(",
"self",
")",
":",
"lapse",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"init_time",
"return",
"lapse",
">",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"timeout",
")"
] | 41.666667 | 0.011765 |
def newsnr(snr, reduced_x2, q=6., n=2.):
"""Calculate the re-weighted SNR statistic ('newSNR') from given SNR and
reduced chi-squared values. See http://arxiv.org/abs/1208.3491 for
definition. Previous implementation in glue/ligolw/lsctables.py
"""
nsnr = numpy.array(snr, ndmin=1, dtype=numpy.float6... | [
"def",
"newsnr",
"(",
"snr",
",",
"reduced_x2",
",",
"q",
"=",
"6.",
",",
"n",
"=",
"2.",
")",
":",
"nsnr",
"=",
"numpy",
".",
"array",
"(",
"snr",
",",
"ndmin",
"=",
"1",
",",
"dtype",
"=",
"numpy",
".",
"float64",
")",
"reduced_x2",
"=",
"num... | 41.764706 | 0.001377 |
def uninstall(**kwargs):
"""Uninstall the current pre-commit hook."""
force = kwargs.get('force')
restore_legacy = kwargs.get('restore_legacy')
colorama.init(strip=kwargs.get('no_color'))
git_dir = current_git_dir()
if git_dir is None:
output(NOT_GIT_REPO_MSG)
exit(1)
hoo... | [
"def",
"uninstall",
"(",
"*",
"*",
"kwargs",
")",
":",
"force",
"=",
"kwargs",
".",
"get",
"(",
"'force'",
")",
"restore_legacy",
"=",
"kwargs",
".",
"get",
"(",
"'restore_legacy'",
")",
"colorama",
".",
"init",
"(",
"strip",
"=",
"kwargs",
".",
"get",... | 32 | 0.001784 |
def _set_location(instance, location):
"""Sets a ``Location`` response header. If the location does not start with
a slash, the path of the current request is prepended.
:param instance: Resource instance (used to access the request and
response)
:type instance: :class:`webob.resou... | [
"def",
"_set_location",
"(",
"instance",
",",
"location",
")",
":",
"location",
"=",
"str",
"(",
"location",
")",
"if",
"not",
"location",
".",
"startswith",
"(",
"'/'",
")",
":",
"location",
"=",
"urljoin",
"(",
"instance",
".",
"request_path",
".",
"rs... | 43 | 0.001898 |
def next(self):
"""
Provide the next element of the list.
"""
if self.idx >= len(self.page_list):
raise StopIteration()
page = self.page_list[self.idx]
self.idx += 1
return page | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"idx",
">=",
"len",
"(",
"self",
".",
"page_list",
")",
":",
"raise",
"StopIteration",
"(",
")",
"page",
"=",
"self",
".",
"page_list",
"[",
"self",
".",
"idx",
"]",
"self",
".",
"idx",
"+=... | 26.333333 | 0.008163 |
def create_multidim_plot(parameters, samples, labels=None,
mins=None, maxs=None, expected_parameters=None,
expected_parameters_color='r',
plot_marginal=True, plot_scatter=True,
marginal_percentiles=None, contour_percenti... | [
"def",
"create_multidim_plot",
"(",
"parameters",
",",
"samples",
",",
"labels",
"=",
"None",
",",
"mins",
"=",
"None",
",",
"maxs",
"=",
"None",
",",
"expected_parameters",
"=",
"None",
",",
"expected_parameters_color",
"=",
"'r'",
",",
"plot_marginal",
"=",
... | 42.366142 | 0.000091 |
def collect_trajectories(env,
policy_fun,
num_trajectories=1,
policy="greedy",
max_timestep=None,
epsilon=0.1):
"""Collect trajectories with the given policy net and behaviour.
Args:
env... | [
"def",
"collect_trajectories",
"(",
"env",
",",
"policy_fun",
",",
"num_trajectories",
"=",
"1",
",",
"policy",
"=",
"\"greedy\"",
",",
"max_timestep",
"=",
"None",
",",
"epsilon",
"=",
"0.1",
")",
":",
"trajectories",
"=",
"[",
"]",
"for",
"t",
"in",
"r... | 38.632479 | 0.008628 |
def Jz(self,**kwargs):
"""
NAME:
Jz
PURPOSE:
Calculate the vertical action
INPUT:
+scipy.integrate.quad keywords
OUTPUT:
J_z(z,vz)/ro/vc + estimate of the error
HISTORY:
2012-06-01 - Written - Bovy (IAS)
"""
... | [
"def",
"Jz",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_Jz'",
")",
":",
"return",
"self",
".",
"_Jz",
"zmax",
"=",
"self",
".",
"calczmax",
"(",
")",
"if",
"zmax",
"==",
"-",
"9999.99",
":",
"return",
... | 32.136364 | 0.019231 |
def _is_auth_info_available():
"""Check if user auth info has been set in environment variables."""
return (_ENDPOINTS_USER_INFO in os.environ or
(_ENV_AUTH_EMAIL in os.environ and _ENV_AUTH_DOMAIN in os.environ) or
_ENV_USE_OAUTH_SCOPE in os.environ) | [
"def",
"_is_auth_info_available",
"(",
")",
":",
"return",
"(",
"_ENDPOINTS_USER_INFO",
"in",
"os",
".",
"environ",
"or",
"(",
"_ENV_AUTH_EMAIL",
"in",
"os",
".",
"environ",
"and",
"_ENV_AUTH_DOMAIN",
"in",
"os",
".",
"environ",
")",
"or",
"_ENV_USE_OAUTH_SCOPE"... | 54.2 | 0.010909 |
def wait_until_exit(self):
""" Wait until thread exit
Used for testing purpose only
"""
if self._timeout is None:
raise Exception("Thread will never exit. Use stop or specify timeout when starting it!")
self._thread.join()
self.stop() | [
"def",
"wait_until_exit",
"(",
"self",
")",
":",
"if",
"self",
".",
"_timeout",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Thread will never exit. Use stop or specify timeout when starting it!\"",
")",
"self",
".",
"_thread",
".",
"join",
"(",
")",
"self",
"... | 26.454545 | 0.009967 |
def _load(self):
"""
Load editable settings from the database and return them as a dict.
Delete any settings from the database that are no longer registered,
and emit a warning if there are settings that are defined in both
settings.py and the database.
"""
from y... | [
"def",
"_load",
"(",
"self",
")",
":",
"from",
"yacms",
".",
"conf",
".",
"models",
"import",
"Setting",
"removed_settings",
"=",
"[",
"]",
"conflicting_settings",
"=",
"[",
"]",
"new_cache",
"=",
"{",
"}",
"for",
"setting_obj",
"in",
"Setting",
".",
"ob... | 40.304348 | 0.001053 |
def update_git_repo():
"""Because GitPython sucks (cmd.commit() hangs)
# pip install GitPython
# import git
# repo = git.Repo('.')
# g = git.cmd.Git('.')
# g.pull()
# g.push()
# g.commit()
"""
today
commands = """
git add docs/*.html
git add docs/images/
... | [
"def",
"update_git_repo",
"(",
")",
":",
"today",
"commands",
"=",
"\"\"\"\n git add docs/*.html\n git add docs/images/\n git add docs*.ipynb\n git commit -am \"autocommit new docs build {}\"\n git push hobson\n git push origin\n\n git checkout master... | 25.025 | 0.000962 |
def get(self, request, bot_id, id, format=None):
"""
Get TelegramBot by id
---
serializer: TelegramBotSerializer
responseMessages:
- code: 401
message: Not authenticated
"""
return super(TelegramBotDetail, self).get(request, bot_i... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
"=",
"None",
")",
":",
"return",
"super",
"(",
"TelegramBotDetail",
",",
"self",
")",
".",
"get",
"(",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
")"
] | 32.5 | 0.008982 |
def dropna(self, drop_nan=True, drop_masked=True, column_names=None):
"""Create a shallow copy of a DataFrame, with filtering set using select_non_missing.
:param drop_nan: drop rows when there is a NaN in any of the columns (will only affect float values)
:param drop_masked: drop rows when the... | [
"def",
"dropna",
"(",
"self",
",",
"drop_nan",
"=",
"True",
",",
"drop_masked",
"=",
"True",
",",
"column_names",
"=",
"None",
")",
":",
"copy",
"=",
"self",
".",
"copy",
"(",
")",
"copy",
".",
"select_non_missing",
"(",
"drop_nan",
"=",
"drop_nan",
",... | 58.833333 | 0.009763 |
def fetchone(self):
""" Fetch next row """
self._check_executed()
row = yield self.read_next()
if row is None:
raise gen.Return(None)
self.rownumber += 1
raise gen.Return(row) | [
"def",
"fetchone",
"(",
"self",
")",
":",
"self",
".",
"_check_executed",
"(",
")",
"row",
"=",
"yield",
"self",
".",
"read_next",
"(",
")",
"if",
"row",
"is",
"None",
":",
"raise",
"gen",
".",
"Return",
"(",
"None",
")",
"self",
".",
"rownumber",
... | 28.5 | 0.008511 |
def _extract_info_from_useragent(user_agent):
"""Extract extra informations from user."""
parsed_string = user_agent_parser.Parse(user_agent)
return {
'os': parsed_string.get('os', {}).get('family'),
'browser': parsed_string.get('user_agent', {}).get('family'),
'browser_version': par... | [
"def",
"_extract_info_from_useragent",
"(",
"user_agent",
")",
":",
"parsed_string",
"=",
"user_agent_parser",
".",
"Parse",
"(",
"user_agent",
")",
"return",
"{",
"'os'",
":",
"parsed_string",
".",
"get",
"(",
"'os'",
",",
"{",
"}",
")",
".",
"get",
"(",
... | 47.666667 | 0.002288 |
def prepare_site_db_and_overrides():
'''Prepare overrides and create _SITE_DB
_SITE_DB.keys() need to be ready for filter_translations
'''
_SITE_DB.clear()
_SITE_DB[_MAIN_LANG] = _MAIN_SITEURL
# make sure it works for both root-relative and absolute
main_siteurl = '/' if _MAIN_SITEURL == ''... | [
"def",
"prepare_site_db_and_overrides",
"(",
")",
":",
"_SITE_DB",
".",
"clear",
"(",
")",
"_SITE_DB",
"[",
"_MAIN_LANG",
"]",
"=",
"_MAIN_SITEURL",
"# make sure it works for both root-relative and absolute",
"main_siteurl",
"=",
"'/'",
"if",
"_MAIN_SITEURL",
"==",
"''"... | 46.4 | 0.001407 |
def stack_plot(df, x='year', y='value', stack='variable',
ax=None, legend=True, title=True, cmap=None, total=None,
**kwargs):
"""Plot data as a stack chart.
Parameters
----------
df : pd.DataFrame
Data to plot as a long-form data frame
x : string, optional
... | [
"def",
"stack_plot",
"(",
"df",
",",
"x",
"=",
"'year'",
",",
"y",
"=",
"'value'",
",",
"stack",
"=",
"'variable'",
",",
"ax",
"=",
"None",
",",
"legend",
"=",
"True",
",",
"title",
"=",
"True",
",",
"cmap",
"=",
"None",
",",
"total",
"=",
"None"... | 35.627329 | 0.00017 |
def _draw_using_figure(self, figure, axs):
"""
Draw onto already created figure and axes
This is can be used to draw animation frames,
or inset plots. It is intended to be used
after the key plot has been drawn.
Parameters
----------
figure : ~matplotlib... | [
"def",
"_draw_using_figure",
"(",
"self",
",",
"figure",
",",
"axs",
")",
":",
"self",
"=",
"deepcopy",
"(",
"self",
")",
"self",
".",
"_build",
"(",
")",
"self",
".",
"theme",
"=",
"self",
".",
"theme",
"or",
"theme_get",
"(",
")",
"self",
".",
"f... | 28.111111 | 0.00191 |
def determine_endpoint_type(features):
""" Determines the type of an endpoint
:param features: pandas.DataFrame
A dataset in a panda's data frame
:returns string
string with a name of a dataset
"""
counter={k.name: v for k, v in features.columns.to_series().groupby(features.dtype... | [
"def",
"determine_endpoint_type",
"(",
"features",
")",
":",
"counter",
"=",
"{",
"k",
".",
"name",
":",
"v",
"for",
"k",
",",
"v",
"in",
"features",
".",
"columns",
".",
"to_series",
"(",
")",
".",
"groupby",
"(",
"features",
".",
"dtypes",
")",
"."... | 37.307692 | 0.01006 |
def scan(python_modules, callback, ignore=tuple()):
"""
Recursively scans `python_modules` for providers registered with
:py:mod:`wiring.scanning.register` module and for each one calls `callback`
with :term:`specification` as the first argument, and the provider object
as the second.
Each elem... | [
"def",
"scan",
"(",
"python_modules",
",",
"callback",
",",
"ignore",
"=",
"tuple",
"(",
")",
")",
":",
"scanner",
"=",
"venusian",
".",
"Scanner",
"(",
"callback",
"=",
"callback",
")",
"for",
"python_module",
"in",
"python_modules",
":",
"if",
"isinstanc... | 39.047619 | 0.00119 |
def word_list(sowpods=False, start="", end=""):
"""Opens the word list file.
Args:
sowpods: a boolean to declare using the sowpods list or TWL (default)
start: a string of starting characters to find anagrams based on
end: a string of ending characters to find anagrams based on
Yei... | [
"def",
"word_list",
"(",
"sowpods",
"=",
"False",
",",
"start",
"=",
"\"\"",
",",
"end",
"=",
"\"\"",
")",
":",
"location",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",... | 32.194444 | 0.000838 |
def encode(self, pdu):
"""Encode a tag on the end of the PDU."""
# check for special encoding
if (self.tagClass == Tag.contextTagClass):
data = 0x08
elif (self.tagClass == Tag.openingTagClass):
data = 0x0E
elif (self.tagClass == Tag.closingTagClass):
... | [
"def",
"encode",
"(",
"self",
",",
"pdu",
")",
":",
"# check for special encoding",
"if",
"(",
"self",
".",
"tagClass",
"==",
"Tag",
".",
"contextTagClass",
")",
":",
"data",
"=",
"0x08",
"elif",
"(",
"self",
".",
"tagClass",
"==",
"Tag",
".",
"openingTa... | 28.714286 | 0.011227 |
def get_parametric(self, check=True, tolerance=0.001):
"""
Calculates the parametric equation of the plane that contains
the polygon. The output has the form np.array([a, b, c, d])
for:
.. math::
a*x + b*y + c*z + d = 0
:param check: Check... | [
"def",
"get_parametric",
"(",
"self",
",",
"check",
"=",
"True",
",",
"tolerance",
"=",
"0.001",
")",
":",
"if",
"self",
".",
"parametric",
"is",
"None",
":",
"# Plane calculation\r",
"a",
",",
"b",
",",
"c",
"=",
"np",
".",
"cross",
"(",
"self",
"."... | 42 | 0.013472 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.