text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def create_function_from_request_pdu(pdu):
""" Return function instance, based on request PDU.
:param pdu: Array of bytes.
:return: Instance of a function.
"""
function_code = get_function_code_from_request_pdu(pdu)
try:
function_class = function_code_to_function_map[function_code]
... | [
"def",
"create_function_from_request_pdu",
"(",
"pdu",
")",
":",
"function_code",
"=",
"get_function_code_from_request_pdu",
"(",
"pdu",
")",
"try",
":",
"function_class",
"=",
"function_code_to_function_map",
"[",
"function_code",
"]",
"except",
"KeyError",
":",
"raise... | 33.076923 | 16.769231 |
def md5_for_file(f, block_size=2 ** 20):
"""Generate an MD5 has for a possibly large file by breaking it into
chunks."""
md5 = hashlib.md5()
try:
# Guess that f is a FLO.
f.seek(0)
return md5_for_stream(f, block_size=block_size)
except AttributeError:
# Nope, not a... | [
"def",
"md5_for_file",
"(",
"f",
",",
"block_size",
"=",
"2",
"**",
"20",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"try",
":",
"# Guess that f is a FLO.",
"f",
".",
"seek",
"(",
"0",
")",
"return",
"md5_for_stream",
"(",
"f",
",",
"bloc... | 25.529412 | 17.294118 |
def group_delete(auth=None, **kwargs):
'''
Delete a group
CLI Example:
.. code-block:: bash
salt '*' keystoneng.group_delete name=group1
salt '*' keystoneng.group_delete name=group2 domain_id=b62e76fbeeff4e8fb77073f591cf211e
salt '*' keystoneng.group_delete name=0e4febc2a5ab4f... | [
"def",
"group_delete",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"delete_group",
"(",
"*",
"*... | 29.733333 | 24.266667 |
def _CheckPacketSize(cursor):
"""Checks that MySQL packet size is big enough for expected query size."""
cur_packet_size = int(_ReadVariable("max_allowed_packet", cursor))
if cur_packet_size < MAX_PACKET_SIZE:
raise Error(
"MySQL max_allowed_packet of {0} is required, got {1}. "
"Please set ma... | [
"def",
"_CheckPacketSize",
"(",
"cursor",
")",
":",
"cur_packet_size",
"=",
"int",
"(",
"_ReadVariable",
"(",
"\"max_allowed_packet\"",
",",
"cursor",
")",
")",
"if",
"cur_packet_size",
"<",
"MAX_PACKET_SIZE",
":",
"raise",
"Error",
"(",
"\"MySQL max_allowed_packet ... | 51.375 | 15.875 |
def AddPort(self,protocol,port,port_to=None):
"""Add and commit a single port.
# Add single port
>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='TCP',port='22').WaitUntilComplete()
0
# Add port range
>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='UD... | [
"def",
"AddPort",
"(",
"self",
",",
"protocol",
",",
"port",
",",
"port_to",
"=",
"None",
")",
":",
"self",
".",
"ports",
".",
"append",
"(",
"Port",
"(",
"self",
",",
"protocol",
",",
"port",
",",
"port_to",
")",
")",
"return",
"(",
"self",
".",
... | 28 | 32.3125 |
def change_parameters(self,params):
"""
Utility function for changing the approximate distribution parameters
"""
no_of_params = 0
for core_param in range(len(self.q)):
for approx_param in range(self.q[core_param].param_no):
self.q[core_param].vi_chang... | [
"def",
"change_parameters",
"(",
"self",
",",
"params",
")",
":",
"no_of_params",
"=",
"0",
"for",
"core_param",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"q",
")",
")",
":",
"for",
"approx_param",
"in",
"range",
"(",
"self",
".",
"q",
"[",
"core_... | 43.222222 | 15.888889 |
def _normalize_properties(self, definition):
"""
Inspects the definition and returns a copy of it that is updated
with any special property such as Condition, UpdatePolicy and the
like.
"""
args = definition.get('Properties', {}).copy()
if 'Condition' in definitio... | [
"def",
"_normalize_properties",
"(",
"self",
",",
"definition",
")",
":",
"args",
"=",
"definition",
".",
"get",
"(",
"'Properties'",
",",
"{",
"}",
")",
".",
"copy",
"(",
")",
"if",
"'Condition'",
"in",
"definition",
":",
"args",
".",
"update",
"(",
"... | 45.3125 | 13.75 |
def rpcexec(self, payload):
""" Execute a call by sending the payload
:param json payload: Payload data
:raises ValueError: if the server does not respond in proper JSON
format
"""
if not self.ws: # pragma: no cover
self.connect()
lo... | [
"def",
"rpcexec",
"(",
"self",
",",
"payload",
")",
":",
"if",
"not",
"self",
".",
"ws",
":",
"# pragma: no cover",
"self",
".",
"connect",
"(",
")",
"log",
".",
"debug",
"(",
"json",
".",
"dumps",
"(",
"payload",
")",
")",
"# Mutex/Lock",
"# We need t... | 29.413793 | 20.172414 |
def collection(self, attribute):
"""Returns the collection corresponding the attribute name."""
return {
"dependencies": self.dependencies,
"publics": self.publics,
"members": self.members,
"types": self.types,
"executables": self.executables,
... | [
"def",
"collection",
"(",
"self",
",",
"attribute",
")",
":",
"return",
"{",
"\"dependencies\"",
":",
"self",
".",
"dependencies",
",",
"\"publics\"",
":",
"self",
".",
"publics",
",",
"\"members\"",
":",
"self",
".",
"members",
",",
"\"types\"",
":",
"sel... | 37.3 | 7.9 |
def get(self, sid):
"""
Constructs a BuildContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.build.BuildContext
:rtype: twilio.rest.serverless.v1.service.build.BuildContext
"""
return BuildContext(self._version, service_sid=self._solution['s... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"BuildContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | 33.5 | 23.5 |
def observe(self, C, obs_mesh_new, obs_vals_new, mean_under=None):
"""
Synchronizes self's observation status with C's.
Values of observation are given by obs_vals.
obs_mesh_new and obs_vals_new should already have
been sliced, as Covariance.observe(..., output_type='o') does.
... | [
"def",
"observe",
"(",
"self",
",",
"C",
",",
"obs_mesh_new",
",",
"obs_vals_new",
",",
"mean_under",
"=",
"None",
")",
":",
"self",
".",
"C",
"=",
"C",
"self",
".",
"obs_mesh",
"=",
"C",
".",
"obs_mesh",
"self",
".",
"obs_len",
"=",
"C",
".",
"obs... | 31.555556 | 21.377778 |
def finalize(self):
""" Is called when the editor is closed. Disconnect signals.
"""
self.pickButton.clicked.disconnect(self.execFontDialog)
super(FontCtiEditor, self).finalize() | [
"def",
"finalize",
"(",
"self",
")",
":",
"self",
".",
"pickButton",
".",
"clicked",
".",
"disconnect",
"(",
"self",
".",
"execFontDialog",
")",
"super",
"(",
"FontCtiEditor",
",",
"self",
")",
".",
"finalize",
"(",
")"
] | 41.2 | 9.8 |
def set_error_pages(self, codes_map=None, common_prefix=None):
"""Add an error pages for managed 403, 404, 500 responses.
Shortcut for ``.set_error_page()``.
:param dict codes_map: Status code mapped into an html filepath or
just a filename if common_prefix is used.
If... | [
"def",
"set_error_pages",
"(",
"self",
",",
"codes_map",
"=",
"None",
",",
"common_prefix",
"=",
"None",
")",
":",
"statuses",
"=",
"[",
"403",
",",
"404",
",",
"500",
"]",
"if",
"common_prefix",
":",
"if",
"not",
"codes_map",
":",
"codes_map",
"=",
"{... | 34.076923 | 25.269231 |
def haversine(lng1, lat1, lng2, lat2):
"""Compute km by geo-coordinates
See also: haversine define https://en.wikipedia.org/wiki/Haversine_formula
"""
# Convert coordinates to floats.
lng1, lat1, lng2, lat2 = map(float, [lng1, lat1, lng2, lat2])
# Convert to radians from degrees
lng1, lat1,... | [
"def",
"haversine",
"(",
"lng1",
",",
"lat1",
",",
"lng2",
",",
"lat2",
")",
":",
"# Convert coordinates to floats.",
"lng1",
",",
"lat1",
",",
"lng2",
",",
"lat2",
"=",
"map",
"(",
"float",
",",
"[",
"lng1",
",",
"lat1",
",",
"lng2",
",",
"lat2",
"]... | 34.294118 | 19.764706 |
def execute(self):
"""
Execute the actions necessary to cleanup the instances and returns
None.
:return: None
"""
self.print_info()
if not self._config.provisioner.playbooks.cleanup:
msg = 'Skipping, cleanup playbook not configured.'
LOG.... | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"print_info",
"(",
")",
"if",
"not",
"self",
".",
"_config",
".",
"provisioner",
".",
"playbooks",
".",
"cleanup",
":",
"msg",
"=",
"'Skipping, cleanup playbook not configured.'",
"LOG",
".",
"warn",
"(",... | 25.2 | 21.066667 |
def update(self,updates={}):
"""
update csp_default.json with dict
if file empty add default-src and create dict
"""
try:
csp = self.read()
except:
csp = {'default-src':"'self'"}
self.write(csp)
csp.update(updates)
self.write(csp) | [
"def",
"update",
"(",
"self",
",",
"updates",
"=",
"{",
"}",
")",
":",
"try",
":",
"csp",
"=",
"self",
".",
"read",
"(",
")",
"except",
":",
"csp",
"=",
"{",
"'default-src'",
":",
"\"'self'\"",
"}",
"self",
".",
"write",
"(",
"csp",
")",
"csp",
... | 19.230769 | 16.692308 |
def configure():
"""Load logging configuration from our own defaults."""
log_levels = {
5: logging.NOTSET,
4: logging.DEBUG,
3: logging.INFO,
2: logging.WARNING,
1: logging.ERROR,
0: logging.CRITICAL
}
logging.captureWarnings(True)
root_logger = loggi... | [
"def",
"configure",
"(",
")",
":",
"log_levels",
"=",
"{",
"5",
":",
"logging",
".",
"NOTSET",
",",
"4",
":",
"logging",
".",
"DEBUG",
",",
"3",
":",
"logging",
".",
"INFO",
",",
"2",
":",
"logging",
".",
"WARNING",
",",
"1",
":",
"logging",
".",... | 32.827586 | 15.62069 |
def get_message(cls, signals=True, farms=False, buffer_size=65536, timeout=-1):
"""Block until a mule message is received and return it.
This can be called from multiple threads in the same programmed mule.
:param bool signals: Whether to manage signals.
:param bool farms: Whether to ... | [
"def",
"get_message",
"(",
"cls",
",",
"signals",
"=",
"True",
",",
"farms",
"=",
"False",
",",
"buffer_size",
"=",
"65536",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"return",
"decode",
"(",
"uwsgi",
".",
"mule_get_msg",
"(",
"signals",
",",
"farms",
... | 30.833333 | 25.111111 |
def f_preset_config(self, config_name, *args, **kwargs):
"""Similar to func:`~pypet.trajectory.Trajectory.f_preset_parameter`"""
if not config_name.startswith('config.'):
config_name = 'config.' + config_name
self._preset(config_name, args, kwargs) | [
"def",
"f_preset_config",
"(",
"self",
",",
"config_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"config_name",
".",
"startswith",
"(",
"'config.'",
")",
":",
"config_name",
"=",
"'config.'",
"+",
"config_name",
"self",
".",
"... | 40 | 17.285714 |
def wind_speed_hub(self, weather_df):
r"""
Calculates the wind speed at hub height.
The method specified by the parameter `wind_speed_model` is used.
Parameters
----------
weather_df : pandas.DataFrame
DataFrame with time series for wind speed `wind_speed` i... | [
"def",
"wind_speed_hub",
"(",
"self",
",",
"weather_df",
")",
":",
"if",
"self",
".",
"power_plant",
".",
"hub_height",
"in",
"weather_df",
"[",
"'wind_speed'",
"]",
":",
"wind_speed_hub",
"=",
"weather_df",
"[",
"'wind_speed'",
"]",
"[",
"self",
".",
"power... | 50.15493 | 22.56338 |
def add_entity(self, rdf_type, superclass, label, definition=None):
''' Adds entity as long as it doesn't exist and has a usable
superclass ILX ID and rdf:type
'''
# Checks if you inputed the right type
rdf_type = rdf_type.lower().strip().replace('owl:Class', 'term')
... | [
"def",
"add_entity",
"(",
"self",
",",
"rdf_type",
",",
"superclass",
",",
"label",
",",
"definition",
"=",
"None",
")",
":",
"# Checks if you inputed the right type",
"rdf_type",
"=",
"rdf_type",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
".",
"replace... | 54.076923 | 24.461538 |
def next_word(self, previous_words):
"""The next word that is generated by the Markov Chain
depends on a tuple of the previous words from the Chain"""
# The previous words may never have appeared in order in the corpus used to
# generate the word_dict. Consequently, we want to try to fin... | [
"def",
"next_word",
"(",
"self",
",",
"previous_words",
")",
":",
"# The previous words may never have appeared in order in the corpus used to",
"# generate the word_dict. Consequently, we want to try to find the previous ",
"# words in orde, but if they are not there, then we remove the earlies... | 58.111111 | 19.111111 |
def cache_key(self, repo: str, branch: str, task: Task, git_repo: Repo) -> str:
""" Returns the key used for storing results in cache.
"""
return "{repo}_{branch}_{hash}_{task}".format(repo=self.repo_id(repo),
branch=branch,
... | [
"def",
"cache_key",
"(",
"self",
",",
"repo",
":",
"str",
",",
"branch",
":",
"str",
",",
"task",
":",
"Task",
",",
"git_repo",
":",
"Repo",
")",
"->",
"str",
":",
"return",
"\"{repo}_{branch}_{hash}_{task}\"",
".",
"format",
"(",
"repo",
"=",
"self",
... | 67.428571 | 28.428571 |
def display(self, image):
"""
Takes a 1-bit :py:mod:`PIL.Image` and dumps it to the OLED
display.
:param image: Image to display.
:type image: :py:mod:`PIL.Image`
"""
assert(image.mode == self.mode)
assert(image.size == self.size)
image = self.pr... | [
"def",
"display",
"(",
"self",
",",
"image",
")",
":",
"assert",
"(",
"image",
".",
"mode",
"==",
"self",
".",
"mode",
")",
"assert",
"(",
"image",
".",
"size",
"==",
"self",
".",
"size",
")",
"image",
"=",
"self",
".",
"preprocess",
"(",
"image",
... | 26.833333 | 16.5 |
def FindChecks(cls,
artifact=None,
os_name=None,
cpe=None,
labels=None,
restrict_checks=None):
"""Takes targeting info, identifies relevant checks.
FindChecks will return results when a host has the conditions necessary for
... | [
"def",
"FindChecks",
"(",
"cls",
",",
"artifact",
"=",
"None",
",",
"os_name",
"=",
"None",
",",
"cpe",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"restrict_checks",
"=",
"None",
")",
":",
"check_ids",
"=",
"set",
"(",
")",
"conditions",
"=",
"lis... | 35.235294 | 19.205882 |
def process(self, session: AppSession):
'''Build MITM proxy server.'''
args = session.args
if not (args.phantomjs or args.youtube_dl or args.proxy_server):
return
proxy_server = session.factory.new(
'HTTPProxyServer',
session.factory['HTTPClient'],
... | [
"def",
"process",
"(",
"self",
",",
"session",
":",
"AppSession",
")",
":",
"args",
"=",
"session",
".",
"args",
"if",
"not",
"(",
"args",
".",
"phantomjs",
"or",
"args",
".",
"youtube_dl",
"or",
"args",
".",
"proxy_server",
")",
":",
"return",
"proxy_... | 32.962963 | 20.222222 |
def py(sfn, string=False, **kwargs): # pylint: disable=C0103
'''
Render a template from a python source file
Returns::
{'result': bool,
'data': <Error data or rendered file path>}
'''
if not os.path.isfile(sfn):
return {}
base_fname = os.path.basename(sfn)
name =... | [
"def",
"py",
"(",
"sfn",
",",
"string",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0103",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"sfn",
")",
":",
"return",
"{",
"}",
"base_fname",
"=",
"os",
".",
"path",
".",
... | 30.792453 | 17.09434 |
def hex2bin(fin, fout, start=None, end=None, size=None, pad=None):
"""Hex-to-Bin convertor engine.
@return 0 if all OK
@param fin input hex file (filename or file-like object)
@param fout output bin file (filename or file-like object)
@param start start of address range (optional)... | [
"def",
"hex2bin",
"(",
"fin",
",",
"fout",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"size",
"=",
"None",
",",
"pad",
"=",
"None",
")",
":",
"try",
":",
"h",
"=",
"IntelHex",
"(",
"fin",
")",
"except",
"HexReaderError",
":",
"e",
... | 31.465116 | 19 |
def delete_blob(call=None, kwargs=None): # pylint: disable=unused-argument
'''
Delete a blob from a container.
'''
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit(
'A container must be specified'
)
if 'blob' not in kwa... | [
"def",
"delete_blob",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"# pylint: disable=unused-argument",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"if",
"'container'",
"not",
"in",
"kwargs",
":",
"raise",
"SaltCloudSystemE... | 25.095238 | 22.238095 |
def _validate_str_list(arg):
'''
ensure ``arg`` is a list of strings
'''
if isinstance(arg, six.binary_type):
ret = [salt.utils.stringutils.to_unicode(arg)]
elif isinstance(arg, six.string_types):
ret = [arg]
elif isinstance(arg, Iterable) and not isinstance(arg, Mapping):
... | [
"def",
"_validate_str_list",
"(",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"six",
".",
"binary_type",
")",
":",
"ret",
"=",
"[",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"arg",
")",
"]",
"elif",
"isinstance",
"(",
... | 30.444444 | 16.444444 |
def _kpatch(url, data):
''' patch any object in kubernetes based on URL '''
# Prepare headers
headers = {"Content-Type": "application/json-patch+json"}
# Make request
ret = http.query(url, method='PATCH', header_dict=headers,
data=salt.utils.json.dumps(data))
# Check reques... | [
"def",
"_kpatch",
"(",
"url",
",",
"data",
")",
":",
"# Prepare headers",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/json-patch+json\"",
"}",
"# Make request",
"ret",
"=",
"http",
".",
"query",
"(",
"url",
",",
"method",
"=",
"'PATCH'",
",",
... | 34.285714 | 20 |
def convert(self, path, version, target = None):
"""Converts the specified file using the relevant template.
:arg path: the full path to the file to convert.
:arg version: the new version of the file.
:arg target: the optional path to save the file under. If not
specified, the... | [
"def",
"convert",
"(",
"self",
",",
"path",
",",
"version",
",",
"target",
"=",
"None",
")",
":",
"#Get the template and values out of the XML input file and",
"#write them in the format of the keywordless file.",
"values",
",",
"template",
"=",
"self",
".",
"parse",
"(... | 43.684211 | 18.210526 |
def imm_transient(imm):
'''
imm_transient(imm) yields a duplicate of the given immutable imm that is transient.
'''
if not is_imm(imm):
raise ValueError('Non-immutable given to imm_transient')
# make a duplicate immutable that is in the transient state
dup = copy.copy(imm)
if _imm_is... | [
"def",
"imm_transient",
"(",
"imm",
")",
":",
"if",
"not",
"is_imm",
"(",
"imm",
")",
":",
"raise",
"ValueError",
"(",
"'Non-immutable given to imm_transient'",
")",
"# make a duplicate immutable that is in the transient state",
"dup",
"=",
"copy",
".",
"copy",
"(",
... | 37.5 | 19.5 |
def get(self, stream, start_time, end_time, start_id=None, limit=None,
order=ResultOrder.ASCENDING, namespace=None, timeout=None):
"""
Queries a stream with name `stream` for all events between `start_time` and
`end_time` (both inclusive). An optional `start_id` allows the client to
restart f... | [
"def",
"get",
"(",
"self",
",",
"stream",
",",
"start_time",
",",
"end_time",
",",
"start_id",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"order",
"=",
"ResultOrder",
".",
"ASCENDING",
",",
"namespace",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
... | 37.888889 | 17.285714 |
def fetch_document(url=None, host=None, path="/", timeout=10, raise_ssl_errors=True, extra_headers=None):
"""Helper method to fetch remote document.
Must be given either the ``url`` or ``host``.
If ``url`` is given, only that will be tried without falling back to http from https.
If ``host`` given, `pa... | [
"def",
"fetch_document",
"(",
"url",
"=",
"None",
",",
"host",
"=",
"None",
",",
"path",
"=",
"\"/\"",
",",
"timeout",
"=",
"10",
",",
"raise_ssl_errors",
"=",
"True",
",",
"extra_headers",
"=",
"None",
")",
":",
"if",
"not",
"url",
"and",
"not",
"ho... | 50.934426 | 22.52459 |
def generate_supported_architectures_source(supported_archs, supported_machines):
"""Extract export symbols using binutils's nm utility from Binutils and
generate a current header for PyBFD.
"""
arch_entries = []
mach_entries = []
for arch, little, big, comment in supported_archs:
arch... | [
"def",
"generate_supported_architectures_source",
"(",
"supported_archs",
",",
"supported_machines",
")",
":",
"arch_entries",
"=",
"[",
"]",
"mach_entries",
"=",
"[",
"]",
"for",
"arch",
",",
"little",
",",
"big",
",",
"comment",
"in",
"supported_archs",
":",
"... | 34.764706 | 20.647059 |
def process_response(self, request, response, spider):
"""Handle the a Scrapy response"""
if not self.is_cloudflare_challenge(response):
return response
logger = logging.getLogger('cloudflaremiddleware')
logger.debug(
'Cloudflare protection detected on %s, tryi... | [
"def",
"process_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"spider",
")",
":",
"if",
"not",
"self",
".",
"is_cloudflare_challenge",
"(",
"response",
")",
":",
"return",
"response",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'cloudfl... | 27.222222 | 24.037037 |
def _new_err(self, errclass: str, *args) -> 'Err':
"""
Error constructor
"""
# get the message or exception
ex, msg = self._get_args(*args)
# construct the error
# handle exception
ftb = None # type: str
function = None # type: str
errtyp... | [
"def",
"_new_err",
"(",
"self",
",",
"errclass",
":",
"str",
",",
"*",
"args",
")",
"->",
"'Err'",
":",
"# get the message or exception",
"ex",
",",
"msg",
"=",
"self",
".",
"_get_args",
"(",
"*",
"args",
")",
"# construct the error",
"# handle exception",
"... | 28.283784 | 13.094595 |
def convert_to_vcard(name, value, allowed_object_type):
"""converts user input into vcard compatible data structures
:param name: object name, only required for error messages
:type name: str
:param value: user input
:type value: str or list(str)
:param allowed_object_type: set the accepted retu... | [
"def",
"convert_to_vcard",
"(",
"name",
",",
"value",
",",
"allowed_object_type",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"if",
"allowed_object_type",
"==",
"ObjectType",
".",
"list_with_strings",
":",
"raise",
"ValueError",
"(",
"\"E... | 43.025641 | 17.564103 |
def sponsor_image_url(sponsor, name):
"""Returns the corresponding url from the sponsors images"""
if sponsor.files.filter(name=name).exists():
# We avoid worrying about multiple matches by always
# returning the first one.
return sponsor.files.filter(name=name).first().item.url
retu... | [
"def",
"sponsor_image_url",
"(",
"sponsor",
",",
"name",
")",
":",
"if",
"sponsor",
".",
"files",
".",
"filter",
"(",
"name",
"=",
"name",
")",
".",
"exists",
"(",
")",
":",
"# We avoid worrying about multiple matches by always",
"# returning the first one.",
"ret... | 45.571429 | 12.428571 |
def h_from_V(self, V, method='spline'):
r'''Method to calculate the height of liquid in a fully defined tank
given a specified volume of liquid in it `V`. `V` must be under the
maximum volume. If the method is 'spline', and the interpolation table
is not yet defined, creates it by callin... | [
"def",
"h_from_V",
"(",
"self",
",",
"V",
",",
"method",
"=",
"'spline'",
")",
":",
"if",
"method",
"==",
"'spline'",
":",
"if",
"not",
"self",
".",
"table",
":",
"self",
".",
"set_table",
"(",
")",
"return",
"float",
"(",
"self",
".",
"interp_h_from... | 41.147059 | 21.382353 |
def start_collecting_data(self, queues=None, edge=None, edge_type=None):
"""Tells the queues to collect data on agents' arrival, service
start, and departure times.
If none of the parameters are given then every
:class:`.QueueServer` will start collecting data.
Parameters
... | [
"def",
"start_collecting_data",
"(",
"self",
",",
"queues",
"=",
"None",
",",
"edge",
"=",
"None",
",",
"edge_type",
"=",
"None",
")",
":",
"queues",
"=",
"_get_queues",
"(",
"self",
".",
"g",
",",
"queues",
",",
"edge",
",",
"edge_type",
")",
"for",
... | 39.566667 | 20.633333 |
def count(self, event):
"""Get the number of listeners for the event.
Args:
event (str): The event for which to count all listeners.
The resulting count is a combination of listeners added using
'on'/'add_listener' and 'once'.
"""
return len(self._listeners[... | [
"def",
"count",
"(",
"self",
",",
"event",
")",
":",
"return",
"len",
"(",
"self",
".",
"_listeners",
"[",
"event",
"]",
")",
"+",
"len",
"(",
"self",
".",
"_once",
"[",
"event",
"]",
")"
] | 34.3 | 20.9 |
def get_content_size(self, path):
"Return size of files/dirs contents excluding parent node."
node = self._get_node(path)
return self._get_content_size(node) - node.size | [
"def",
"get_content_size",
"(",
"self",
",",
"path",
")",
":",
"node",
"=",
"self",
".",
"_get_node",
"(",
"path",
")",
"return",
"self",
".",
"_get_content_size",
"(",
"node",
")",
"-",
"node",
".",
"size"
] | 47.5 | 13.5 |
def calculate_split_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, C] ---> [N', C]
2. [N, C, H, W] ---> [N', C, H, W]
'''
check_input_and_output_numbers(operator, input_count_range=1, output_count_range=[1, None])
check_input_and_output_types(operator, good_inp... | [
"def",
"calculate_split_output_shapes",
"(",
"operator",
")",
":",
"check_input_and_output_numbers",
"(",
"operator",
",",
"input_count_range",
"=",
"1",
",",
"output_count_range",
"=",
"[",
"1",
",",
"None",
"]",
")",
"check_input_and_output_types",
"(",
"operator",
... | 39.210526 | 25.947368 |
def descendents(class_):
"""
Return a list of the class hierarchy below (and including) the given class.
The list is ordered from least- to most-specific. Can be useful for
printing the contents of an entire class hierarchy.
"""
assert isinstance(class_,type)
q = [class_]
out = []
... | [
"def",
"descendents",
"(",
"class_",
")",
":",
"assert",
"isinstance",
"(",
"class_",
",",
"type",
")",
"q",
"=",
"[",
"class_",
"]",
"out",
"=",
"[",
"]",
"while",
"len",
"(",
"q",
")",
":",
"x",
"=",
"q",
".",
"pop",
"(",
"0",
")",
"out",
"... | 28.941176 | 17.647059 |
def system_drop_column_family(self, column_family):
"""
drops a column family. returns the new schema id.
Parameters:
- column_family
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_drop_column_family(column_family)
return d | [
"def",
"system_drop_column_family",
"(",
"self",
",",
"column_family",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_system_drop_co... | 26.272727 | 16.454545 |
def op_symbol(op_node):
"""Get the GLSL symbol for a Python operator."""
ops = {
# TODO(nicholasbishop): other unary ops
ast.UAdd: '+',
ast.USub: '-',
# TODO(nicholasbishop): FloorDiv, Pow, LShift, RShift,
# BitOr, BitXor, BitAnd
ast.Add: '+',
ast.Sub: '-... | [
"def",
"op_symbol",
"(",
"op_node",
")",
":",
"ops",
"=",
"{",
"# TODO(nicholasbishop): other unary ops",
"ast",
".",
"UAdd",
":",
"'+'",
",",
"ast",
".",
"USub",
":",
"'-'",
",",
"# TODO(nicholasbishop): FloorDiv, Pow, LShift, RShift,",
"# BitOr, BitXor, BitAnd",
"as... | 24.37037 | 18.222222 |
def validate_account_id(sts_client, account_id):
"""Exit if get_caller_identity doesn't match account_id."""
resp = sts_client.get_caller_identity()
if 'Account' in resp:
if resp['Account'] == account_id:
LOGGER.info('Verified current AWS account matches required '
... | [
"def",
"validate_account_id",
"(",
"sts_client",
",",
"account_id",
")",
":",
"resp",
"=",
"sts_client",
".",
"get_caller_identity",
"(",
")",
"if",
"'Account'",
"in",
"resp",
":",
"if",
"resp",
"[",
"'Account'",
"]",
"==",
"account_id",
":",
"LOGGER",
".",
... | 40.941176 | 13.705882 |
def cmd_land(self, args):
'''auto land commands'''
if len(args) < 1:
self.master.mav.command_long_send(self.settings.target_system,
0,
mavutil.mavlink.MAV_CMD_DO_LAND_START,
... | [
"def",
"cmd_land",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"self",
".",
"master",
".",
"mav",
".",
"command_long_send",
"(",
"self",
".",
"settings",
".",
"target_system",
",",
"0",
",",
"mavutil",
".",
"ma... | 51.142857 | 21.571429 |
def p_instance_port_arg_none(self, p):
'instance_port_arg : DOT ID LPAREN RPAREN'
p[0] = PortArg(p[2], None, lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_instance_port_arg_none",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"PortArg",
"(",
"p",
"[",
"2",
"]",
",",
"None",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"... | 44.5 | 7.5 |
def peek_stack_dwords(self, count, offset = 0):
"""
Tries to read DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int..... | [
"def",
"peek_stack_dwords",
"(",
"self",
",",
"count",
",",
"offset",
"=",
"0",
")",
":",
"stackData",
"=",
"self",
".",
"peek_stack_data",
"(",
"count",
"*",
"4",
",",
"offset",
")",
"if",
"len",
"(",
"stackData",
")",
"&",
"3",
":",
"stackData",
"=... | 34.25 | 17.25 |
def any_match(self, urls):
"""Check if any of the given URLs has a matching host.
:param urls: an iterable containing URLs
:returns: True if any host has a listed match
:raises InvalidURLError: if there are any invalid URLs in
the sequence
"""
return any(urlparse... | [
"def",
"any_match",
"(",
"self",
",",
"urls",
")",
":",
"return",
"any",
"(",
"urlparse",
"(",
"u",
")",
".",
"hostname",
"in",
"self",
"for",
"u",
"in",
"urls",
")"
] | 38.555556 | 15.777778 |
def _handleParListMismatch(self, probStr, extra=False):
""" Handle the situation where two par lists do not match.
This is meant to allow subclasses to override. Note that this only
handles "missing" pars and "extra" pars, not wrong-type pars. """
errmsg = 'ERROR: mismatch between defau... | [
"def",
"_handleParListMismatch",
"(",
"self",
",",
"probStr",
",",
"extra",
"=",
"False",
")",
":",
"errmsg",
"=",
"'ERROR: mismatch between default and current par lists '",
"+",
"'for task \"'",
"+",
"self",
".",
"taskName",
"+",
"'\"'",
"if",
"probStr",
":",
"e... | 45.166667 | 17.583333 |
def from_json(cls, json_data):
"""Instantiate a Credentials object from a JSON description of it.
The JSON should have been produced by calling .to_json() on the object.
Args:
json_data: string or bytes, JSON to deserialize.
Returns:
An instance of a Credential... | [
"def",
"from_json",
"(",
"cls",
",",
"json_data",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"_helpers",
".",
"_from_bytes",
"(",
"json_data",
")",
")",
"if",
"(",
"data",
".",
"get",
"(",
"'token_expiry'",
")",
"and",
"not",
"isinstance",
"(",
... | 38.342857 | 15.8 |
def system_commands(self, action):
""" Perform system commands """
if action == 'backup':
status = self.api_action.backup()
if status[0]:
notify_confirm('Vent backup successful')
else:
notify_confirm('Vent backup could not be completed'... | [
"def",
"system_commands",
"(",
"self",
",",
"action",
")",
":",
"if",
"action",
"==",
"'backup'",
":",
"status",
"=",
"self",
".",
"api_action",
".",
"backup",
"(",
")",
"if",
"status",
"[",
"0",
"]",
":",
"notify_confirm",
"(",
"'Vent backup successful'",... | 44.180556 | 14.222222 |
async def AddCharm(self, channel, url):
'''
channel : str
url : str
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Client',
request='AddCharm',
version=1,
params=_... | [
"async",
"def",
"AddCharm",
"(",
"self",
",",
"channel",
",",
"url",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Client'",
",",
"request",
"=",
"'AddCharm'",
",",
"version",
"=",
"1"... | 27.1875 | 12.8125 |
def nics_skipped(name, nics, ipv6=False):
'''
name
Meaningless arg, but required for state.
nics
A list of nics to skip.
ipv6
Boolean. Set to true if you want to skip
the ipv6 interface. Default false (ipv4).
'''
ret = {'name': ','.join(nics),
'change... | [
"def",
"nics_skipped",
"(",
"name",
",",
"nics",
",",
"ipv6",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"','",
".",
"join",
"(",
"nics",
")",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"'NI... | 26.826087 | 19.869565 |
def load(fp, separator=DEFAULT, index_separator=DEFAULT, cls=dict, list_cls=list):
'''Load an object from the file pointer.
:param fp: A readable filehandle.
:param separator: The separator between key and value. Defaults to u'|' or b'|', depending on the types.
:param index_separator: The separator b... | [
"def",
"load",
"(",
"fp",
",",
"separator",
"=",
"DEFAULT",
",",
"index_separator",
"=",
"DEFAULT",
",",
"cls",
"=",
"dict",
",",
"list_cls",
"=",
"list",
")",
":",
"converter",
"=",
"None",
"output",
"=",
"cls",
"(",
")",
"arraykeys",
"=",
"set",
"(... | 34.25 | 22.573529 |
def enable_logging(main):
"""
This decorator is used to decorate main functions.
It adds the initialization of the logger and an argument parser that allows
one to select the loglevel.
Useful if we are writing simple main functions that call libraries where
the logging module is used
Args:
... | [
"def",
"enable_logging",
"(",
"main",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"main",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
... | 33.459459 | 20.756757 |
def compute(self):
"""Run SuperSmoother."""
self.smooth_result = run_freidman_supsmu(self.x, self.y)
self._store_unsorted_results(self.smooth_result, numpy.zeros(len(self.smooth_result))) | [
"def",
"compute",
"(",
"self",
")",
":",
"self",
".",
"smooth_result",
"=",
"run_freidman_supsmu",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
")",
"self",
".",
"_store_unsorted_results",
"(",
"self",
".",
"smooth_result",
",",
"numpy",
".",
"zeros",
"... | 52 | 25 |
def append(self, data):
"""
Appends the given data to the buffer, and triggers all connected
monitors, if any of them match the buffer content.
:type data: str
:param data: The data that is appended.
"""
self.io.write(data)
if not self.monitors:
... | [
"def",
"append",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"io",
".",
"write",
"(",
"data",
")",
"if",
"not",
"self",
".",
"monitors",
":",
"return",
"# Check whether any of the monitoring regular expressions matches.",
"# If it does, we need to disable that mo... | 39.04 | 16.32 |
def _from_dict(cls, _dict):
"""Initialize a SpeechModels object from a json dictionary."""
args = {}
if 'models' in _dict:
args['models'] = [
SpeechModel._from_dict(x) for x in (_dict.get('models'))
]
else:
raise ValueError(
... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'models'",
"in",
"_dict",
":",
"args",
"[",
"'models'",
"]",
"=",
"[",
"SpeechModel",
".",
"_from_dict",
"(",
"x",
")",
"for",
"x",
"in",
"(",
"_dict",
".",
"g... | 36.909091 | 18.909091 |
def __status(self, job_directory, proxy_status):
""" Use proxied manager's status to compute the real
(stateful) status of job.
"""
if proxy_status == status.COMPLETE:
if not job_directory.has_metadata(JOB_FILE_POSTPROCESSED):
job_status = status.POSTPROCESSIN... | [
"def",
"__status",
"(",
"self",
",",
"job_directory",
",",
"proxy_status",
")",
":",
"if",
"proxy_status",
"==",
"status",
".",
"COMPLETE",
":",
"if",
"not",
"job_directory",
".",
"has_metadata",
"(",
"JOB_FILE_POSTPROCESSED",
")",
":",
"job_status",
"=",
"sta... | 37.583333 | 10.833333 |
def delete(self, tag_id):
"""
Delete the specified InactivityAlert
:param tag_id: The tag ID to delete
:type tag_id: str
:raises: This will raise a
:class:`ServerException <logentries_api.exceptions.ServerException>`
if there is an error from Logentries
... | [
"def",
"delete",
"(",
"self",
",",
"tag_id",
")",
":",
"tag_url",
"=",
"'https://logentries.com/rest/{account_id}/api/tags/{tag_id}'",
"self",
".",
"_api_delete",
"(",
"url",
"=",
"tag_url",
".",
"format",
"(",
"account_id",
"=",
"self",
".",
"account_id",
",",
... | 28.894737 | 18.157895 |
def _update_records(self, records, data):
"""Insert or update a list of DNS records, specified in the netcup API
convention.
The fields ``hostname``, ``type``, and ``destination`` are mandatory
and must be provided either in the record dict or through ``data``!
"""
data ... | [
"def",
"_update_records",
"(",
"self",
",",
"records",
",",
"data",
")",
":",
"data",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"data",
".",
"items",
"(",
")",
"if",
"v",
"}",
"records",
"=",
"[",
"dict",
"(",
"record",
",",
"*",
"... | 42 | 14.928571 |
def add_relationship_methods(self):
"""
Adds relationship methods to applicable model classes.
"""
Entry = apps.get_model('wagtailrelations', 'Entry')
@cached_property
def related(instance):
return instance.get_related()
@cached_property
... | [
"def",
"add_relationship_methods",
"(",
"self",
")",
":",
"Entry",
"=",
"apps",
".",
"get_model",
"(",
"'wagtailrelations'",
",",
"'Entry'",
")",
"@",
"cached_property",
"def",
"related",
"(",
"instance",
")",
":",
"return",
"instance",
".",
"get_related",
"("... | 30.431034 | 14.568966 |
def from_http_exception(cls, e):
"""Create ``APIError`` from ``requests.exception.HTTPError``."""
assert isinstance(e, requests.exceptions.HTTPError)
response = e.response
try:
message = response.json()['message']
except (KeyError, ValueError):
message = r... | [
"def",
"from_http_exception",
"(",
"cls",
",",
"e",
")",
":",
"assert",
"isinstance",
"(",
"e",
",",
"requests",
".",
"exceptions",
".",
"HTTPError",
")",
"response",
"=",
"e",
".",
"response",
"try",
":",
"message",
"=",
"response",
".",
"json",
"(",
... | 36.2 | 13.6 |
def set_session(self, autocommit=None, readonly=None):
"""Sets one or more parameters in the current connection.
:param autocommit:
Switch the connection to autocommit mode. With the current
version, you need to always enable this, because
:meth:`commit` is not imple... | [
"def",
"set_session",
"(",
"self",
",",
"autocommit",
"=",
"None",
",",
"readonly",
"=",
"None",
")",
":",
"props",
"=",
"{",
"}",
"if",
"autocommit",
"is",
"not",
"None",
":",
"props",
"[",
"'autoCommit'",
"]",
"=",
"bool",
"(",
"autocommit",
")",
"... | 39.85 | 14.65 |
def watch_record(indexer, use_polling=False):
"""
Start watching `cfstore.record_path`.
:type indexer: rash.indexer.Indexer
"""
if use_polling:
from watchdog.observers.polling import PollingObserver as Observer
Observer # fool pyflakes
else:
from watchdog.observers imp... | [
"def",
"watch_record",
"(",
"indexer",
",",
"use_polling",
"=",
"False",
")",
":",
"if",
"use_polling",
":",
"from",
"watchdog",
".",
"observers",
".",
"polling",
"import",
"PollingObserver",
"as",
"Observer",
"Observer",
"# fool pyflakes",
"else",
":",
"from",
... | 30.407407 | 17.444444 |
def enable(self):
"""Enable contextual logging"""
with self._lock:
if self.filter is None:
self.filter = self._filter_type(self) | [
"def",
"enable",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"filter",
"is",
"None",
":",
"self",
".",
"filter",
"=",
"self",
".",
"_filter_type",
"(",
"self",
")"
] | 33.6 | 11.4 |
def _layout_to_vdev(layout, device_dir=None):
'''
Turn the layout data into usable vdevs spedcification
We need to support 2 ways of passing the layout:
.. code::
layout_new:
- mirror:
- disk0
- disk1
- mirror:
- disk2
- disk3... | [
"def",
"_layout_to_vdev",
"(",
"layout",
",",
"device_dir",
"=",
"None",
")",
":",
"vdevs",
"=",
"[",
"]",
"# NOTE: check device_dir exists",
"if",
"device_dir",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"device_dir",
")",
":",
"device_dir",
"=",
... | 29.042254 | 20.450704 |
def _get_sdict(self, env):
"""
Returns a dictionary mapping all of the source suffixes of all
src_builders of this Builder to the underlying Builder that
should be called first.
This dictionary is used for each target specified, so we save a
lot of extra computation by m... | [
"def",
"_get_sdict",
"(",
"self",
",",
"env",
")",
":",
"sdict",
"=",
"{",
"}",
"for",
"bld",
"in",
"self",
".",
"get_src_builders",
"(",
"env",
")",
":",
"for",
"suf",
"in",
"bld",
".",
"src_suffixes",
"(",
"env",
")",
":",
"sdict",
"[",
"suf",
... | 42.72 | 22.24 |
async def api_postcode(request):
"""
Gets data from a postcode.
:param request: The aiohttp request.
"""
postcode: Optional[str] = request.match_info.get('postcode', None)
try:
coroutine = get_postcode_random() if postcode == "random" else get_postcode(postcode)
postcode: Option... | [
"async",
"def",
"api_postcode",
"(",
"request",
")",
":",
"postcode",
":",
"Optional",
"[",
"str",
"]",
"=",
"request",
".",
"match_info",
".",
"get",
"(",
"'postcode'",
",",
"None",
")",
"try",
":",
"coroutine",
"=",
"get_postcode_random",
"(",
")",
"if... | 34.052632 | 18.473684 |
def __refund(self, subscription_charge_id, **kwargs):
"""Call documentation: `/subscription_charge/refund
<https://www.wepay.com/developer/reference/subscription_charge#refund>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``a... | [
"def",
"__refund",
"(",
"self",
",",
"subscription_charge_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'subscription_charge_id'",
":",
"subscription_charge_id",
"}",
"return",
"self",
".",
"make_call",
"(",
"self",
".",
"__refund",
",",
"params... | 38.043478 | 22.391304 |
def storage_expansion(network, basemap=True, scaling=1, filename=None):
"""
Plot storage distribution as circles on grid nodes
Displays storage size and distribution in network.
Parameters
----------
network : PyPSA network container
Holds topology of grid including results from pow... | [
"def",
"storage_expansion",
"(",
"network",
",",
"basemap",
"=",
"True",
",",
"scaling",
"=",
"1",
",",
"filename",
"=",
"None",
")",
":",
"stores",
"=",
"network",
".",
"storage_units",
"[",
"network",
".",
"storage_units",
".",
"carrier",
"==",
"'extenda... | 38.883929 | 20.526786 |
def _read_response(self, response):
"""
JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Security+Configuration+JSON
"""
self.name = response['name']
self.description = response['description']
self.autoJoin = response['autoJoin']
self.realm = respo... | [
"def",
"_read_response",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"name",
"=",
"response",
"[",
"'name'",
"]",
"self",
".",
"description",
"=",
"response",
"[",
"'description'",
"]",
"self",
".",
"autoJoin",
"=",
"response",
"[",
"'autoJoin'",
... | 43.666667 | 12.555556 |
def require_json():
""" Load the best available json library on demand.
"""
# Fails when "json" is missing and "simplejson" is not installed either
try:
import json # pylint: disable=F0401
return json
except ImportError:
try:
import simplejson # pylint: disable=F0... | [
"def",
"require_json",
"(",
")",
":",
"# Fails when \"json\" is missing and \"simplejson\" is not installed either",
"try",
":",
"import",
"json",
"# pylint: disable=F0401",
"return",
"json",
"except",
"ImportError",
":",
"try",
":",
"import",
"simplejson",
"# pylint: disable... | 36 | 14.384615 |
def fit(self, X, ranks, replicates=1, verbose=True):
"""
Fits CP tensor decompositions for different choices of rank.
Parameters
----------
X : array_like
Real tensor
ranks : int, or iterable
iterable specifying number of components in each model
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"ranks",
",",
"replicates",
"=",
"1",
",",
"verbose",
"=",
"True",
")",
":",
"# Make ranks iterable if necessary.",
"if",
"not",
"isinstance",
"(",
"ranks",
",",
"collections",
".",
"Iterable",
")",
":",
"ranks",
... | 38.333333 | 19.527778 |
def update_gradients_full(self, dL_dK, X, X2=None):
"""derivative of the covariance matrix with respect to the parameters."""
X,slices = X[:,:-1],index_to_slices(X[:,-1])
if X2 is None:
X2,slices2 = X,slices
K = np.zeros((X.shape[0]... | [
"def",
"update_gradients_full",
"(",
"self",
",",
"dL_dK",
",",
"X",
",",
"X2",
"=",
"None",
")",
":",
"X",
",",
"slices",
"=",
"X",
"[",
":",
",",
":",
"-",
"1",
"]",
",",
"index_to_slices",
"(",
"X",
"[",
":",
",",
"-",
"1",
"]",
")",
"if",... | 50.702703 | 29.175676 |
def _attach(cls, disk_id, vm_id, options=None):
""" Attach a disk to a vm. """
options = options or {}
oper = cls.call('hosting.vm.disk_attach', vm_id, disk_id, options)
return oper | [
"def",
"_attach",
"(",
"cls",
",",
"disk_id",
",",
"vm_id",
",",
"options",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"{",
"}",
"oper",
"=",
"cls",
".",
"call",
"(",
"'hosting.vm.disk_attach'",
",",
"vm_id",
",",
"disk_id",
",",
"options"... | 41.8 | 14.2 |
def list_available_genomes(provider=None):
"""
List all available genomes.
Parameters
----------
provider : str, optional
List genomes from specific provider. Genomes from all
providers will be returned if not specified.
Returns
-------
list with genome names
"""
... | [
"def",
"list_available_genomes",
"(",
"provider",
"=",
"None",
")",
":",
"if",
"provider",
":",
"providers",
"=",
"[",
"ProviderBase",
".",
"create",
"(",
"provider",
")",
"]",
"else",
":",
"# if provider is not specified search all providers",
"providers",
"=",
"... | 27.208333 | 18.208333 |
def add_instance(self,
role,
instance,
username='root',
key_filename=None,
output_shell=False):
"""
Add instance to the setup
@param role: instance's role
@type role: str
@param ... | [
"def",
"add_instance",
"(",
"self",
",",
"role",
",",
"instance",
",",
"username",
"=",
"'root'",
",",
"key_filename",
"=",
"None",
",",
"output_shell",
"=",
"False",
")",
":",
"if",
"not",
"role",
"in",
"self",
".",
"Instances",
".",
"keys",
"(",
")",... | 36.857143 | 18 |
def to_keypoints(self):
"""
Convert this polygon's `exterior` to ``Keypoint`` instances.
Returns
-------
list of imgaug.Keypoint
Exterior vertices as ``Keypoint`` instances.
"""
# TODO get rid of this deferred import
from imgaug.augmentables.... | [
"def",
"to_keypoints",
"(",
"self",
")",
":",
"# TODO get rid of this deferred import",
"from",
"imgaug",
".",
"augmentables",
".",
"kps",
"import",
"Keypoint",
"return",
"[",
"Keypoint",
"(",
"x",
"=",
"point",
"[",
"0",
"]",
",",
"y",
"=",
"point",
"[",
... | 28.857143 | 21 |
def get_sngl_snrs(self, instruments=None):
"""
Get the single-detector SNRs for each row in the table.
"""
if len(self) and instruments is None:
instruments = map(str, \
instrument_set_from_ifos(self[0].ifos))
elif instruments is None:
instruments = []
return dict((ifo, self.get_sng... | [
"def",
"get_sngl_snrs",
"(",
"self",
",",
"instruments",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
")",
"and",
"instruments",
"is",
"None",
":",
"instruments",
"=",
"map",
"(",
"str",
",",
"instrument_set_from_ifos",
"(",
"self",
"[",
"0",
"]",
... | 32.727273 | 8.363636 |
def _check_object_exists(self):
"""Raise a KeyError if the scheduling object doesnt exist.
Raise:
KeyError, if the object doesnt exist in the database.
"""
if not DB.get_keys(self.key):
raise KeyError("Object with key '{}' not exist".format(self.key)) | [
"def",
"_check_object_exists",
"(",
"self",
")",
":",
"if",
"not",
"DB",
".",
"get_keys",
"(",
"self",
".",
"key",
")",
":",
"raise",
"KeyError",
"(",
"\"Object with key '{}' not exist\"",
".",
"format",
"(",
"self",
".",
"key",
")",
")"
] | 33.444444 | 20 |
def uniform(nmr_distributions, nmr_samples, low=0, high=1, ctype='float', seed=None):
"""Draw random samples from the Uniform distribution.
Args:
nmr_distributions (int): the number of unique continuous_distributions to create
nmr_samples (int): The number of samples to draw
low (double... | [
"def",
"uniform",
"(",
"nmr_distributions",
",",
"nmr_samples",
",",
"low",
"=",
"0",
",",
"high",
"=",
"1",
",",
"ctype",
"=",
"'float'",
",",
"seed",
"=",
"None",
")",
":",
"if",
"is_scalar",
"(",
"low",
")",
":",
"low",
"=",
"np",
".",
"ones",
... | 43.052632 | 26.105263 |
def poll(self, timeout=None):
"""Wait for an event to occur.
If `timeout` is given, if specifies the length of time in milliseconds
which the function will wait for events before returing. If `timeout`
is omitted, negative or None, the call will block until there is an
event.
... | [
"def",
"poll",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"-",
"1",
"ret",
"=",
"api",
".",
"py_aa_async_poll",
"(",
"self",
".",
"handle",
",",
"timeout",
")",
"_raise_error_if_negative",
"(... | 33.26087 | 21.652174 |
def get_value(self, field):
'''
Return a random value that can be assigned to the passed *field*
instance.
'''
if field not in self._field_generators:
self._field_generators[field] = self.get_generator(field)
generator = self._field_generators[field]
i... | [
"def",
"get_value",
"(",
"self",
",",
"field",
")",
":",
"if",
"field",
"not",
"in",
"self",
".",
"_field_generators",
":",
"self",
".",
"_field_generators",
"[",
"field",
"]",
"=",
"self",
".",
"get_generator",
"(",
"field",
")",
"generator",
"=",
"self... | 34.583333 | 18.25 |
def df_to_geojson(df, properties=None, lat='lat', lon='lon', precision=6, date_format='epoch', filename=None):
"""Serialize a Pandas dataframe to a geojson format Python dictionary / file
"""
if not properties:
# if no properties are selected, use all properties in dataframe
properties = [c... | [
"def",
"df_to_geojson",
"(",
"df",
",",
"properties",
"=",
"None",
",",
"lat",
"=",
"'lat'",
",",
"lon",
"=",
"'lon'",
",",
"precision",
"=",
"6",
",",
"date_format",
"=",
"'epoch'",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"properties",
... | 41.553191 | 25.021277 |
def rename_ligand(self,ligand_name,mol_file):
"""
Get an atom selection for the selected from both topology and trajectory. Rename the ligand LIG
to help with ligand names that are not standard, e.g. contain numbers.
Takes:
* ligand_name * - MDAnalysis atom selection ... | [
"def",
"rename_ligand",
"(",
"self",
",",
"ligand_name",
",",
"mol_file",
")",
":",
"self",
".",
"universe",
".",
"ligand",
"=",
"self",
".",
"universe",
".",
"select_atoms",
"(",
"ligand_name",
")",
"#Both resname and resnames options need to be reset in order for co... | 52.55 | 28.95 |
def _http_put(self, url, data, **kwargs):
"""
Performs the HTTP PUT request.
"""
kwargs.update({'data': json.dumps(data)})
return self._http_request('put', url, kwargs) | [
"def",
"_http_put",
"(",
"self",
",",
"url",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'data'",
":",
"json",
".",
"dumps",
"(",
"data",
")",
"}",
")",
"return",
"self",
".",
"_http_request",
"(",
"'put'",
... | 25.375 | 13.125 |
def course_is_open_to_user(self, course, username=None, lti=None):
"""
Checks if a user is can access a course
:param course: a Course object
:param username: The username of the user that we want to check. If None, uses self.session_username()
:param lti: indicates if the user i... | [
"def",
"course_is_open_to_user",
"(",
"self",
",",
"course",
",",
"username",
"=",
"None",
",",
"lti",
"=",
"None",
")",
":",
"if",
"username",
"is",
"None",
":",
"username",
"=",
"self",
".",
"session_username",
"(",
")",
"if",
"lti",
"==",
"\"auto\"",
... | 42.033333 | 24.033333 |
def list_versions_for_product(id=None, name=None, page_size=200, page_index=0, sort='', q=''):
"""
List all ProductVersions for a given Product
"""
content = list_versions_for_product_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | [
"def",
"list_versions_for_product",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"page_size",
"=",
"200",
",",
"page_index",
"=",
"0",
",",
"sort",
"=",
"''",
",",
"q",
"=",
"''",
")",
":",
"content",
"=",
"list_versions_for_product_raw",
"(",
... | 43.142857 | 19.714286 |
def read_whole_file(self):
"""
Slurp the whole file into memory.
Should only be used with relatively small files.
:return: str: file contents
"""
chunk = None
with open(self.path, 'rb') as infile:
chunk = infile.read()
return chunk | [
"def",
"read_whole_file",
"(",
"self",
")",
":",
"chunk",
"=",
"None",
"with",
"open",
"(",
"self",
".",
"path",
",",
"'rb'",
")",
"as",
"infile",
":",
"chunk",
"=",
"infile",
".",
"read",
"(",
")",
"return",
"chunk"
] | 29.8 | 8.8 |
def pack_triples_numpy(triples):
"""Packs a list of triple indexes into a 2D numpy array."""
if len(triples) == 0:
return np.array([], dtype=np.int64)
return np.stack(list(map(_transform_triple_numpy, triples)), axis=0) | [
"def",
"pack_triples_numpy",
"(",
"triples",
")",
":",
"if",
"len",
"(",
"triples",
")",
"==",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"return",
"np",
".",
"stack",
"(",
"list",
"(",
"map... | 47 | 11.6 |
def supplement(self,coordsys='gal'):
""" Add some supplemental columns """
from ugali.utils.projector import gal2cel, gal2cel_angle
from ugali.utils.projector import cel2gal, cel2gal_angle
coordsys = coordsys.lower()
kwargs = dict(usemask=False, asrecarray=True)
out = co... | [
"def",
"supplement",
"(",
"self",
",",
"coordsys",
"=",
"'gal'",
")",
":",
"from",
"ugali",
".",
"utils",
".",
"projector",
"import",
"gal2cel",
",",
"gal2cel_angle",
"from",
"ugali",
".",
"utils",
".",
"projector",
"import",
"cel2gal",
",",
"cel2gal_angle",... | 40.681818 | 18.159091 |
def valid_configs(self):
""" Return a list of slots having a valid configurtion. Requires firmware 2.1. """
if self.ykver() < (2,1,0):
raise YubiKeyUSBHIDError('Valid configs unsupported in firmware %s' % (self.version()))
res = []
if self.touch_level & self.CONFIG1_VALID == ... | [
"def",
"valid_configs",
"(",
"self",
")",
":",
"if",
"self",
".",
"ykver",
"(",
")",
"<",
"(",
"2",
",",
"1",
",",
"0",
")",
":",
"raise",
"YubiKeyUSBHIDError",
"(",
"'Valid configs unsupported in firmware %s'",
"%",
"(",
"self",
".",
"version",
"(",
")"... | 47.3 | 21.9 |
def ProcessRepliesWithOutputPlugins(self, replies):
"""Processes replies with output plugins."""
for output_plugin_state in self.context.output_plugins_states:
plugin_descriptor = output_plugin_state.plugin_descriptor
output_plugin_cls = plugin_descriptor.GetPluginClass()
output_plugin = outpu... | [
"def",
"ProcessRepliesWithOutputPlugins",
"(",
"self",
",",
"replies",
")",
":",
"for",
"output_plugin_state",
"in",
"self",
".",
"context",
".",
"output_plugins_states",
":",
"plugin_descriptor",
"=",
"output_plugin_state",
".",
"plugin_descriptor",
"output_plugin_cls",
... | 42.972222 | 16.638889 |
def validate(self, instance, value):
"""Checks if value is a boolean"""
if self.cast:
value = bool(value)
if not isinstance(value, BOOLEAN_TYPES):
self.error(instance, value)
return value | [
"def",
"validate",
"(",
"self",
",",
"instance",
",",
"value",
")",
":",
"if",
"self",
".",
"cast",
":",
"value",
"=",
"bool",
"(",
"value",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"BOOLEAN_TYPES",
")",
":",
"self",
".",
"error",
"(",
"i... | 33.857143 | 8.714286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.