text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def getOrderedGlyphSet(self):
"""Return OrderedDict[glyphName, glyph] sorted by glyphOrder.
"""
compiler = self.context.compiler
if compiler is not None:
return compiler.glyphSet
from ufo2ft.util import makeOfficialGlyphOrder
glyphSet = self.context.font
... | [
"def",
"getOrderedGlyphSet",
"(",
"self",
")",
":",
"compiler",
"=",
"self",
".",
"context",
".",
"compiler",
"if",
"compiler",
"is",
"not",
"None",
":",
"return",
"compiler",
".",
"glyphSet",
"from",
"ufo2ft",
".",
"util",
"import",
"makeOfficialGlyphOrder",
... | 36.333333 | 14.166667 |
def __imap_fetch_content_type(self, msg_nums, content_type):
"""
Given a message number that we found with imap_search, fetch the
whole source, dump that into an email object, and pick out the part
that matches the content type specified. Return that, if we got
multiple emails, r... | [
"def",
"__imap_fetch_content_type",
"(",
"self",
",",
"msg_nums",
",",
"content_type",
")",
":",
"if",
"not",
"msg_nums",
":",
"raise",
"Exception",
"(",
"\"Invalid Message Number!\"",
")",
"if",
"not",
"content_type",
":",
"raise",
"Exception",
"(",
"\"Need a con... | 41.71875 | 19.53125 |
def accounts_pending(self, accounts, count=None, threshold=None, source=False):
"""
Returns a list of block hashes which have not yet been received by
these **accounts**
:param accounts: Accounts to return list of block hashes for
:type accounts: list of str
:param coun... | [
"def",
"accounts_pending",
"(",
"self",
",",
"accounts",
",",
"count",
"=",
"None",
",",
"threshold",
"=",
"None",
",",
"source",
"=",
"False",
")",
":",
"payload",
"=",
"{",
"\"accounts\"",
":",
"accounts",
"}",
"accounts",
"=",
"self",
".",
"_process_v... | 35.567164 | 24.19403 |
def main():
"""
Main function
"""
parsed_configuration = AlignakConfigParser()
try:
parsed_configuration.parse()
except configparser.ParsingError as exp:
print("Environment file parsing error: %s", exp)
if parsed_configuration.export:
# Export Alignak version
... | [
"def",
"main",
"(",
")",
":",
"parsed_configuration",
"=",
"AlignakConfigParser",
"(",
")",
"try",
":",
"parsed_configuration",
".",
"parse",
"(",
")",
"except",
"configparser",
".",
"ParsingError",
"as",
"exp",
":",
"print",
"(",
"\"Environment file parsing error... | 29.538462 | 16.307692 |
def foreignKeys(self, *a, **kw): # nopep8
"""Executes the SQLForeignKeys function and creates a result set
of column names that are foreign keys in the specified table (columns
in the specified table that refer to primary keys in other tables)
or foreign keys in other tables that refer ... | [
"def",
"foreignKeys",
"(",
"self",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"# nopep8",
"fut",
"=",
"self",
".",
"_run_operation",
"(",
"self",
".",
"_impl",
".",
"foreignKeys",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
"return",
"fut"
] | 51.222222 | 18.444444 |
def _handle_metadata(self, node, scope, ctxt, stream):
"""Handle metadata for the node
"""
self._dlog("handling node metadata {}".format(node.metadata.keyvals))
keyvals = node.metadata.keyvals
metadata_info = []
if "watch" in node.metadata.keyvals or "update" in keyval... | [
"def",
"_handle_metadata",
"(",
"self",
",",
"node",
",",
"scope",
",",
"ctxt",
",",
"stream",
")",
":",
"self",
".",
"_dlog",
"(",
"\"handling node metadata {}\"",
".",
"format",
"(",
"node",
".",
"metadata",
".",
"keyvals",
")",
")",
"keyvals",
"=",
"n... | 32.2 | 23.2 |
def _find_stars(data, kernel, threshold_eff, min_separation=None,
mask=None, exclude_border=False):
"""
Find stars in an image.
Parameters
----------
data : 2D array_like
The 2D array of the image.
kernel : `_StarFinderKernel`
The convolution kernel.
thresh... | [
"def",
"_find_stars",
"(",
"data",
",",
"kernel",
",",
"threshold_eff",
",",
"min_separation",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"exclude_border",
"=",
"False",
")",
":",
"convolved_data",
"=",
"filter_data",
"(",
"data",
",",
"kernel",
".",
"dat... | 36.472727 | 19.818182 |
def merge(self, other):
"""
Merges this node with the other, returning a new node that spans the both.
"""
new_node = self.copy()
new_node.size += other.size
new_node.instruction_addrs += other.instruction_addrs
# FIXME: byte_string should never be none, but it is... | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"new_node",
"=",
"self",
".",
"copy",
"(",
")",
"new_node",
".",
"size",
"+=",
"other",
".",
"size",
"new_node",
".",
"instruction_addrs",
"+=",
"other",
".",
"instruction_addrs",
"# FIXME: byte_string sho... | 42.428571 | 17.571429 |
def _wait_trigger(self):
"""Called to launch the next request in the queue."""
if _debug: IOQController._debug("_wait_trigger")
# make sure we are waiting
if (self.state != CTRL_WAITING):
raise RuntimeError("not waiting")
# change our state
self.state = CTRL... | [
"def",
"_wait_trigger",
"(",
"self",
")",
":",
"if",
"_debug",
":",
"IOQController",
".",
"_debug",
"(",
"\"_wait_trigger\"",
")",
"# make sure we are waiting",
"if",
"(",
"self",
".",
"state",
"!=",
"CTRL_WAITING",
")",
":",
"raise",
"RuntimeError",
"(",
"\"n... | 32.214286 | 16.571429 |
def get_battery_info(self) -> dict:
'''Show device battery information.
Returns:
A dict. For example:
{'AC powered': 'false',
'Charge counter': '0',
'Max charging current': '0',
'Max charging voltage': '0',
'US... | [
"def",
"get_battery_info",
"(",
"self",
")",
"->",
"dict",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'dumpsys'",
",",
"'battery'",
")",
"battery_status",
"=",
"re",
".",
"sp... | 35.24 | 12.04 |
def get(self, key: str, *,
prompt: Optional[Message_T] = None,
arg_filters: Optional[List[Filter_T]] = None,
**kwargs) -> Any:
"""
Get an argument with a given key.
If the argument does not exist in the current session,
a pause exception will be raise... | [
"def",
"get",
"(",
"self",
",",
"key",
":",
"str",
",",
"*",
",",
"prompt",
":",
"Optional",
"[",
"Message_T",
"]",
"=",
"None",
",",
"arg_filters",
":",
"Optional",
"[",
"List",
"[",
"Filter_T",
"]",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
")... | 35.083333 | 13.25 |
def symmetry(self, input_entity, coefficients, duplicate=True):
"""Transforms all elementary entities symmetrically to a plane. The vector
should contain four expressions giving the coefficients of the plane's equation.
"""
d = {1: "Line", 2: "Surface", 3: "Volume"}
entity = "{}{... | [
"def",
"symmetry",
"(",
"self",
",",
"input_entity",
",",
"coefficients",
",",
"duplicate",
"=",
"True",
")",
":",
"d",
"=",
"{",
"1",
":",
"\"Line\"",
",",
"2",
":",
"\"Surface\"",
",",
"3",
":",
"\"Volume\"",
"}",
"entity",
"=",
"\"{}{{{}}};\"",
".",... | 39.0625 | 22.25 |
def checkKey(self, key=None):
'''
Checks that an API key is valid.
:param str key: (optional) A key that you want to check the validity of. Defaults to the one provided on initialization.
:returns: If the key is valid, this method will return ``True``.
:rtype: `bool`
:ra... | [
"def",
"checkKey",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"# Get site",
"url",
"=",
"Client",
".",
"ENDPOINT",
".",
"format",
"(",
"'checkKey'",
")",
"if",
"not",
"key",
":",
"key",
"=",
"self",
".",
"apiKey",
"params",
"=",
"{",
"'apiKey'",... | 34.166667 | 21.75 |
def _tab_changed(self):
"""Triggered when the current tab is changed."""
current = self.tab_widget.currentWidget()
if current == self.analysisTab:
self.btn_back.setEnabled(False)
self.btn_next.setEnabled(True)
elif current == self.reportingTab:
if self... | [
"def",
"_tab_changed",
"(",
"self",
")",
":",
"current",
"=",
"self",
".",
"tab_widget",
".",
"currentWidget",
"(",
")",
"if",
"current",
"==",
"self",
".",
"analysisTab",
":",
"self",
".",
"btn_back",
".",
"setEnabled",
"(",
"False",
")",
"self",
".",
... | 42.611111 | 7.055556 |
def has_implementation(self, number, arch, abi_list=()):
"""
Pretty much the intersection of SimLibrary.has_implementation() and SimSyscallLibrary.get().
:param number: The syscall number
:param arch: The architecture being worked with, as either a string name or an archinfo... | [
"def",
"has_implementation",
"(",
"self",
",",
"number",
",",
"arch",
",",
"abi_list",
"=",
"(",
")",
")",
":",
"name",
",",
"_",
",",
"_",
"=",
"self",
".",
"_canonicalize",
"(",
"number",
",",
"arch",
",",
"abi_list",
")",
"return",
"super",
"(",
... | 57.090909 | 29.636364 |
def validate_attribute(attr, name, expected_type=None, required=False):
'''Validates that an attribute meets expectations.
This function will check if the given attribute value matches a necessary
type and/or is not None, an empty string, an empty list, etc. It will raise
suitable exceptions on validat... | [
"def",
"validate_attribute",
"(",
"attr",
",",
"name",
",",
"expected_type",
"=",
"None",
",",
"required",
"=",
"False",
")",
":",
"if",
"expected_type",
":",
"if",
"type",
"(",
"expected_type",
")",
"==",
"list",
":",
"if",
"not",
"_check_type",
"(",
"a... | 43.8 | 22.28 |
def _determine_stream_spreadLB(self,simple=_USESIMPLE,
ro=None,vo=None,
R0=None,Zsun=None,vsun=None):
"""Determine the spread in the stream in observable coordinates"""
if not hasattr(self,'_allErrCovs'):
self._determine_s... | [
"def",
"_determine_stream_spreadLB",
"(",
"self",
",",
"simple",
"=",
"_USESIMPLE",
",",
"ro",
"=",
"None",
",",
"vo",
"=",
"None",
",",
"R0",
"=",
"None",
",",
"Zsun",
"=",
"None",
",",
"vsun",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"... | 53.923077 | 21.269231 |
def get_buckets(self, bucket_type=None, timeout=None):
"""
Serialize bucket listing request and deserialize response
"""
msg_code = riak.pb.messages.MSG_CODE_LIST_BUCKETS_REQ
codec = self._get_codec(msg_code)
msg = codec.encode_get_buckets(bucket_type,
... | [
"def",
"get_buckets",
"(",
"self",
",",
"bucket_type",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"msg_code",
"=",
"riak",
".",
"pb",
".",
"messages",
".",
"MSG_CODE_LIST_BUCKETS_REQ",
"codec",
"=",
"self",
".",
"_get_codec",
"(",
"msg_code",
")",... | 43.6 | 12 |
def loadFunction(self, root):
"""
Loads a list with all the functions in the Fortran File
Args:
root: The root of the XML ast tree.
Returns:
None
Does not return anything but populates a list (self.functionList) that
contains all the functions i... | [
"def",
"loadFunction",
"(",
"self",
",",
"root",
")",
":",
"for",
"element",
"in",
"root",
".",
"iter",
"(",
")",
":",
"if",
"element",
".",
"tag",
"==",
"\"function\"",
":",
"self",
".",
"functionList",
".",
"append",
"(",
"element",
".",
"attrib",
... | 29.9375 | 19.9375 |
def getTrustForJID(self, bare_jid):
"""
All-in-one trust information for all devices of a bare jid.
The result is structured like this:
{
"active" : { device: int => trust_info }
"inactive" : { device: int => trust_info }
}
where trust_info is ... | [
"def",
"getTrustForJID",
"(",
"self",
",",
"bare_jid",
")",
":",
"result",
"=",
"{",
"\"active\"",
":",
"{",
"}",
",",
"\"inactive\"",
":",
"{",
"}",
"}",
"devices",
"=",
"yield",
"self",
".",
"__loadActiveDevices",
"(",
"bare_jid",
")",
"for",
"device",... | 28.689655 | 24.482759 |
def get_album_time(self, round_number=2):
"""
Retrieves all of the track's length and returns the sum of all
:param round_number: Int. Number of decimals to round the sum
:return: Int. Sum of all the track's length
"""
if not self._track_list:
self.get_tracks(... | [
"def",
"get_album_time",
"(",
"self",
",",
"round_number",
"=",
"2",
")",
":",
"if",
"not",
"self",
".",
"_track_list",
":",
"self",
".",
"get_tracks",
"(",
")",
"if",
"self",
".",
"_album_time",
"is",
"None",
":",
"album_time",
"=",
"0.0",
"for",
"tra... | 40.928571 | 11.357143 |
def call(ezo, name, method, data, target):
'''
calls a method with data and returns a result without changing the chain state
:param ezo: ezo instance
:param name: name of the Contract
:param method: name of the contract method
:param data: formatted data to send to th... | [
"def",
"call",
"(",
"ezo",
",",
"name",
",",
"method",
",",
"data",
",",
"target",
")",
":",
"# load the contract by name",
"c",
",",
"err",
"=",
"Contract",
".",
"get",
"(",
"name",
",",
"ezo",
")",
"if",
"err",
":",
"return",
"None",
",",
"err",
... | 32.02381 | 21.833333 |
def set_menu(self, ):
"""Setup the menu that the menu_tb button uses
:returns: None
:rtype: None
:raises: None
"""
self.menu = QtGui.QMenu(self)
actions = self.reftrack.get_additional_actions()
self.actions = []
for a in actions:
if a.... | [
"def",
"set_menu",
"(",
"self",
",",
")",
":",
"self",
".",
"menu",
"=",
"QtGui",
".",
"QMenu",
"(",
"self",
")",
"actions",
"=",
"self",
".",
"reftrack",
".",
"get_additional_actions",
"(",
")",
"self",
".",
"actions",
"=",
"[",
"]",
"for",
"a",
"... | 33.545455 | 11.590909 |
def add_callback(self, fd, events, callback):
"""Add a new callback.
The file descriptor *fd* will be watched for the events specified by
the *events* parameter, which should be a bitwise OR of the constants
``READABLE`` and ``WRITABLE``. Whenever one or more of the specified
ev... | [
"def",
"add_callback",
"(",
"self",
",",
"fd",
",",
"events",
",",
"callback",
")",
":",
"if",
"self",
".",
"_mpoll",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Poller instance is closed'",
")",
"try",
":",
"mpoll",
"=",
"self",
".",
"_mpoll",
"[... | 44.85 | 22.5 |
def find_atoms_within_distance(atoms, cutoff_distance, point):
"""Returns atoms within the distance from the point.
Parameters
----------
atoms : [ampal.atom]
A list of `ampal.atoms`.
cutoff_distance : float
Maximum distance from point.
point : (float, float, float)
Refe... | [
"def",
"find_atoms_within_distance",
"(",
"atoms",
",",
"cutoff_distance",
",",
"point",
")",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"atoms",
"if",
"distance",
"(",
"x",
",",
"point",
")",
"<=",
"cutoff_distance",
"]"
] | 28.444444 | 16.611111 |
def fetch_and_execute_function_to_run(self, key):
"""Run on arbitrary function on the worker."""
(driver_id, serialized_function,
run_on_other_drivers) = self.redis_client.hmget(
key, ["driver_id", "function", "run_on_other_drivers"])
if (utils.decode(run_on_other_drivers)... | [
"def",
"fetch_and_execute_function_to_run",
"(",
"self",
",",
"key",
")",
":",
"(",
"driver_id",
",",
"serialized_function",
",",
"run_on_other_drivers",
")",
"=",
"self",
".",
"redis_client",
".",
"hmget",
"(",
"key",
",",
"[",
"\"driver_id\"",
",",
"\"function... | 42.730769 | 16.192308 |
def get_available_images(request, project_id=None, images_cache=None):
"""Returns a list of available images
Returns a list of images that are public, shared, community or owned by
the given project_id. If project_id is not specified, only public and
community images are returned.
:param images_ca... | [
"def",
"get_available_images",
"(",
"request",
",",
"project_id",
"=",
"None",
",",
"images_cache",
"=",
"None",
")",
":",
"if",
"images_cache",
"is",
"None",
":",
"images_cache",
"=",
"{",
"}",
"public_images",
"=",
"images_cache",
".",
"get",
"(",
"'public... | 38.380952 | 17.071429 |
def update(self, client):
"""Execute update command on instance."""
update_cmd = "{sudo} '{refresh};{update}'".format(
sudo=self.get_sudo_exec_wrapper(),
refresh=self.get_refresh_repo_cmd(),
update=self.get_update_cmd()
)
out = ''
try:
... | [
"def",
"update",
"(",
"self",
",",
"client",
")",
":",
"update_cmd",
"=",
"\"{sudo} '{refresh};{update}'\"",
".",
"format",
"(",
"sudo",
"=",
"self",
".",
"get_sudo_exec_wrapper",
"(",
")",
",",
"refresh",
"=",
"self",
".",
"get_refresh_repo_cmd",
"(",
")",
... | 30.526316 | 16.789474 |
def read_info_string(self):
"""Reads the information string for the OPC
:rtype: string
:Example:
>>> alpha.read_info_string()
'OPC-N2 FirmwareVer=OPC-018.2....................BD'
"""
infostring = []
# Send the command byte and sleep for 9 ms
se... | [
"def",
"read_info_string",
"(",
"self",
")",
":",
"infostring",
"=",
"[",
"]",
"# Send the command byte and sleep for 9 ms",
"self",
".",
"cnxn",
".",
"xfer",
"(",
"[",
"0x3F",
"]",
")",
"sleep",
"(",
"9e-3",
")",
"# Read the info string by sending 60 empty bytes",
... | 23.541667 | 19.875 |
def download_data(url:str, fname:PathOrStr=None, data:bool=True, ext:str='.tgz') -> Path:
"Download `url` to destination `fname`."
fname = Path(ifnone(fname, _url2tgz(url, data, ext=ext)))
os.makedirs(fname.parent, exist_ok=True)
if not fname.exists():
print(f'Downloading {url}')
downloa... | [
"def",
"download_data",
"(",
"url",
":",
"str",
",",
"fname",
":",
"PathOrStr",
"=",
"None",
",",
"data",
":",
"bool",
"=",
"True",
",",
"ext",
":",
"str",
"=",
"'.tgz'",
")",
"->",
"Path",
":",
"fname",
"=",
"Path",
"(",
"ifnone",
"(",
"fname",
... | 44.625 | 15.375 |
def merge_configs(main, tweaks):
"""Merge tweaks into a main config file."""
for section in tweaks.sections():
for option in tweaks.options(section):
value = tweaks.get(section, option)
if option.endswith("+"):
option = option[:-1]
value = main.get... | [
"def",
"merge_configs",
"(",
"main",
",",
"tweaks",
")",
":",
"for",
"section",
"in",
"tweaks",
".",
"sections",
"(",
")",
":",
"for",
"option",
"in",
"tweaks",
".",
"options",
"(",
"section",
")",
":",
"value",
"=",
"tweaks",
".",
"get",
"(",
"secti... | 42.444444 | 5.888889 |
def preprocess_model(model, rewrap=True, **kwargs):
"""Preprocess a MiniZinc model.
This function takes care of preprocessing the model by resolving the
template using the arguments passed as keyword arguments to this function.
Optionally, this function can also "rewrap" the model, deleting spaces at
... | [
"def",
"preprocess_model",
"(",
"model",
",",
"rewrap",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"{",
"*",
"*",
"kwargs",
",",
"*",
"*",
"config",
".",
"get",
"(",
"'args'",
",",
"{",
"}",
")",
"}",
"model",
"=",
"_process_tem... | 29.677419 | 24.645161 |
def write_repo_json(self, date=(datetime.date.today()),
organization='llnl', dict_to_write={}, path_ending_type='',
is_list=False, is_dict=False):
"""
#Writes repo specific data to JSON.
"""
for repo in dict_to_write:
path = ('../github-data/' + organization +... | [
"def",
"write_repo_json",
"(",
"self",
",",
"date",
"=",
"(",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
",",
"organization",
"=",
"'llnl'",
",",
"dict_to_write",
"=",
"{",
"}",
",",
"path_ending_type",
"=",
"''",
",",
"is_list",
"=",
"False... | 46.5 | 15.714286 |
def _decompress(self, cmd, s3_snap):
"""Adds the appropriate command to decompress the zfs stream
This is determined from the metadata of the s3_snap.
"""
compressor = COMPRESSORS.get(s3_snap.compressor)
if compressor is None:
return cmd
decompress_cmd = compr... | [
"def",
"_decompress",
"(",
"self",
",",
"cmd",
",",
"s3_snap",
")",
":",
"compressor",
"=",
"COMPRESSORS",
".",
"get",
"(",
"s3_snap",
".",
"compressor",
")",
"if",
"compressor",
"is",
"None",
":",
"return",
"cmd",
"decompress_cmd",
"=",
"compressor",
"[",... | 42.666667 | 9.888889 |
def signals():
"""Show all signal types."""
signalbus = current_app.extensions['signalbus']
for signal_model in signalbus.get_signal_models():
click.echo(signal_model.__name__) | [
"def",
"signals",
"(",
")",
":",
"signalbus",
"=",
"current_app",
".",
"extensions",
"[",
"'signalbus'",
"]",
"for",
"signal_model",
"in",
"signalbus",
".",
"get_signal_models",
"(",
")",
":",
"click",
".",
"echo",
"(",
"signal_model",
".",
"__name__",
")"
] | 32 | 15.333333 |
def onCopySelection(self, event):
"""
Copies self.df_slice to the Clipboard if slice exists
"""
if self.df_slice is not None:
pd.DataFrame.to_clipboard(self.df_slice, header=False, index=False)
self.grid.ClearSelection()
self.df_slice = None
... | [
"def",
"onCopySelection",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"df_slice",
"is",
"not",
"None",
":",
"pd",
".",
"DataFrame",
".",
"to_clipboard",
"(",
"self",
".",
"df_slice",
",",
"header",
"=",
"False",
",",
"index",
"=",
"False",
... | 58.454545 | 32.272727 |
def flatsize(obj, align=0, **opts):
'''Return the flat size of an object (in bytes),
optionally aligned to a given power of 2.
See function **basicsize** for a description of
the other options. See the documentation of
this module for the definition of flat size.
'''
v = _typed... | [
"def",
"flatsize",
"(",
"obj",
",",
"align",
"=",
"0",
",",
"*",
"*",
"opts",
")",
":",
"v",
"=",
"_typedefof",
"(",
"obj",
",",
"*",
"*",
"opts",
")",
"if",
"v",
":",
"if",
"align",
">",
"1",
":",
"m",
"=",
"align",
"-",
"1",
"if",
"(",
... | 31.111111 | 19.111111 |
def iter_related(self):
'''
Generator function that iterates this object's related providers,
which includes this provider.
'''
for tpl in self.provider_run.templates:
yield tpl.providers[self.index] | [
"def",
"iter_related",
"(",
"self",
")",
":",
"for",
"tpl",
"in",
"self",
".",
"provider_run",
".",
"templates",
":",
"yield",
"tpl",
".",
"providers",
"[",
"self",
".",
"index",
"]"
] | 35 | 17.285714 |
def get_varied_cfg_lbls(cfg_list, default_cfg=None, mainkey='_cfgname',
checkname=False):
r"""
Args:
cfg_list (list):
default_cfg (None): (default = None)
checkname (bool): if True removes names if they are all the same.
Returns:
list: cfglbl_list
... | [
"def",
"get_varied_cfg_lbls",
"(",
"cfg_list",
",",
"default_cfg",
"=",
"None",
",",
"mainkey",
"=",
"'_cfgname'",
",",
"checkname",
"=",
"False",
")",
":",
"import",
"utool",
"as",
"ut",
"try",
":",
"cfgname_list",
"=",
"[",
"cfg",
"[",
"mainkey",
"]",
... | 37.3 | 19.925 |
def getServiceDependenciesUIDs(self):
"""
This methods returns a list with the service dependencies UIDs
:return: a list of uids
"""
deps = self.getServiceDependencies()
deps_uids = [service.UID() for service in deps]
return deps_uids | [
"def",
"getServiceDependenciesUIDs",
"(",
"self",
")",
":",
"deps",
"=",
"self",
".",
"getServiceDependencies",
"(",
")",
"deps_uids",
"=",
"[",
"service",
".",
"UID",
"(",
")",
"for",
"service",
"in",
"deps",
"]",
"return",
"deps_uids"
] | 35.375 | 9.625 |
def _load_actor_from_local(self, driver_id, function_descriptor):
"""Load actor class from local code."""
module_name, class_name = (function_descriptor.module_name,
function_descriptor.class_name)
try:
module = importlib.import_module(module_name)
... | [
"def",
"_load_actor_from_local",
"(",
"self",
",",
"driver_id",
",",
"function_descriptor",
")",
":",
"module_name",
",",
"class_name",
"=",
"(",
"function_descriptor",
".",
"module_name",
",",
"function_descriptor",
".",
"class_name",
")",
"try",
":",
"module",
"... | 46.117647 | 17.823529 |
def draw_arc(self, color, world_loc, world_radius, start_angle, stop_angle,
thickness=1):
"""Draw an arc using world coordinates, radius, start and stop angles."""
center = self.world_to_surf.fwd_pt(world_loc).round()
radius = max(1, int(self.world_to_surf.fwd_dist(world_radius)))
rect = ... | [
"def",
"draw_arc",
"(",
"self",
",",
"color",
",",
"world_loc",
",",
"world_radius",
",",
"start_angle",
",",
"stop_angle",
",",
"thickness",
"=",
"1",
")",
":",
"center",
"=",
"self",
".",
"world_to_surf",
".",
"fwd_pt",
"(",
"world_loc",
")",
".",
"rou... | 62 | 20.375 |
def doctype_matches(text, regex):
"""Check if the doctype matches a regular expression (if present).
Note that this method only checks the first part of a DOCTYPE.
eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'
"""
m = doctype_lookup_re.match(text)
if m is None:
return False
d... | [
"def",
"doctype_matches",
"(",
"text",
",",
"regex",
")",
":",
"m",
"=",
"doctype_lookup_re",
".",
"match",
"(",
"text",
")",
"if",
"m",
"is",
"None",
":",
"return",
"False",
"doctype",
"=",
"m",
".",
"group",
"(",
"2",
")",
"return",
"re",
".",
"c... | 36.272727 | 16.363636 |
def org_by_addr(self, addr):
"""
Returns Organization, ISP, or ASNum name for given IP address.
:arg addr: IP address (e.g. 203.0.113.30)
"""
valid = (const.ORG_EDITION, const.ISP_EDITION,
const.ASNUM_EDITION, const.ASNUM_EDITION_V6)
if self._databaseTyp... | [
"def",
"org_by_addr",
"(",
"self",
",",
"addr",
")",
":",
"valid",
"=",
"(",
"const",
".",
"ORG_EDITION",
",",
"const",
".",
"ISP_EDITION",
",",
"const",
".",
"ASNUM_EDITION",
",",
"const",
".",
"ASNUM_EDITION_V6",
")",
"if",
"self",
".",
"_databaseType",
... | 36.142857 | 15.428571 |
def execute(self, cacheable=False):
"""Returns the XML DOM response of the POST Request from the server"""
if self.network.is_caching_enabled() and cacheable:
response = self._get_cached_response()
else:
response = self._download_response()
return minidom.parseS... | [
"def",
"execute",
"(",
"self",
",",
"cacheable",
"=",
"False",
")",
":",
"if",
"self",
".",
"network",
".",
"is_caching_enabled",
"(",
")",
"and",
"cacheable",
":",
"response",
"=",
"self",
".",
"_get_cached_response",
"(",
")",
"else",
":",
"response",
... | 40.333333 | 21 |
def get_remarks(txt: str) -> ([str], str): # type: ignore
"""
Returns the report split into components and the remarks string
Remarks can include items like RMK and on, NOSIG and on, and BECMG and on
"""
txt = txt.replace('?', '').strip()
# First look for Altimeter in txt
alt_index = len(t... | [
"def",
"get_remarks",
"(",
"txt",
":",
"str",
")",
"->",
"(",
"[",
"str",
"]",
",",
"str",
")",
":",
"# type: ignore",
"txt",
"=",
"txt",
".",
"replace",
"(",
"'?'",
",",
"''",
")",
".",
"strip",
"(",
")",
"# First look for Altimeter in txt",
"alt_inde... | 41.272727 | 15 |
def perform_index_validation(self, data):
"""
Validate any unique indexes specified on the model.
This should happen after all the normal fields have been validated.
This can add error messages to multiple fields.
:return: None
"""
# Build a list of dict containi... | [
"def",
"perform_index_validation",
"(",
"self",
",",
"data",
")",
":",
"# Build a list of dict containing query values for each unique index.",
"index_data",
"=",
"[",
"]",
"for",
"columns",
",",
"unique",
"in",
"self",
".",
"instance",
".",
"_meta",
".",
"indexes",
... | 44.6 | 20.12 |
def info(job_name_or_id):
"""
View detailed information of a job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(job_name_or_id))
except FloydException:
experiment = ExperimentClient().get(job_name_or_id)
task_instance_id = get_module_task_instance_id(experiment... | [
"def",
"info",
"(",
"job_name_or_id",
")",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"job_name_or_id",
")",
")",
"except",
"FloydException",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")... | 48.25 | 20.166667 |
def _get_django_queryset(self):
"""Return Django QuerySet with prefetches properly configured."""
prefetches = []
for field, fprefetch in self.prefetches.items():
has_query = hasattr(fprefetch, 'query')
qs = fprefetch.query.queryset if has_query else None
pre... | [
"def",
"_get_django_queryset",
"(",
"self",
")",
":",
"prefetches",
"=",
"[",
"]",
"for",
"field",
",",
"fprefetch",
"in",
"self",
".",
"prefetches",
".",
"items",
"(",
")",
":",
"has_query",
"=",
"hasattr",
"(",
"fprefetch",
",",
"'query'",
")",
"qs",
... | 32.6875 | 18.875 |
def _request_xml(sport):
"""
Request XML data from scorespro.com
:param sport: sport being played
:type sport: string
:return: XML data
:rtype: string
"""
url = 'http://www.scorespro.com/rss2/live-{}.xml'.format(sport)
r = requests.get(url)
if r.ok:
return _load_xml(r.co... | [
"def",
"_request_xml",
"(",
"sport",
")",
":",
"url",
"=",
"'http://www.scorespro.com/rss2/live-{}.xml'",
".",
"format",
"(",
"sport",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"r",
".",
"ok",
":",
"return",
"_load_xml",
"(",
"r",
"."... | 24.066667 | 15.133333 |
def wait_on_job(self, job_id):
"""Poll task status until STOPPED"""
while True:
status = self.get_job_status(job_id)
if status == 'SUCCEEDED':
logger.info('Batch job {} SUCCEEDED'.format(job_id))
return True
elif status == 'FAILED':
... | [
"def",
"wait_on_job",
"(",
"self",
",",
"job_id",
")",
":",
"while",
"True",
":",
"status",
"=",
"self",
".",
"get_job_status",
"(",
"job_id",
")",
"if",
"status",
"==",
"'SUCCEEDED'",
":",
"logger",
".",
"info",
"(",
"'Batch job {} SUCCEEDED'",
".",
"form... | 41.590909 | 18.409091 |
def _expand_endpoint_name(endpoint_name, flags):
"""
Populate any ``{endpoint_name}`` tags in the flag names for the given
handler, based on the handlers module / file name.
"""
return tuple(flag.format(endpoint_name=endpoint_name) for flag in flags) | [
"def",
"_expand_endpoint_name",
"(",
"endpoint_name",
",",
"flags",
")",
":",
"return",
"tuple",
"(",
"flag",
".",
"format",
"(",
"endpoint_name",
"=",
"endpoint_name",
")",
"for",
"flag",
"in",
"flags",
")"
] | 44.166667 | 15.166667 |
def _get(self, *args, **kwargs):
"""
A wrapper for getting things
:returns: The response of your get
:rtype: dict
"""
response = requests.get(*args, **kwargs)
response.raise_for_status()
return response.json() | [
"def",
"_get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"response",
".",
"raise_for_status",
"(",
")",
"return",
"response",
".",
"jso... | 22.083333 | 14.75 |
def freeze(config, urls_file=None):
"""Freeze the application by creating a static version of it."""
if urls_file:
app = make_app(config=config, URLS_FILE=urls_file)
else:
app = make_app(config=config)
app.logger.info('freezing app to directory: %s' % app.config['FREEZER_DESTINATION'])
... | [
"def",
"freeze",
"(",
"config",
",",
"urls_file",
"=",
"None",
")",
":",
"if",
"urls_file",
":",
"app",
"=",
"make_app",
"(",
"config",
"=",
"config",
",",
"URLS_FILE",
"=",
"urls_file",
")",
"else",
":",
"app",
"=",
"make_app",
"(",
"config",
"=",
"... | 43.052632 | 22.926316 |
def is_same_channel(self, left, right):
""" Check if given nicknames are equal in the server's case mapping. """
return self.normalize(left) == self.normalize(right) | [
"def",
"is_same_channel",
"(",
"self",
",",
"left",
",",
"right",
")",
":",
"return",
"self",
".",
"normalize",
"(",
"left",
")",
"==",
"self",
".",
"normalize",
"(",
"right",
")"
] | 59.666667 | 7 |
def _list_repos():
"""Lists all the installed repos as well as their last start and finish
times from the cron's perspective.
"""
if not args["list"]:
return
#Just loop over the list of repos we have in a server instance. See if
#they also exist in the db's status; if they do, inclu... | [
"def",
"_list_repos",
"(",
")",
":",
"if",
"not",
"args",
"[",
"\"list\"",
"]",
":",
"return",
"#Just loop over the list of repos we have in a server instance. See if",
"#they also exist in the db's status; if they do, include the start/end",
"#times we have saved.",
"from",
"pyci"... | 39.37037 | 20.333333 |
def insert(self):
"""persist the field values of this orm"""
ret = True
schema = self.schema
fields = self.depopulate(False)
q = self.query
q.set_fields(fields)
pk = q.insert()
if pk:
fields = q.fields
fields[schema.pk.name] = pk
... | [
"def",
"insert",
"(",
"self",
")",
":",
"ret",
"=",
"True",
"schema",
"=",
"self",
".",
"schema",
"fields",
"=",
"self",
".",
"depopulate",
"(",
"False",
")",
"q",
"=",
"self",
".",
"query",
"q",
".",
"set_fields",
"(",
"fields",
")",
"pk",
"=",
... | 20.789474 | 19.736842 |
def get_selected_buffer(self):
"""returns currently selected :class:`Buffer` element from list"""
linewidget, _ = self.bufferlist.get_focus()
bufferlinewidget = linewidget.get_focus().original_widget
return bufferlinewidget.get_buffer() | [
"def",
"get_selected_buffer",
"(",
"self",
")",
":",
"linewidget",
",",
"_",
"=",
"self",
".",
"bufferlist",
".",
"get_focus",
"(",
")",
"bufferlinewidget",
"=",
"linewidget",
".",
"get_focus",
"(",
")",
".",
"original_widget",
"return",
"bufferlinewidget",
".... | 52.8 | 10 |
def col_rename(df,col_name,new_col_name):
""" Changes a column name in a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to change
new_col_name - string
New name of column
"""
col_list = list(df.columns)
for index,valu... | [
"def",
"col_rename",
"(",
"df",
",",
"col_name",
",",
"new_col_name",
")",
":",
"col_list",
"=",
"list",
"(",
"df",
".",
"columns",
")",
"for",
"index",
",",
"value",
"in",
"enumerate",
"(",
"col_list",
")",
":",
"if",
"value",
"==",
"col_name",
":",
... | 27.9375 | 11 |
def reload(self, env=None, silent=None): # pragma: no cover
"""Clean end Execute all loaders"""
self.clean()
self.execute_loaders(env, silent) | [
"def",
"reload",
"(",
"self",
",",
"env",
"=",
"None",
",",
"silent",
"=",
"None",
")",
":",
"# pragma: no cover",
"self",
".",
"clean",
"(",
")",
"self",
".",
"execute_loaders",
"(",
"env",
",",
"silent",
")"
] | 41 | 10.25 |
def to_prettytable(df):
"""Convert DataFrame into ``PrettyTable``.
"""
pt = PrettyTable()
pt.field_names = df.columns
for tp in zip(*(l for col, l in df.iteritems())):
pt.add_row(tp)
return pt | [
"def",
"to_prettytable",
"(",
"df",
")",
":",
"pt",
"=",
"PrettyTable",
"(",
")",
"pt",
".",
"field_names",
"=",
"df",
".",
"columns",
"for",
"tp",
"in",
"zip",
"(",
"*",
"(",
"l",
"for",
"col",
",",
"l",
"in",
"df",
".",
"iteritems",
"(",
")",
... | 27.125 | 12.75 |
def enhance_function_signatures(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]:
"""Enhance function signatures
Add required and optional objects to signatures objects for semantic validation
support.
Args:
spec_dict (Mapping[str, Any]): bel specification dictionary
Returns:
Ma... | [
"def",
"enhance_function_signatures",
"(",
"spec_dict",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"for",
"func",
"in",
"spec_dict",
"[",
"\"functions\"",
"]",
"[",
"\"signatures\"",
"]",
":",
"fo... | 43.171875 | 25.78125 |
def paginated_retrieval(methodname, itemtype):
"""decorator factory for retrieval queries from query params"""
return compose(
reusable,
basic_interaction,
map_yield(partial(_params_as_get, methodname)),
) | [
"def",
"paginated_retrieval",
"(",
"methodname",
",",
"itemtype",
")",
":",
"return",
"compose",
"(",
"reusable",
",",
"basic_interaction",
",",
"map_yield",
"(",
"partial",
"(",
"_params_as_get",
",",
"methodname",
")",
")",
",",
")"
] | 33.571429 | 16.285714 |
def _represent_match_traversal(match_traversal):
"""Emit MATCH query code for an entire MATCH traversal sequence."""
output = []
output.append(_first_step_to_match(match_traversal[0]))
for step in match_traversal[1:]:
output.append(_subsequent_step_to_match(step))
return u''.join(output) | [
"def",
"_represent_match_traversal",
"(",
"match_traversal",
")",
":",
"output",
"=",
"[",
"]",
"output",
".",
"append",
"(",
"_first_step_to_match",
"(",
"match_traversal",
"[",
"0",
"]",
")",
")",
"for",
"step",
"in",
"match_traversal",
"[",
"1",
":",
"]",... | 34.444444 | 18.111111 |
def dfa_minimization(dfa: dict) -> dict:
""" Returns the minimization of the DFA in input through a
greatest fix-point method.
Given a completed DFA :math:`A = (Σ, S, s_0 , ρ, F )` there
exists a single minimal DFA :math:`A_m`
which is equivalent to A, i.e. reads the same language
:math:`L(A) =... | [
"def",
"dfa_minimization",
"(",
"dfa",
":",
"dict",
")",
"->",
"dict",
":",
"dfa",
"=",
"dfa_completion",
"(",
"deepcopy",
"(",
"dfa",
")",
")",
"################################################################",
"### Greatest-fixpoint",
"z_current",
"=",
"set",
"(",
... | 36.896226 | 18.09434 |
def tsv_pairs_to_dict(line: str, key_lower: bool = True) -> Dict[str, str]:
r"""
Converts a TSV line into sequential key/value pairs as a dictionary.
For example,
.. code-block:: none
field1\tvalue1\tfield2\tvalue2
becomes
.. code-block:: none
{"field1": "value1", "field2":... | [
"def",
"tsv_pairs_to_dict",
"(",
"line",
":",
"str",
",",
"key_lower",
":",
"bool",
"=",
"True",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"items",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"d",
"=",
"{",
"}",
"# type: Dict[str, str]... | 23.484848 | 22.30303 |
def set_value(self, obj, value):
"""Sets value to model if not empty"""
if value:
obj.set_field_value(self.name, value)
else:
self.delete_value(obj) | [
"def",
"set_value",
"(",
"self",
",",
"obj",
",",
"value",
")",
":",
"if",
"value",
":",
"obj",
".",
"set_field_value",
"(",
"self",
".",
"name",
",",
"value",
")",
"else",
":",
"self",
".",
"delete_value",
"(",
"obj",
")"
] | 31.833333 | 12.166667 |
def _construct_return_type(self, result, axes=None):
"""
Return the type for the ndim of the result.
"""
ndim = getattr(result, 'ndim', None)
# need to assume they are the same
if ndim is None:
if isinstance(result, dict):
ndim = getattr(list(... | [
"def",
"_construct_return_type",
"(",
"self",
",",
"result",
",",
"axes",
"=",
"None",
")",
":",
"ndim",
"=",
"getattr",
"(",
"result",
",",
"'ndim'",
",",
"None",
")",
"# need to assume they are the same",
"if",
"ndim",
"is",
"None",
":",
"if",
"isinstance"... | 33.914286 | 18.885714 |
def __xinclude_libxml2(target, source, env):
"""
Resolving XIncludes, using the libxml2 module.
"""
doc = libxml2.readFile(str(source[0]), None, libxml2.XML_PARSE_NOENT)
doc.xincludeProcessFlags(libxml2.XML_PARSE_NOENT)
doc.saveFile(str(target[0]))
doc.freeDoc()
return None | [
"def",
"__xinclude_libxml2",
"(",
"target",
",",
"source",
",",
"env",
")",
":",
"doc",
"=",
"libxml2",
".",
"readFile",
"(",
"str",
"(",
"source",
"[",
"0",
"]",
")",
",",
"None",
",",
"libxml2",
".",
"XML_PARSE_NOENT",
")",
"doc",
".",
"xincludeProce... | 29.8 | 15.6 |
def import_ohm(filename, verbose=False, reciprocals=False):
"""Construct pandas data frame from BERT`s unified data format (.ohm).
Parameters
----------
filename : string
File path to .ohm file
verbose : bool, optional
Enables extended debug output
reciprocals : int, optional
... | [
"def",
"import_ohm",
"(",
"filename",
",",
"verbose",
"=",
"False",
",",
"reciprocals",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"(",
"\"Reading in %s... \\n\"",
"%",
"filename",
")",
")",
"file",
"=",
"open",
"(",
"filename",
")",
"el... | 30.758242 | 18.549451 |
def create_application_version(self, version_label, key):
"""
Creates an application version
"""
out("Creating application version " + str(version_label) + " for " + str(key))
self.ebs.create_application_version(self.app_name, version_label,
... | [
"def",
"create_application_version",
"(",
"self",
",",
"version_label",
",",
"key",
")",
":",
"out",
"(",
"\"Creating application version \"",
"+",
"str",
"(",
"version_label",
")",
"+",
"\" for \"",
"+",
"str",
"(",
"key",
")",
")",
"self",
".",
"ebs",
".",... | 54.142857 | 23 |
def any2sql(func, definition_dict=None, **definition_kwargs):
"""Handle general to SQL conversion.
:param func: function to be called on the given definition
:param definition_dict: statement definition in dict
:param definition_kwargs: statement definition as kwargs
:return: raw SQL statement
... | [
"def",
"any2sql",
"(",
"func",
",",
"definition_dict",
"=",
"None",
",",
"*",
"*",
"definition_kwargs",
")",
":",
"if",
"definition_dict",
"and",
"definition_kwargs",
":",
"raise",
"InputError",
"(",
"\"Cannot process dict and kwargs input at the same time\"",
")",
"d... | 37.285714 | 23.392857 |
def add(self, rule, method, target, name=None, static=False):
''' Add a new route or replace the target for an existing route. '''
if static:
depr("Use a backslash to escape ':' in routes.") # 0.9
rule = rule.replace(':','\\:')
if rule in self.routes:
self.ro... | [
"def",
"add",
"(",
"self",
",",
"rule",
",",
"method",
",",
"target",
",",
"name",
"=",
"None",
",",
"static",
"=",
"False",
")",
":",
"if",
"static",
":",
"depr",
"(",
"\"Use a backslash to escape ':' in routes.\"",
")",
"# 0.9",
"rule",
"=",
"rule",
".... | 42.066667 | 19 |
def set_http_header(self, coap_response):
"""
Sets http headers.
:param coap_response: the coap response
"""
logger.debug(
("Server: %s\n"\
"codice risposta: %s\n"\
"PROXED: %s\n"\
"payload r... | [
"def",
"set_http_header",
"(",
"self",
",",
"coap_response",
")",
":",
"logger",
".",
"debug",
"(",
"(",
"\"Server: %s\\n\"",
"\"codice risposta: %s\\n\"",
"\"PROXED: %s\\n\"",
"\"payload risposta: %s\"",
")",
",",
"coap_response",
".",
"source",
",",
"coap_response",
... | 36.388889 | 11.388889 |
def input(self, str):
""" Defines input string, removing current lexer.
"""
self.input_data = str
self.lex = lex.lex(object=self)
self.lex.input(self.input_data) | [
"def",
"input",
"(",
"self",
",",
"str",
")",
":",
"self",
".",
"input_data",
"=",
"str",
"self",
".",
"lex",
"=",
"lex",
".",
"lex",
"(",
"object",
"=",
"self",
")",
"self",
".",
"lex",
".",
"input",
"(",
"self",
".",
"input_data",
")"
] | 32.666667 | 5.333333 |
def pipeline_status(url, pipeline_id, auth, verify_ssl):
"""Retrieve the current status for a pipeline.
Args:
url (str): the host url in the form 'http://host:port/'.
pipeline_id (str): the ID of of the exported pipeline.
auth (tuple): a tuple of username, and password... | [
"def",
"pipeline_status",
"(",
"url",
",",
"pipeline_id",
",",
"auth",
",",
"verify_ssl",
")",
":",
"status_result",
"=",
"requests",
".",
"get",
"(",
"url",
"+",
"'/'",
"+",
"pipeline_id",
"+",
"'/status'",
",",
"headers",
"=",
"X_REQ_BY",
",",
"auth",
... | 39.222222 | 22.944444 |
def export(self, container, chunk_size=DEFAULT_DATA_CHUNK_SIZE):
"""
Export the contents of a filesystem as a tar archive.
Args:
container (str): The container to export
chunk_size (int): The number of bytes returned by each iteration
of the generator. If... | [
"def",
"export",
"(",
"self",
",",
"container",
",",
"chunk_size",
"=",
"DEFAULT_DATA_CHUNK_SIZE",
")",
":",
"res",
"=",
"self",
".",
"_get",
"(",
"self",
".",
"_url",
"(",
"\"/containers/{0}/export\"",
",",
"container",
")",
",",
"stream",
"=",
"True",
")... | 35.904762 | 21.904762 |
def upsert_and_get(self, conflict_target: List, fields: Dict, index_predicate: str=None):
"""Creates a new record or updates the existing one
with the specified data and then gets the row.
Arguments:
conflict_target:
Fields to pass into the ON CONFLICT clause.
... | [
"def",
"upsert_and_get",
"(",
"self",
",",
"conflict_target",
":",
"List",
",",
"fields",
":",
"Dict",
",",
"index_predicate",
":",
"str",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_queryset",
"(",
")",
".",
"upsert_and_get",
"(",
"conflict_target",
... | 33.6 | 23.5 |
def _parse_message_to_mqtt(self, data):
"""Parse a mysensors command string.
Return a MQTT topic, payload and qos-level as a tuple.
"""
msg = Message(data, self)
payload = str(msg.payload)
msg.payload = ''
# prefix/node/child/type/ack/subtype : payload
re... | [
"def",
"_parse_message_to_mqtt",
"(",
"self",
",",
"data",
")",
":",
"msg",
"=",
"Message",
"(",
"data",
",",
"self",
")",
"payload",
"=",
"str",
"(",
"msg",
".",
"payload",
")",
"msg",
".",
"payload",
"=",
"''",
"# prefix/node/child/type/ack/subtype : paylo... | 36.818182 | 13.090909 |
def do_walk(data_path):
"""
Walk through data_files and list all in dict format
"""
data_files = {}
def cond(File, prefix):
"""
Return True for useful files
Return False for non-useful files
"""
file_path = path.join(prefix, 'data_files', File)
return ... | [
"def",
"do_walk",
"(",
"data_path",
")",
":",
"data_files",
"=",
"{",
"}",
"def",
"cond",
"(",
"File",
",",
"prefix",
")",
":",
"\"\"\"\n Return True for useful files\n Return False for non-useful files\n \"\"\"",
"file_path",
"=",
"path",
".",
"joi... | 32.384615 | 12 |
def build_dynamic_field(self, group, field_meta):
"""
Builds a field based on JIRA's meta field information
"""
schema = field_meta['schema']
# set up some defaults for form fields
fieldtype = 'text'
fkwargs = {
'label': field_meta['name'],
... | [
"def",
"build_dynamic_field",
"(",
"self",
",",
"group",
",",
"field_meta",
")",
":",
"schema",
"=",
"field_meta",
"[",
"'schema'",
"]",
"# set up some defaults for form fields",
"fieldtype",
"=",
"'text'",
"fkwargs",
"=",
"{",
"'label'",
":",
"field_meta",
"[",
... | 42.58 | 19.86 |
def get_form_list(self):
"""
This method returns a form_list based on the initial form list but
checks if there is a condition method/value in the condition_list.
If an entry exists in the condition list, it will call/read the value
and respect the result. (True means add the for... | [
"def",
"get_form_list",
"(",
"self",
")",
":",
"form_list",
"=",
"SortedDict",
"(",
")",
"for",
"form_key",
",",
"form_class",
"in",
"self",
".",
"form_list",
".",
"iteritems",
"(",
")",
":",
"# try to fetch the value from condition list, by default, the form",
"# g... | 46.545455 | 20.363636 |
def _imul(self, n):
"""Concatenate n copies of self in place. Return self."""
assert n >= 0
if not n:
self._clear()
return self
m = 1
old_len = self.len
while m * 2 < n:
self._append(self)
m *= 2
self._append(self[0:... | [
"def",
"_imul",
"(",
"self",
",",
"n",
")",
":",
"assert",
"n",
">=",
"0",
"if",
"not",
"n",
":",
"self",
".",
"_clear",
"(",
")",
"return",
"self",
"m",
"=",
"1",
"old_len",
"=",
"self",
".",
"len",
"while",
"m",
"*",
"2",
"<",
"n",
":",
"... | 26.692308 | 16.307692 |
def complete(self):
"""Task is complete if completion marker is set and all requirements are complete
"""
is_complete = super(ORMWrapperTask, self).complete()
for req in self.requires():
is_complete &= req.complete()
return is_complete | [
"def",
"complete",
"(",
"self",
")",
":",
"is_complete",
"=",
"super",
"(",
"ORMWrapperTask",
",",
"self",
")",
".",
"complete",
"(",
")",
"for",
"req",
"in",
"self",
".",
"requires",
"(",
")",
":",
"is_complete",
"&=",
"req",
".",
"complete",
"(",
"... | 35.125 | 12.625 |
def create_shared_folder(self, name, host_path, writable, automount, auto_mount_point):
"""Creates a new global shared folder by associating the given logical
name with the given host path, adds it to the collection of shared
folders and starts sharing it. Refer to the description of
:py... | [
"def",
"create_shared_folder",
"(",
"self",
",",
"name",
",",
"host_path",
",",
"writable",
",",
"automount",
",",
"auto_mount_point",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"name can only be... | 46.775 | 24.05 |
def instantiate_tasks(self):
""" All loaded tasks are initialized. Depending on configuration fails in such instantiations may be silent """
self.tasks_instances = {}
for task_name, task_class in self.tasks_classes.items():
try:
self.tasks_instances[task_name] = task_... | [
"def",
"instantiate_tasks",
"(",
"self",
")",
":",
"self",
".",
"tasks_instances",
"=",
"{",
"}",
"for",
"task_name",
",",
"task_class",
"in",
"self",
".",
"tasks_classes",
".",
"items",
"(",
")",
":",
"try",
":",
"self",
".",
"tasks_instances",
"[",
"ta... | 61.9 | 23.6 |
def process(self, block=True):
'''process and display graph'''
self.msg_types = set()
self.multiplier = []
self.field_types = []
# work out msg types we are interested in
self.x = []
self.y = []
self.modes = []
self.axes = []
self.first_on... | [
"def",
"process",
"(",
"self",
",",
"block",
"=",
"True",
")",
":",
"self",
".",
"msg_types",
"=",
"set",
"(",
")",
"self",
".",
"multiplier",
"=",
"[",
"]",
"self",
".",
"field_types",
"=",
"[",
"]",
"# work out msg types we are interested in",
"self",
... | 33.740741 | 14.333333 |
def shell_sort(arr):
''' Shell Sort
Complexity: O(n^2)
'''
n = len(arr)
# Initialize size of the gap
gap = n//2
while gap > 0:
y_index = gap
while y_index < len(arr):
y = arr[y_index]
x_index = y_index - gap
while x_index >= 0 and ... | [
"def",
"shell_sort",
"(",
"arr",
")",
":",
"n",
"=",
"len",
"(",
"arr",
")",
"# Initialize size of the gap",
"gap",
"=",
"n",
"//",
"2",
"while",
"gap",
">",
"0",
":",
"y_index",
"=",
"gap",
"while",
"y_index",
"<",
"len",
"(",
"arr",
")",
":",
"y"... | 24.809524 | 17.190476 |
def main():
"""
main function
"""
s = ttk.Style()
s.theme_use('clam')
ents = makeform(root)
root.mainloop() | [
"def",
"main",
"(",
")",
":",
"s",
"=",
"ttk",
".",
"Style",
"(",
")",
"s",
".",
"theme_use",
"(",
"'clam'",
")",
"ents",
"=",
"makeform",
"(",
"root",
")",
"root",
".",
"mainloop",
"(",
")"
] | 13.375 | 17.625 |
def __add_text(self, text):
"""Adds the given Unicode text as a locally defined symbol."""
if text is not None and not isinstance(text, six.text_type):
raise TypeError('Local symbol definition must be a Unicode sequence or None: %r' % text)
sid = self.__new_sid()
location = N... | [
"def",
"__add_text",
"(",
"self",
",",
"text",
")",
":",
"if",
"text",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"text",
",",
"six",
".",
"text_type",
")",
":",
"raise",
"TypeError",
"(",
"'Local symbol definition must be a Unicode sequence or None: ... | 45.272727 | 16.727273 |
def set_fields(
self,
new_fields):
"""set_fields
Change the fields that will be added in on
a log
:param new_fields: new fields to patch in
"""
self.org_fields = {}
self.fields_to_add = {}
for k in new_fields:
self.org... | [
"def",
"set_fields",
"(",
"self",
",",
"new_fields",
")",
":",
"self",
".",
"org_fields",
"=",
"{",
"}",
"self",
".",
"fields_to_add",
"=",
"{",
"}",
"for",
"k",
"in",
"new_fields",
":",
"self",
".",
"org_fields",
"[",
"k",
"]",
"=",
"new_fields",
"[... | 25.466667 | 15.866667 |
def load_config(self):
"""Load configuration: tree widget state"""
expanded_state = self.get_option('expanded_state', None)
# Sometimes the expanded state option may be truncated in .ini file
# (for an unknown reason), in this case it would be converted to a
# string by 'use... | [
"def",
"load_config",
"(",
"self",
")",
":",
"expanded_state",
"=",
"self",
".",
"get_option",
"(",
"'expanded_state'",
",",
"None",
")",
"# Sometimes the expanded state option may be truncated in .ini file\r",
"# (for an unknown reason), in this case it would be converted to a\r",... | 51.2 | 16 |
def encoder(self, query: Dict[str, Any]):
"""编码请求为bytes.
检查是否使用debug模式和是否对数据进行压缩.之后根据状态将python字典形式的请求编码为字节串.
Parameters:
query (Dict[str, Any]): - python字典形式的请求数据
Return:
(bytes): - 请求的字节串
"""
if self.debug is True:
queryb = json.... | [
"def",
"encoder",
"(",
"self",
",",
"query",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"if",
"self",
".",
"debug",
"is",
"True",
":",
"queryb",
"=",
"json",
".",
"dumps",
"(",
"query",
",",
"ensure_ascii",
"=",
"False",
")",
".",
"encod... | 22.16 | 20.52 |
def load_dot_env():
"""Loads .env file into sys.environ."""
if not environments.PIPENV_DONT_LOAD_ENV:
# If the project doesn't exist yet, check current directory for a .env file
project_directory = project.project_directory or "."
dotenv_file = environments.PIPENV_DOTENV_LOCATION or os.s... | [
"def",
"load_dot_env",
"(",
")",
":",
"if",
"not",
"environments",
".",
"PIPENV_DONT_LOAD_ENV",
":",
"# If the project doesn't exist yet, check current directory for a .env file",
"project_directory",
"=",
"project",
".",
"project_directory",
"or",
"\".\"",
"dotenv_file",
"="... | 44.230769 | 22.961538 |
def use_comparative_assessment_part_bank_view(self):
"""Pass through to provider AssessmentPartBankSession.use_comparative_assessment_part_bank_view"""
self._bank_view = COMPARATIVE
# self._get_provider_session('assessment_part_bank_session') # To make sure the session is tracked
for ses... | [
"def",
"use_comparative_assessment_part_bank_view",
"(",
"self",
")",
":",
"self",
".",
"_bank_view",
"=",
"COMPARATIVE",
"# self._get_provider_session('assessment_part_bank_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provider_sessio... | 52.777778 | 17.222222 |
def convert(cls, obj, parent):
"""Converts objects to registered tracked types
This checks the type of the given object against the registered tracked
types. When a match is found, the given object will be converted to the
tracked type, its parent set to the provided parent, and returne... | [
"def",
"convert",
"(",
"cls",
",",
"obj",
",",
"parent",
")",
":",
"replacement_type",
"=",
"cls",
".",
"_type_mapping",
".",
"get",
"(",
"type",
"(",
"obj",
")",
")",
"if",
"replacement_type",
"is",
"not",
"None",
":",
"new",
"=",
"replacement_type",
... | 40.3125 | 19.9375 |
def resample(self, resampledWaveTab):
"""Resample the spectrum for the given wavelength set.
Given wavelength array must be monotonically increasing
or decreasing. Flux interpolation is done using :func:`numpy.interp`.
Parameters
----------
resampledWaveTab : array_like... | [
"def",
"resample",
"(",
"self",
",",
"resampledWaveTab",
")",
":",
"# Check whether the input wavetab is in descending order",
"if",
"resampledWaveTab",
"[",
"0",
"]",
"<",
"resampledWaveTab",
"[",
"-",
"1",
"]",
":",
"newwave",
"=",
"resampledWaveTab",
"newasc",
"=... | 35.327273 | 18.618182 |
def _get_shoulds(options):
"""Return the list of 'SHOULD' validators for the correct version of STIX.
Args:
options: ValidationOptions instance with validation options for this
validation run, including the STIX spec version.
"""
if options.version == '2.0':
return shoulds20... | [
"def",
"_get_shoulds",
"(",
"options",
")",
":",
"if",
"options",
".",
"version",
"==",
"'2.0'",
":",
"return",
"shoulds20",
".",
"list_shoulds",
"(",
"options",
")",
"else",
":",
"return",
"shoulds21",
".",
"list_shoulds",
"(",
"options",
")"
] | 35.363636 | 17.454545 |
def plot_volume_exposures_longshort(longed_threshold, shorted_threshold,
percentile, ax=None):
"""
Plots outputs of compute_volume_exposures as line graphs
Parameters
----------
longed_threshold, shorted_threshold : pd.Series
Series of longed and shorted ... | [
"def",
"plot_volume_exposures_longshort",
"(",
"longed_threshold",
",",
"shorted_threshold",
",",
"percentile",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"ax",
".",
"plot",
"(",
"longed_thresho... | 33.1 | 19.633333 |
def p_function(self, p):
'''function : oneway function_type IDENTIFIER '(' field_seq ')' \
throws annotations '''
p[0] = ast.Function(
name=p[3],
parameters=p[5],
return_type=p[2],
exceptions=p[7],
oneway=p[1],
... | [
"def",
"p_function",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Function",
"(",
"name",
"=",
"p",
"[",
"3",
"]",
",",
"parameters",
"=",
"p",
"[",
"5",
"]",
",",
"return_type",
"=",
"p",
"[",
"2",
"]",
",",
"exce... | 30.75 | 15.416667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.