text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def start(self, app):
""" Start application. """
app.middlewares.insert(0, debugtoolbar_middleware_factory)
self.global_panels = [Panel(self.app) for Panel in self.cfg.global_panels] | [
"def",
"start",
"(",
"self",
",",
"app",
")",
":",
"app",
".",
"middlewares",
".",
"insert",
"(",
"0",
",",
"debugtoolbar_middleware_factory",
")",
"self",
".",
"global_panels",
"=",
"[",
"Panel",
"(",
"self",
".",
"app",
")",
"for",
"Panel",
"in",
"se... | 50.75 | 21.75 |
def string(prompt=None, empty=False):
"""Prompt a string.
Parameters
----------
prompt : str, optional
Use an alternative prompt.
empty : bool, optional
Allow an empty response.
Returns
-------
str or None
A str if the user entered a non-empty string.
No... | [
"def",
"string",
"(",
"prompt",
"=",
"None",
",",
"empty",
"=",
"False",
")",
":",
"s",
"=",
"_prompt_input",
"(",
"prompt",
")",
"if",
"empty",
"and",
"not",
"s",
":",
"return",
"None",
"else",
":",
"if",
"s",
":",
"return",
"s",
"else",
":",
"r... | 21.96 | 20.28 |
def update(self, role_sid=values.unset,
last_consumed_message_index=values.unset):
"""
Update the MemberInstance
:param unicode role_sid: The Role assigned to this member.
:param unicode last_consumed_message_index: An Integer representing index of the last Message this M... | [
"def",
"update",
"(",
"self",
",",
"role_sid",
"=",
"values",
".",
"unset",
",",
"last_consumed_message_index",
"=",
"values",
".",
"unset",
")",
":",
"return",
"self",
".",
"_proxy",
".",
"update",
"(",
"role_sid",
"=",
"role_sid",
",",
"last_consumed_messa... | 40.866667 | 22.733333 |
def manage(self):
"""
Manage the task to handle restarts, reconfiguration, etc.
Returns True to request a shorter period before the next call,
False if nothing special is needed.
"""
log = self._params.get('log', self._discard)
if self._stopping:
log.debu... | [
"def",
"manage",
"(",
"self",
")",
":",
"log",
"=",
"self",
".",
"_params",
".",
"get",
"(",
"'log'",
",",
"self",
".",
"_discard",
")",
"if",
"self",
".",
"_stopping",
":",
"log",
".",
"debug",
"(",
"\"Task '%s', stopping, retrying stop()\"",
",",
"self... | 42.26087 | 19.652174 |
def upload(self,
file,
name=None,
prefix=None,
extensions=None,
overwrite=False,
public=False,
random_name=False,
**kwargs):
"""
To upload file
:param file: FileStorage object ... | [
"def",
"upload",
"(",
"self",
",",
"file",
",",
"name",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"extensions",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"public",
"=",
"False",
",",
"random_name",
"=",
"False",
",",
"*",
"*",
"kwargs",
... | 41.39759 | 21.542169 |
def endpoint(self, endpoint):
"""A decorator to register a function as an endpoint.
Example::
@app.endpoint('example.endpoint')
def example():
return "example"
:param endpoint: the name of the endpoint
"""
def decorator(f):
se... | [
"def",
"endpoint",
"(",
"self",
",",
"endpoint",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"view_functions",
"[",
"endpoint",
"]",
"=",
"f",
"return",
"f",
"return",
"decorator"
] | 27.428571 | 14.714286 |
def update(self, gradient, step):
"""Update the search direction given the latest gradient and step"""
self.old_gradient = self.gradient
self.gradient = gradient
N = len(self.gradient)
if self.inv_hessian is None:
# update the direction
self.direction = -s... | [
"def",
"update",
"(",
"self",
",",
"gradient",
",",
"step",
")",
":",
"self",
".",
"old_gradient",
"=",
"self",
".",
"gradient",
"self",
".",
"gradient",
"=",
"gradient",
"N",
"=",
"len",
"(",
"self",
".",
"gradient",
")",
"if",
"self",
".",
"inv_hes... | 38.92 | 10.6 |
def translate_func(name, block, args):
"""Translates functions and all nested functions to Python code.
name - name of that function (global functions will be available under var while
inline will be available directly under this name )
block - code of the function (*with* brackets {} )
... | [
"def",
"translate_func",
"(",
"name",
",",
"block",
",",
"args",
")",
":",
"inline",
"=",
"name",
".",
"startswith",
"(",
"'PyJsLvalInline'",
")",
"real_name",
"=",
"''",
"if",
"inline",
":",
"name",
",",
"real_name",
"=",
"name",
".",
"split",
"(",
"'... | 48.8 | 17.577778 |
def from_segment_xml(cls, xml_file, **kwargs):
"""
Read a ligo.segments.segmentlist from the file object file containing an
xml segment table.
Parameters
-----------
xml_file : file object
file object for segment xml file
"""
# load xmldocumen... | [
"def",
"from_segment_xml",
"(",
"cls",
",",
"xml_file",
",",
"*",
"*",
"kwargs",
")",
":",
"# load xmldocument and SegmentDefTable and SegmentTables",
"fp",
"=",
"open",
"(",
"xml_file",
",",
"'r'",
")",
"xmldoc",
",",
"_",
"=",
"ligolw_utils",
".",
"load_fileob... | 42.789474 | 21.982456 |
def process_nxml_file(fname, output_fmt='json', outbuf=None, cleanup=True,
**kwargs):
"""Return processor with Statements extracted by reading an NXML file.
Parameters
----------
fname : str
The path to the NXML file to be read.
output_fmt: Optional[str]
The ou... | [
"def",
"process_nxml_file",
"(",
"fname",
",",
"output_fmt",
"=",
"'json'",
",",
"outbuf",
"=",
"None",
",",
"cleanup",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"sp",
"=",
"None",
"out_fname",
"=",
"None",
"try",
":",
"out_fname",
"=",
"run_spar... | 33.085714 | 21.914286 |
def execute(self, query, *multiparams, **params):
"""Executes a SQL query with optional parameters.
query - a SQL query string or any sqlalchemy expression.
*multiparams/**params - represent bound parameter values to be
used in the execution. Typically, the format is a dictionary
... | [
"def",
"execute",
"(",
"self",
",",
"query",
",",
"*",
"multiparams",
",",
"*",
"*",
"params",
")",
":",
"coro",
"=",
"self",
".",
"_execute",
"(",
"query",
",",
"*",
"multiparams",
",",
"*",
"*",
"params",
")",
"return",
"_SAConnectionContextManager",
... | 30.564103 | 22.512821 |
def load_handlers(handler_mapping):
"""
Given a dictionary mapping which looks like the following, import the
objects based on the dotted path and yield the packet type and handler as
pairs.
If the special string '*' is passed, don't process that, pass it on as it
is a wildcard.
If an non-... | [
"def",
"load_handlers",
"(",
"handler_mapping",
")",
":",
"handlers",
"=",
"{",
"}",
"for",
"packet_type",
",",
"handler",
"in",
"handler_mapping",
".",
"items",
"(",
")",
":",
"if",
"packet_type",
"==",
"'*'",
":",
"Packet",
"=",
"packet_type",
"elif",
"i... | 28.977273 | 22.840909 |
def get_authorisation_url(self, reset=False):
""" Initialises the OAuth2 Process by asking the auth server for a login URL.
Once called, the user can login by being redirected to the url returned by
this function.
If there is an error during authorisation, None is returned.""... | [
"def",
"get_authorisation_url",
"(",
"self",
",",
"reset",
"=",
"False",
")",
":",
"if",
"reset",
":",
"self",
".",
"auth_url",
"=",
"None",
"if",
"not",
"self",
".",
"auth_url",
":",
"try",
":",
"oauth",
"=",
"OAuth2Session",
"(",
"self",
".",
"client... | 43.611111 | 20.944444 |
def on_left_click(self, event, grid, choices):
"""
creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values
"""
row, col = event.GetRow(), event.Get... | [
"def",
"on_left_click",
"(",
"self",
",",
"event",
",",
"grid",
",",
"choices",
")",
":",
"row",
",",
"col",
"=",
"event",
".",
"GetRow",
"(",
")",
",",
"event",
".",
"GetCol",
"(",
")",
"if",
"col",
"==",
"0",
"and",
"self",
".",
"grid",
".",
... | 46.280702 | 19.614035 |
def clear(self):
'''
Clear plugin manager state.
Registered mimetype functions will be disposed after calling this
method.
'''
self._mimetype_functions = list(self._default_mimetype_functions)
super(MimetypePluginManager, self).clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_mimetype_functions",
"=",
"list",
"(",
"self",
".",
"_default_mimetype_functions",
")",
"super",
"(",
"MimetypePluginManager",
",",
"self",
")",
".",
"clear",
"(",
")"
] | 31.555556 | 25.333333 |
def lengths( self ):
"""
The cell lengths.
Args:
None
Returns:
(np.array(a,b,c)): The cell lengths.
"""
return( np.array( [ math.sqrt( sum( row**2 ) ) for row in self.matrix ] ) ) | [
"def",
"lengths",
"(",
"self",
")",
":",
"return",
"(",
"np",
".",
"array",
"(",
"[",
"math",
".",
"sqrt",
"(",
"sum",
"(",
"row",
"**",
"2",
")",
")",
"for",
"row",
"in",
"self",
".",
"matrix",
"]",
")",
")"
] | 22.090909 | 21.909091 |
def ignore_warning(warning):
"""
Ignore any emitted warnings from a function.
:param warning: The category of warning to ignore.
"""
def decorator(func):
"""
Return a decorated function whose emitted warnings are ignored.
"""
@wraps(func)
def wrapper(*args, *... | [
"def",
"ignore_warning",
"(",
"warning",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"\n Return a decorated function whose emitted warnings are ignored.\n \"\"\"",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*... | 26.947368 | 10.736842 |
def beacon(config):
'''
Scan for the configured services and fire events
Example Config
.. code-block:: yaml
beacons:
service:
- services:
salt-master: {}
mysql: {}
The config above sets up beacons to check for
the salt-master and... | [
"def",
"beacon",
"(",
"config",
")",
":",
"ret",
"=",
"[",
"]",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config",
".",
"update",
",",
"config",
")",
")",
"for",
"service",
"in",
"_config",
".",
"get",
"(",
"'services'",
",",
"{",
"}",... | 40.380165 | 23.917355 |
def to_qasm(self,
header: Optional[str] = None,
precision: int = 10,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
) -> str:
"""Returns QASM equivalent to the circuit.
Args:
header: A multi-line string that is pla... | [
"def",
"to_qasm",
"(",
"self",
",",
"header",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"precision",
":",
"int",
"=",
"10",
",",
"qubit_order",
":",
"ops",
".",
"QubitOrderOrList",
"=",
"ops",
".",
"QubitOrder",
".",
"DEFAULT",
",",
")",
"-... | 43.733333 | 21.533333 |
def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
",",
"minutes",
")",
":",
"value",
"=",
"self",
".",
"serialize",
"(",
"value",
")",
"minutes",
"=",
"max",
"(",
"1",
",",
"minutes",
")",
"self",
".",
"_redis",
".",
"setex",
"(",
"self",
".",... | 26.055556 | 19.388889 |
def t_heredocvar_ENCAPSED_AND_WHITESPACE(t):
r'( [^\n\\${] | \\. | \$(?![A-Za-z_{]) | \{(?!\$) )+\n? | \\?\n'
t.lexer.lineno += t.value.count("\n")
t.lexer.pop_state()
return t | [
"def",
"t_heredocvar_ENCAPSED_AND_WHITESPACE",
"(",
"t",
")",
":",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"t",
".",
"value",
".",
"count",
"(",
"\"\\n\"",
")",
"t",
".",
"lexer",
".",
"pop_state",
"(",
")",
"return",
"t"
] | 37.6 | 15.6 |
def reactions_to_files(model, dest, writer, split_subsystem):
"""Turn the reaction subsystems into their own files.
If a subsystem has a number of reactions over the threshold, it gets its
own YAML file. All other reactions, those that don't have a subsystem or
are in a subsystem that falls below the t... | [
"def",
"reactions_to_files",
"(",
"model",
",",
"dest",
",",
"writer",
",",
"split_subsystem",
")",
":",
"def",
"safe_file_name",
"(",
"origin_name",
")",
":",
"safe_name",
"=",
"re",
".",
"sub",
"(",
"r'\\W+'",
",",
"'_'",
",",
"origin_name",
",",
"flags"... | 41.085714 | 18.657143 |
def sh(cmd):
"""
Run the given command in a shell.
The command should be a single string containing a shell command. If the
command contains the names of any local variables enclosed in braces, the
actual values of the named variables will be filled in. (Note that this
works on variables defi... | [
"def",
"sh",
"(",
"cmd",
")",
":",
"# Figure out what local variables are defined in the calling scope.",
"import",
"inspect",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"try",
":",
"locals",
"=",
"frame",
".",
"f_back",
".",
"f_locals",
"finally",
":... | 38.967742 | 24.451613 |
def list_ptr_records(self, device):
"""
Returns a list of all PTR records configured for this device.
"""
device_type = self._resolve_device_type(device)
href, svc_name = self._get_ptr_details(device, device_type)
uri = "/rdns/%s?href=%s" % (svc_name, href)
try:
... | [
"def",
"list_ptr_records",
"(",
"self",
",",
"device",
")",
":",
"device_type",
"=",
"self",
".",
"_resolve_device_type",
"(",
"device",
")",
"href",
",",
"svc_name",
"=",
"self",
".",
"_get_ptr_details",
"(",
"device",
",",
"device_type",
")",
"uri",
"=",
... | 38.357143 | 14.214286 |
def sum_by_n(d, w, n):
"""A utility function to summarize a data array into n values
after weighting the array with another weight array w
Parameters
----------
d : array
(t, 1), numerical values
w : array
(t, 1), numerical values for weigh... | [
"def",
"sum_by_n",
"(",
"d",
",",
"w",
",",
"n",
")",
":",
"t",
"=",
"len",
"(",
"d",
")",
"h",
"=",
"t",
"//",
"n",
"#must be floor!",
"d",
"=",
"d",
"*",
"w",
"return",
"np",
".",
"array",
"(",
"[",
"sum",
"(",
"d",
"[",
"i",
":",
"i",
... | 24.111111 | 23.044444 |
def send(self, packet_buffer):
"""
send a buffer as a packet to the network interface
:param packet_buffer: buffer to send (length shouldn't exceed MAX_INT)
"""
if self._handle is None:
raise self.DeviceIsNotOpen()
buffer_length = len(packet_buffer)
bu... | [
"def",
"send",
"(",
"self",
",",
"packet_buffer",
")",
":",
"if",
"self",
".",
"_handle",
"is",
"None",
":",
"raise",
"self",
".",
"DeviceIsNotOpen",
"(",
")",
"buffer_length",
"=",
"len",
"(",
"packet_buffer",
")",
"buf_send",
"=",
"ctypes",
".",
"cast"... | 47.454545 | 16 |
def calcFstats(predTst, yTest, p, axis=0):
"""calculate coefficient of determination. Assumes that axis=0 is time
Parameters
----------
predTst : np.array, predicted reponse for yTest
yTest : np.array, acxtually observed response for yTest
p: float, number of predictors
... | [
"def",
"calcFstats",
"(",
"predTst",
",",
"yTest",
",",
"p",
",",
"axis",
"=",
"0",
")",
":",
"rss",
"=",
"np",
".",
"sum",
"(",
"(",
"yTest",
"-",
"predTst",
")",
"**",
"2",
",",
"axis",
"=",
"axis",
")",
"tss",
"=",
"np",
".",
"sum",
"(",
... | 30.32 | 15.88 |
def _format_num(self, value):
"""Return the number value for value, given this field's `num_type`."""
# (value is True or value is False) is ~5x faster than isinstance(value, bool)
if value is True or value is False:
raise TypeError('value must be a Number, not a boolean.')
r... | [
"def",
"_format_num",
"(",
"self",
",",
"value",
")",
":",
"# (value is True or value is False) is ~5x faster than isinstance(value, bool)",
"if",
"value",
"is",
"True",
"or",
"value",
"is",
"False",
":",
"raise",
"TypeError",
"(",
"'value must be a Number, not a boolean.'"... | 56.833333 | 15.666667 |
def add_cache(self, namespace, key, query_hash, length, cache):
"""Add cached values for the specified date range and query"""
start = 0
bulk_insert = self.bulk_insert
cache_len = len(cache)
row = '(%s,%s,%s,%s,%s,%s)'
query = 'INSERT INTO gauged_cache ' \
'(n... | [
"def",
"add_cache",
"(",
"self",
",",
"namespace",
",",
"key",
",",
"query_hash",
",",
"length",
",",
"cache",
")",
":",
"start",
"=",
"0",
"bulk_insert",
"=",
"self",
".",
"bulk_insert",
"cache_len",
"=",
"len",
"(",
"cache",
")",
"row",
"=",
"'(%s,%s... | 43.55 | 11.25 |
def set_background(self, image=None, path=None, resize=True):
"""
Set the background image of the Canvas.
:param image: background image
:type image: PhotoImage
:param path: background image path
:type path: str
:param resize: whether to resize the image ... | [
"def",
"set_background",
"(",
"self",
",",
"image",
"=",
"None",
",",
"path",
"=",
"None",
",",
"resize",
"=",
"True",
")",
":",
"if",
"not",
"image",
"and",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"\"You must either pass a PhotoImage object or a path ... | 50.233333 | 22.033333 |
def init_heat_consumer(self, mq):
"""
Init openstack heat mq
1. Check if enable listening heat notification
2. Create consumer
:param mq: class ternya.mq.MQ
"""
if not self.enable_component_notification(Openstack.Heat):
log.debug("disable listening h... | [
"def",
"init_heat_consumer",
"(",
"self",
",",
"mq",
")",
":",
"if",
"not",
"self",
".",
"enable_component_notification",
"(",
"Openstack",
".",
"Heat",
")",
":",
"log",
".",
"debug",
"(",
"\"disable listening heat notification\"",
")",
"return",
"for",
"i",
"... | 34.631579 | 20.421053 |
def scale_and_crop(im, crop_spec):
"""
Scale and Crop.
"""
im = im.crop((crop_spec.x, crop_spec.y, crop_spec.x2, crop_spec.y2))
if crop_spec.width and crop_spec.height:
im = im.resize((crop_spec.width, crop_spec.height),
resample=Image.ANTIALIAS)
return im | [
"def",
"scale_and_crop",
"(",
"im",
",",
"crop_spec",
")",
":",
"im",
"=",
"im",
".",
"crop",
"(",
"(",
"crop_spec",
".",
"x",
",",
"crop_spec",
".",
"y",
",",
"crop_spec",
".",
"x2",
",",
"crop_spec",
".",
"y2",
")",
")",
"if",
"crop_spec",
".",
... | 27.181818 | 17.545455 |
def _create_from_owl(self):
"""
create a standard data object based on CSV file
"""
self.content['data'] = 'TODO - read OWL from ' + self.input_data
lg.record_process('_create_from_owl', 'read ' + self._calc_size_stats() + ' from ' + self.input_data) | [
"def",
"_create_from_owl",
"(",
"self",
")",
":",
"self",
".",
"content",
"[",
"'data'",
"]",
"=",
"'TODO - read OWL from '",
"+",
"self",
".",
"input_data",
"lg",
".",
"record_process",
"(",
"'_create_from_owl'",
",",
"'read '",
"+",
"self",
".",
"_calc_size_... | 41.857143 | 23 |
def should_cache(self, request, response):
""" Given the request and response should it be cached """
if not getattr(request, '_cache_update_cache', False):
return False
if not response.status_code in getattr(settings, 'BETTERCACHE_CACHEABLE_STATUS', CACHEABLE_STATUS):
r... | [
"def",
"should_cache",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"if",
"not",
"getattr",
"(",
"request",
",",
"'_cache_update_cache'",
",",
"False",
")",
":",
"return",
"False",
"if",
"not",
"response",
".",
"status_code",
"in",
"getattr",
"(... | 47.333333 | 26 |
def _walk(self):
"""Loop through all the instructions that are `_todo`."""
while self._todo:
args = self._todo.pop(0)
self._step(*args) | [
"def",
"_walk",
"(",
"self",
")",
":",
"while",
"self",
".",
"_todo",
":",
"args",
"=",
"self",
".",
"_todo",
".",
"pop",
"(",
"0",
")",
"self",
".",
"_step",
"(",
"*",
"args",
")"
] | 34.2 | 10.8 |
def random_board(max_x, max_y, load_factor):
"""Return a random board with given max x and y coords."""
return dict(((randint(0, max_x), randint(0, max_y)), 0) for _ in
xrange(int(max_x * max_y / load_factor))) | [
"def",
"random_board",
"(",
"max_x",
",",
"max_y",
",",
"load_factor",
")",
":",
"return",
"dict",
"(",
"(",
"(",
"randint",
"(",
"0",
",",
"max_x",
")",
",",
"randint",
"(",
"0",
",",
"max_y",
")",
")",
",",
"0",
")",
"for",
"_",
"in",
"xrange",... | 57.75 | 12.25 |
def _load_yaml_config(path=None):
"""Open and return the yaml contents."""
furious_yaml_path = path or find_furious_yaml()
if furious_yaml_path is None:
logging.debug("furious.yaml not found.")
return None
with open(furious_yaml_path) as yaml_file:
return yaml_file.read() | [
"def",
"_load_yaml_config",
"(",
"path",
"=",
"None",
")",
":",
"furious_yaml_path",
"=",
"path",
"or",
"find_furious_yaml",
"(",
")",
"if",
"furious_yaml_path",
"is",
"None",
":",
"logging",
".",
"debug",
"(",
"\"furious.yaml not found.\"",
")",
"return",
"None... | 33.888889 | 12.111111 |
def modifier_list_id(self, modifier_list_id):
"""
Sets the modifier_list_id of this CatalogItemModifierListInfo.
The ID of the [CatalogModifierList](#type-catalogmodifierlist) controlled by this [CatalogModifierListInfo](#type-catalogmodifierlistinfo).
:param modifier_list_id: The modif... | [
"def",
"modifier_list_id",
"(",
"self",
",",
"modifier_list_id",
")",
":",
"if",
"modifier_list_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `modifier_list_id`, must not be `None`\"",
")",
"if",
"len",
"(",
"modifier_list_id",
")",
"<",
"1"... | 47.666667 | 31.4 |
def create_variant(cls, variant, **kwargs):
"""Create Variant
Create a new Variant
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_variant(variant, async=True)
>>> result = thre... | [
"def",
"create_variant",
"(",
"cls",
",",
"variant",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_create_variant_with_http_info",... | 38.809524 | 18.333333 |
def call(self, args=None, kwargs=None, node=None, send_timeout=1000, recv_timeout=5000, zmq_ctx=None):
"""
Calls a service on a node with req as arguments. if node is None, a node is chosen by zmq.
if zmq_ctx is passed, it will use the existing context
Uses a REQ socket. Ref : http://api... | [
"def",
"call",
"(",
"self",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"node",
"=",
"None",
",",
"send_timeout",
"=",
"1000",
",",
"recv_timeout",
"=",
"5000",
",",
"zmq_ctx",
"=",
"None",
")",
":",
"context",
"=",
"zmq_ctx",
"or",
... | 47.425926 | 27.240741 |
def getpexts(lsp):
'''
Get information from pext planes. This might or might not work, use with
caution!
Parameters:
-----------
lsp : .lsp string
Returns a list of dicts with information for all pext planes
'''
lines=lsp.split('\n');
#unfortunately regex doesn't work ... | [
"def",
"getpexts",
"(",
"lsp",
")",
":",
"lines",
"=",
"lsp",
".",
"split",
"(",
"'\\n'",
")",
"#unfortunately regex doesn't work here",
"lns",
",",
"planens",
"=",
"zip",
"(",
"*",
"[",
"(",
"i",
",",
"int",
"(",
"re",
".",
"search",
"(",
"'^ *extract... | 28.06 | 18.34 |
def truncate_html(html, *args, **kwargs):
"""Truncates HTML string.
:param html: The HTML string or parsed element tree (with
:func:`html5lib.parse`).
:param kwargs: Similar with :class:`.filters.TruncationFilter`.
:return: The truncated HTML string.
"""
if hasattr(html, 'getc... | [
"def",
"truncate_html",
"(",
"html",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"html",
",",
"'getchildren'",
")",
":",
"etree",
"=",
"html",
"else",
":",
"etree",
"=",
"html5lib",
".",
"parse",
"(",
"html",
")",
"wa... | 28.130435 | 17.434783 |
def update(self, webhook_url=values.unset, friendly_name=values.unset,
reachability_webhooks_enabled=values.unset,
acl_enabled=values.unset):
"""
Update the ServiceInstance
:param unicode webhook_url: A URL that will receive event updates when objects are manipulat... | [
"def",
"update",
"(",
"self",
",",
"webhook_url",
"=",
"values",
".",
"unset",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"reachability_webhooks_enabled",
"=",
"values",
".",
"unset",
",",
"acl_enabled",
"=",
"values",
".",
"unset",
")",
":",
... | 52.6 | 28.6 |
def _get_prereq_datasets(self, comp_id, prereq_nodes, keepables, skip=False):
"""Get a composite's prerequisites, generating them if needed.
Args:
comp_id (DatasetID): DatasetID for the composite whose
prerequisites are being collected.
prereq_no... | [
"def",
"_get_prereq_datasets",
"(",
"self",
",",
"comp_id",
",",
"prereq_nodes",
",",
"keepables",
",",
"skip",
"=",
"False",
")",
":",
"prereq_datasets",
"=",
"[",
"]",
"delayed_gen",
"=",
"False",
"for",
"prereq_node",
"in",
"prereq_nodes",
":",
"prereq_id",... | 47.9 | 25.8 |
def _parse_plt_segment(self, fptr):
"""Parse the PLT segment.
The packet headers are not parsed, i.e. they remain uninterpreted raw
data buffers.
Parameters
----------
fptr : file
Open file object.
Returns
-------
PLTSegment
... | [
"def",
"_parse_plt_segment",
"(",
"self",
",",
"fptr",
")",
":",
"offset",
"=",
"fptr",
".",
"tell",
"(",
")",
"-",
"2",
"read_buffer",
"=",
"fptr",
".",
"read",
"(",
"3",
")",
"length",
",",
"zplt",
"=",
"struct",
".",
"unpack",
"(",
"'>HB'",
",",... | 24.512821 | 19.589744 |
def tags(self):
# type: () -> Set[str]
"""
Tags applied to operation.
"""
tags = set()
if self._tags:
tags.update(self._tags)
if self.binding:
binding_tags = getattr(self.binding, 'tags', None)
if binding_tags:
t... | [
"def",
"tags",
"(",
"self",
")",
":",
"# type: () -> Set[str]",
"tags",
"=",
"set",
"(",
")",
"if",
"self",
".",
"_tags",
":",
"tags",
".",
"update",
"(",
"self",
".",
"_tags",
")",
"if",
"self",
".",
"binding",
":",
"binding_tags",
"=",
"getattr",
"... | 27.076923 | 12 |
def iterpackages(self):
"""
Return an iterator over all the packages in the PackageStore.
"""
pkgdir = os.path.join(self._path, self.PKG_DIR)
if not os.path.isdir(pkgdir):
return
for team in sub_dirs(pkgdir):
for user in sub_dirs(self.team_path(tea... | [
"def",
"iterpackages",
"(",
"self",
")",
":",
"pkgdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"self",
".",
"PKG_DIR",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"pkgdir",
")",
":",
"return",
"for",
"tea... | 47 | 18.384615 |
def values(self):
"""Gets the parameter values
:returns: dict of inputs:
| *'nfft'*: int -- length, in samples, of FFT chunks
| *'window'*: str -- name of window to apply to FFT chunks
| *'overlap'*: float -- percent overlap of windows
"""
s... | [
"def",
"values",
"(",
"self",
")",
":",
"self",
".",
"vals",
"[",
"'nfft'",
"]",
"=",
"self",
".",
"ui",
".",
"nfftSpnbx",
".",
"value",
"(",
")",
"self",
".",
"vals",
"[",
"'window'",
"]",
"=",
"str",
"(",
"self",
".",
"ui",
".",
"windowCmbx",
... | 42.833333 | 19.916667 |
def update(self, x_list=list(), y_list=list()):
"""
update interpolation data
:param list(float) x_list: x values
:param list(float) y_list: y values
"""
if not y_list:
for x in x_list:
if x in self.x_list:
i = self.x_list.i... | [
"def",
"update",
"(",
"self",
",",
"x_list",
"=",
"list",
"(",
")",
",",
"y_list",
"=",
"list",
"(",
")",
")",
":",
"if",
"not",
"y_list",
":",
"for",
"x",
"in",
"x_list",
":",
"if",
"x",
"in",
"self",
".",
"x_list",
":",
"i",
"=",
"self",
".... | 38.25 | 9.45 |
def fpsInformation(self,args):
'''fps command'''
invalidStr = 'Invalid number of arguments. Usage horizon-fps set <fps> or horizon-fps get. Set fps to zero to get unrestricted framerate.'
if len(args)>0:
if args[0] == "get":
'''Get the current framerate.'''
... | [
"def",
"fpsInformation",
"(",
"self",
",",
"args",
")",
":",
"invalidStr",
"=",
"'Invalid number of arguments. Usage horizon-fps set <fps> or horizon-fps get. Set fps to zero to get unrestricted framerate.'",
"if",
"len",
"(",
"args",
")",
">",
"0",
":",
"if",
"args",
"[",
... | 41.428571 | 16.214286 |
def __response(self,stanza):
"""Handle successful disco response.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
try:
d=self.disco_class(stanza.get_query())
self.got_it(d)
except ValueEr... | [
"def",
"__response",
"(",
"self",
",",
"stanza",
")",
":",
"try",
":",
"d",
"=",
"self",
".",
"disco_class",
"(",
"stanza",
".",
"get_query",
"(",
")",
")",
"self",
".",
"got_it",
"(",
"d",
")",
"except",
"ValueError",
",",
"e",
":",
"self",
".",
... | 28.416667 | 15 |
def _reap_payloads(self):
"""Clean up all finished payloads"""
for thread in self._threads.copy():
# CapturingThread.join will throw
if thread.join(timeout=0):
self._threads.remove(thread)
self._logger.debug('reaped thread %s', thread) | [
"def",
"_reap_payloads",
"(",
"self",
")",
":",
"for",
"thread",
"in",
"self",
".",
"_threads",
".",
"copy",
"(",
")",
":",
"# CapturingThread.join will throw",
"if",
"thread",
".",
"join",
"(",
"timeout",
"=",
"0",
")",
":",
"self",
".",
"_threads",
"."... | 43 | 7.285714 |
def _ingest_source(self, source, ps, force=None):
"""Ingest a single source"""
from ambry.bundle.process import call_interval
try:
from ambry.orm.exc import NotFoundError
if not source.is_partition and source.datafile.exists:
if not source.datafile.is_... | [
"def",
"_ingest_source",
"(",
"self",
",",
"source",
",",
"ps",
",",
"force",
"=",
"None",
")",
":",
"from",
"ambry",
".",
"bundle",
".",
"process",
"import",
"call_interval",
"try",
":",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError"... | 38.569892 | 25.83871 |
def encode(self, x):
"""
Encode given input.
"""
if not self.encoding_network:
self.encoding_network = NeuralNetwork(self.input_dim, self.input_tensor)
self.encoding_network.input_variables = self.input_variables
for layer in self.encoding_layes:
... | [
"def",
"encode",
"(",
"self",
",",
"x",
")",
":",
"if",
"not",
"self",
".",
"encoding_network",
":",
"self",
".",
"encoding_network",
"=",
"NeuralNetwork",
"(",
"self",
".",
"input_dim",
",",
"self",
".",
"input_tensor",
")",
"self",
".",
"encoding_network... | 42.6 | 15.6 |
def checktype(self, elt, ps):
'''See if the type of the "elt" element is what we're looking for.
Return the element's type.
Parameters:
elt -- the DOM element being parsed
ps -- the ParsedSoap object.
'''
typeName = _find_type(elt)
if typeName is N... | [
"def",
"checktype",
"(",
"self",
",",
"elt",
",",
"ps",
")",
":",
"typeName",
"=",
"_find_type",
"(",
"elt",
")",
"if",
"typeName",
"is",
"None",
"or",
"typeName",
"==",
"\"\"",
":",
"return",
"(",
"None",
",",
"None",
")",
"# Parse the QNAME.",
"prefi... | 38.444444 | 15.851852 |
def account_lists(self, id):
"""
Get all of the logged-in users lists which the specified user is
a member of.
Returns a list of `list dicts`_.
"""
id = self.__unpack_id(id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/accounts... | [
"def",
"account_lists",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'id'",
"]",
")",
"url",
"=",
"'/api/v1/accounts/{0}/li... | 35.545455 | 13.727273 |
def iter_referents_tuples(self):
""" Generates target sets (as tuples of indicies) that are compatible with
the current beliefstate."""
tlow, thigh = self['targetset_arity'].get_tuple()
clow, chigh = self['contrast_arity'].get_tuple()
singletons = list([int(i) for i,_ in self.ite... | [
"def",
"iter_referents_tuples",
"(",
"self",
")",
":",
"tlow",
",",
"thigh",
"=",
"self",
"[",
"'targetset_arity'",
"]",
".",
"get_tuple",
"(",
")",
"clow",
",",
"chigh",
"=",
"self",
"[",
"'contrast_arity'",
"]",
".",
"get_tuple",
"(",
")",
"singletons",
... | 50.923077 | 14.692308 |
def tfds_dir():
"""Path to tensorflow_datasets directory."""
return os.path.dirname(os.path.dirname(os.path.dirname(__file__))) | [
"def",
"tfds_dir",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")"
] | 43 | 17.666667 |
def make_purge(parser):
"""
Remove Ceph packages from remote hosts and purge all data.
"""
parser.add_argument(
'host',
metavar='HOST',
nargs='+',
help='hosts to purge Ceph from',
)
parser.set_defaults(
func=purge,
) | [
"def",
"make_purge",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'host'",
",",
"metavar",
"=",
"'HOST'",
",",
"nargs",
"=",
"'+'",
",",
"help",
"=",
"'hosts to purge Ceph from'",
",",
")",
"parser",
".",
"set_defaults",
"(",
"func",
"=",
... | 21.538462 | 16.769231 |
def parse_cmdln_opts(parser, cmdln_args):
"""Rather than have this all clutter main(), let's split this out.
Clean arch decision: rather than parsing sys.argv directly, pass
sys.argv[1:] to this function (or any iterable for testing.)
"""
parser.set_defaults(
hosts=[],
cert=None,
... | [
"def",
"parse_cmdln_opts",
"(",
"parser",
",",
"cmdln_args",
")",
":",
"parser",
".",
"set_defaults",
"(",
"hosts",
"=",
"[",
"]",
",",
"cert",
"=",
"None",
",",
"log_level",
"=",
"logging",
".",
"INFO",
",",
"output_dir",
"=",
"None",
",",
"output_file"... | 37.108696 | 20.666667 |
def rpr(s):
"""Create a representation of a Unicode string that can be used in both
Python 2 and Python 3k, allowing for use of the u() function"""
if s is None:
return 'None'
seen_unicode = False
results = []
for cc in s:
ccn = ord(cc)
if ccn >= 32 and ccn < 127:
... | [
"def",
"rpr",
"(",
"s",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"'None'",
"seen_unicode",
"=",
"False",
"results",
"=",
"[",
"]",
"for",
"cc",
"in",
"s",
":",
"ccn",
"=",
"ord",
"(",
"cc",
")",
"if",
"ccn",
">=",
"32",
"and",
"ccn",
... | 31.806452 | 11.806452 |
def element_background_color_should_be(self, locator, expected):
"""Verifies the element identified by `locator` has the expected
background color (it verifies the CSS attribute background-color). Color should
be in RGBA format.
Example of rgba format: rgba(RED, GREEN, BLUE, ALPHA)
| *Argument* | *Descripti... | [
"def",
"element_background_color_should_be",
"(",
"self",
",",
"locator",
",",
"expected",
")",
":",
"self",
".",
"_info",
"(",
"\"Verifying element '%s' has background color '%s'\"",
"%",
"(",
"locator",
",",
"expected",
")",
")",
"self",
".",
"_check_element_css_val... | 45.692308 | 24.076923 |
def parse_division(l, c, line, root_node, last_section_node):
"""
Extracts a division node from a line
:param l: The line number (starting from 0)
:param c: The column number
:param line: The line string (without indentation)
:param root_node: The document root node.
:return: tuple(last... | [
"def",
"parse_division",
"(",
"l",
",",
"c",
",",
"line",
",",
"root_node",
",",
"last_section_node",
")",
":",
"name",
"=",
"line",
"name",
"=",
"name",
".",
"replace",
"(",
"\".\"",
",",
"\"\"",
")",
"# trim whitespaces/tabs between XXX and DIVISION",
"token... | 30.730769 | 16.192308 |
def setAll(self, pairs):
"""
Set multiple parameters, passed as a list of key-value pairs.
:param pairs: list of key-value pairs to set
"""
for (k, v) in pairs:
self.set(k, v)
return self | [
"def",
"setAll",
"(",
"self",
",",
"pairs",
")",
":",
"for",
"(",
"k",
",",
"v",
")",
"in",
"pairs",
":",
"self",
".",
"set",
"(",
"k",
",",
"v",
")",
"return",
"self"
] | 26.666667 | 16 |
def set_payload(self, payload):
"""Set stanza payload to a single item.
All current stanza content of will be dropped.
Marks the stanza dirty.
:Parameters:
- `payload`: XML element or stanza payload object to use
:Types:
- `payload`: :etree:`ElementTree.... | [
"def",
"set_payload",
"(",
"self",
",",
"payload",
")",
":",
"if",
"isinstance",
"(",
"payload",
",",
"ElementClass",
")",
":",
"self",
".",
"_payload",
"=",
"[",
"XMLPayload",
"(",
"payload",
")",
"]",
"elif",
"isinstance",
"(",
"payload",
",",
"StanzaP... | 34.333333 | 16.111111 |
def generate(self):
'''
Generate noise samples.
Returns:
`np.ndarray` of samples.
'''
sampled_arr = np.zeros((self.__batch_size, self.__channel, self.__seq_len, self.__dim))
for batch in range(self.__batch_size):
for i in range(... | [
"def",
"generate",
"(",
"self",
")",
":",
"sampled_arr",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"__batch_size",
",",
"self",
".",
"__channel",
",",
"self",
".",
"__seq_len",
",",
"self",
".",
"__dim",
")",
")",
"for",
"batch",
"in",
"range",... | 42.37931 | 23.413793 |
def output(output_id, name, value_class=NumberValue):
"""Add output to controller"""
def _init():
return value_class(
name,
input_id=output_id,
is_input=False,
index=-1
)
def _decorator(cls):
seta... | [
"def",
"output",
"(",
"output_id",
",",
"name",
",",
"value_class",
"=",
"NumberValue",
")",
":",
"def",
"_init",
"(",
")",
":",
"return",
"value_class",
"(",
"name",
",",
"input_id",
"=",
"output_id",
",",
"is_input",
"=",
"False",
",",
"index",
"=",
... | 29.615385 | 12.846154 |
def _add_hypotheses_assuming_new_stroke(self,
new_stroke,
stroke_nr,
new_beam):
"""
Get new guesses by assuming new_stroke is a new symbol.
Parameters
----... | [
"def",
"_add_hypotheses_assuming_new_stroke",
"(",
"self",
",",
"new_stroke",
",",
"stroke_nr",
",",
"new_beam",
")",
":",
"guesses",
"=",
"single_clf",
".",
"predict",
"(",
"{",
"'data'",
":",
"[",
"new_stroke",
"]",
",",
"'id'",
":",
"None",
"}",
")",
"[... | 45 | 14.698113 |
def restart_with_reloader():
"""Create a new process and a subprocess in it with the same arguments as
this one.
"""
cwd = os.getcwd()
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ["SANIC_SERVER_RUNNING"] = "true"
cmd = " ".join(args)
worker_process = P... | [
"def",
"restart_with_reloader",
"(",
")",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"args",
"=",
"_get_args_for_reloading",
"(",
")",
"new_environ",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"new_environ",
"[",
"\"SANIC_SERVER_RUNNING\"",
"]",
... | 30.5 | 13.625 |
def _printM(self, messages):
"""print a list of strings - for the mom used only by stats printout"""
if len(messages) == 2:
print(Style.BRIGHT + messages[0] + Style.RESET_ALL +
Fore.BLUE + messages[1] + Style.RESET_ALL)
else:
print("Not implemented") | [
"def",
"_printM",
"(",
"self",
",",
"messages",
")",
":",
"if",
"len",
"(",
"messages",
")",
"==",
"2",
":",
"print",
"(",
"Style",
".",
"BRIGHT",
"+",
"messages",
"[",
"0",
"]",
"+",
"Style",
".",
"RESET_ALL",
"+",
"Fore",
".",
"BLUE",
"+",
"mes... | 44.285714 | 13.857143 |
def getIndices(self):
"""Returns a generator function over all the existing indexes
@returns A generator function over all rhe Index objects"""
for indexName in self.neograph.nodes.indexes.keys():
indexObject = self.neograph.nodes.indexes.get(indexName)
yield Index(index... | [
"def",
"getIndices",
"(",
"self",
")",
":",
"for",
"indexName",
"in",
"self",
".",
"neograph",
".",
"nodes",
".",
"indexes",
".",
"keys",
"(",
")",
":",
"indexObject",
"=",
"self",
".",
"neograph",
".",
"nodes",
".",
"indexes",
".",
"get",
"(",
"inde... | 56.1 | 22.3 |
def ensure_utf8(image_tag):
"""wrapper for ensuring image_tag returns utf8-encoded str on Python 2"""
if py3compat.PY3:
# nothing to do on Python 3
return image_tag
def utf8_image_tag(*args, **kwargs):
s = image_tag(*args, **kwargs)
if isinstance(s, unicode):
... | [
"def",
"ensure_utf8",
"(",
"image_tag",
")",
":",
"if",
"py3compat",
".",
"PY3",
":",
"# nothing to do on Python 3",
"return",
"image_tag",
"def",
"utf8_image_tag",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"image_tag",
"(",
"*",
"args... | 31.083333 | 12 |
def route(self, path=None, method='GET', callback=None, name=None,
apply=None, skip=None, **config):
""" A decorator to bind a function to a request URL. Example::
@app.route('/hello/:name')
def hello(name):
return 'Hello %s' % name
... | [
"def",
"route",
"(",
"self",
",",
"path",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"callback",
"=",
"None",
",",
"name",
"=",
"None",
",",
"apply",
"=",
"None",
",",
"skip",
"=",
"None",
",",
"*",
"*",
"config",
")",
":",
"if",
"callable",
... | 51.348837 | 21.744186 |
def submit_recording(raw_data_json):
"""Submit a recording to the database on write-math.com.
Parameters
----------
raw_data_json : str
Raw data in JSON format
Raises
------
requests.exceptions.ConnectionError
If the internet connection is lost.
"""
url = "http://ww... | [
"def",
"submit_recording",
"(",
"raw_data_json",
")",
":",
"url",
"=",
"\"http://www.martin-thoma.de/write-math/classify/index.php\"",
"headers",
"=",
"{",
"'User-Agent'",
":",
"'Mozilla/5.0'",
",",
"'Content-Type'",
":",
"'application/x-www-form-urlencoded'",
"}",
"payload",... | 29.590909 | 18.272727 |
def format(self, record):
'''
Format the log record to include exc_info if the handler is enabled for a specific log level
'''
formatted_record = super(ExcInfoOnLogLevelFormatMixIn, self).format(record)
exc_info_on_loglevel = getattr(record, 'exc_info_on_loglevel', None)
... | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"formatted_record",
"=",
"super",
"(",
"ExcInfoOnLogLevelFormatMixIn",
",",
"self",
")",
".",
"format",
"(",
"record",
")",
"exc_info_on_loglevel",
"=",
"getattr",
"(",
"record",
",",
"'exc_info_on_loglevel'... | 54.134615 | 29.711538 |
def dumps(self, cnf, **kwargs):
"""
Dump config 'cnf' to a string.
:param cnf: Configuration data to dump
:param kwargs: optional keyword parameters to be sanitized :: dict
:return: string represents the configuration
"""
kwargs = anyconfig.utils.filter_options(... | [
"def",
"dumps",
"(",
"self",
",",
"cnf",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"anyconfig",
".",
"utils",
".",
"filter_options",
"(",
"self",
".",
"_dump_opts",
",",
"kwargs",
")",
"return",
"self",
".",
"dump_to_string",
"(",
"cnf",
",",
... | 34.909091 | 16.727273 |
def _run_server(self):
"""
启动 HTTP Server
"""
try:
if __conf__.DEBUG:
self._webapp.listen(self._port)
else:
server = HTTPServer(self._webapp)
server.bind(self._port)
server.start(0)
... | [
"def",
"_run_server",
"(",
"self",
")",
":",
"try",
":",
"if",
"__conf__",
".",
"DEBUG",
":",
"self",
".",
"_webapp",
".",
"listen",
"(",
"self",
".",
"_port",
")",
"else",
":",
"server",
"=",
"HTTPServer",
"(",
"self",
".",
"_webapp",
")",
"server",... | 27.2 | 11.466667 |
def get_ddo(self, ont_id: str) -> dict:
"""
This interface is used to get a DDO object in the from of dict.
:param ont_id: the unique ID for identity.
:return: a description object of ONT ID in the from of dict.
"""
args = dict(ontid=ont_id.encode('utf-8'))
invok... | [
"def",
"get_ddo",
"(",
"self",
",",
"ont_id",
":",
"str",
")",
"->",
"dict",
":",
"args",
"=",
"dict",
"(",
"ontid",
"=",
"ont_id",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"invoke_code",
"=",
"build_vm",
".",
"build_native_invoke_code",
"(",
"self",
"... | 48.428571 | 22.285714 |
def xception_exit(inputs):
"""Xception exit flow."""
with tf.variable_scope("xception_exit"):
x = inputs
x_shape = x.get_shape().as_list()
if x_shape[1] is None or x_shape[2] is None:
length_float = tf.to_float(tf.shape(x)[1])
length_float *= tf.to_float(tf.shape(x)[2])
spatial_dim_flo... | [
"def",
"xception_exit",
"(",
"inputs",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"xception_exit\"",
")",
":",
"x",
"=",
"inputs",
"x_shape",
"=",
"x",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"if",
"x_shape",
"[",
"1",
"]",
"... | 43.952381 | 15.904762 |
def parent(self, index):
"""
Reimplements the :meth:`QAbstractItemModel.parent` method.
:param index: Index.
:type index: QModelIndex
:return: Parent.
:rtype: QModelIndex
"""
if not index.isValid():
return QModelIndex()
node = self.g... | [
"def",
"parent",
"(",
"self",
",",
"index",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"QModelIndex",
"(",
")",
"node",
"=",
"self",
".",
"get_node",
"(",
"index",
")",
"parent_node",
"=",
"node",
".",
"parent",
"if",
... | 26.478261 | 17.869565 |
def speech(self) -> str:
"""
Report summary designed to be read by a text-to-speech program
"""
if not self.data:
self.update()
return speech.metar(self.data, self.units) | [
"def",
"speech",
"(",
"self",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"data",
":",
"self",
".",
"update",
"(",
")",
"return",
"speech",
".",
"metar",
"(",
"self",
".",
"data",
",",
"self",
".",
"units",
")"
] | 30.857143 | 12.285714 |
def get_security_group_dict():
"""Returns dictionary of named security groups {name: securitygroup}."""
client = get_ec2_client()
response = client.describe_security_groups()
assert is_good_response(response)
result = OrderedDict()
ec2 = get_ec2_resource()
for security_group_response in response['Securi... | [
"def",
"get_security_group_dict",
"(",
")",
":",
"client",
"=",
"get_ec2_client",
"(",
")",
"response",
"=",
"client",
".",
"describe_security_groups",
"(",
")",
"assert",
"is_good_response",
"(",
"response",
")",
"result",
"=",
"OrderedDict",
"(",
")",
"ec2",
... | 37.047619 | 18.095238 |
def description(self):
"""This read-only attribute is a sequence of 7-item sequences.
Each of these sequences contains information describing one result column:
- name
- type_code
- display_size (None in current implementation)
- internal_size (None in current implement... | [
"def",
"description",
"(",
"self",
")",
":",
"# Sleep until we're done or we got the columns",
"if",
"self",
".",
"_columns",
"is",
"None",
":",
"return",
"[",
"]",
"return",
"[",
"# name, type_code, display_size, internal_size, precision, scale, null_ok",
"(",
"col",
"["... | 39.391304 | 24.043478 |
def dms_to_degrees(v):
"""Convert degree/minute/second to decimal degrees."""
d = float(v[0][0]) / float(v[0][1])
m = float(v[1][0]) / float(v[1][1])
s = float(v[2][0]) / float(v[2][1])
return d + (m / 60.0) + (s / 3600.0) | [
"def",
"dms_to_degrees",
"(",
"v",
")",
":",
"d",
"=",
"float",
"(",
"v",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"/",
"float",
"(",
"v",
"[",
"0",
"]",
"[",
"1",
"]",
")",
"m",
"=",
"float",
"(",
"v",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"/... | 33.857143 | 8.714286 |
def tags(self):
"""
FEFF job parameters.
Returns:
Tags
"""
if "RECIPROCAL" in self.config_dict:
if self.small_system:
self.config_dict["CIF"] = "{}.cif".format(
self.structure.formula.replace(" ", ""))
s... | [
"def",
"tags",
"(",
"self",
")",
":",
"if",
"\"RECIPROCAL\"",
"in",
"self",
".",
"config_dict",
":",
"if",
"self",
".",
"small_system",
":",
"self",
".",
"config_dict",
"[",
"\"CIF\"",
"]",
"=",
"\"{}.cif\"",
".",
"format",
"(",
"self",
".",
"structure",... | 43.357143 | 19.571429 |
def run_until(self, endtime, timeunit='minutes', save=True):
"""
Run a case untile the specifiend endtime
"""
integrator = self.case.solver.Integrator
integrator.rununtil(endtime, timeunit)
if save is True:
self.case.save() | [
"def",
"run_until",
"(",
"self",
",",
"endtime",
",",
"timeunit",
"=",
"'minutes'",
",",
"save",
"=",
"True",
")",
":",
"integrator",
"=",
"self",
".",
"case",
".",
"solver",
".",
"Integrator",
"integrator",
".",
"rununtil",
"(",
"endtime",
",",
"timeuni... | 34.5 | 8.75 |
def unit_get(attribute):
"""Get the unit ID for the remote unit"""
_args = ['unit-get', '--format=json', attribute]
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None | [
"def",
"unit_get",
"(",
"attribute",
")",
":",
"_args",
"=",
"[",
"'unit-get'",
",",
"'--format=json'",
",",
"attribute",
"]",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"subprocess",
".",
"check_output",
"(",
"_args",
")",
".",
"decode",
"(",
"'UT... | 34.714286 | 18.857143 |
def perplexity(self):
"""
Compute perplexity for each sample.
"""
return samplers_lda.perplexity_comp(self.docid, self.tokens,
self.tt, self.dt, self.N,
self.K, self.samples) | [
"def",
"perplexity",
"(",
"self",
")",
":",
"return",
"samplers_lda",
".",
"perplexity_comp",
"(",
"self",
".",
"docid",
",",
"self",
".",
"tokens",
",",
"self",
".",
"tt",
",",
"self",
".",
"dt",
",",
"self",
".",
"N",
",",
"self",
".",
"K",
",",
... | 32 | 20.444444 |
def _desc_has_data(desc):
"""Returns true if there is any data set for a particular PhoneNumberDesc."""
if desc is None:
return False
# Checking most properties since we don't know what's present, since a custom build may have
# stripped just one of them (e.g. liteBuild strips exampleNumber). We... | [
"def",
"_desc_has_data",
"(",
"desc",
")",
":",
"if",
"desc",
"is",
"None",
":",
"return",
"False",
"# Checking most properties since we don't know what's present, since a custom build may have",
"# stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking... | 61.363636 | 27.636364 |
def set_opcode(self, opcode):
"""Set the opcode.
@param opcode: the opcode
@type opcode: int
"""
self.flags &= 0x87FF
self.flags |= dns.opcode.to_flags(opcode) | [
"def",
"set_opcode",
"(",
"self",
",",
"opcode",
")",
":",
"self",
".",
"flags",
"&=",
"0x87FF",
"self",
".",
"flags",
"|=",
"dns",
".",
"opcode",
".",
"to_flags",
"(",
"opcode",
")"
] | 28.714286 | 7.714286 |
def mapfivo(ol,*args,**kwargs):
'''
#mapfivo f,i,v,o四元决定 fivo-4-tuple-engine
#map_func diff_func(index,value,*diff_args)
'''
args = list(args)
lngth = args.__len__()
if(lngth==0):
diff_funcs_arr = kwargs['map_funcs']
diff_args_arr ... | [
"def",
"mapfivo",
"(",
"ol",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"list",
"(",
"args",
")",
"lngth",
"=",
"args",
".",
"__len__",
"(",
")",
"if",
"(",
"lngth",
"==",
"0",
")",
":",
"diff_funcs_arr",
"=",
"kwargs",
"... | 30.3 | 16.5 |
def plot_multi(data, cols=None, spacing=.06, color_map=None, plot_kw=None, **kwargs):
"""
Plot data with multiple scaels together
Args:
data: DataFrame of data
cols: columns to be plotted
spacing: spacing between legends
color_map: customized colors in map
plot_kw: k... | [
"def",
"plot_multi",
"(",
"data",
",",
"cols",
"=",
"None",
",",
"spacing",
"=",
".06",
",",
"color_map",
"=",
"None",
",",
"plot_kw",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"from",
"pandas... | 34.464286 | 19.75 |
def none(n, coef):
"""
Build a matrix of zeros for features that should go unpenalized
Parameters
----------
n : int
number of splines
coef : unused
for compatibility with constraints
Returns
-------
penalty matrix : sparse csc matrix of shape (n,n)
"""
retu... | [
"def",
"none",
"(",
"n",
",",
"coef",
")",
":",
"return",
"sp",
".",
"sparse",
".",
"csc_matrix",
"(",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"n",
")",
")",
")"
] | 21.625 | 20.625 |
def get_error(self, block = True, timeout = None):
"""
Gets the next error message.
Each error message is a 2-tuple of (status, identifier)."""
return self._error_queue.get(block = block, timeout = timeout) | [
"def",
"get_error",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"_error_queue",
".",
"get",
"(",
"block",
"=",
"block",
",",
"timeout",
"=",
"timeout",
")"
] | 35.333333 | 13.666667 |
def dispatch_write(self, buf):
"""Augment the buffer with stuff to write when possible"""
self.write_buffer += buf
if len(self.write_buffer) > self.MAX_BUFFER_SIZE:
console_output('Buffer too big ({:d}) for {}\n'.format(
len(self.write_buffer), str(self)).encode())
... | [
"def",
"dispatch_write",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"write_buffer",
"+=",
"buf",
"if",
"len",
"(",
"self",
".",
"write_buffer",
")",
">",
"self",
".",
"MAX_BUFFER_SIZE",
":",
"console_output",
"(",
"'Buffer too big ({:d}) for {}\\n'",
".",... | 46 | 13.25 |
def read(cls, data):
"""Reads data from URL, Dataframe, JSON string, JSON file
or OrderedDict.
Args:
data: can be a Pandas Dataframe, a JSON string, a JSON file,
an OrderedDict or a URL pointing to a JSONstat file.
Returns:
An object of class... | [
"def",
"read",
"(",
"cls",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"pd",
".",
"DataFrame",
")",
":",
"output",
"=",
"OrderedDict",
"(",
"{",
"}",
")",
"output",
"[",
"'version'",
"]",
"=",
"'2.0'",
"output",
"[",
"'class'",
"]"... | 40.809524 | 17.142857 |
def url2path(url):
"""
If url identifies a file on the local host, return the path to the
file otherwise raise ValueError.
"""
scheme, host, path, nul, nul, nul = urlparse(url)
if scheme.lower() in ("", "file") and host.lower() in ("", "localhost"):
return path
raise ValueError(url) | [
"def",
"url2path",
"(",
"url",
")",
":",
"scheme",
",",
"host",
",",
"path",
",",
"nul",
",",
"nul",
",",
"nul",
"=",
"urlparse",
"(",
"url",
")",
"if",
"scheme",
".",
"lower",
"(",
")",
"in",
"(",
"\"\"",
",",
"\"file\"",
")",
"and",
"host",
"... | 31.555556 | 16 |
def eval(self, exp):
"main dispatch for expression evaluation"
# todo: this needs an AST-assert that all BaseX descendants are being handled
if isinstance(exp,sqparse2.BinX): return evalop(exp.op.op, *map(self.eval, (exp.left, exp.right)))
elif isinstance(exp,sqparse2.UnX): return self.eval_unx(exp)
... | [
"def",
"eval",
"(",
"self",
",",
"exp",
")",
":",
"# todo: this needs an AST-assert that all BaseX descendants are being handled",
"if",
"isinstance",
"(",
"exp",
",",
"sqparse2",
".",
"BinX",
")",
":",
"return",
"evalop",
"(",
"exp",
".",
"op",
".",
"op",
",",
... | 65.219512 | 30.487805 |
def receive_device_value(self, raw_value: int):
"""
Set a new value, called from within the joystick implementation class when parsing the event queue.
:param raw_value: the raw value from the joystick hardware
:internal:
"""
new_value = self._input_to_raw_value(raw_val... | [
"def",
"receive_device_value",
"(",
"self",
",",
"raw_value",
":",
"int",
")",
":",
"new_value",
"=",
"self",
".",
"_input_to_raw_value",
"(",
"raw_value",
")",
"if",
"self",
".",
"button",
"is",
"not",
"None",
":",
"if",
"new_value",
">",
"(",
"self",
"... | 42.052632 | 20.368421 |
def summarize(group, fs=None, include_source=True):
"""
Tabulate and write the results of ComparisonBenchmarks to a file or standard out.
:param str group: name of the comparison group.
:param fs: file-like object (Optional)
"""
_line_break = '{0:-<120}\n'.format('')
... | [
"def",
"summarize",
"(",
"group",
",",
"fs",
"=",
"None",
",",
"include_source",
"=",
"True",
")",
":",
"_line_break",
"=",
"'{0:-<120}\\n'",
".",
"format",
"(",
"''",
")",
"tests",
"=",
"sorted",
"(",
"ComparisonBenchmark",
".",
"groups",
"[",
"group",
... | 40.469388 | 17.612245 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.