text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def html(cls, string, show_everything=False, translation=gettext.NullTranslations()): # pylint: disable=unused-argument
"""Parses HTML"""
out, _ = tidylib.tidy_fragment(string)
return out | [
"def",
"html",
"(",
"cls",
",",
"string",
",",
"show_everything",
"=",
"False",
",",
"translation",
"=",
"gettext",
".",
"NullTranslations",
"(",
")",
")",
":",
"# pylint: disable=unused-argument",
"out",
",",
"_",
"=",
"tidylib",
".",
"tidy_fragment",
"(",
... | 52.25 | 27 |
def setup(self,
file_path_list,
reason, grr_server_url, grr_username, grr_password, approvers=None,
verify=True):
"""Initializes a GRR Hunt file collector.
Args:
file_path_list: comma-separated list of file paths.
reason: justification for GRR access.
grr_s... | [
"def",
"setup",
"(",
"self",
",",
"file_path_list",
",",
"reason",
",",
"grr_server_url",
",",
"grr_username",
",",
"grr_password",
",",
"approvers",
"=",
"None",
",",
"verify",
"=",
"True",
")",
":",
"super",
"(",
"GRRHuntFileCollector",
",",
"self",
")",
... | 41.454545 | 16.818182 |
def board(board: Optional[chess.BaseBoard] = None, *,
squares: Optional[chess.IntoSquareSet] = None,
flipped: bool = False,
coordinates: bool = True,
lastmove: Optional[chess.Move] = None,
check: Optional[chess.Square] = None,
arrows: Iterable[Union[Arrow, Tup... | [
"def",
"board",
"(",
"board",
":",
"Optional",
"[",
"chess",
".",
"BaseBoard",
"]",
"=",
"None",
",",
"*",
",",
"squares",
":",
"Optional",
"[",
"chess",
".",
"IntoSquareSet",
"]",
"=",
"None",
",",
"flipped",
":",
"bool",
"=",
"False",
",",
"coordin... | 39.863388 | 20.79235 |
def manage(self):
"""
Handle the current hook by doing The Right Thing with the registered services.
"""
hookenv._run_atstart()
try:
hook_name = hookenv.hook_name()
if hook_name == 'stop':
self.stop_services()
else:
... | [
"def",
"manage",
"(",
"self",
")",
":",
"hookenv",
".",
"_run_atstart",
"(",
")",
"try",
":",
"hook_name",
"=",
"hookenv",
".",
"hook_name",
"(",
")",
"if",
"hook_name",
"==",
"'stop'",
":",
"self",
".",
"stop_services",
"(",
")",
"else",
":",
"self",
... | 32.375 | 11.125 |
def setup_handler(context):
"""SENAITE setup handler
"""
if context.readDataFile("bika.lims_various.txt") is None:
return
logger.info("SENAITE setup handler [BEGIN]")
portal = context.getSite()
# Run Installers
remove_default_content(portal)
hide_navbar_items(portal)
rein... | [
"def",
"setup_handler",
"(",
"context",
")",
":",
"if",
"context",
".",
"readDataFile",
"(",
"\"bika.lims_various.txt\"",
")",
"is",
"None",
":",
"return",
"logger",
".",
"info",
"(",
"\"SENAITE setup handler [BEGIN]\"",
")",
"portal",
"=",
"context",
".",
"getS... | 25.384615 | 18.346154 |
def send_keys_to_element(self, element, *keys_to_send):
"""
Sends keys to an element.
:Args:
- element: The element to send keys.
- keys_to_send: The keys to send. Modifier keys constants can be found in the
'Keys' class.
"""
self.click(element)
... | [
"def",
"send_keys_to_element",
"(",
"self",
",",
"element",
",",
"*",
"keys_to_send",
")",
":",
"self",
".",
"click",
"(",
"element",
")",
"self",
".",
"send_keys",
"(",
"*",
"keys_to_send",
")",
"return",
"self"
] | 30.25 | 16.083333 |
def init():
'''
Initializes git repo for nbinteract.
1. Checks for requirements.txt or Dockerfile, offering to create a
requirements.txt if needed.
2. Sets the Binder spec using the `origin` git remote in .nbinteract.json.
3. Prints a Binder URL so the user can debug their image if needed.
... | [
"def",
"init",
"(",
")",
":",
"log",
"(",
"'Initializing folder for nbinteract.'",
")",
"log",
"(",
")",
"log",
"(",
"'Checking to see if this folder is the root folder of a git project.'",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"'.git'",
")",
":",
"log"... | 34.952381 | 24.285714 |
def smart_insert(engine, table, data, minimal_size=5):
"""
An optimized Insert strategy. Guarantee successful and highest insertion
speed. But ATOMIC WRITE IS NOT ENSURED IF THE PROGRAM IS INTERRUPTED.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采... | [
"def",
"smart_insert",
"(",
"engine",
",",
"table",
",",
"data",
",",
"minimal_size",
"=",
"5",
")",
":",
"insert",
"=",
"table",
".",
"insert",
"(",
")",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"# 首先进行尝试bulk insert",
"try",
":",
"engin... | 29.73913 | 17.913043 |
def calculate_concordance_helper(graph: BELGraph,
key: str,
cutoff: Optional[float] = None,
) -> Tuple[int, int, int, int]:
"""Help calculate network-wide concordance
Assumes data already annotated with given key... | [
"def",
"calculate_concordance_helper",
"(",
"graph",
":",
"BELGraph",
",",
"key",
":",
"str",
",",
"cutoff",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
",",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
",",
"int",
"]",
":",
"scores",... | 33.833333 | 17.625 |
def path(self, source, target):
"""
Find the path of id fields connecting two tables.
This is just a basic breadth-first-search. The relations file
should be small enough to not be a problem.
Returns:
list: (table, fieldname) pairs describing the path from
... | [
"def",
"path",
"(",
"self",
",",
"source",
",",
"target",
")",
":",
"visited",
"=",
"set",
"(",
"source",
".",
"split",
"(",
"'+'",
")",
")",
"# split on + for joins",
"targets",
"=",
"set",
"(",
"target",
".",
"split",
"(",
"'+'",
")",
")",
"-",
"... | 36.229167 | 15.895833 |
def get_vnetwork_dvs_output_vnetwork_dvs_pnic(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvs = ET.Element("get_vnetwork_dvs")
config = get_vnetwork_dvs
output = ET.SubElement(get_vnetwork_dvs, "output")
vnetwork_dvs = ET... | [
"def",
"get_vnetwork_dvs_output_vnetwork_dvs_pnic",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_dvs",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_dvs\"",
")",
"config",
"=",
"ge... | 40.307692 | 12.692308 |
def main(dbfile, pidfile, mode):
'''
Main analyzer routine.
'''
Inspector(dbfile, pidfile).reuse_snapshot().snapshot(mode) | [
"def",
"main",
"(",
"dbfile",
",",
"pidfile",
",",
"mode",
")",
":",
"Inspector",
"(",
"dbfile",
",",
"pidfile",
")",
".",
"reuse_snapshot",
"(",
")",
".",
"snapshot",
"(",
"mode",
")"
] | 26.8 | 22 |
def set_transition_down(self, p_self):
'''Set the downbeat-tracking transition matrix according to
self-loop probabilities.
Parameters
----------
p_self : None, float in (0, 1), or np.ndarray [shape=(2,)]
Optional self-loop probability(ies), used for Viterbi decoding... | [
"def",
"set_transition_down",
"(",
"self",
",",
"p_self",
")",
":",
"if",
"p_self",
"is",
"None",
":",
"self",
".",
"down_transition",
"=",
"None",
"else",
":",
"self",
".",
"down_transition",
"=",
"transition_loop",
"(",
"2",
",",
"p_self",
")"
] | 35.615385 | 21 |
def on_timer(self, event=None):
"""Timer event handler
Parameters
----------
event : instance of Event
The timer event.
"""
# Smoothly update center and magnification properties of the transform
k = np.clip(100. / self.mag.mag, 10, 100)
s = 10... | [
"def",
"on_timer",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"# Smoothly update center and magnification properties of the transform",
"k",
"=",
"np",
".",
"clip",
"(",
"100.",
"/",
"self",
".",
"mag",
".",
"mag",
",",
"10",
",",
"100",
")",
"s",
"... | 31.115385 | 17.153846 |
def is_multilingual_project(site_id=None):
"""
Whether the current Django project is configured for multilingual support.
"""
from parler import appsettings
if site_id is None:
site_id = getattr(settings, 'SITE_ID', None)
return appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS or site_id i... | [
"def",
"is_multilingual_project",
"(",
"site_id",
"=",
"None",
")",
":",
"from",
"parler",
"import",
"appsettings",
"if",
"site_id",
"is",
"None",
":",
"site_id",
"=",
"getattr",
"(",
"settings",
",",
"'SITE_ID'",
",",
"None",
")",
"return",
"appsettings",
"... | 42.875 | 16.875 |
def decode_setid(encoded):
"""Decode setid as uint128"""
try:
lo, hi = struct.unpack('<QQ', b32decode(encoded.upper() + '======'))
except struct.error:
raise ValueError('Cannot decode {!r}'.format(encoded))
return (hi << 64) + lo | [
"def",
"decode_setid",
"(",
"encoded",
")",
":",
"try",
":",
"lo",
",",
"hi",
"=",
"struct",
".",
"unpack",
"(",
"'<QQ'",
",",
"b32decode",
"(",
"encoded",
".",
"upper",
"(",
")",
"+",
"'======'",
")",
")",
"except",
"struct",
".",
"error",
":",
"r... | 36.428571 | 19.142857 |
def add_command(self, handler, name=None):
"""Add a subcommand `name` which invokes `handler`.
"""
if name is None:
name = docstring_to_subcommand(handler.__doc__)
# TODO: Prevent overwriting 'help'?
self._commands[name] = handler | [
"def",
"add_command",
"(",
"self",
",",
"handler",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"docstring_to_subcommand",
"(",
"handler",
".",
"__doc__",
")",
"# TODO: Prevent overwriting 'help'?",
"self",
".",
"_commands"... | 34.5 | 10.25 |
def MessageSetItemSizer(field_number):
"""Returns a sizer for extensions of MessageSet.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
}
"""
static_size = (_TagSize(1) * 2 + _... | [
"def",
"MessageSetItemSizer",
"(",
"field_number",
")",
":",
"static_size",
"=",
"(",
"_TagSize",
"(",
"1",
")",
"*",
"2",
"+",
"_TagSize",
"(",
"2",
")",
"+",
"_VarintSize",
"(",
"field_number",
")",
"+",
"_TagSize",
"(",
"3",
")",
")",
"local_VarintSiz... | 26.15 | 17.2 |
def import_deleted_fields(self, data):
"""
Set data fields to deleted
"""
def child_delete_from_str(data_str):
"""
Inner function to set children fields to deleted
"""
parts = data_str.split('.', 1)
if parts[0].isnumeric:
... | [
"def",
"import_deleted_fields",
"(",
"self",
",",
"data",
")",
":",
"def",
"child_delete_from_str",
"(",
"data_str",
")",
":",
"\"\"\"\n Inner function to set children fields to deleted\n \"\"\"",
"parts",
"=",
"data_str",
".",
"split",
"(",
"'.'",
"... | 32.263158 | 10.368421 |
def order(self, order='asc'):
"""
This method retrieve an iterable object that implements the method
__iter__. The arguments given will compose the parameters in the
request url.
This method can be used compounded with query, filter,
sort and facet methods.
kwar... | [
"def",
"order",
"(",
"self",
",",
"order",
"=",
"'asc'",
")",
":",
"context",
"=",
"str",
"(",
"self",
".",
"context",
")",
"request_url",
"=",
"build_url_endpoint",
"(",
"self",
".",
"ENDPOINT",
",",
"context",
")",
"request_params",
"=",
"dict",
"(",
... | 45.290909 | 29.181818 |
def reject(self, pn_condition=None):
"""See Link Reject, AMQP1.0 spec."""
self._pn_link.source.type = proton.Terminus.UNSPECIFIED
super(SenderLink, self).reject(pn_condition) | [
"def",
"reject",
"(",
"self",
",",
"pn_condition",
"=",
"None",
")",
":",
"self",
".",
"_pn_link",
".",
"source",
".",
"type",
"=",
"proton",
".",
"Terminus",
".",
"UNSPECIFIED",
"super",
"(",
"SenderLink",
",",
"self",
")",
".",
"reject",
"(",
"pn_con... | 48.75 | 9.75 |
def pull_screenrecord(self, bit_rate: int = 5000000, time_limit: int = 180, remote: _PATH = '/sdcard/demo.mp4', local: _PATH = 'demo.mp4') -> None:
'''Recording the display of devices running Android 4.4 (API level 19) and higher. Then copy it to your computer.
Args:
bit_rate:You can increa... | [
"def",
"pull_screenrecord",
"(",
"self",
",",
"bit_rate",
":",
"int",
"=",
"5000000",
",",
"time_limit",
":",
"int",
"=",
"180",
",",
"remote",
":",
"_PATH",
"=",
"'/sdcard/demo.mp4'",
",",
"local",
":",
"_PATH",
"=",
"'demo.mp4'",
")",
"->",
"None",
":"... | 68.666667 | 51.777778 |
def reset(self):
"""" Reset the state as new """
self.last_usage = None
self.last_collect = None
self.last_metrics = None
self.snapshot_countdown = 0
self.run() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"last_usage",
"=",
"None",
"self",
".",
"last_collect",
"=",
"None",
"self",
".",
"last_metrics",
"=",
"None",
"self",
".",
"snapshot_countdown",
"=",
"0",
"self",
".",
"run",
"(",
")"
] | 28.857143 | 11 |
def lpc(blk, order=None):
"""
Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object,
the analysis whitening filter. This implementation uses the autocorrelation
method, using numpy.linalg.pinv as a linear system solver.
Parameters
----------
blk :
An iterable with well-defined leng... | [
"def",
"lpc",
"(",
"blk",
",",
"order",
"=",
"None",
")",
":",
"from",
"numpy",
"import",
"matrix",
"from",
"numpy",
".",
"linalg",
"import",
"pinv",
"acdata",
"=",
"acorr",
"(",
"blk",
",",
"order",
")",
"coeffs",
"=",
"pinv",
"(",
"toeplitz",
"(",
... | 30.358974 | 26.974359 |
def permission_to_pyramid_acls(permissions):
"""
Returns a list of permissions in a format understood by pyramid
:param permissions:
:return:
"""
acls = []
for perm in permissions:
if perm.type == "user":
acls.append((Allow, perm.user.id, perm.perm_name))
elif per... | [
"def",
"permission_to_pyramid_acls",
"(",
"permissions",
")",
":",
"acls",
"=",
"[",
"]",
"for",
"perm",
"in",
"permissions",
":",
"if",
"perm",
".",
"type",
"==",
"\"user\"",
":",
"acls",
".",
"append",
"(",
"(",
"Allow",
",",
"perm",
".",
"user",
"."... | 32.230769 | 16.384615 |
def _raise_error(self, *args, **kwargs):
"""
Raises the proper exception for passed error code. These must then be
handled by the layer calling _raise_error()
"""
log.debug("_raise_error(): %s" % kwargs)
try:
error_code = str(kwargs['code'])
except Key... | [
"def",
"_raise_error",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"debug",
"(",
"\"_raise_error(): %s\"",
"%",
"kwargs",
")",
"try",
":",
"error_code",
"=",
"str",
"(",
"kwargs",
"[",
"'code'",
"]",
")",
"except",
"... | 34.133333 | 15.066667 |
def is_vert_aligned_right(c):
"""Return true if all components vertically aligned on their right border.
Vertical alignment means that the bounding boxes of each Mention of c
shares a similar x-axis value in the visual rendering of the document. In
this function the similarity of the x-axis value is ba... | [
"def",
"is_vert_aligned_right",
"(",
"c",
")",
":",
"return",
"all",
"(",
"[",
"_to_span",
"(",
"c",
"[",
"i",
"]",
")",
".",
"sentence",
".",
"is_visual",
"(",
")",
"and",
"bbox_vert_aligned_right",
"(",
"bbox_from_span",
"(",
"_to_span",
"(",
"c",
"[",... | 34.05 | 21.1 |
def validate (self):
"""Returns True if this Sequence is valid, False otherwise.
Validation error messages are stored in self.messages.
"""
if not os.path.isfile(self.pathname):
self.message.append('Filename "%s" does not exist.')
else:
try:
with open(self.pathname, 'r') as strea... | [
"def",
"validate",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"pathname",
")",
":",
"self",
".",
"message",
".",
"append",
"(",
"'Filename \"%s\" does not exist.'",
")",
"else",
":",
"try",
":",
"with",
"ope... | 33.75 | 18.35 |
def stop(self, container, raise_on_error=True, **kwargs):
"""
Stops a container. For convenience optionally ignores API errors.
:param container: Container name.
:type container: unicode | str
:param raise_on_error: Errors on stop and removal may result from Docker volume proble... | [
"def",
"stop",
"(",
"self",
",",
"container",
",",
"raise_on_error",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"super",
"(",
"DockerClientWrapper",
",",
"self",
")",
".",
"stop",
"(",
"container",
",",
"*",
"*",
"kwargs",
")",
"exce... | 47.894737 | 23.894737 |
def get_creation_date_tags(url, domain, as_dicts=False):
"""
Put together all data sources in this module and return it's output.
Args:
url (str): URL of the web. With relative paths and so on.
domain (str): Just the domain of the web.
as_dicts (bool, default False): Convert output ... | [
"def",
"get_creation_date_tags",
"(",
"url",
",",
"domain",
",",
"as_dicts",
"=",
"False",
")",
":",
"creation_date_tags",
"=",
"[",
"mementoweb_api_tags",
"(",
"url",
")",
",",
"get_whois_tags",
"(",
"domain",
")",
",",
"]",
"creation_date_tags",
"=",
"sorted... | 26.433333 | 21.433333 |
def get_description(self):
"""Returns description text as provided by the studio"""
if self._description:
return self._description
try:
trailerURL= "http://trailers.apple.com%s" % self.baseURL
response = urllib.request.urlopen(trailerURL)
Reader =... | [
"def",
"get_description",
"(",
"self",
")",
":",
"if",
"self",
".",
"_description",
":",
"return",
"self",
".",
"_description",
"try",
":",
"trailerURL",
"=",
"\"http://trailers.apple.com%s\"",
"%",
"self",
".",
"baseURL",
"response",
"=",
"urllib",
".",
"requ... | 39.7 | 15.2 |
def register_hid_device(screen_width, screen_height,
absolute=False, integrated_display=False):
"""Create a new REGISTER_HID_DEVICE_MESSAGE."""
message = create(protobuf.REGISTER_HID_DEVICE_MESSAGE)
descriptor = message.inner().deviceDescriptor
descriptor.absolute = 1 if absolute... | [
"def",
"register_hid_device",
"(",
"screen_width",
",",
"screen_height",
",",
"absolute",
"=",
"False",
",",
"integrated_display",
"=",
"False",
")",
":",
"message",
"=",
"create",
"(",
"protobuf",
".",
"REGISTER_HID_DEVICE_MESSAGE",
")",
"descriptor",
"=",
"messa... | 49.7 | 13 |
def _parse_caps_loader(node):
'''
Parse the <loader> element of the domain capabilities.
'''
enums = [_parse_caps_enum(enum) for enum in node.findall('enum')]
result = {item[0]: item[1] for item in enums if item[0]}
values = [child.text for child in node.findall('value')]
if values:
... | [
"def",
"_parse_caps_loader",
"(",
"node",
")",
":",
"enums",
"=",
"[",
"_parse_caps_enum",
"(",
"enum",
")",
"for",
"enum",
"in",
"node",
".",
"findall",
"(",
"'enum'",
")",
"]",
"result",
"=",
"{",
"item",
"[",
"0",
"]",
":",
"item",
"[",
"1",
"]"... | 27.230769 | 26.153846 |
def speaker(self):
"""
Lazy-loads the speaker for this word
:getter: Returns the plain string value of the speaker tag for the word
:type: str
"""
if self._speaker is None:
speakers = self._element.xpath('Speaker/text()')
if len(speakers) > 0:
... | [
"def",
"speaker",
"(",
"self",
")",
":",
"if",
"self",
".",
"_speaker",
"is",
"None",
":",
"speakers",
"=",
"self",
".",
"_element",
".",
"xpath",
"(",
"'Speaker/text()'",
")",
"if",
"len",
"(",
"speakers",
")",
">",
"0",
":",
"self",
".",
"_speaker"... | 29.076923 | 16.615385 |
def dateTimeAt( self, point ):
"""
Returns the date time at the inputed point.
:param point | <QPoint>
"""
for dtime, data in self._dateTimeGrid.items():
if ( data[1].contains(point) ):
return QDateTime.fromTime_t(dtime)
... | [
"def",
"dateTimeAt",
"(",
"self",
",",
"point",
")",
":",
"for",
"dtime",
",",
"data",
"in",
"self",
".",
"_dateTimeGrid",
".",
"items",
"(",
")",
":",
"if",
"(",
"data",
"[",
"1",
"]",
".",
"contains",
"(",
"point",
")",
")",
":",
"return",
"QDa... | 32.9 | 9.9 |
def orderBy(self, field, direct="desc"):
"""
Allows for the results to be ordered by a specific field. If given,
direction can be set with passing an additional argument in the form
of "asc" or "desc"
"""
if direct == "desc":
self._query = self._query.order_by... | [
"def",
"orderBy",
"(",
"self",
",",
"field",
",",
"direct",
"=",
"\"desc\"",
")",
":",
"if",
"direct",
"==",
"\"desc\"",
":",
"self",
".",
"_query",
"=",
"self",
".",
"_query",
".",
"order_by",
"(",
"r",
".",
"desc",
"(",
"field",
")",
")",
"else",... | 35 | 18.833333 |
def _logout(self):
"""Do logout from zabbix server."""
if self.auth:
logger.debug("ZabbixAPI.logout()")
if self.user.logout():
self.auth = None | [
"def",
"_logout",
"(",
"self",
")",
":",
"if",
"self",
".",
"auth",
":",
"logger",
".",
"debug",
"(",
"\"ZabbixAPI.logout()\"",
")",
"if",
"self",
".",
"user",
".",
"logout",
"(",
")",
":",
"self",
".",
"auth",
"=",
"None"
] | 24.25 | 17.625 |
def do_round(value, precision=0, method='common'):
"""Round the number to a given precision. The first
parameter specifies the precision (default is ``0``), the
second the rounding method:
- ``'common'`` rounds either up or down
- ``'ceil'`` always rounds up
- ``'floor'`` always rounds down
... | [
"def",
"do_round",
"(",
"value",
",",
"precision",
"=",
"0",
",",
"method",
"=",
"'common'",
")",
":",
"if",
"not",
"method",
"in",
"(",
"'common'",
",",
"'ceil'",
",",
"'floor'",
")",
":",
"raise",
"FilterArgumentError",
"(",
"'method must be common, ceil o... | 30.25 | 18.8125 |
def selected_classification(self):
"""Obtain the classification selected by user.
:returns: Metadata of the selected classification.
:rtype: dict, None
"""
item = self.lstClassifications.currentItem()
try:
return definition(item.data(QtCore.Qt.UserRole))
... | [
"def",
"selected_classification",
"(",
"self",
")",
":",
"item",
"=",
"self",
".",
"lstClassifications",
".",
"currentItem",
"(",
")",
"try",
":",
"return",
"definition",
"(",
"item",
".",
"data",
"(",
"QtCore",
".",
"Qt",
".",
"UserRole",
")",
")",
"exc... | 33.909091 | 14.363636 |
def transpose(self, interval, up=True):
"""Transpose the notes in the bar up or down the interval.
Call transpose() on all NoteContainers in the bar.
"""
for cont in self.bar:
cont[2].transpose(interval, up) | [
"def",
"transpose",
"(",
"self",
",",
"interval",
",",
"up",
"=",
"True",
")",
":",
"for",
"cont",
"in",
"self",
".",
"bar",
":",
"cont",
"[",
"2",
"]",
".",
"transpose",
"(",
"interval",
",",
"up",
")"
] | 35.142857 | 10.428571 |
def make_attrstring(attr):
"""Returns an attribute string in the form key="val" """
attrstring = ' '.join(['%s="%s"' % (k, v) for k, v in attr.items()])
return '%s%s' % (' ' if attrstring != '' else '', attrstring) | [
"def",
"make_attrstring",
"(",
"attr",
")",
":",
"attrstring",
"=",
"' '",
".",
"join",
"(",
"[",
"'%s=\"%s\"'",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"attr",
".",
"items",
"(",
")",
"]",
")",
"return",
"'%s%s'",
"%",
"(",
"... | 55.75 | 17.75 |
def get_json_event_start(event_buffer):
""" get the event start of an event that is different (in time)from the
adjoining event, in XML format """
event_start_pattern = '{"_cd":"'
time_key_pattern = '"_time":"'
time_end_pattern = '"'
event_end_pattern = '"},\n'
event_end_pattern2 = '"}[... | [
"def",
"get_json_event_start",
"(",
"event_buffer",
")",
":",
"event_start_pattern",
"=",
"'{\"_cd\":\"'",
"time_key_pattern",
"=",
"'\"_time\":\"'",
"time_end_pattern",
"=",
"'\"'",
"event_end_pattern",
"=",
"'\"},\\n'",
"event_end_pattern2",
"=",
"'\"}[]'",
"# old json ou... | 40.674419 | 17.72093 |
def broadcast(self):
""" Broadcast a transaction to the blockchain network
:param tx tx: Signed transaction to broadcast
"""
# Sign if not signed
if not self._is_signed():
self.sign()
# Cannot broadcast an empty transaction
if "operations" not in... | [
"def",
"broadcast",
"(",
"self",
")",
":",
"# Sign if not signed",
"if",
"not",
"self",
".",
"_is_signed",
"(",
")",
":",
"self",
".",
"sign",
"(",
")",
"# Cannot broadcast an empty transaction",
"if",
"\"operations\"",
"not",
"in",
"self",
"or",
"not",
"self"... | 29.526316 | 20.105263 |
def can_create_replica_without_replication_connection(self):
""" go through the replication methods to see if there are ones
that does not require a working replication connection.
"""
replica_methods = self._create_replica_methods
return any(self.replica_method_can_work_with... | [
"def",
"can_create_replica_without_replication_connection",
"(",
"self",
")",
":",
"replica_methods",
"=",
"self",
".",
"_create_replica_methods",
"return",
"any",
"(",
"self",
".",
"replica_method_can_work_without_replication_connection",
"(",
"method",
")",
"for",
"method... | 63.333333 | 23 |
def registry_hostname(registry):
"""
Strip a reference to a registry to just the hostname:port
"""
if registry.startswith('http:') or registry.startswith('https:'):
return urlparse(registry).netloc
else:
return registry | [
"def",
"registry_hostname",
"(",
"registry",
")",
":",
"if",
"registry",
".",
"startswith",
"(",
"'http:'",
")",
"or",
"registry",
".",
"startswith",
"(",
"'https:'",
")",
":",
"return",
"urlparse",
"(",
"registry",
")",
".",
"netloc",
"else",
":",
"return... | 31 | 13.25 |
def BuildNodes(self, nodes):
"""
Tries to build the given nodes immediately. Returns 1 on success,
0 on error.
"""
if self.logstream is not None:
# override stdout / stderr to write in log file
oldStdout = sys.stdout
sys.stdout = self.logstream... | [
"def",
"BuildNodes",
"(",
"self",
",",
"nodes",
")",
":",
"if",
"self",
".",
"logstream",
"is",
"not",
"None",
":",
"# override stdout / stderr to write in log file",
"oldStdout",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"self",
".",
"logstream",
... | 37.884615 | 14.807692 |
def funTransChica(imagl, idril, ibfield, gamma0, xoy='x'):
""" Chicane matrix, composed of four rbends, seperated by drifts
:param imagl: rbend width, in [m]
:param idril: drift length between two adjacent rbends, in [m]
:param ibfield: rbend magnetic strength, in [T]
:param gamma0: electron energy... | [
"def",
"funTransChica",
"(",
"imagl",
",",
"idril",
",",
"ibfield",
",",
"gamma0",
",",
"xoy",
"=",
"'x'",
")",
":",
"m0",
"=",
"9.10938215e-31",
"e0",
"=",
"1.602176487e-19",
"c0",
"=",
"299792458",
"rho",
"=",
"np",
".",
"sqrt",
"(",
"gamma0",
"**",
... | 44.025 | 19.9 |
def _continuous_colormap(hue, cmap, vmin, vmax):
"""
Creates a continuous colormap.
Parameters
----------
hue : iterable
The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue``
parameters ingest many argument signatures, not just it... | [
"def",
"_continuous_colormap",
"(",
"hue",
",",
"cmap",
",",
"vmin",
",",
"vmax",
")",
":",
"mn",
"=",
"min",
"(",
"hue",
")",
"if",
"vmin",
"is",
"None",
"else",
"vmin",
"mx",
"=",
"max",
"(",
"hue",
")",
"if",
"vmax",
"is",
"None",
"else",
"vma... | 51.333333 | 31.466667 |
def _replace_local_codeuri(self):
"""
Replaces the CodeUri in AWS::Serverless::Function and DefinitionUri in AWS::Serverless::Api to a fake
S3 Uri. This is to support running the SAM Translator with valid values for these fields. If this in not done,
the template is invalid in the eyes o... | [
"def",
"_replace_local_codeuri",
"(",
"self",
")",
":",
"all_resources",
"=",
"self",
".",
"sam_template",
".",
"get",
"(",
"\"Resources\"",
",",
"{",
"}",
")",
"for",
"_",
",",
"resource",
"in",
"all_resources",
".",
"items",
"(",
")",
":",
"resource_type... | 43.64 | 32.12 |
def reserve_ipblock(self, ipblock):
"""
Reserves an IP block within your account.
"""
properties = {
"name": ipblock.name
}
if ipblock.location:
properties['location'] = ipblock.location
if ipblock.size:
properties['size'] = ... | [
"def",
"reserve_ipblock",
"(",
"self",
",",
"ipblock",
")",
":",
"properties",
"=",
"{",
"\"name\"",
":",
"ipblock",
".",
"name",
"}",
"if",
"ipblock",
".",
"location",
":",
"properties",
"[",
"'location'",
"]",
"=",
"ipblock",
".",
"location",
"if",
"ip... | 22.347826 | 20.173913 |
def recover_fast_dynamic_model_from_data(model_class, original_data, modified_data, deleted_data, field_types):
"""
Function to reconstruct a model from DirtyModel basic information: original data, the modified and deleted
fields.
Necessary for pickle an object
"""
model = model_class()
mod... | [
"def",
"recover_fast_dynamic_model_from_data",
"(",
"model_class",
",",
"original_data",
",",
"modified_data",
",",
"deleted_data",
",",
"field_types",
")",
":",
"model",
"=",
"model_class",
"(",
")",
"model",
".",
"__field_types__",
"=",
"{",
"k",
":",
"d",
"["... | 42.454545 | 32.090909 |
def add_edge(self, u, v, key=None, attr_dict=None, **attr):
"""Version of add_edge that only writes to the database once."""
if attr_dict is None:
attr_dict = attr
else:
try:
attr_dict.update(attr)
except AttributeError:
raise N... | [
"def",
"add_edge",
"(",
"self",
",",
"u",
",",
"v",
",",
"key",
"=",
"None",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"if",
"attr_dict",
"is",
"None",
":",
"attr_dict",
"=",
"attr",
"else",
":",
"try",
":",
"attr_dict",
"."... | 32.84375 | 11.15625 |
def add_states(self, *states):
'''
Add @states.
'''
for state in states:
self.states[state] = EventManagerPlus(self) | [
"def",
"add_states",
"(",
"self",
",",
"*",
"states",
")",
":",
"for",
"state",
"in",
"states",
":",
"self",
".",
"states",
"[",
"state",
"]",
"=",
"EventManagerPlus",
"(",
"self",
")"
] | 25.833333 | 19.166667 |
def add_button(self, name, button_class=wtf_fields.SubmitField, **options):
"""Adds a button to the form."""
self._buttons[name] = button_class(**options) | [
"def",
"add_button",
"(",
"self",
",",
"name",
",",
"button_class",
"=",
"wtf_fields",
".",
"SubmitField",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"_buttons",
"[",
"name",
"]",
"=",
"button_class",
"(",
"*",
"*",
"options",
")"
] | 56 | 16 |
def import_string(dotted_path: str) -> Any:
"""
Stolen approximately from django. Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import fails.
"""
try:
module_path, class_name = dotted_path.strip(' ').rsplit('.', 1... | [
"def",
"import_string",
"(",
"dotted_path",
":",
"str",
")",
"->",
"Any",
":",
"try",
":",
"module_path",
",",
"class_name",
"=",
"dotted_path",
".",
"strip",
"(",
"' '",
")",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueError",
"as",
"e",... | 43.266667 | 24.6 |
def select_font(self, font):
'''Select font type
Choices are:
<Bit map fonts>
'brougham'
'lettergothicbold'
'brusselsbit'
'helsinkibit'
'sandiego'
<Outline fonts>
'lettergothic'
'brusselsoutline'
'helsinkioutline'
... | [
"def",
"select_font",
"(",
"self",
",",
"font",
")",
":",
"fonts",
"=",
"{",
"'brougham'",
":",
"0",
",",
"'lettergothicbold'",
":",
"1",
",",
"'brusselsbit'",
":",
"2",
",",
"'helsinkibit'",
":",
"3",
",",
"'sandiego'",
":",
"4",
",",
"'lettergothic'",
... | 28.825 | 17.875 |
def _config_convert_to_address_helper(self) -> None:
"""
converts the config from ports to zmq ip addresses
Operates on `self.config` using `self._socket_factory.to_address`
"""
to_address = self._socket_factory.to_address
for k, v in self.config.items():
if k... | [
"def",
"_config_convert_to_address_helper",
"(",
"self",
")",
"->",
"None",
":",
"to_address",
"=",
"self",
".",
"_socket_factory",
".",
"to_address",
"for",
"k",
",",
"v",
"in",
"self",
".",
"config",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'chat... | 40.818182 | 10.090909 |
def update(self, enabled=None, cnames=None, comment=None):
"""
Update the configuration of the StreamingDistribution. The only values
of the StreamingDistributionConfig that can be directly updated are:
* CNAMES
* Comment
* Whether the Distribution is enabled or not
... | [
"def",
"update",
"(",
"self",
",",
"enabled",
"=",
"None",
",",
"cnames",
"=",
"None",
",",
"comment",
"=",
"None",
")",
":",
"new_config",
"=",
"StreamingDistributionConfig",
"(",
"self",
".",
"connection",
",",
"self",
".",
"config",
".",
"origin",
","... | 45.511111 | 23.377778 |
def run_step(context):
"""Write payload out to json file.
Args:
context: pypyr.context.Context. Mandatory.
The following context keys expected:
- fileWriteJson
- path. mandatory. path-like. Write output file to
here. Will create... | [
"def",
"run_step",
"(",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"context",
".",
"assert_child_key_has_value",
"(",
"'fileWriteJson'",
",",
"'path'",
",",
"__name__",
")",
"out_path",
"=",
"context",
".",
"get_formatted_string",
"(",... | 39.863636 | 25.886364 |
def should_set_tablename(cls):
"""Determine whether ``__tablename__`` should be automatically generated
for a model.
* If no class in the MRO sets a name, one should be generated.
* If a declared attr is found, it should be used instead.
* If a name is found, it should be used if the class is a mix... | [
"def",
"should_set_tablename",
"(",
"cls",
")",
":",
"if",
"(",
"cls",
".",
"__dict__",
".",
"get",
"(",
"'__abstract__'",
",",
"False",
")",
"or",
"not",
"any",
"(",
"isinstance",
"(",
"b",
",",
"DeclarativeMeta",
")",
"for",
"b",
"in",
"cls",
".",
... | 33.029412 | 23.352941 |
def quattodcm(quat):
"""Convert quaternion to DCM
This function will convert a quaternion to the equivalent rotation matrix,
or direction cosine matrix.
Parameters:
----------
quat - (4,) numpy array
Array defining a quaterion where the quaternion is defined in terms of
a vecto... | [
"def",
"quattodcm",
"(",
"quat",
")",
":",
"dcm",
"=",
"(",
"quat",
"[",
"-",
"1",
"]",
"**",
"2",
"-",
"np",
".",
"inner",
"(",
"quat",
"[",
"0",
":",
"3",
"]",
",",
"quat",
"[",
"0",
":",
"3",
"]",
")",
")",
"*",
"np",
".",
"eye",
"("... | 32.181818 | 29.318182 |
def root_endpoint(request, format=None):
"""
List of all the available resources of this RESTful API.
"""
endpoints = []
# loop over url modules
for urlmodule in urlpatterns:
# is it a urlconf module?
if hasattr(urlmodule, 'urlconf_module'):
is_urlconf_module = True
... | [
"def",
"root_endpoint",
"(",
"request",
",",
"format",
"=",
"None",
")",
":",
"endpoints",
"=",
"[",
"]",
"# loop over url modules",
"for",
"urlmodule",
"in",
"urlpatterns",
":",
"# is it a urlconf module?",
"if",
"hasattr",
"(",
"urlmodule",
",",
"'urlconf_module... | 38.766667 | 13.033333 |
def ensure_list(value: Union[T, Sequence[T]]) -> Sequence[T]:
"""Wrap value in list if it is not one."""
if value is None:
return []
return value if isinstance(value, list) else [value] | [
"def",
"ensure_list",
"(",
"value",
":",
"Union",
"[",
"T",
",",
"Sequence",
"[",
"T",
"]",
"]",
")",
"->",
"Sequence",
"[",
"T",
"]",
":",
"if",
"value",
"is",
"None",
":",
"return",
"[",
"]",
"return",
"value",
"if",
"isinstance",
"(",
"value",
... | 40.2 | 15.8 |
def build_plan(description, graph,
targets=None, reverse=False):
"""Builds a plan from a list of steps.
Args:
description (str): an arbitrary string to
describe the plan.
graph (:class:`Graph`): a list of :class:`Graph` to execute.
targets (list): an optional l... | [
"def",
"build_plan",
"(",
"description",
",",
"graph",
",",
"targets",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"# If we want to execute the plan in reverse (e.g. Destroy), transpose the",
"# graph.",
"if",
"reverse",
":",
"graph",
"=",
"graph",
".",
"tr... | 38.166667 | 19.2 |
def _normalize_rename_handler(self, mapping, schema, field):
""" {'oneof': [
{'type': 'callable'},
{'type': 'list',
'schema': {'oneof': [{'type': 'callable'},
{'type': 'string'}]}},
{'type': 'string'}
... | [
"def",
"_normalize_rename_handler",
"(",
"self",
",",
"mapping",
",",
"schema",
",",
"field",
")",
":",
"if",
"'rename_handler'",
"not",
"in",
"schema",
"[",
"field",
"]",
":",
"return",
"new_name",
"=",
"self",
".",
"__normalize_coerce",
"(",
"schema",
"[",... | 40.125 | 9.8125 |
def get_temp_directory():
"""Return an absolute path to an existing temporary directory"""
# Supports all platforms supported by tempfile
directory = os.path.join(gettempdir(), "ttkthemes")
if not os.path.exists(directory):
os.makedirs(directory)
return directory | [
"def",
"get_temp_directory",
"(",
")",
":",
"# Supports all platforms supported by tempfile",
"directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"gettempdir",
"(",
")",
",",
"\"ttkthemes\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directo... | 40.714286 | 10.428571 |
def save_lines(lines, filename):
"""
Save an array of lines to a file.
Args:
lines: An array of strings that will be saved as individual lines.
filename: Path to the output file.
"""
with open(filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines)) | [
"def",
"save_lines",
"(",
"lines",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"lines",
")",
")"
] | 26.636364 | 16.090909 |
def read_gds(self,
infile,
units='skip',
rename={},
layers={},
datatypes={},
texttypes={}):
"""
Read a GDSII file into this library.
Parameters
----------
infile : file or strin... | [
"def",
"read_gds",
"(",
"self",
",",
"infile",
",",
"units",
"=",
"'skip'",
",",
"rename",
"=",
"{",
"}",
",",
"layers",
"=",
"{",
"}",
",",
"datatypes",
"=",
"{",
"}",
",",
"texttypes",
"=",
"{",
"}",
")",
":",
"self",
".",
"_references",
"=",
... | 40.13089 | 15.303665 |
def _scrape_document(self):
'''Extract links from the DOM.'''
mock_response = self._new_mock_response(
self._response, self._get_temp_path('phantom', '.html')
)
self._item_session.request = self._request
self._item_session.response = mock_response
self._proc... | [
"def",
"_scrape_document",
"(",
"self",
")",
":",
"mock_response",
"=",
"self",
".",
"_new_mock_response",
"(",
"self",
".",
"_response",
",",
"self",
".",
"_get_temp_path",
"(",
"'phantom'",
",",
"'.html'",
")",
")",
"self",
".",
"_item_session",
".",
"requ... | 32.307692 | 19.384615 |
def merge_dicts(i):
"""
Input: {
dict1 - merge this dict with dict2 (will be directly modified!)
dict2 - dict
Output: {
return - return code = 0, if successful
dict1 - output dict
}
"""
a=i['dict1']
b=i['dict2'... | [
"def",
"merge_dicts",
"(",
"i",
")",
":",
"a",
"=",
"i",
"[",
"'dict1'",
"]",
"b",
"=",
"i",
"[",
"'dict2'",
"]",
"for",
"k",
"in",
"b",
":",
"v",
"=",
"b",
"[",
"k",
"]",
"if",
"type",
"(",
"v",
")",
"is",
"dict",
":",
"if",
"k",
"not",
... | 21.575758 | 20.787879 |
def date_uncertainty_due_to_rate(self, node, interval=(0.05, 0.095)):
"""use previously calculated variation of the rate to estimate
the uncertainty in a particular numdate due to rate variation.
Parameters
----------
node : PhyloTree.Clade
node for which the confide... | [
"def",
"date_uncertainty_due_to_rate",
"(",
"self",
",",
"node",
",",
"interval",
"=",
"(",
"0.05",
",",
"0.095",
")",
")",
":",
"if",
"hasattr",
"(",
"node",
",",
"\"numdate_rate_variation\"",
")",
":",
"from",
"scipy",
".",
"special",
"import",
"erfinv",
... | 40.952381 | 22.428571 |
def mousePressEvent(self, event):
"""Reimplement Qt method"""
if event.button() != Qt.LeftButton:
QTableView.mousePressEvent(self, event)
return
index_clicked = self.indexAt(event.pos())
if index_clicked.isValid():
if index_clicked == self.curre... | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"button",
"(",
")",
"!=",
"Qt",
".",
"LeftButton",
":",
"QTableView",
".",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
"return",
"index_clicked",
"=",
"self",
".",
... | 38.066667 | 11.8 |
def linkHasRel(link_attrs, target_rel):
"""Does this link have target_rel as a relationship?"""
# XXX: TESTME
rel_attr = link_attrs.get('rel')
return rel_attr and relMatches(rel_attr, target_rel) | [
"def",
"linkHasRel",
"(",
"link_attrs",
",",
"target_rel",
")",
":",
"# XXX: TESTME",
"rel_attr",
"=",
"link_attrs",
".",
"get",
"(",
"'rel'",
")",
"return",
"rel_attr",
"and",
"relMatches",
"(",
"rel_attr",
",",
"target_rel",
")"
] | 41.4 | 8.8 |
def ids(args):
"""
%prog ids cdhit.clstr
Get the representative ids from clstr file.
"""
p = OptionParser(ids.__doc__)
p.add_option("--prefix", type="int",
help="Find rep id for prefix of len [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 1:
... | [
"def",
"ids",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"ids",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--prefix\"",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Find rep id for prefix of len [default: %default]\"",
")",
"opts",
... | 25.69697 | 19.151515 |
def compile_regex_from_str(self, ft_str):
"""Given a string describing features masks for a sequence of segments,
return a regex matching the corresponding strings.
Args:
ft_str (str): feature masks, each enclosed in square brackets, in
which the features are delimited b... | [
"def",
"compile_regex_from_str",
"(",
"self",
",",
"ft_str",
")",
":",
"sequence",
"=",
"[",
"]",
"for",
"m",
"in",
"re",
".",
"finditer",
"(",
"r'\\[([^]]+)\\]'",
",",
"ft_str",
")",
":",
"ft_mask",
"=",
"fts",
"(",
"m",
".",
"group",
"(",
"1",
")",... | 37 | 18.142857 |
def cdf(arr, **kwargs):
"""
ARGS
arr array to calculate cumulative distribution function
**kwargs
Passed directly to numpy.histogram. Typical options include:
bins = <num_bins>
normed = True|False
DESC
Determines the cumulative distribution functi... | [
"def",
"cdf",
"(",
"arr",
",",
"*",
"*",
"kwargs",
")",
":",
"counts",
",",
"bin_edges",
"=",
"histogram",
"(",
"arr",
",",
"*",
"*",
"kwargs",
")",
"cdf",
"=",
"cumsum",
"(",
"counts",
")",
"return",
"cdf"
] | 25.3125 | 21.8125 |
def _find_remote_bundle(self, ref, remote_service_type='s3'):
"""
Locate a bundle, by any reference, among the configured remotes. The routine will
only look in the cache directory lists stored in the remotes, which must
be updated to be current.
:param ref:
:return: (re... | [
"def",
"_find_remote_bundle",
"(",
"self",
",",
"ref",
",",
"remote_service_type",
"=",
"'s3'",
")",
":",
"for",
"r",
"in",
"self",
".",
"remotes",
":",
"if",
"remote_service_type",
"and",
"r",
".",
"service",
"!=",
"remote_service_type",
":",
"continue",
"i... | 30.913043 | 22.304348 |
def next_permutation(tab):
"""find the next permutation of tab in the lexicographical order
:param tab: table with n elements from an ordered set
:modifies: table to next permutation
:returns: False if permutation is already lexicographical maximal
:complexity: O(n)
"""
n = len(tab)
piv... | [
"def",
"next_permutation",
"(",
"tab",
")",
":",
"n",
"=",
"len",
"(",
"tab",
")",
"pivot",
"=",
"None",
"# find pivot",
"for",
"i",
"in",
"range",
"(",
"n",
"-",
"1",
")",
":",
"if",
"tab",
"[",
"i",
"]",
"<",
"tab",
"[",
"i",
"+",
"1",
"]",... | 33.269231 | 17.538462 |
def has_key(tup, key):
"""has(tuple, string) -> bool
Return whether a given tuple has a key and the key is bound.
"""
if isinstance(tup, framework.TupleLike):
return tup.is_bound(key)
if isinstance(tup, dict):
return key in tup
if isinstance(tup, list):
if not isinstance(key, int):
raise ... | [
"def",
"has_key",
"(",
"tup",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"tup",
",",
"framework",
".",
"TupleLike",
")",
":",
"return",
"tup",
".",
"is_bound",
"(",
"key",
")",
"if",
"isinstance",
"(",
"tup",
",",
"dict",
")",
":",
"return",
"k... | 31.928571 | 14.785714 |
def get_aes_mode(mode):
"""Return pycrypto's AES mode, raise exception if not supported"""
aes_mode_attr = "MODE_{}".format(mode.upper())
try:
aes_mode = getattr(AES, aes_mode_attr)
except AttributeError:
raise Exception(
"Pycrypto/pycryptodome does not seem to support {}. ".... | [
"def",
"get_aes_mode",
"(",
"mode",
")",
":",
"aes_mode_attr",
"=",
"\"MODE_{}\"",
".",
"format",
"(",
"mode",
".",
"upper",
"(",
")",
")",
"try",
":",
"aes_mode",
"=",
"getattr",
"(",
"AES",
",",
"aes_mode_attr",
")",
"except",
"AttributeError",
":",
"r... | 40.818182 | 21.909091 |
def run(self, *, delay=None):
"""Run this pipeline.
Parameters:
delay(int): The minimum amount of time, in milliseconds, the
pipeline should be delayed by.
Returns:
pipeline: Itself.
"""
self.broker.enqueue(self.messages[0], delay=delay)
... | [
"def",
"run",
"(",
"self",
",",
"*",
",",
"delay",
"=",
"None",
")",
":",
"self",
".",
"broker",
".",
"enqueue",
"(",
"self",
".",
"messages",
"[",
"0",
"]",
",",
"delay",
"=",
"delay",
")",
"return",
"self"
] | 26.666667 | 18.333333 |
def setCurrent(self, state=True):
"""
Marks this view as the current source based on the inputed flag. \
This method will return True if the currency changes.
:return <bool> | changed
"""
if self._current == state:
return False
w... | [
"def",
"setCurrent",
"(",
"self",
",",
"state",
"=",
"True",
")",
":",
"if",
"self",
".",
"_current",
"==",
"state",
":",
"return",
"False",
"widget",
"=",
"self",
".",
"viewWidget",
"(",
")",
"if",
"widget",
":",
"for",
"other",
"in",
"widget",
".",... | 32.535714 | 14.107143 |
def current_app(device_id):
""" Get currently running app. """
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
current = devices[device_id].current_app
if current is None:
abort(404)
return jsonify(current_app=current) | [
"def",
"current_app",
"(",
"device_id",
")",
":",
"if",
"not",
"is_valid_device_id",
"(",
"device_id",
")",
":",
"abort",
"(",
"403",
")",
"if",
"device_id",
"not",
"in",
"devices",
":",
"abort",
"(",
"404",
")",
"current",
"=",
"devices",
"[",
"device_i... | 24.833333 | 15.833333 |
def _sample_as_dict(self, sample):
"""Convert list-like ``sample`` (list/dict/dimod.SampleView),
``list: var``, to ``map: idx -> var``.
"""
if isinstance(sample, dict):
return sample
if isinstance(sample, (list, numpy.ndarray)):
sample = enumerate(sample)
... | [
"def",
"_sample_as_dict",
"(",
"self",
",",
"sample",
")",
":",
"if",
"isinstance",
"(",
"sample",
",",
"dict",
")",
":",
"return",
"sample",
"if",
"isinstance",
"(",
"sample",
",",
"(",
"list",
",",
"numpy",
".",
"ndarray",
")",
")",
":",
"sample",
... | 37.666667 | 6.555556 |
def normalizeDefaultLayerName(value, font):
"""
Normalizes default layer name.
* **value** must normalize as layer name with
:func:`normalizeLayerName`.
* **value** must be a layer in **font**.
* Returned value will be an unencoded ``unicode`` string.
"""
value = normalizeLayerName(va... | [
"def",
"normalizeDefaultLayerName",
"(",
"value",
",",
"font",
")",
":",
"value",
"=",
"normalizeLayerName",
"(",
"value",
")",
"if",
"value",
"not",
"in",
"font",
".",
"layerOrder",
":",
"raise",
"ValueError",
"(",
"\"No layer with the name '%s' exists.\"",
"%",
... | 34.384615 | 11 |
def get_attrition_in_years(self):
"""
Function for the Basic UI
"""
attrition_of_nets = self.itn.find("attritionOfNets")
function = attrition_of_nets.attrib["function"]
if function != "step":
return None
L = attrition_of_nets.attrib["L"]
return... | [
"def",
"get_attrition_in_years",
"(",
"self",
")",
":",
"attrition_of_nets",
"=",
"self",
".",
"itn",
".",
"find",
"(",
"\"attritionOfNets\"",
")",
"function",
"=",
"attrition_of_nets",
".",
"attrib",
"[",
"\"function\"",
"]",
"if",
"function",
"!=",
"\"step\"",... | 31.3 | 10.1 |
def delete_records(self, domain, name, record_type=None):
"""Deletes records by name. You can also add a record type, which will only delete records with the
specified type/name combo. If no record type is specified, ALL records that have a matching name will be
deleted.
This is hapha... | [
"def",
"delete_records",
"(",
"self",
",",
"domain",
",",
"name",
",",
"record_type",
"=",
"None",
")",
":",
"records",
"=",
"self",
".",
"get_records",
"(",
"domain",
")",
"if",
"records",
"is",
"None",
":",
"return",
"False",
"# we don't want to replace th... | 45.09375 | 28.125 |
def table_dump(self, table):
"""dump all the rows of the given table name"""
if not table: raise ValueError("no table")
print('------- dumping table {}'.format(table))
pipes = ["gzip"]
outfile_path = self._get_outfile_path(table)
cmd = self._get_args(
"pg_dum... | [
"def",
"table_dump",
"(",
"self",
",",
"table",
")",
":",
"if",
"not",
"table",
":",
"raise",
"ValueError",
"(",
"\"no table\"",
")",
"print",
"(",
"'------- dumping table {}'",
".",
"format",
"(",
"table",
")",
")",
"pipes",
"=",
"[",
"\"gzip\"",
"]",
"... | 31.136364 | 15.181818 |
def scan(self, file_or_stream):
"""
:param file_or_stream: :class:`Blob` instance, filename or file object
:returns: True if file is 'clean', False if a virus is detected, None if
file could not be scanned.
If `file_or_stream` is a Blob, scan result is stored in
Blob.me... | [
"def",
"scan",
"(",
"self",
",",
"file_or_stream",
")",
":",
"if",
"not",
"clamd",
":",
"return",
"None",
"res",
"=",
"self",
".",
"_scan",
"(",
"file_or_stream",
")",
"if",
"isinstance",
"(",
"file_or_stream",
",",
"Blob",
")",
":",
"file_or_stream",
".... | 31.470588 | 18.647059 |
def _build_udf(name, code, return_type, params, language, imports):
"""Creates the UDF part of a BigQuery query using its pieces
Args:
name: the name of the javascript function
code: function body implementing the logic.
return_type: BigQuery data type of the function return. See supported da... | [
"def",
"_build_udf",
"(",
"name",
",",
"code",
",",
"return_type",
",",
"params",
",",
"language",
",",
"imports",
")",
":",
"params",
"=",
"','",
".",
"join",
"(",
"[",
"'%s %s'",
"%",
"named_param",
"for",
"named_param",
"in",
"params",
"]",
")",
"im... | 39.588235 | 18.705882 |
def getMemoKeyForAccount(self, name):
""" Obtain owner Memo Key for an account from the wallet database
"""
account = self.rpc.get_account(name)
key = self.getPrivateKeyForPublicKey(account["options"]["memo_key"])
if key:
return key
return False | [
"def",
"getMemoKeyForAccount",
"(",
"self",
",",
"name",
")",
":",
"account",
"=",
"self",
".",
"rpc",
".",
"get_account",
"(",
"name",
")",
"key",
"=",
"self",
".",
"getPrivateKeyForPublicKey",
"(",
"account",
"[",
"\"options\"",
"]",
"[",
"\"memo_key\"",
... | 37.25 | 13.25 |
def _create_search_filter(filter_by):
"""
:param filter_by:
:return: dict
"""
return ",".join(
[
"{0}:{1}".format(key, value)
for key, value in filter_by.items()
if value is not None
]
) | [
"def",
"_create_search_filter",
"(",
"filter_by",
")",
":",
"return",
"\",\"",
".",
"join",
"(",
"[",
"\"{0}:{1}\"",
".",
"format",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"filter_by",
".",
"items",
"(",
")",
"if",
"value",
"is... | 24.583333 | 13.083333 |
def login(self, db, login='admin', password='admin'):
"""Log in as the given `user` with the password `passwd` on the
database `db`.
.. doctest::
:options: +SKIP
>>> odoo.login('db_name', 'admin', 'admin')
>>> odoo.env.user.name
'Administrator'
... | [
"def",
"login",
"(",
"self",
",",
"db",
",",
"login",
"=",
"'admin'",
",",
"password",
"=",
"'admin'",
")",
":",
"# Get the user's ID and generate the corresponding user record",
"data",
"=",
"self",
".",
"json",
"(",
"'/web/session/authenticate'",
",",
"{",
"'db'... | 32.454545 | 18.818182 |
def orchestration_save(self, mode="shallow", custom_params=None):
"""Orchestration Save command
:param mode:
:param custom_params: json with all required action to configure or remove vlans from certain port
:return Serialized OrchestrationSavedArtifact to json
:rtype json
... | [
"def",
"orchestration_save",
"(",
"self",
",",
"mode",
"=",
"\"shallow\"",
",",
"custom_params",
"=",
"None",
")",
":",
"save_params",
"=",
"{",
"'folder_path'",
":",
"''",
",",
"'configuration_type'",
":",
"'running'",
",",
"'return_artifact'",
":",
"True",
"... | 47.703704 | 32.074074 |
def proccess_lowstates(**kwargs):
'''
return proccessed lowstate data that was not blacklisted
render_module_function is used to provide your own.
defaults to from_lowstate
'''
states = []
config = _get_config(**kwargs)
proccesser = config.get('proccesser')
ls = __salt__['state.show... | [
"def",
"proccess_lowstates",
"(",
"*",
"*",
"kwargs",
")",
":",
"states",
"=",
"[",
"]",
"config",
"=",
"_get_config",
"(",
"*",
"*",
"kwargs",
")",
"proccesser",
"=",
"config",
".",
"get",
"(",
"'proccesser'",
")",
"ls",
"=",
"__salt__",
"[",
"'state.... | 32.36 | 22.84 |
def trading_dates(start, end, calendar='US'):
"""
Trading dates for given exchange
Args:
start: start date
end: end date
calendar: exchange as string
Returns:
pd.DatetimeIndex: datetime index
Examples:
>>> bus_dates = ['2018-12-24', '2018-12-26', '2018-12-2... | [
"def",
"trading_dates",
"(",
"start",
",",
"end",
",",
"calendar",
"=",
"'US'",
")",
":",
"kw",
"=",
"dict",
"(",
"start",
"=",
"pd",
".",
"Timestamp",
"(",
"start",
",",
"tz",
"=",
"'UTC'",
")",
".",
"date",
"(",
")",
",",
"end",
"=",
"pd",
".... | 35.714286 | 22.47619 |
def logistic(x, a=0., b=1.):
r"""Computes the logistic function with range :math:`\in (a, b)`.
This is given by:
.. math::
\mathrm{logistic}(x; a, b) = \frac{a + b e^x}{1 + e^x}.
Note that this is also the inverse of the logit function with domain
:math:`(a, b)`.
... | [
"def",
"logistic",
"(",
"x",
",",
"a",
"=",
"0.",
",",
"b",
"=",
"1.",
")",
":",
"expx",
"=",
"numpy",
".",
"exp",
"(",
"x",
")",
"return",
"(",
"a",
"+",
"b",
"*",
"expx",
")",
"/",
"(",
"1.",
"+",
"expx",
")"
] | 26.2 | 22.933333 |
def _get_and_write_archive(self, hunt, output_file_path):
"""Gets and writes a hunt archive.
Function is necessary for the _check_approval_wrapper to work.
Args:
hunt: The GRR hunt object.
output_file_path: The output path where to write the Hunt Archive.
"""
hunt_archive = hunt.GetFil... | [
"def",
"_get_and_write_archive",
"(",
"self",
",",
"hunt",
",",
"output_file_path",
")",
":",
"hunt_archive",
"=",
"hunt",
".",
"GetFilesArchive",
"(",
")",
"hunt_archive",
".",
"WriteToFile",
"(",
"output_file_path",
")"
] | 33.454545 | 18.272727 |
def start(self):
'''start sending packets'''
if self.sock is not None:
self.sock.close()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.connect(('', gen_setting... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"sock",
"is",
"not",
"None",
":",
"self",
".",
"sock",
".",
"close",
"(",
")",
"self",
".",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_D... | 35.034483 | 18.965517 |
def visit_NameConstant(self, node):
""" Python 3 """
nnode = self.dnode(node)
copy_from_lineno_col_offset(
nnode, str(node.value), self.bytes_pos_to_utf8, to=node) | [
"def",
"visit_NameConstant",
"(",
"self",
",",
"node",
")",
":",
"nnode",
"=",
"self",
".",
"dnode",
"(",
"node",
")",
"copy_from_lineno_col_offset",
"(",
"nnode",
",",
"str",
"(",
"node",
".",
"value",
")",
",",
"self",
".",
"bytes_pos_to_utf8",
",",
"t... | 39 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.