text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def __generate_point(self, index_cluster):
"""!
@brief Generates point in line with parameters of specified cluster.
@param[in] index_cluster (uint): Index of cluster whose parameters are used for point generation.
@return (list) New generated point in line with normal distributi... | [
"def",
"__generate_point",
"(",
"self",
",",
"index_cluster",
")",
":",
"return",
"[",
"random",
".",
"gauss",
"(",
"self",
".",
"__cluster_centers",
"[",
"index_cluster",
"]",
"[",
"index_dimension",
"]",
",",
"self",
".",
"__cluster_width",
"[",
"index_clust... | 48.166667 | 32.25 |
def fixPoint(self, plotterPoint, canvasPoint):
'adjust visibleBox.xymin so that canvasPoint is plotted at plotterPoint'
self.visibleBox.xmin = canvasPoint.x - self.canvasW(plotterPoint.x-self.plotviewBox.xmin)
self.visibleBox.ymin = canvasPoint.y - self.canvasH(plotterPoint.y-self.plotviewBox.ym... | [
"def",
"fixPoint",
"(",
"self",
",",
"plotterPoint",
",",
"canvasPoint",
")",
":",
"self",
".",
"visibleBox",
".",
"xmin",
"=",
"canvasPoint",
".",
"x",
"-",
"self",
".",
"canvasW",
"(",
"plotterPoint",
".",
"x",
"-",
"self",
".",
"plotviewBox",
".",
"... | 68.4 | 35.6 |
def _readline(self, timeout=1):
"""
Read line from serial port.
:param timeout: timeout, default is 1
:return: stripped line or None
"""
line = self.port.readline(timeout=timeout)
return strip_escape(line.strip()) if line is not None else line | [
"def",
"_readline",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"line",
"=",
"self",
".",
"port",
".",
"readline",
"(",
"timeout",
"=",
"timeout",
")",
"return",
"strip_escape",
"(",
"line",
".",
"strip",
"(",
")",
")",
"if",
"line",
"is",
"no... | 32.444444 | 11.333333 |
def do_raw_get(self, line):
"""raw_get <peer>
"""
def f(p, args):
result = p.raw_get()
tree = ET.fromstring(result)
validate(tree)
print(et_tostring_pp(tree))
self._request(line, f) | [
"def",
"do_raw_get",
"(",
"self",
",",
"line",
")",
":",
"def",
"f",
"(",
"p",
",",
"args",
")",
":",
"result",
"=",
"p",
".",
"raw_get",
"(",
")",
"tree",
"=",
"ET",
".",
"fromstring",
"(",
"result",
")",
"validate",
"(",
"tree",
")",
"print",
... | 23 | 13 |
def projC(gamma, q):
"""return the KL projection on the column constrints """
return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10)) | [
"def",
"projC",
"(",
"gamma",
",",
"q",
")",
":",
"return",
"np",
".",
"multiply",
"(",
"gamma",
",",
"q",
"/",
"np",
".",
"maximum",
"(",
"np",
".",
"sum",
"(",
"gamma",
",",
"axis",
"=",
"0",
")",
",",
"1e-10",
")",
")"
] | 51.666667 | 18.333333 |
def for_stmt(self, for_loc, target, in_loc, iter, for_colon_loc, body, else_opt):
"""for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]"""
stmt = ast.For(target=self._assignable(target), iter=iter, body=body, orelse=[],
keyword_loc=for_loc, in_loc=in_loc, for_colo... | [
"def",
"for_stmt",
"(",
"self",
",",
"for_loc",
",",
"target",
",",
"in_loc",
",",
"iter",
",",
"for_colon_loc",
",",
"body",
",",
"else_opt",
")",
":",
"stmt",
"=",
"ast",
".",
"For",
"(",
"target",
"=",
"self",
".",
"_assignable",
"(",
"target",
")... | 55.909091 | 26.909091 |
def load_acknowledge_config(self, file_id):
"""
Loads the CWR acknowledge config
:return: the values matrix
"""
if self._cwr_defaults is None:
self._cwr_defaults = self._reader.read_yaml_file(
'acknowledge_config_%s.yml' % file_id)
return self... | [
"def",
"load_acknowledge_config",
"(",
"self",
",",
"file_id",
")",
":",
"if",
"self",
".",
"_cwr_defaults",
"is",
"None",
":",
"self",
".",
"_cwr_defaults",
"=",
"self",
".",
"_reader",
".",
"read_yaml_file",
"(",
"'acknowledge_config_%s.yml'",
"%",
"file_id",
... | 32.5 | 9.3 |
def get_all(self) -> List[Commodity]:
""" Loads all non-currency commodities, assuming they are stocks. """
query = (
self.query
.order_by(Commodity.namespace, Commodity.mnemonic)
)
return query.all() | [
"def",
"get_all",
"(",
"self",
")",
"->",
"List",
"[",
"Commodity",
"]",
":",
"query",
"=",
"(",
"self",
".",
"query",
".",
"order_by",
"(",
"Commodity",
".",
"namespace",
",",
"Commodity",
".",
"mnemonic",
")",
")",
"return",
"query",
".",
"all",
"(... | 35.714286 | 15.857143 |
def sliding_window_3d(image, step_size, window_size, mask=None, only_whole=True, include_last=False):
"""
Creates generator of sliding windows.
:param image: input image
:param step_size: number of pixels we are going to skip in both the (x, y) direction
:param window_size: the width and height of t... | [
"def",
"sliding_window_3d",
"(",
"image",
",",
"step_size",
",",
"window_size",
",",
"mask",
"=",
"None",
",",
"only_whole",
"=",
"True",
",",
"include_last",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"step_size",
",",
"tuple",
")",
":",
"s... | 53.55102 | 19.714286 |
def download_workflow_description_file(self, filename):
'''Downloads the workflow description and writes it to a *YAML* file.
Parameters
----------
filename: str
path to the file to which description should be written
See also
--------
:meth:`tmclien... | [
"def",
"download_workflow_description_file",
"(",
"self",
",",
"filename",
")",
":",
"description",
"=",
"self",
".",
"download_workflow_description",
"(",
")",
"logger",
".",
"info",
"(",
"'write workflow description to file: %s'",
",",
"filename",
")",
"with",
"open... | 36.052632 | 23.842105 |
def _update_resume_for_completed(self):
# type: (Descriptor) -> None
"""Update resume for completion
:param Descriptor self: this
"""
if not self.is_resumable:
return
with self._meta_lock:
self._resume_mgr.add_or_update_record(
self... | [
"def",
"_update_resume_for_completed",
"(",
"self",
")",
":",
"# type: (Descriptor) -> None",
"if",
"not",
"self",
".",
"is_resumable",
":",
"return",
"with",
"self",
".",
"_meta_lock",
":",
"self",
".",
"_resume_mgr",
".",
"add_or_update_record",
"(",
"self",
"."... | 35 | 10.166667 |
def violationScore(self,meterPos,pos_i=None,slot_i=None,num_slots=None,all_positions=None,parse=None):
"""call this on a MeterPosition to return an integer representing the violation value
for this Constraint in this MPos (0 represents no violation)"""
violation = None
if self.constr != None:
violation = sel... | [
"def",
"violationScore",
"(",
"self",
",",
"meterPos",
",",
"pos_i",
"=",
"None",
",",
"slot_i",
"=",
"None",
",",
"num_slots",
"=",
"None",
",",
"all_positions",
"=",
"None",
",",
"parse",
"=",
"None",
")",
":",
"violation",
"=",
"None",
"if",
"self",... | 36.666667 | 22.428571 |
def get(self, default=None):
"""
return the cached value or default if it can't be found
:param default: default value
:return: cached value
"""
d = cache.get(self.key)
return ((json.loads(d.decode('utf-8')) if self.serialize else d)
if d is not N... | [
"def",
"get",
"(",
"self",
",",
"default",
"=",
"None",
")",
":",
"d",
"=",
"cache",
".",
"get",
"(",
"self",
".",
"key",
")",
"return",
"(",
"(",
"json",
".",
"loads",
"(",
"d",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"if",
"self",
".",
"se... | 31.181818 | 13.545455 |
def _get_bls_stats(stimes,
smags,
serrs,
thistransdepth,
thistransduration,
ingressdurationfraction,
nphasebins,
thistransingressbin,
thistransegressbin,
... | [
"def",
"_get_bls_stats",
"(",
"stimes",
",",
"smags",
",",
"serrs",
",",
"thistransdepth",
",",
"thistransduration",
",",
"ingressdurationfraction",
",",
"nphasebins",
",",
"thistransingressbin",
",",
"thistransegressbin",
",",
"thisbestperiod",
",",
"thisnphasebins",
... | 36.345833 | 19.120833 |
def _set_src_ip_host(self, v, load=False):
"""
Setter method for src_ip_host, mapped from YANG variable /overlay/access_list/type/vxlan/extended/ext_seq/src_ip_host (inet:ipv4-address)
If this variable is read-only (config: false) in the
source YANG file, then _set_src_ip_host is considered as a private... | [
"def",
"_set_src_ip_host",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"ba... | 105.5 | 50.636364 |
def dict_pop_or(d, key, default=None):
""" Try popping a key from a dict.
Instead of raising KeyError, just return the default value.
"""
val = default
with suppress(KeyError):
val = d.pop(key)
return val | [
"def",
"dict_pop_or",
"(",
"d",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"val",
"=",
"default",
"with",
"suppress",
"(",
"KeyError",
")",
":",
"val",
"=",
"d",
".",
"pop",
"(",
"key",
")",
"return",
"val"
] | 29.125 | 13.25 |
def writeProxy(self, obj):
"""
Encodes a proxied object to the stream.
@since: 0.6
"""
proxy = self.context.getProxyForObject(obj)
self.writeObject(proxy, is_proxy=True) | [
"def",
"writeProxy",
"(",
"self",
",",
"obj",
")",
":",
"proxy",
"=",
"self",
".",
"context",
".",
"getProxyForObject",
"(",
"obj",
")",
"self",
".",
"writeObject",
"(",
"proxy",
",",
"is_proxy",
"=",
"True",
")"
] | 23.444444 | 15.444444 |
async def _load_all(self):
'''
Load all the appointments from persistent storage
'''
to_delete = []
for iden, val in self._hivedict.items():
try:
appt = _Appt.unpack(val)
if appt.iden != iden:
raise s_exc.Inconsisten... | [
"async",
"def",
"_load_all",
"(",
"self",
")",
":",
"to_delete",
"=",
"[",
"]",
"for",
"iden",
",",
"val",
"in",
"self",
".",
"_hivedict",
".",
"items",
"(",
")",
":",
"try",
":",
"appt",
"=",
"_Appt",
".",
"unpack",
"(",
"val",
")",
"if",
"appt"... | 41.56 | 21 |
def _replace_coerce(self, to_replace, value, inplace=True, regex=False,
convert=False, mask=None):
"""
Replace value corresponding to the given boolean array with another
value.
Parameters
----------
to_replace : object or pattern
Scal... | [
"def",
"_replace_coerce",
"(",
"self",
",",
"to_replace",
",",
"value",
",",
"inplace",
"=",
"True",
",",
"regex",
"=",
"False",
",",
"convert",
"=",
"False",
",",
"mask",
"=",
"None",
")",
":",
"if",
"mask",
".",
"any",
"(",
")",
":",
"block",
"="... | 37.470588 | 17.588235 |
def visit(self, node):
"""walk on the tree from <node>, getting callbacks from handler"""
method = self.get_callbacks(node)[0]
if method is not None:
method(node) | [
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"method",
"=",
"self",
".",
"get_callbacks",
"(",
"node",
")",
"[",
"0",
"]",
"if",
"method",
"is",
"not",
"None",
":",
"method",
"(",
"node",
")"
] | 38.8 | 9.6 |
def parse_number_of_html_pages(html_question):
"""Parse number of answer pages to paginate over them.
:param html_question: raw HTML question element
:returns: an integer with the number of pages
"""
bs_question = bs4.BeautifulSoup(html_question, "html.parser")
try:
... | [
"def",
"parse_number_of_html_pages",
"(",
"html_question",
")",
":",
"bs_question",
"=",
"bs4",
".",
"BeautifulSoup",
"(",
"html_question",
",",
"\"html.parser\"",
")",
"try",
":",
"bs_question",
".",
"select",
"(",
"'div.paginator'",
")",
"[",
"0",
"]",
"except... | 35.928571 | 20.571429 |
def permute(self, qubits: Qubits) -> 'Density':
"""Return a copy of this state with qubit labels permuted"""
vec = self.vec.permute(qubits)
return Density(vec.tensor, vec.qubits, self._memory) | [
"def",
"permute",
"(",
"self",
",",
"qubits",
":",
"Qubits",
")",
"->",
"'Density'",
":",
"vec",
"=",
"self",
".",
"vec",
".",
"permute",
"(",
"qubits",
")",
"return",
"Density",
"(",
"vec",
".",
"tensor",
",",
"vec",
".",
"qubits",
",",
"self",
".... | 53.25 | 7.25 |
def index(
config, date=None, directory=None, concurrency=5, accounts=None,
tag=None, verbose=False):
"""index traildbs directly from s3 for multiple accounts.
context: assumes a daily traildb file in s3 with dated key path
"""
logging.basicConfig(level=(verbose and logging.DEBUG or lo... | [
"def",
"index",
"(",
"config",
",",
"date",
"=",
"None",
",",
"directory",
"=",
"None",
",",
"concurrency",
"=",
"5",
",",
"accounts",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"logging",
".",
"basicConfig",
"(",
... | 37.090909 | 18.4 |
def _set_ipv6_config(self, v, load=False):
"""
Setter method for ipv6_config, mapped from YANG variable /routing_system/interface/ve/ipv6/ipv6_config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ipv6_config is considered as a private
method. Backends l... | [
"def",
"_set_ipv6_config",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"ba... | 86.636364 | 40.863636 |
def get_artifact_filename(self, package_name, artifact_name):
"""
Similar to pkg_resources.resource_filename, however this works
with the information cached in this registry instance, and
arguments are not quite the same.
Arguments:
package_name
The name of ... | [
"def",
"get_artifact_filename",
"(",
"self",
",",
"package_name",
",",
"artifact_name",
")",
":",
"project_name",
"=",
"self",
".",
"packages",
".",
"normalize",
"(",
"package_name",
")",
"return",
"self",
".",
"records",
".",
"get",
"(",
"(",
"project_name",
... | 34.105263 | 21.157895 |
def width(self, level):
"""
Width at given level
:param level:
:return:
"""
return self.x_at_y(level, reverse=True) - self.x_at_y(level) | [
"def",
"width",
"(",
"self",
",",
"level",
")",
":",
"return",
"self",
".",
"x_at_y",
"(",
"level",
",",
"reverse",
"=",
"True",
")",
"-",
"self",
".",
"x_at_y",
"(",
"level",
")"
] | 25.428571 | 14.285714 |
def save_ext(self):
"""Write the internal data into an external data file."""
try:
sequencemanager = hydpy.pub.sequencemanager
except AttributeError:
raise RuntimeError(
'The time series of sequence %s cannot be saved. Firstly,'
'you have ... | [
"def",
"save_ext",
"(",
"self",
")",
":",
"try",
":",
"sequencemanager",
"=",
"hydpy",
".",
"pub",
".",
"sequencemanager",
"except",
"AttributeError",
":",
"raise",
"RuntimeError",
"(",
"'The time series of sequence %s cannot be saved. Firstly,'",
"'you have to prepare `... | 44.5 | 15.8 |
def get_stack_frame(self, max_size = None):
"""
Reads the contents of the current stack frame.
Only works for functions with standard prologue and epilogue.
@type max_size: int
@param max_size: (Optional) Maximum amount of bytes to read.
@rtype: str
@return: S... | [
"def",
"get_stack_frame",
"(",
"self",
",",
"max_size",
"=",
"None",
")",
":",
"sp",
",",
"fp",
"=",
"self",
".",
"get_stack_frame_range",
"(",
")",
"size",
"=",
"fp",
"-",
"sp",
"if",
"max_size",
"and",
"size",
">",
"max_size",
":",
"size",
"=",
"ma... | 35.96 | 17.56 |
def _iter_font_files_in(cls, directory):
"""
Generate the OpenType font files found in and under *directory*. Each
item is a key/value pair. The key is a (family_name, is_bold,
is_italic) 3-tuple, like ('Arial', True, False), and the value is the
absolute path to the font file.
... | [
"def",
"_iter_font_files_in",
"(",
"cls",
",",
"directory",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"for",
"filename",
"in",
"files",
":",
"file_ext",
"=",
"os",
".",
"path",
".",
"spli... | 49.2 | 15.6 |
def print_all_commands(self, *, no_pager=False):
"""Print help for all commands.
Commands are sorted in alphabetical order and wrapping is done
based on the width of the terminal.
"""
formatter = self.parent_parser._get_formatter()
command_names = sorted(self.parent_pars... | [
"def",
"print_all_commands",
"(",
"self",
",",
"*",
",",
"no_pager",
"=",
"False",
")",
":",
"formatter",
"=",
"self",
".",
"parent_parser",
".",
"_get_formatter",
"(",
")",
"command_names",
"=",
"sorted",
"(",
"self",
".",
"parent_parser",
".",
"subparsers"... | 43.068966 | 15.068966 |
def get_group_partition(group, partition_count):
"""Given a group name, return the partition number of the consumer offset
topic containing the data associated to that group."""
def java_string_hashcode(s):
h = 0
for c in s:
h = (31 * h + ord(c)) & 0xFFFFFFFF
return ((h +... | [
"def",
"get_group_partition",
"(",
"group",
",",
"partition_count",
")",
":",
"def",
"java_string_hashcode",
"(",
"s",
")",
":",
"h",
"=",
"0",
"for",
"c",
"in",
"s",
":",
"h",
"=",
"(",
"31",
"*",
"h",
"+",
"ord",
"(",
"c",
")",
")",
"&",
"0xFFF... | 45.888889 | 12.222222 |
def _check_vmware_player_requirements(self, player_version):
"""
Check minimum requirements to use VMware Player.
VIX 1.13 was the release for Player 6.
VIX 1.14 was the release for Player 7.
VIX 1.15 was the release for Workstation Player 12.
:param player_version: VMw... | [
"def",
"_check_vmware_player_requirements",
"(",
"self",
",",
"player_version",
")",
":",
"player_version",
"=",
"int",
"(",
"player_version",
")",
"if",
"player_version",
"<",
"6",
":",
"raise",
"VMwareError",
"(",
"\"Using VMware Player requires version 6 or above\"",
... | 42 | 19.619048 |
def make_grammar(allow_errors):
"""Make the part of the grammar that depends on whether we swallow errors or not."""
if allow_errors in GRAMMAR_CACHE:
return GRAMMAR_CACHE[allow_errors]
tuple = p.Forward()
catch_errors = p.Forward()
catch_errors << (p.Regex('[^{};]*') - p.Optional(tuple) - p.Regex('[^;}]... | [
"def",
"make_grammar",
"(",
"allow_errors",
")",
":",
"if",
"allow_errors",
"in",
"GRAMMAR_CACHE",
":",
"return",
"GRAMMAR_CACHE",
"[",
"allow_errors",
"]",
"tuple",
"=",
"p",
".",
"Forward",
"(",
")",
"catch_errors",
"=",
"p",
".",
"Forward",
"(",
")",
"c... | 49.713333 | 36.9 |
def bst(height=3, is_perfect=False):
"""Generate a random BST (binary search tree) and return its root node.
:param height: Height of the BST (default: 3, range: 0 - 9 inclusive).
:type height: int
:param is_perfect: If set to True (default: False), a perfect BST with all
levels filled is retur... | [
"def",
"bst",
"(",
"height",
"=",
"3",
",",
"is_perfect",
"=",
"False",
")",
":",
"_validate_tree_height",
"(",
"height",
")",
"if",
"is_perfect",
":",
"return",
"_generate_perfect_bst",
"(",
"height",
")",
"values",
"=",
"_generate_random_node_values",
"(",
"... | 27.078125 | 20.703125 |
def remove_spin(self):
"""
Removes spin states from a structure.
"""
for site in self.sites:
new_sp = collections.defaultdict(float)
for sp, occu in site.species.items():
oxi_state = getattr(sp, "oxi_state", None)
new_sp[Specie(sp.s... | [
"def",
"remove_spin",
"(",
"self",
")",
":",
"for",
"site",
"in",
"self",
".",
"sites",
":",
"new_sp",
"=",
"collections",
".",
"defaultdict",
"(",
"float",
")",
"for",
"sp",
",",
"occu",
"in",
"site",
".",
"species",
".",
"items",
"(",
")",
":",
"... | 38.7 | 11.3 |
def new(cls, repo, *tree_sha):
""" Merge the given treeish revisions into a new index which is returned.
This method behaves like git-read-tree --aggressive when doing the merge.
:param repo: The repository treeish are located in.
:param tree_sha:
20 byte or 40 byte tree sh... | [
"def",
"new",
"(",
"cls",
",",
"repo",
",",
"*",
"tree_sha",
")",
":",
"base_entries",
"=",
"aggressive_tree_merge",
"(",
"repo",
".",
"odb",
",",
"[",
"to_bin_sha",
"(",
"str",
"(",
"t",
")",
")",
"for",
"t",
"in",
"tree_sha",
"]",
")",
"inst",
"=... | 39.909091 | 25.818182 |
def set_volume_level(self, volume):
"""Set volume level."""
if self._volume_level is not None:
if volume > self._volume_level:
num = int(self._max_volume * (volume - self._volume_level))
self._volume_level = volume
self._device.vol_up(num=num)
... | [
"def",
"set_volume_level",
"(",
"self",
",",
"volume",
")",
":",
"if",
"self",
".",
"_volume_level",
"is",
"not",
"None",
":",
"if",
"volume",
">",
"self",
".",
"_volume_level",
":",
"num",
"=",
"int",
"(",
"self",
".",
"_max_volume",
"*",
"(",
"volume... | 47.454545 | 9.181818 |
def get_repair_task_list(
self, task_id_filter=None, state_filter=None, executor_filter=None, custom_headers=None, raw=False, **operation_config):
"""Gets a list of repair tasks matching the given filters.
This API supports the Service Fabric platform; it is not meant to be
used dir... | [
"def",
"get_repair_task_list",
"(",
"self",
",",
"task_id_filter",
"=",
"None",
",",
"state_filter",
"=",
"None",
",",
"executor_filter",
"=",
"None",
",",
"custom_headers",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"*",
"*",
"operation_config",
")",
":",
... | 42.070423 | 24.112676 |
def parse_line(self, line):
"""Parses a single line of a GPI.
Return a tuple `(processed_line, entities)`. Typically
there will be a single entity, but in some cases there
may be none (invalid line) or multiple (disjunctive clause in
annotation extensions)
Note: most ap... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"vals",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"if",
"len",
"(",
"vals",
")",
"<",
"7",
":",
"self",
".",
"report",
".",
"error",
"(",
"line",
",",
"assocparser",
".",
"Report",
".... | 29.243902 | 21.170732 |
def build_recursive_gcs_delocalize_env(source, outputs):
"""Return a multi-line string with export statements for the variables.
Arguments:
source: Folder with the data.
For example /mnt/data
outputs: a list of OutputFileParam
Returns:
a multi-line string with a shell script that sets en... | [
"def",
"build_recursive_gcs_delocalize_env",
"(",
"source",
",",
"outputs",
")",
":",
"filtered_outs",
"=",
"[",
"var",
"for",
"var",
"in",
"outputs",
"if",
"var",
".",
"recursive",
"and",
"var",
".",
"file_provider",
"==",
"job_model",
".",
"P_GCS",
"]",
"r... | 31.5 | 18.590909 |
def model_sizes(m:nn.Module, size:tuple=(64,64))->Tuple[Sizes,Tensor,Hooks]:
"Pass a dummy input through the model `m` to get the various sizes of activations."
with hook_outputs(m) as hooks:
x = dummy_eval(m, size)
return [o.stored.shape for o in hooks] | [
"def",
"model_sizes",
"(",
"m",
":",
"nn",
".",
"Module",
",",
"size",
":",
"tuple",
"=",
"(",
"64",
",",
"64",
")",
")",
"->",
"Tuple",
"[",
"Sizes",
",",
"Tensor",
",",
"Hooks",
"]",
":",
"with",
"hook_outputs",
"(",
"m",
")",
"as",
"hooks",
... | 54.8 | 20.8 |
def handle_write(self):
"""
Handle the 'channel writable' state. E.g. send buffered data via a
socket.
"""
with self.lock:
logger.debug("handle_write: queue: {0!r}".format(self._write_queue))
try:
job = self._write_queue.popleft()
... | [
"def",
"handle_write",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"logger",
".",
"debug",
"(",
"\"handle_write: queue: {0!r}\"",
".",
"format",
"(",
"self",
".",
"_write_queue",
")",
")",
"try",
":",
"job",
"=",
"self",
".",
"_write_queue",
... | 40.363636 | 15.181818 |
def resize_volume(self, volumeObj, sizeInGb, bsize=1000):
"""
Resize a volume to new GB size, must be larger than original.
:param volumeObj: ScaleIO Volume Object
:param sizeInGb: New size in GB (have to be larger than original)
:param bsize: 1000
:return: POST request r... | [
"def",
"resize_volume",
"(",
"self",
",",
"volumeObj",
",",
"sizeInGb",
",",
"bsize",
"=",
"1000",
")",
":",
"current_vol",
"=",
"self",
".",
"get_volume_by_id",
"(",
"volumeObj",
".",
"id",
")",
"if",
"current_vol",
".",
"size_kb",
">",
"(",
"sizeInGb",
... | 49.722222 | 21.166667 |
def add_team(name,
description=None,
repo_names=None,
privacy=None,
permission=None,
profile="github"):
'''
Create a new Github team within an organization.
name
The name of the team to be created.
description
The descrip... | [
"def",
"add_team",
"(",
"name",
",",
"description",
"=",
"None",
",",
"repo_names",
"=",
"None",
",",
"privacy",
"=",
"None",
",",
"permission",
"=",
"None",
",",
"profile",
"=",
"\"github\"",
")",
":",
"try",
":",
"client",
"=",
"_get_client",
"(",
"p... | 26.460317 | 20.619048 |
def do_global_lock(self, args):
'''read (or clear) the global lock'''
if args.purge:
self.task_master.registry.force_clear_lock()
else:
owner = self.task_master.registry.read_lock()
if owner:
heartbeat = self.task_master.get_heartbeat(owner)
... | [
"def",
"do_global_lock",
"(",
"self",
",",
"args",
")",
":",
"if",
"args",
".",
"purge",
":",
"self",
".",
"task_master",
".",
"registry",
".",
"force_clear_lock",
"(",
")",
"else",
":",
"owner",
"=",
"self",
".",
"task_master",
".",
"registry",
".",
"... | 43 | 18.333333 |
def asdict(self):
"""Return a recursive dict representation of self
"""
d = dict(self._odict)
for k,v in d.items():
if isinstance(v, Struct):
d[k] = v.asdict()
return d | [
"def",
"asdict",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"self",
".",
"_odict",
")",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"Struct",
")",
":",
"d",
"[",
"k",
"]",
"=",
"v",
... | 22.9 | 15.9 |
def create_job_queue(self, queue_name, priority, state, compute_env_order):
"""
Create a job queue
:param queue_name: Queue name
:type queue_name: str
:param priority: Queue priority
:type priority: int
:param state: Queue state
:type state: string
... | [
"def",
"create_job_queue",
"(",
"self",
",",
"queue_name",
",",
"priority",
",",
"state",
",",
"compute_env_order",
")",
":",
"for",
"variable",
",",
"var_name",
"in",
"(",
"(",
"queue_name",
",",
"'jobQueueName'",
")",
",",
"(",
"priority",
",",
"'priority'... | 46.568182 | 24.568182 |
def _clean_files_only(self, files):
''' if a user only wants to process one or more specific files, instead of a full sosreport '''
try:
if not (os.path.exists(self.origin_path)):
self.logger.info("Creating Origin Path - %s" % self.origin_path)
os.makedirs(sel... | [
"def",
"_clean_files_only",
"(",
"self",
",",
"files",
")",
":",
"try",
":",
"if",
"not",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"origin_path",
")",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Creating Origin Path - %s\"",
"... | 46.47619 | 21.428571 |
async def help(self, command_name=None):
"""
Sends a SMTP 'HELP' command.
For further details please check out `RFC 5321 § 4.1.1.8`_.
Args:
command_name (str or None, optional): Name of a command for which
you want help. For example, if you want to get help ... | [
"async",
"def",
"help",
"(",
"self",
",",
"command_name",
"=",
"None",
")",
":",
"if",
"command_name",
"is",
"None",
":",
"command_name",
"=",
"\"\"",
"code",
",",
"message",
"=",
"await",
"self",
".",
"do_cmd",
"(",
"\"HELP\"",
",",
"command_name",
")",... | 32.148148 | 24.074074 |
def _rollback(self):
"""Restore the index in its previous state
This uses values that were indexed/deindexed since the last call
to `_reset_cache`.
This is used when an error is encountered while updating a value,
to return to the previous state
"""
# to avoid u... | [
"def",
"_rollback",
"(",
"self",
")",
":",
"# to avoid using self set that may be updated during the process",
"indexed_values",
"=",
"set",
"(",
"self",
".",
"_indexed_values",
")",
"deindexed_values",
"=",
"set",
"(",
"self",
".",
"_deindexed_values",
")",
"for",
"a... | 36.470588 | 17.941176 |
def get_proficiency_lookup_session_for_objective_bank(self, objective_bank_id, proxy):
"""Gets the ``OsidSession`` associated with the proficiency lookup service for the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
obective bank
arg: proxy (... | [
"def",
"get_proficiency_lookup_session_for_objective_bank",
"(",
"self",
",",
"objective_bank_id",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_proficiency_lookup",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
"# Also includ... | 48.925926 | 21.407407 |
def _signal_handler_init(self):
"""Catch interupt signals."""
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGTERM, self._signal_handler) | [
"def",
"_signal_handler_init",
"(",
"self",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_IGN",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"self",
".",
"_signal_handler",
")",
"signal",
".... | 47.4 | 11.6 |
def main():
'''
Bootstrapper CLI
'''
parser = argparse.ArgumentParser(prog='kclboot',
description='kclboot - Kinesis Client Library Bootstrapper')
subparsers = parser.add_subparsers(title='Subcommands', help='Additional help', dest='subparser')
# Common arguments
jar_path_parser =... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"'kclboot'",
",",
"description",
"=",
"'kclboot - Kinesis Client Library Bootstrapper'",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"title",
"=",
... | 44.025 | 30.775 |
def _set_box(self):
"""
Set the box size for the molecular assembly
"""
net_volume = 0.0
for idx, mol in enumerate(self.mols):
length = max([np.max(mol.cart_coords[:, i])-np.min(mol.cart_coords[:, i])
for i in range(3)]) + 2.0
ne... | [
"def",
"_set_box",
"(",
"self",
")",
":",
"net_volume",
"=",
"0.0",
"for",
"idx",
",",
"mol",
"in",
"enumerate",
"(",
"self",
".",
"mols",
")",
":",
"length",
"=",
"max",
"(",
"[",
"np",
".",
"max",
"(",
"mol",
".",
"cart_coords",
"[",
":",
",",
... | 44.461538 | 15.076923 |
def handle_initiate_stateful_checkpoint(self, ckptmsg):
"""Called when we get InitiateStatefulCheckpoint message
:param ckptmsg: InitiateStatefulCheckpoint type
"""
self.in_stream.offer(ckptmsg)
if self.my_pplan_helper.is_topology_running():
self.my_instance.py_class.process_incoming_tuples() | [
"def",
"handle_initiate_stateful_checkpoint",
"(",
"self",
",",
"ckptmsg",
")",
":",
"self",
".",
"in_stream",
".",
"offer",
"(",
"ckptmsg",
")",
"if",
"self",
".",
"my_pplan_helper",
".",
"is_topology_running",
"(",
")",
":",
"self",
".",
"my_instance",
".",
... | 44.714286 | 8.571429 |
def hat_map(vec):
"""Return that hat map of a vector
Inputs:
vec - 3 element vector
Outputs:
skew - 3,3 skew symmetric matrix
"""
vec = np.squeeze(vec)
skew = np.array([
[0, -vec[2], vec[1]],
[vec[2], 0, -vec[0]],
... | [
"def",
"hat_map",
"(",
"vec",
")",
":",
"vec",
"=",
"np",
".",
"squeeze",
"(",
"vec",
")",
"skew",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0",
",",
"-",
"vec",
"[",
"2",
"]",
",",
"vec",
"[",
"1",
"]",
"]",
",",
"[",
"vec",
"[",
"2",
"... | 20.294118 | 18.117647 |
def pynac_in_sub_directory(num, file_list):
"""
A context manager to create a new directory, move the files listed in ``file_list``
to that directory, and change to that directory before handing control back to
context. The closing action is to change back to the original directory.
... | [
"def",
"pynac_in_sub_directory",
"(",
"num",
",",
"file_list",
")",
":",
"print",
"(",
"'Running %d'",
"%",
"num",
")",
"new_dir",
"=",
"'dynacProc_%04d'",
"%",
"num",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"new_dir",
")",
":",
"shutil",
".",
"rmtre... | 36.625 | 21.708333 |
def _list_syntax_error():
"""
If we're going through a syntax error, add the directory of the error to
the watchlist.
"""
_, e, _ = sys.exc_info()
if isinstance(e, SyntaxError) and hasattr(e, 'filename'):
yield path.dirname(e.filename) | [
"def",
"_list_syntax_error",
"(",
")",
":",
"_",
",",
"e",
",",
"_",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"isinstance",
"(",
"e",
",",
"SyntaxError",
")",
"and",
"hasattr",
"(",
"e",
",",
"'filename'",
")",
":",
"yield",
"path",
".",
"dirna... | 28.888889 | 16.444444 |
def setup_application (self):
""" Allows us to use method, injected as dependency earlier to set
up argparser before autocompletion/running the app.
"""
# figure out precise method name, specific to this use
name = 'configure_%s_app' % self.parent.name
# call generic set up method
getattr(se... | [
"def",
"setup_application",
"(",
"self",
")",
":",
"# figure out precise method name, specific to this use",
"name",
"=",
"'configure_%s_app'",
"%",
"self",
".",
"parent",
".",
"name",
"# call generic set up method",
"getattr",
"(",
"self",
".",
"method",
",",
"'configu... | 47.9 | 13.4 |
def has(self, querypart_name, value=None):
"""Returns True if `querypart_name` with `value` is set.
For example you can check if you already used condition by `sql.has('where')`.
If you want to check for more information, for example if that condition
also contain ID, you can do this b... | [
"def",
"has",
"(",
"self",
",",
"querypart_name",
",",
"value",
"=",
"None",
")",
":",
"querypart",
"=",
"self",
".",
"_queryparts",
".",
"get",
"(",
"querypart_name",
")",
"if",
"not",
"querypart",
":",
"return",
"False",
"if",
"not",
"querypart",
".",
... | 36.75 | 19.5625 |
def get_page_api(client_access_token, page_id):
"""
You can also skip the above if you get a page token:
http://stackoverflow.com/questions/8231877
and make that long-lived token as in Step 3
"""
graph = GraphAPI(client_access_token)
# Get page token to post as the page. You can skip
# t... | [
"def",
"get_page_api",
"(",
"client_access_token",
",",
"page_id",
")",
":",
"graph",
"=",
"GraphAPI",
"(",
"client_access_token",
")",
"# Get page token to post as the page. You can skip",
"# the following if you want to post as yourself.",
"resp",
"=",
"graph",
".",
"get",
... | 32.722222 | 11.944444 |
def _parse_model(topology, scope, model, inputs=None, outputs=None):
'''
This is a delegate function of all top-level parsing functions. It does nothing but call a proper function
to parse the given model.
'''
if inputs is None:
inputs = list()
if outputs is None:
outputs = list... | [
"def",
"_parse_model",
"(",
"topology",
",",
"scope",
",",
"model",
",",
"inputs",
"=",
"None",
",",
"outputs",
"=",
"None",
")",
":",
"if",
"inputs",
"is",
"None",
":",
"inputs",
"=",
"list",
"(",
")",
"if",
"outputs",
"is",
"None",
":",
"outputs",
... | 41.555556 | 30 |
def __stopOpenThreadWpan(self):
"""stop OpenThreadWpan
Returns:
True: successfully stop OpenThreadWpan
False: failed to stop OpenThreadWpan
"""
print 'call stopOpenThreadWpan'
try:
if self.__sendCommand(WPANCTL_CMD + 'leave')[0] != 'Fail' and ... | [
"def",
"__stopOpenThreadWpan",
"(",
"self",
")",
":",
"print",
"'call stopOpenThreadWpan'",
"try",
":",
"if",
"self",
".",
"__sendCommand",
"(",
"WPANCTL_CMD",
"+",
"'leave'",
")",
"[",
"0",
"]",
"!=",
"'Fail'",
"and",
"self",
".",
"__sendCommand",
"(",
"WPA... | 37.333333 | 21.533333 |
def handle_requires(metadata, pkg_info, key):
"""
Place the runtime requirements from pkg_info into metadata.
"""
may_requires = defaultdict(list)
for value in pkg_info.get_all(key):
extra_match = EXTRA_RE.search(value)
if extra_match:
groupdict = extra_match.groupdict()
... | [
"def",
"handle_requires",
"(",
"metadata",
",",
"pkg_info",
",",
"key",
")",
":",
"may_requires",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"value",
"in",
"pkg_info",
".",
"get_all",
"(",
"key",
")",
":",
"extra_match",
"=",
"EXTRA_RE",
".",
"search",
... | 37.30303 | 11.545455 |
def get_update_status_brok(self):
"""
Create an update item brok
:return: Brok object
:rtype: alignak.Brok
"""
data = {'uuid': self.uuid}
self.fill_data_brok_from(data, 'full_status')
return Brok({'type': 'update_' + self.my_type + '_status', 'data': data... | [
"def",
"get_update_status_brok",
"(",
"self",
")",
":",
"data",
"=",
"{",
"'uuid'",
":",
"self",
".",
"uuid",
"}",
"self",
".",
"fill_data_brok_from",
"(",
"data",
",",
"'full_status'",
")",
"return",
"Brok",
"(",
"{",
"'type'",
":",
"'update_'",
"+",
"s... | 31.3 | 13.7 |
def get_first_weekday_after(day, weekday):
"""Get the first weekday after a given day. If the day is the same
weekday, the same day will be returned.
>>> # the first monday after Apr 1 2015
>>> Calendar.get_first_weekday_after(date(2015, 4, 1), MON)
datetime.date(2015, 4, 6)
... | [
"def",
"get_first_weekday_after",
"(",
"day",
",",
"weekday",
")",
":",
"day_delta",
"=",
"(",
"weekday",
"-",
"day",
".",
"weekday",
"(",
")",
")",
"%",
"7",
"day",
"=",
"day",
"+",
"timedelta",
"(",
"days",
"=",
"day_delta",
")",
"return",
"day"
] | 38.933333 | 13.933333 |
def set_tg(self):
""" Try to grab the treatment group number for the student.
If there is no treatment group number available, request it
from the server.
"""
# Checks to see the student currently has a treatment group number.
if not os.path.isfile(self.current_working_di... | [
"def",
"set_tg",
"(",
"self",
")",
":",
"# Checks to see the student currently has a treatment group number.",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"current_working_dir",
"+",
"LOCAL_TG_FILE",
")",
":",
"cur_email",
"=",
"self",
".",
"a... | 42.71875 | 20.21875 |
def load_containers(self, service, configs, use_cache):
"""
:param service_name:
:return None:
"""
if not isinstance(service, Service):
raise TypeError("service must be and instance of service. {0} was passed.".format(service))
if not self.healthy():
... | [
"def",
"load_containers",
"(",
"self",
",",
"service",
",",
"configs",
",",
"use_cache",
")",
":",
"if",
"not",
"isinstance",
"(",
"service",
",",
"Service",
")",
":",
"raise",
"TypeError",
"(",
"\"service must be and instance of service. {0} was passed.\"",
".",
... | 38.384615 | 21.461538 |
def transaction_effects(self, tx_hash, cursor=None, order='asc', limit=10):
"""This endpoint represents all effects that occurred as a result of a
given transaction.
`GET /transactions/{hash}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/ef... | [
"def",
"transaction_effects",
"(",
"self",
",",
"tx_hash",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/transactions/{tx_hash}/effects'",
".",
"format",
"(",
"tx_hash",
"=",
"tx_hash",
")",
... | 50.611111 | 27.222222 |
def set_colors(self, text='black', background='white'):
"""
Sets the colors of the text area.
"""
if self._multiline: self._widget.setStyleSheet("QTextEdit {background-color: "+str(background)+"; color: "+str(text)+"}")
else: self._widget.setStyleSheet("QLineEdit {b... | [
"def",
"set_colors",
"(",
"self",
",",
"text",
"=",
"'black'",
",",
"background",
"=",
"'white'",
")",
":",
"if",
"self",
".",
"_multiline",
":",
"self",
".",
"_widget",
".",
"setStyleSheet",
"(",
"\"QTextEdit {background-color: \"",
"+",
"str",
"(",
"backgr... | 62.666667 | 32.333333 |
def list_jobs(self, limit=None, skip=None):
"""
Lists replication jobs. Includes replications created via
/_replicate endpoint as well as those created from replication
documents. Does not include replications which have completed
or have failed to start because replication docum... | [
"def",
"list_jobs",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"skip",
"=",
"None",
")",
":",
"params",
"=",
"dict",
"(",
")",
"if",
"limit",
"is",
"not",
"None",
":",
"params",
"[",
"\"limit\"",
"]",
"=",
"limit",
"if",
"skip",
"is",
"not",
"N... | 45.380952 | 19.190476 |
def qr_code(self, instance):
"""
Display picture of QR-code from used secret
"""
try:
return self._qr_code(instance)
except Exception as err:
if settings.DEBUG:
import traceback
return "<pre>%s</pre>" % traceback.format_exc(... | [
"def",
"qr_code",
"(",
"self",
",",
"instance",
")",
":",
"try",
":",
"return",
"self",
".",
"_qr_code",
"(",
"instance",
")",
"except",
"Exception",
"as",
"err",
":",
"if",
"settings",
".",
"DEBUG",
":",
"import",
"traceback",
"return",
"\"<pre>%s</pre>\"... | 31.2 | 10.2 |
def commit_transaction(self):
"""
Commit the currently active transaction (Pipeline). If no
transaction is active in the current thread, an exception
will be raised.
:returns: The return value of executing the Pipeline.
:raises: ``ValueError`` if no transaction is active... | [
"def",
"commit_transaction",
"(",
"self",
")",
":",
"with",
"self",
".",
"_transaction_lock",
":",
"local",
"=",
"self",
".",
"_transaction_local",
"if",
"not",
"local",
".",
"pipes",
":",
"raise",
"ValueError",
"(",
"'No transaction is currently active.'",
")",
... | 38.5 | 15.214286 |
def get_node_dict(self, return_internal=False, return_nodes=False):
"""
Return node labels as a dictionary mapping {idx: name} where idx is
the order of nodes in 'preorder' traversal. Used internally by the
func .get_node_values() to return values in proper order.
return_inter... | [
"def",
"get_node_dict",
"(",
"self",
",",
"return_internal",
"=",
"False",
",",
"return_nodes",
"=",
"False",
")",
":",
"if",
"return_internal",
":",
"if",
"return_nodes",
":",
"return",
"{",
"i",
".",
"idx",
":",
"i",
"for",
"i",
"in",
"self",
".",
"t... | 38.517241 | 22.448276 |
def generateBatches(tasks, givens):
"""
A function to generate a batch of commands to run in a specific order as to
meet all the dependencies for each command. For example, the commands with
no dependencies are run first, and the commands with the most deep
dependencies are run last
"""
_rem... | [
"def",
"generateBatches",
"(",
"tasks",
",",
"givens",
")",
":",
"_removeGivensFromTasks",
"(",
"tasks",
",",
"givens",
")",
"batches",
"=",
"[",
"]",
"while",
"tasks",
":",
"batch",
"=",
"set",
"(",
")",
"for",
"task",
",",
"dependencies",
"in",
"tasks"... | 28.724138 | 17.827586 |
def _is_instance(self, triple):
"""helper, returns the class type of subj"""
subj, pred, obj = triple
input_pred_ns = self._namespace_from_uri(self._expand_qname(pred))
triples = self.graph.triples(
(subj, rt.URIRef(self.schema_def.lexicon['type']), None)
)
if... | [
"def",
"_is_instance",
"(",
"self",
",",
"triple",
")",
":",
"subj",
",",
"pred",
",",
"obj",
"=",
"triple",
"input_pred_ns",
"=",
"self",
".",
"_namespace_from_uri",
"(",
"self",
".",
"_expand_qname",
"(",
"pred",
")",
")",
"triples",
"=",
"self",
".",
... | 42.846154 | 15.769231 |
def process_md5(self, md5_output, pattern=r"^([a-fA-F0-9]+)$"):
"""
IOS-XR defaults with timestamps enabled
# show md5 file /bootflash:/boot/grub/grub.cfg
Sat Mar 3 17:49:03.596 UTC
c84843f0030efd44b01343fdb8c2e801
"""
match = re.search(pattern, md5_output, flag... | [
"def",
"process_md5",
"(",
"self",
",",
"md5_output",
",",
"pattern",
"=",
"r\"^([a-fA-F0-9]+)$\"",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"pattern",
",",
"md5_output",
",",
"flags",
"=",
"re",
".",
"M",
")",
"if",
"match",
":",
"return",
"m... | 36 | 16.153846 |
def parse_list(self, entries):
"""Parse a JSON array into a list of model instances."""
result_entries = SearchableList()
for entry in entries:
result_entries.append(self.instance.parse(self.requester, entry))
return result_entries | [
"def",
"parse_list",
"(",
"self",
",",
"entries",
")",
":",
"result_entries",
"=",
"SearchableList",
"(",
")",
"for",
"entry",
"in",
"entries",
":",
"result_entries",
".",
"append",
"(",
"self",
".",
"instance",
".",
"parse",
"(",
"self",
".",
"requester",... | 45 | 11.666667 |
def transform(self, X):
"""
Delete all features, which were not relevant in the fit phase.
:param X: data sample with all features, which will be reduced to only those that are relevant
:type X: pandas.DataSeries or numpy.array
:return: same data sample as X, but with only the ... | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"if",
"self",
".",
"relevant_features",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"You have to call fit before.\"",
")",
"if",
"isinstance",
"(",
"X",
",",
"pd",
".",
"DataFrame",
")",
":",
"ret... | 38.176471 | 21 |
def apps_location_installations_reorder(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/app_location_installations#reorder-app-installations-for-location"
api_path = "/api/v2/apps/location_installations/reorder.json"
return self.call(api_path, method="POST", data=data, *... | [
"def",
"apps_location_installations_reorder",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/apps/location_installations/reorder.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
... | 81.25 | 41.25 |
def filter(self, condition):
"""Filters rows using the given condition.
:func:`where` is an alias for :func:`filter`.
:param condition: a :class:`Column` of :class:`types.BooleanType`
or a string of SQL expression.
>>> df.filter(df.age > 3).collect()
[Row(age=5, na... | [
"def",
"filter",
"(",
"self",
",",
"condition",
")",
":",
"if",
"isinstance",
"(",
"condition",
",",
"basestring",
")",
":",
"jdf",
"=",
"self",
".",
"_jdf",
".",
"filter",
"(",
"condition",
")",
"elif",
"isinstance",
"(",
"condition",
",",
"Column",
"... | 34.68 | 13.28 |
def deselect_nodenames(self, *substrings: str) -> 'Selection':
"""Restrict the current selection to all nodes with a name
not containing at least one of the given substrings (does not
affect any elements).
See the documentation on method |Selection.search_nodenames| for
addition... | [
"def",
"deselect_nodenames",
"(",
"self",
",",
"*",
"substrings",
":",
"str",
")",
"->",
"'Selection'",
":",
"self",
".",
"nodes",
"-=",
"self",
".",
"search_nodenames",
"(",
"*",
"substrings",
")",
".",
"nodes",
"return",
"self"
] | 42.1 | 18.6 |
def run(self, format=None, reduce=False, *args, **kwargs):
"""Generates the underlying graph and prints it.
"""
plan = self._generate_plan()
if reduce:
# This will performa a transitive reduction on the underlying
# graph, producing less edges. Mostly useful for ... | [
"def",
"run",
"(",
"self",
",",
"format",
"=",
"None",
",",
"reduce",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"plan",
"=",
"self",
".",
"_generate_plan",
"(",
")",
"if",
"reduce",
":",
"# This will performa a transitive reducti... | 37.8 | 17.866667 |
def accept(self):
"""accept a connection on the host/port to which the socket is bound
.. note::
if there is no connection attempt already queued, this method will
block until a connection is made
:returns:
a two-tuple of ``(socket, address)`` where the soc... | [
"def",
"accept",
"(",
"self",
")",
":",
"with",
"self",
".",
"_registered",
"(",
"'re'",
")",
":",
"while",
"1",
":",
"try",
":",
"client",
",",
"addr",
"=",
"self",
".",
"_sock",
".",
"accept",
"(",
")",
"except",
"socket",
".",
"error",
",",
"e... | 40.111111 | 19.185185 |
def problem(problem_name, **kwargs):
"""Get possibly copied/reversed problem in `base_registry` or `env_registry`.
Args:
problem_name: string problem name. See `parse_problem_name`.
**kwargs: forwarded to env problem's initialize method.
Returns:
possibly reversed/copied version of base problem regi... | [
"def",
"problem",
"(",
"problem_name",
",",
"*",
"*",
"kwargs",
")",
":",
"spec",
"=",
"parse_problem_name",
"(",
"problem_name",
")",
"try",
":",
"return",
"Registries",
".",
"problems",
"[",
"spec",
".",
"base_name",
"]",
"(",
"was_copy",
"=",
"spec",
... | 35.888889 | 21.222222 |
def print_table(table, title='', delim='|', centering='center', col_padding=2,
header=True, headerchar='-'):
"""Print a table from a list of lists representing the rows of a table.
Parameters
----------
table : list
list of lists, e.g. a table with 3 columns and 2 rows could be
... | [
"def",
"print_table",
"(",
"table",
",",
"title",
"=",
"''",
",",
"delim",
"=",
"'|'",
",",
"centering",
"=",
"'center'",
",",
"col_padding",
"=",
"2",
",",
"header",
"=",
"True",
",",
"headerchar",
"=",
"'-'",
")",
":",
"table_str",
"=",
"'\\n'",
"#... | 32.198198 | 20.216216 |
def login():
'''Log in as administrator
You can use wither basic auth or form based login (via POST).
:param username: The administrator's username
:type username: string
:param password: The administrator's password
:type password: string
'''
username = None
password = None
ne... | [
"def",
"login",
"(",
")",
":",
"username",
"=",
"None",
"password",
"=",
"None",
"next",
"=",
"flask",
".",
"request",
".",
"args",
".",
"get",
"(",
"'next'",
")",
"auth",
"=",
"flask",
".",
"request",
".",
"authorization",
"if",
"flask",
".",
"reque... | 34.72093 | 17.511628 |
def cov_params(self, r_matrix=None, column=None, scale=None, cov_p=None,
other=None):
"""
Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast
of the estimates of params or all params multiplied by scale which
will ... | [
"def",
"cov_params",
"(",
"self",
",",
"r_matrix",
"=",
"None",
",",
"column",
"=",
"None",
",",
"scale",
"=",
"None",
",",
"cov_p",
"=",
"None",
",",
"other",
"=",
"None",
")",
":",
"if",
"(",
"hasattr",
"(",
"self",
",",
"'mle_settings'",
")",
"a... | 42.17284 | 17.901235 |
def analysis(self):
"""Return an AnalysisPartition proxy, which wraps this partition to provide acess to
dataframes, shapely shapes and other analysis services"""
if isinstance(self, PartitionProxy):
return AnalysisPartition(self._obj)
else:
return AnalysisPartiti... | [
"def",
"analysis",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
",",
"PartitionProxy",
")",
":",
"return",
"AnalysisPartition",
"(",
"self",
".",
"_obj",
")",
"else",
":",
"return",
"AnalysisPartition",
"(",
"self",
")"
] | 46 | 8.714286 |
def temporal_segmentation(segments, min_time):
""" Segments based on time distant points
Args:
segments (:obj:`list` of :obj:`list` of :obj:`Point`): segment points
min_time (int): minimum required time for segmentation
"""
final_segments = []
for segment in segments:
final_... | [
"def",
"temporal_segmentation",
"(",
"segments",
",",
"min_time",
")",
":",
"final_segments",
"=",
"[",
"]",
"for",
"segment",
"in",
"segments",
":",
"final_segments",
".",
"append",
"(",
"[",
"]",
")",
"for",
"point",
"in",
"segment",
":",
"if",
"point",
... | 31.5 | 15.5 |
def get_tags(filesystemid,
keyid=None,
key=None,
profile=None,
region=None,
**kwargs):
'''
Return the tags associated with an EFS instance.
filesystemid
(string) - ID of the file system whose tags to list
returns
(list) -... | [
"def",
"get_tags",
"(",
"filesystemid",
",",
"keyid",
"=",
"None",
",",
"key",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"region",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_conn",
"(",
"key",
"=",
"key",
",",
"keyid"... | 26.741935 | 23.709677 |
def project_create_func(self, proj_id, proj=None):
"""Create project given project uuid"""
if self.get_project_name(proj_id):
LOG.info("project %s exists, returning", proj_id)
return
if not proj:
try:
proj = self.keystone_event._service.proje... | [
"def",
"project_create_func",
"(",
"self",
",",
"proj_id",
",",
"proj",
"=",
"None",
")",
":",
"if",
"self",
".",
"get_project_name",
"(",
"proj_id",
")",
":",
"LOG",
".",
"info",
"(",
"\"project %s exists, returning\"",
",",
"proj_id",
")",
"return",
"if",
... | 49.422222 | 22.777778 |
def set_all_attribute_values(self, value):
"""
sets all the attribute values to the value and propagate to any children
"""
for attribute_name, type_instance in inspect.getmembers(self):
if attribute_name.startswith('__') or inspect.ismethod(type_instance):
... | [
"def",
"set_all_attribute_values",
"(",
"self",
",",
"value",
")",
":",
"for",
"attribute_name",
",",
"type_instance",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
")",
":",
"if",
"attribute_name",
".",
"startswith",
"(",
"'__'",
")",
"or",
"inspect",
".... | 40.466667 | 22.466667 |
def parse_storage_size(storage_size):
"""
Parses an expression that represents an amount of storage/memory and returns the number of bytes it represents.
Args:
storage_size(str): Size in bytes. The units ``k`` (kibibytes), ``m`` (mebibytes) and ``g``
(gibibytes) are suppo... | [
"def",
"parse_storage_size",
"(",
"storage_size",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'^([0-9]+(\\.[0-9]+)?)([gmk])?$'",
",",
"re",
".",
"I",
")",
"units",
"=",
"{",
"'k'",
":",
"1024",
",",
"'m'",
":",
"1024",
"*",
"1024",
",",
"'g'",... | 30.25 | 28.4375 |
def route(self, req, node, path):
'''
Looks up a controller from a node based upon the specified path.
:param node: The node, such as a root controller object.
:param path: The path to look up on this node.
'''
path = path.split('/')[1:]
try:
node, re... | [
"def",
"route",
"(",
"self",
",",
"req",
",",
"node",
",",
"path",
")",
":",
"path",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
":",
"]",
"try",
":",
"node",
",",
"remainder",
"=",
"lookup_controller",
"(",
"node",
",",
"path",
",",
... | 45.88 | 19.32 |
def set_regs(self):
''' setting unicorn registers '''
uc = self.uc
if self.state.arch.qemu_name == 'x86_64':
fs = self.state.solver.eval(self.state.regs.fs)
gs = self.state.solver.eval(self.state.regs.gs)
self.write_msr(fs, 0xC0000100)
self.write_... | [
"def",
"set_regs",
"(",
"self",
")",
":",
"uc",
"=",
"self",
".",
"uc",
"if",
"self",
".",
"state",
".",
"arch",
".",
"qemu_name",
"==",
"'x86_64'",
":",
"fs",
"=",
"self",
".",
"state",
".",
"solver",
".",
"eval",
"(",
"self",
".",
"state",
".",... | 46.305882 | 21.976471 |
def get_all_items_of_invoice(self, invoice_id):
"""
Get all items of invoice
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param invoice_id: the invoice id
:return: list
... | [
"def",
"get_all_items_of_invoice",
"(",
"self",
",",
"invoice_id",
")",
":",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"get_function",
"=",
"self",
".",
"get_items_of_invoice_per_page",
",",
"resource",
"=",
"INVOICE_ITEMS",
",",
"*",
"*",
"{",
"'invoi... | 36.214286 | 15.071429 |
def call():
"""Execute command line helper."""
args = get_arguments()
# Set up logging
if args.debug:
log_level = logging.DEBUG
elif args.quiet:
log_level = logging.WARN
else:
log_level = logging.INFO
setup_logging(log_level)
skybell = None
try:
# ... | [
"def",
"call",
"(",
")",
":",
"args",
"=",
"get_arguments",
"(",
")",
"# Set up logging",
"if",
"args",
".",
"debug",
":",
"log_level",
"=",
"logging",
".",
"DEBUG",
"elif",
"args",
".",
"quiet",
":",
"log_level",
"=",
"logging",
".",
"WARN",
"else",
"... | 31.666667 | 19.229167 |
def implements(obj, protocol):
"""Does the object 'obj' implement the 'prococol'?"""
if isinstance(obj, type):
raise TypeError("First argument to implements must be an instance. "
"Got %r." % obj)
return isinstance(obj, protocol) or issubclass(AnyType, protocol) | [
"def",
"implements",
"(",
"obj",
",",
"protocol",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"type",
")",
":",
"raise",
"TypeError",
"(",
"\"First argument to implements must be an instance. \"",
"\"Got %r.\"",
"%",
"obj",
")",
"return",
"isinstance",
"(",
"... | 50.166667 | 14.333333 |
def pretty_list(rtlst, header, sortBy=0, borders=False):
"""Pretty list to fit the terminal, and add header"""
if borders:
_space = "|"
else:
_space = " "
# Windows has a fat terminal border
_spacelen = len(_space) * (len(header) - 1) + (10 if WINDOWS else 0)
_croped = False
... | [
"def",
"pretty_list",
"(",
"rtlst",
",",
"header",
",",
"sortBy",
"=",
"0",
",",
"borders",
"=",
"False",
")",
":",
"if",
"borders",
":",
"_space",
"=",
"\"|\"",
"else",
":",
"_space",
"=",
"\" \"",
"# Windows has a fat terminal border",
"_spacelen",
"=",
... | 36.533333 | 14.422222 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.