text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def _smallest_integer_by_dtype(dt):
"""Helper returning the smallest integer exactly representable by dtype."""
if not _is_known_dtype(dt):
raise TypeError("Unrecognized dtype: {}".format(dt.name))
if _is_known_unsigned_by_dtype(dt):
return 0
return -1 * _largest_integer_by_dtype(dt) | [
"def",
"_smallest_integer_by_dtype",
"(",
"dt",
")",
":",
"if",
"not",
"_is_known_dtype",
"(",
"dt",
")",
":",
"raise",
"TypeError",
"(",
"\"Unrecognized dtype: {}\"",
".",
"format",
"(",
"dt",
".",
"name",
")",
")",
"if",
"_is_known_unsigned_by_dtype",
"(",
"... | 42 | 10.142857 |
def check_io_access(ioobj, access, is_file=False):
''' check if a file/folder exists and has a given IO access '''
if ((is_file and not os.path.isfile(ioobj)) or
(not is_file and not os.path.isdir(ioobj)) or
not os.access(ioobj, access)):
_objtype = "File" if is_file else "Direct... | [
"def",
"check_io_access",
"(",
"ioobj",
",",
"access",
",",
"is_file",
"=",
"False",
")",
":",
"if",
"(",
"(",
"is_file",
"and",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"ioobj",
")",
")",
"or",
"(",
"not",
"is_file",
"and",
"not",
"os",
".",
... | 55.714286 | 15.714286 |
def setup_blueprint(self):
"""Initialize the blueprint."""
# Register endpoints.
self.blueprint.add_url_rule("/", "status", self.status)
self.blueprint.add_url_rule("/healthy", "health", self.healthy)
self.blueprint.add_url_rule("/ready", "ready", self.ready)
self.bluepr... | [
"def",
"setup_blueprint",
"(",
"self",
")",
":",
"# Register endpoints.",
"self",
".",
"blueprint",
".",
"add_url_rule",
"(",
"\"/\"",
",",
"\"status\"",
",",
"self",
".",
"status",
")",
"self",
".",
"blueprint",
".",
"add_url_rule",
"(",
"\"/healthy\"",
",",
... | 46.125 | 22.5 |
def _process_output_chunk(self, start_count, next_idx, sources, i_str,
t_path):
'''
for the current output chunk (which should be open):
1. run batch transforms
2. run post-batch incremental transforms
3. run 'writers' to load-out the data to f... | [
"def",
"_process_output_chunk",
"(",
"self",
",",
"start_count",
",",
"next_idx",
",",
"sources",
",",
"i_str",
",",
"t_path",
")",
":",
"if",
"not",
"self",
".",
"t_chunk",
":",
"# nothing to do",
"return",
"[",
"]",
"self",
".",
"t_chunk",
".",
"close",
... | 40.348837 | 19.465116 |
def write(self, _force=False, _exists_ok=False, **items):
"""
Creates a db file with the core schema.
:param force: If `True` an existing db file will be overwritten.
"""
if self.fname and self.fname.exists():
raise ValueError('db file already exists, use force=True ... | [
"def",
"write",
"(",
"self",
",",
"_force",
"=",
"False",
",",
"_exists_ok",
"=",
"False",
",",
"*",
"*",
"items",
")",
":",
"if",
"self",
".",
"fname",
"and",
"self",
".",
"fname",
".",
"exists",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'db fil... | 44.423077 | 18.5 |
def response(resp):
"""remove first and last lines to get only json"""
json_resp = resp.text[resp.text.find('\n') + 1:resp.text.rfind('\n') - 2]
results = []
try:
conversion_rate = float(json.loads(json_resp)['conversion']['converted-amount'])
except:
return results
answer = '{0}... | [
"def",
"response",
"(",
"resp",
")",
":",
"json_resp",
"=",
"resp",
".",
"text",
"[",
"resp",
".",
"text",
".",
"find",
"(",
"'\\n'",
")",
"+",
"1",
":",
"resp",
".",
"text",
".",
"rfind",
"(",
"'\\n'",
")",
"-",
"2",
"]",
"results",
"=",
"[",
... | 34.916667 | 22.166667 |
def brightness(frames):
"""parse a brightness message"""
reader = MessageReader(frames)
res = reader.string("command").uint32("brightness").assert_end().get()
if res.command != "brightness":
raise MessageParserError("Command is not 'brightness'")
return (res.brightnes... | [
"def",
"brightness",
"(",
"frames",
")",
":",
"reader",
"=",
"MessageReader",
"(",
"frames",
")",
"res",
"=",
"reader",
".",
"string",
"(",
"\"command\"",
")",
".",
"uint32",
"(",
"\"brightness\"",
")",
".",
"assert_end",
"(",
")",
".",
"get",
"(",
")"... | 46 | 12.571429 |
def run (self, project, name, prop_set, sources):
""" Tries to invoke this generator on the given sources. Returns a
list of generated targets (instances of 'virtual-target').
project: Project for which the targets are generated.
name: Determines the name o... | [
"def",
"run",
"(",
"self",
",",
"project",
",",
"name",
",",
"prop_set",
",",
"sources",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"targets",
"import",
"ProjectTarget",
"assert",
"isinstance",
"(",
"project",
",",
"ProjectTarget",
")",
"# intermediary t... | 50.297872 | 27.808511 |
def VerifyGitkitToken(self, jwt):
"""Verifies a Gitkit token string.
Args:
jwt: string, the token to be checked
Returns:
GitkitUser, if the token is valid. None otherwise.
"""
certs = self.rpc_helper.GetPublicCert()
crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400 # 30 days
parsed =... | [
"def",
"VerifyGitkitToken",
"(",
"self",
",",
"jwt",
")",
":",
"certs",
"=",
"self",
".",
"rpc_helper",
".",
"GetPublicCert",
"(",
")",
"crypt",
".",
"MAX_TOKEN_LIFETIME_SECS",
"=",
"30",
"*",
"86400",
"# 30 days",
"parsed",
"=",
"None",
"for",
"aud",
"in"... | 31.238095 | 18.333333 |
def _update_state(self, vals):
"""
Takes as input a list or tuple of two elements. First the
value returned by incrementing by 'stepsize' followed by the
value returned after a 'stepsize' decrement.
"""
self._steps_complete += 1
if self._steps_complete == self.max... | [
"def",
"_update_state",
"(",
"self",
",",
"vals",
")",
":",
"self",
".",
"_steps_complete",
"+=",
"1",
"if",
"self",
".",
"_steps_complete",
"==",
"self",
".",
"max_steps",
":",
"self",
".",
"_termination_info",
"=",
"(",
"False",
",",
"self",
".",
"_bes... | 40.714286 | 16.047619 |
def SetField(cls, default=NOTHING, required=True, repr=False, key=None):
"""
Create new set field on a model.
:param cls: class (or name) of the model to be related in Set.
:param default: any TypedSet or set
:param bool required: whether or not the object is invalid if not provided.
:param boo... | [
"def",
"SetField",
"(",
"cls",
",",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"default",
",",
"set",... | 51.3125 | 21.0625 |
def data_received(self, data):
"""
Called when a chunk of data is received from the remote worker. These
chunks are stored in a buffer. When a complete line is found in the
buffer, it removed and sent to line_received().
"""
self._buffer.extend(data)
while True:
... | [
"def",
"data_received",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_buffer",
".",
"extend",
"(",
"data",
")",
"while",
"True",
":",
"i",
"=",
"self",
".",
"_buffer",
".",
"find",
"(",
"b\"\\n\"",
")",
"if",
"i",
"==",
"-",
"1",
":",
"break... | 34.2 | 14.2 |
def mirror(self):
"""
This function takes a tlsSession object and swaps the IP addresses,
ports, connection ends and connection states. The triggered_commit are
also swapped (though it is probably overkill, it is cleaner this way).
It is useful for static analysis of a series of... | [
"def",
"mirror",
"(",
"self",
")",
":",
"self",
".",
"ipdst",
",",
"self",
".",
"ipsrc",
"=",
"self",
".",
"ipsrc",
",",
"self",
".",
"ipdst",
"self",
".",
"dport",
",",
"self",
".",
"sport",
"=",
"self",
".",
"sport",
",",
"self",
".",
"dport",
... | 37.377778 | 22.088889 |
def detect_partition_strategy(bid, delimiters=('/', '-'), prefix=''):
"""Try to detect the best partitioning strategy for a large bucket
Consider nested buckets with common prefixes, and flat buckets.
"""
account, bucket = bid.split(":", 1)
region = connection.hget('bucket-regions', bid)
versio... | [
"def",
"detect_partition_strategy",
"(",
"bid",
",",
"delimiters",
"=",
"(",
"'/'",
",",
"'-'",
")",
",",
"prefix",
"=",
"''",
")",
":",
"account",
",",
"bucket",
"=",
"bid",
".",
"split",
"(",
"\":\"",
",",
"1",
")",
"region",
"=",
"connection",
"."... | 39.419355 | 19.790323 |
def list_adb_devices_by_usb_id():
"""List the usb id of all android devices connected to the computer that
are detected by adb.
Returns:
A list of strings that are android device usb ids. Empty if there's
none.
"""
out = adb.AdbProxy().devices(['-l'])
clean_lines = new_str(out, ... | [
"def",
"list_adb_devices_by_usb_id",
"(",
")",
":",
"out",
"=",
"adb",
".",
"AdbProxy",
"(",
")",
".",
"devices",
"(",
"[",
"'-l'",
"]",
")",
"clean_lines",
"=",
"new_str",
"(",
"out",
",",
"'utf-8'",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
... | 33 | 15.5625 |
def get_persons(self):
"""
Returns list of strings which represents persons being chated with
"""
cs = self.data["to"]["data"]
res = []
for c in cs:
res.append(c["name"])
return res | [
"def",
"get_persons",
"(",
"self",
")",
":",
"cs",
"=",
"self",
".",
"data",
"[",
"\"to\"",
"]",
"[",
"\"data\"",
"]",
"res",
"=",
"[",
"]",
"for",
"c",
"in",
"cs",
":",
"res",
".",
"append",
"(",
"c",
"[",
"\"name\"",
"]",
")",
"return",
"res"... | 27 | 14.333333 |
def close(self):
"""Disconnects uWSGI from the client."""
uwsgi.disconnect()
if self._req_ctx is None:
# better kill it here in case wait() is not called again
self._select_greenlet.kill()
self._event.set() | [
"def",
"close",
"(",
"self",
")",
":",
"uwsgi",
".",
"disconnect",
"(",
")",
"if",
"self",
".",
"_req_ctx",
"is",
"None",
":",
"# better kill it here in case wait() is not called again",
"self",
".",
"_select_greenlet",
".",
"kill",
"(",
")",
"self",
".",
"_ev... | 37.142857 | 12 |
def hash(self):
'''
:rtype: int
:return: hash of the field
'''
hashed = super(Dynamic, self).hash()
return khash(hashed, self._key, self._length) | [
"def",
"hash",
"(",
"self",
")",
":",
"hashed",
"=",
"super",
"(",
"Dynamic",
",",
"self",
")",
".",
"hash",
"(",
")",
"return",
"khash",
"(",
"hashed",
",",
"self",
".",
"_key",
",",
"self",
".",
"_length",
")"
] | 26.714286 | 18.142857 |
def dispatch(self, *args, **kwargs):
'''Find and evaluate/return the first method this input dispatches to.
'''
for result in self.gen_dispatch(*args, **kwargs):
return result | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"result",
"in",
"self",
".",
"gen_dispatch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"result"
] | 41.4 | 20.6 |
def _set_wmi_setting(wmi_class_name, setting, value, server):
'''
Set the value of the setting for the provided class.
'''
with salt.utils.winapi.Com():
try:
connection = wmi.WMI(namespace=_WMI_NAMESPACE)
wmi_class = getattr(connection, wmi_class_name)
objs =... | [
"def",
"_set_wmi_setting",
"(",
"wmi_class_name",
",",
"setting",
",",
"value",
",",
"server",
")",
":",
"with",
"salt",
".",
"utils",
".",
"winapi",
".",
"Com",
"(",
")",
":",
"try",
":",
"connection",
"=",
"wmi",
".",
"WMI",
"(",
"namespace",
"=",
... | 37.217391 | 20.086957 |
def cli(env, network, quantity, vlan_id, ipv6, test):
"""Add a new subnet to your account. Valid quantities vary by type.
\b
Type - Valid Quantities (IPv4)
public - 4, 8, 16, 32
private - 4, 8, 16, 32, 64
\b
Type - Valid Quantities (IPv6)
public - 64
"""
mgr = SoftLayer.Ne... | [
"def",
"cli",
"(",
"env",
",",
"network",
",",
"quantity",
",",
"vlan_id",
",",
"ipv6",
",",
"test",
")",
":",
"mgr",
"=",
"SoftLayer",
".",
"NetworkManager",
"(",
"env",
".",
"client",
")",
"if",
"not",
"(",
"test",
"or",
"env",
".",
"skip_confirmat... | 30.488372 | 23.790698 |
def set_pkg_cr_text(self, doc, text):
"""Sets the package's copyright text.
Raises OrderError if no package previously defined.
Raises CardinalityError if already set.
Raises value error if text is not one of [None, NOASSERT, TEXT].
"""
self.assert_package_exists()
... | [
"def",
"set_pkg_cr_text",
"(",
"self",
",",
"doc",
",",
"text",
")",
":",
"self",
".",
"assert_package_exists",
"(",
")",
"if",
"not",
"self",
".",
"package_cr_text_set",
":",
"self",
".",
"package_cr_text_set",
"=",
"True",
"if",
"validations",
".",
"valida... | 44.111111 | 13.888889 |
def _sync_kaggle_download(self, kaggle_url, destination_path):
"""Download with Kaggle API."""
kaggle_file = kaggle.KaggleFile.from_url(kaggle_url)
downloader = self.kaggle_downloader(kaggle_file.competition)
filepath = downloader.download_file(kaggle_file.filename, destination_path)
dl_size = tf.i... | [
"def",
"_sync_kaggle_download",
"(",
"self",
",",
"kaggle_url",
",",
"destination_path",
")",
":",
"kaggle_file",
"=",
"kaggle",
".",
"KaggleFile",
".",
"from_url",
"(",
"kaggle_url",
")",
"downloader",
"=",
"self",
".",
"kaggle_downloader",
"(",
"kaggle_file",
... | 39.533333 | 16.4 |
def generateImplicitParameters(obj):
"""
Generate a UID if one does not exist.
This is just a dummy implementation, for now.
"""
if not hasattr(obj, 'uid'):
rand = int(random.random() * 100000)
now = datetime.datetime.now(utc)
now = dateTimeTo... | [
"def",
"generateImplicitParameters",
"(",
"obj",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'uid'",
")",
":",
"rand",
"=",
"int",
"(",
"random",
".",
"random",
"(",
")",
"*",
"100000",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now"... | 39.230769 | 11.538462 |
def slots(self, inherited=False):
"""Iterate over the Slots of the class."""
data = clips.data.DataObject(self._env)
lib.EnvClassSlots(self._env, self._cls, data.byref, int(inherited))
return (ClassSlot(self._env, self._cls, n.encode()) for n in data.value) | [
"def",
"slots",
"(",
"self",
",",
"inherited",
"=",
"False",
")",
":",
"data",
"=",
"clips",
".",
"data",
".",
"DataObject",
"(",
"self",
".",
"_env",
")",
"lib",
".",
"EnvClassSlots",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_cls",
",",
"data"... | 40.714286 | 24.142857 |
def draw_visibility_image_internal(gl, v, f):
"""Assumes camera is set up correctly in gl context."""
gl.Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
fc = np.arange(1, len(f)+1)
fc = np.tile(col(fc), (1, 3))
fc[:, 0] = fc[:, 0] & 255
fc[:, 1] = (fc[:, 1] >> 8 ) & 255
fc[:, 2] = (fc[:, ... | [
"def",
"draw_visibility_image_internal",
"(",
"gl",
",",
"v",
",",
"f",
")",
":",
"gl",
".",
"Clear",
"(",
"GL_COLOR_BUFFER_BIT",
"|",
"GL_DEPTH_BUFFER_BIT",
")",
"fc",
"=",
"np",
".",
"arange",
"(",
"1",
",",
"len",
"(",
"f",
")",
"+",
"1",
")",
"fc... | 35.333333 | 12.6 |
def _chunk_read(response, local_file, chunk_size=65536, initial_size=0):
"""Download a file chunk by chunk and show advancement
Can also be used when resuming downloads over http.
Parameters
----------
response: urllib.response.addinfourl
Response to the download request in order to get fi... | [
"def",
"_chunk_read",
"(",
"response",
",",
"local_file",
",",
"chunk_size",
"=",
"65536",
",",
"initial_size",
"=",
"0",
")",
":",
"# Adapted from NISL:",
"# https://github.com/nisl/tutorial/blob/master/nisl/datasets.py",
"bytes_so_far",
"=",
"initial_size",
"# Returns onl... | 36.205882 | 19.294118 |
def football_data(season='1617', data_set='football_data'):
"""Football data from English games since 1993. This downloads data from football-data.co.uk for the given season. """
league_dict = {'E0':0, 'E1':1, 'E2': 2, 'E3': 3, 'EC':4}
def league2num(string):
if isinstance(string, bytes):
... | [
"def",
"football_data",
"(",
"season",
"=",
"'1617'",
",",
"data_set",
"=",
"'football_data'",
")",
":",
"league_dict",
"=",
"{",
"'E0'",
":",
"0",
",",
"'E1'",
":",
"1",
",",
"'E2'",
":",
"2",
",",
"'E3'",
":",
"3",
",",
"'EC'",
":",
"4",
"}",
"... | 46.481481 | 19.37037 |
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data.get("properties", {})
raw_metadata = raw_data.get("resourceMetadata", None)
if raw_metadata is not None:
metadata = ResourceMetadata.from_raw_data(raw_metadata)
... | [
"def",
"process_raw_data",
"(",
"cls",
",",
"raw_data",
")",
":",
"properties",
"=",
"raw_data",
".",
"get",
"(",
"\"properties\"",
",",
"{",
"}",
")",
"raw_metadata",
"=",
"raw_data",
".",
"get",
"(",
"\"resourceMetadata\"",
",",
"None",
")",
"if",
"raw_m... | 43.4 | 20.333333 |
def Initialize(api_key, api_secret, api_host="localhost", api_port=443, api_ssl=True, asyncblock=False, timeout=10, req_method="get"):
""" Initializes the Cloudstack API
Accepts arguments:
api_host (localhost)
api_port (443)
api_ssl (True)
api_key
... | [
"def",
"Initialize",
"(",
"api_key",
",",
"api_secret",
",",
"api_host",
"=",
"\"localhost\"",
",",
"api_port",
"=",
"443",
",",
"api_ssl",
"=",
"True",
",",
"asyncblock",
"=",
"False",
",",
"timeout",
"=",
"10",
",",
"req_method",
"=",
"\"get\"",
")",
"... | 39.488889 | 20.4 |
def get_pdb_id_map(self):
''' Returns a dict mapping PDB IDs to:
i) their number of associated records, if self.restrict_to_transmembrane_proteins is False;
ii) the type of transmembrane protein if self.restrict_to_transmembrane_proteins is True.
At the time of writing... | [
"def",
"get_pdb_id_map",
"(",
"self",
")",
":",
"self",
".",
"ids",
"=",
"{",
"}",
"context",
"=",
"etree",
".",
"iterparse",
"(",
"io",
".",
"BytesIO",
"(",
"self",
".",
"xml_contents",
")",
",",
"events",
"=",
"(",
"'end'",
",",
")",
",",
"tag",
... | 66.9 | 37.1 |
def calc(n2, n1, operator):
"""
Calculate operation result
n2 Number: Number 2
n1 Number: Number 1
operator Char: Operation to calculate
"""
if operator == '-': return n1 - n2
elif operator == '+': return n1 + n2
elif operator == '*': return n1 * n2
elif operator == '... | [
"def",
"calc",
"(",
"n2",
",",
"n1",
",",
"operator",
")",
":",
"if",
"operator",
"==",
"'-'",
":",
"return",
"n1",
"-",
"n2",
"elif",
"operator",
"==",
"'+'",
":",
"return",
"n1",
"+",
"n2",
"elif",
"operator",
"==",
"'*'",
":",
"return",
"n1",
... | 27.285714 | 9.142857 |
def normalize_funcs(mean:FloatTensor, std:FloatTensor, do_x:bool=True, do_y:bool=False)->Tuple[Callable,Callable]:
"Create normalize/denormalize func using `mean` and `std`, can specify `do_y` and `device`."
mean,std = tensor(mean),tensor(std)
return (partial(_normalize_batch, mean=mean, std=std, do_x=do_x,... | [
"def",
"normalize_funcs",
"(",
"mean",
":",
"FloatTensor",
",",
"std",
":",
"FloatTensor",
",",
"do_x",
":",
"bool",
"=",
"True",
",",
"do_y",
":",
"bool",
"=",
"False",
")",
"->",
"Tuple",
"[",
"Callable",
",",
"Callable",
"]",
":",
"mean",
",",
"st... | 79.6 | 40 |
def add_scalar(self, logger, k, v, event_name, global_step):
"""
Helper method to log a scalar with VisdomLogger.
Args:
logger (VisdomLogger): visdom logger
k (str): scalar name which is used to set window title and y-axis label
v (int or float): scalar value... | [
"def",
"add_scalar",
"(",
"self",
",",
"logger",
",",
"k",
",",
"v",
",",
"event_name",
",",
"global_step",
")",
":",
"if",
"k",
"not",
"in",
"self",
".",
"windows",
":",
"self",
".",
"windows",
"[",
"k",
"]",
"=",
"{",
"'win'",
":",
"None",
",",... | 35.3 | 19.25 |
def _Plot_HorProj_Ves(V, ax=None, Elt='PI', Nstep=_def.TorNTheta,
Pdict=_def.TorPd, Idict=_def.TorITord,
Bsdict=_def.TorBsTord, Bvdict=_def.TorBvTord,
LegDict=_def.TorLegd, indices=False,
draw=True, fs=None, wintit=_wintit, Test=Tru... | [
"def",
"_Plot_HorProj_Ves",
"(",
"V",
",",
"ax",
"=",
"None",
",",
"Elt",
"=",
"'PI'",
",",
"Nstep",
"=",
"_def",
".",
"TorNTheta",
",",
"Pdict",
"=",
"_def",
".",
"TorPd",
",",
"Idict",
"=",
"_def",
".",
"TorITord",
",",
"Bsdict",
"=",
"_def",
"."... | 45.820313 | 19.359375 |
def to_image_header(img):
'''
to_image_header(img) yields img.header if img is a nibabel image object.
to_image_header(hdr) yields hdr if hdr is a nibabel header object.
to_image_header(obj) raises an error for other input types.
'''
if not img.__module__.startswith('nibabel.'):
raise Va... | [
"def",
"to_image_header",
"(",
"img",
")",
":",
"if",
"not",
"img",
".",
"__module__",
".",
"startswith",
"(",
"'nibabel.'",
")",
":",
"raise",
"ValueError",
"(",
"'to_image_header: only nibabel obejcts can be coerced to headers'",
")",
"if",
"type",
"(",
"img",
"... | 48.923077 | 26.461538 |
def GetConvertersByClass(value_cls):
"""Returns all converters that take given value as an input value."""
try:
return ExportConverter.converters_cache[value_cls]
except KeyError:
results = [
cls for cls in itervalues(ExportConverter.classes)
if cls.input_rdf_type == value_cl... | [
"def",
"GetConvertersByClass",
"(",
"value_cls",
")",
":",
"try",
":",
"return",
"ExportConverter",
".",
"converters_cache",
"[",
"value_cls",
"]",
"except",
"KeyError",
":",
"results",
"=",
"[",
"cls",
"for",
"cls",
"in",
"itervalues",
"(",
"ExportConverter",
... | 33.428571 | 18.357143 |
def upgrade(self, dependencies=False, prerelease=False, force=False):
"""
Upgrade the package unconditionaly
Args:
dependencies: update package dependencies if True (see pip --no-deps)
prerelease: update to pre-release and development versions
force: reinstall... | [
"def",
"upgrade",
"(",
"self",
",",
"dependencies",
"=",
"False",
",",
"prerelease",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"pip_args",
"=",
"[",
"'install'",
",",
"self",
".",
"pkg",
"]",
"found",
"=",
"self",
".",
"_get_current",
"(",
... | 32.380952 | 20.52381 |
def servers_update_addresses(request, servers, all_tenants=False):
"""Retrieve servers networking information from Neutron if enabled.
Should be used when up to date networking information is required,
and Nova's networking info caching mechanism is not fast enough.
"""
# NOTE(e0ne): we don'... | [
"def",
"servers_update_addresses",
"(",
"request",
",",
"servers",
",",
"all_tenants",
"=",
"False",
")",
":",
"# NOTE(e0ne): we don't need to call neutron if we have no instances",
"if",
"not",
"servers",
":",
"return",
"# Get all (filtered for relevant servers) information from... | 37.378788 | 18.409091 |
def get(request, obj_id):
"""Returns a serialized object
:param obj_id: ID of comment object
:type obj_id: int
:returns: json
"""
res = Result()
c = Comment.objects.get(pk=obj_id)
res.append(commentToJson(c))
return JsonResponse(res.asDict()) | [
"def",
"get",
"(",
"request",
",",
"obj_id",
")",
":",
"res",
"=",
"Result",
"(",
")",
"c",
"=",
"Comment",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"obj_id",
")",
"res",
".",
"append",
"(",
"commentToJson",
"(",
"c",
")",
")",
"return",
"Json... | 24.454545 | 12 |
def filter(self, *args, **kwargs):
"""
Works just like the default Manager's :func:`filter` method, but
you can pass an additional keyword argument named ``path`` specifying
the full **path of the folder whose immediate child objects** you
want to retrieve, e.g. ``"path/to/folder... | [
"def",
"filter",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'path'",
"in",
"kwargs",
":",
"kwargs",
"=",
"self",
".",
"get_filter_args_with_path",
"(",
"False",
",",
"*",
"*",
"kwargs",
")",
"return",
"super",
"(",
"File... | 49.3 | 18.7 |
def update_defaults(self, defaults):
"""
Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists).
"""
# Then go and look for the other sources of configuration:
config = {}
... | [
"def",
"update_defaults",
"(",
"self",
",",
"defaults",
")",
":",
"# Then go and look for the other sources of configuration:",
"config",
"=",
"{",
"}",
"# 1. config files",
"config",
".",
"update",
"(",
"dict",
"(",
"self",
".",
"get_config_section",
"(",
"'virtualen... | 40.923077 | 11.025641 |
def _VarintEncoder():
"""Return an encoder for a basic varint value."""
local_chr = chr
def EncodeVarint(write, value):
bits = value & 0x7f
value >>= 7
while value:
write(0x80|bits)
bits = value & 0x7f
value >>= 7
return write(bits)
return EncodeVarint | [
"def",
"_VarintEncoder",
"(",
")",
":",
"local_chr",
"=",
"chr",
"def",
"EncodeVarint",
"(",
"write",
",",
"value",
")",
":",
"bits",
"=",
"value",
"&",
"0x7f",
"value",
">>=",
"7",
"while",
"value",
":",
"write",
"(",
"0x80",
"|",
"bits",
")",
"bits... | 20.214286 | 20.571429 |
def run_callback(self):
"""Runs the callback for the pipeline specified in the request.
Raises:
_CallbackTaskError if something was wrong with the request parameters.
"""
pipeline_id = self.request.get('pipeline_id')
if not pipeline_id:
raise _CallbackTaskError('"pipeline_id" parameter ... | [
"def",
"run_callback",
"(",
"self",
")",
":",
"pipeline_id",
"=",
"self",
".",
"request",
".",
"get",
"(",
"'pipeline_id'",
")",
"if",
"not",
"pipeline_id",
":",
"raise",
"_CallbackTaskError",
"(",
"'\"pipeline_id\" parameter missing.'",
")",
"pipeline_key",
"=",
... | 37.784615 | 18.430769 |
def restart(self, **kwargs):
"""
Restart this container. Similar to the ``docker restart`` command.
Args:
timeout (int): Number of seconds to try to stop for before killing
the container. Once killed it will then be restarted. Default
is 10 seconds.
... | [
"def",
"restart",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"client",
".",
"api",
".",
"restart",
"(",
"self",
".",
"id",
",",
"*",
"*",
"kwargs",
")"
] | 34.785714 | 20.928571 |
def is_adjacent(self, another_edge):
"""Check if two edges are adjacent.
Args:
:param another_edge: edge object of another edge
:type another_edge: edge object
This function will return true if the two edges are adjacent.
"""
return (
self.L ... | [
"def",
"is_adjacent",
"(",
"self",
",",
"another_edge",
")",
":",
"return",
"(",
"self",
".",
"L",
"==",
"another_edge",
".",
"L",
"or",
"self",
".",
"L",
"==",
"another_edge",
".",
"R",
"or",
"self",
".",
"R",
"==",
"another_edge",
".",
"L",
"or",
... | 30.2 | 15 |
def ComplementaryColor(self, mode='ryb'):
'''Create a new instance which is the complementary color of this one.
Parameters:
:mode:
Select which color wheel to use for the generation (ryb/rgb).
Returns:
A grapefruit.Color instance.
>>> Color.NewFromHsl(30, 1, 0.5).ComplementaryCo... | [
"def",
"ComplementaryColor",
"(",
"self",
",",
"mode",
"=",
"'ryb'",
")",
":",
"h",
",",
"s",
",",
"l",
"=",
"self",
".",
"__hsl",
"if",
"mode",
"==",
"'ryb'",
":",
"h",
"=",
"Color",
".",
"RgbToRyb",
"(",
"h",
")",
"h",
"=",
"(",
"h",
"+",
"... | 26.208333 | 25.875 |
def from_interval_shorthand(self, startnote, shorthand, up=True):
"""Empty the container and add the note described in the startnote and
shorthand.
See core.intervals for the recognized format.
Examples:
>>> nc = NoteContainer()
>>> nc.from_interval_shorthand('C', '5')
... | [
"def",
"from_interval_shorthand",
"(",
"self",
",",
"startnote",
",",
"shorthand",
",",
"up",
"=",
"True",
")",
":",
"self",
".",
"empty",
"(",
")",
"if",
"type",
"(",
"startnote",
")",
"==",
"str",
":",
"startnote",
"=",
"Note",
"(",
"startnote",
")",... | 33.75 | 15.8 |
def traverse_data(obj, key_target):
''' will traverse nested list and dicts until key_target equals the current dict key '''
if isinstance(obj, str) and '.json' in str(obj):
obj = json.load(open(obj, 'r'))
if isinstance(obj, list):
queue = obj.copy()
elif isinstance(obj, dict):
q... | [
"def",
"traverse_data",
"(",
"obj",
",",
"key_target",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
"and",
"'.json'",
"in",
"str",
"(",
"obj",
")",
":",
"obj",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"obj",
",",
"'r'",
")",
")",... | 34.259259 | 13.444444 |
def call_with_retry(func: Callable, exceptions, max_retries: int,
logger: Logger, *args, **kwargs):
"""Call a function and retry it on failure."""
attempt = 0
while True:
try:
return func(*args, **kwargs)
except exceptions as e:
attempt += 1
... | [
"def",
"call_with_retry",
"(",
"func",
":",
"Callable",
",",
"exceptions",
",",
"max_retries",
":",
"int",
",",
"logger",
":",
"Logger",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"attempt",
"=",
"0",
"while",
"True",
":",
"try",
":",
"retu... | 34.866667 | 16.066667 |
def group_items(items, by=None, sorted_=True):
"""
Groups a list of items by group id.
Args:
items (list): a list of the values to be grouped.
if `by` is None, then each item is assumed to be a
(groupid, value) pair.
by (list): a corresponding list to group items by.... | [
"def",
"group_items",
"(",
"items",
",",
"by",
"=",
"None",
",",
"sorted_",
"=",
"True",
")",
":",
"if",
"by",
"is",
"not",
"None",
":",
"pairs",
"=",
"list",
"(",
"zip",
"(",
"by",
",",
"items",
")",
")",
"if",
"sorted_",
":",
"# Sort by groupid f... | 38.185185 | 21.592593 |
def present(name, description=None, config=None, devices=None,
remote_addr=None, cert=None, key=None, verify_cert=True):
'''
Creates or updates LXD profiles
name :
The name of the profile to create/update
description :
A description string
config :
A config dic... | [
"def",
"present",
"(",
"name",
",",
"description",
"=",
"None",
",",
"config",
"=",
"None",
",",
"devices",
"=",
"None",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
")",
":",
... | 26.598592 | 22.176056 |
def fill_tree_from_xml(tag, ar_tree, namespace):
# type: (_Element, ArTree, str) -> None
"""Parse the xml tree into ArTree objects."""
for child in tag: # type: _Element
name_elem = child.find('./' + namespace + 'SHORT-NAME')
# long_name = child.find('./' + namespace + 'LONG-NAME')
... | [
"def",
"fill_tree_from_xml",
"(",
"tag",
",",
"ar_tree",
",",
"namespace",
")",
":",
"# type: (_Element, ArTree, str) -> None",
"for",
"child",
"in",
"tag",
":",
"# type: _Element",
"name_elem",
"=",
"child",
".",
"find",
"(",
"'./'",
"+",
"namespace",
"+",
"'SH... | 56.2 | 15.5 |
def ListClients(self, request, timeout=None):
"""Provides basic information about Fleetspeak clients.
Args:
request: fleetspeak.admin.ListClientsRequest
timeout: How many seconds to try for.
Returns: fleetspeak.admin.ListClientsResponse
"""
return self._RetryLoop(
lambda t: se... | [
"def",
"ListClients",
"(",
"self",
",",
"request",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"_RetryLoop",
"(",
"lambda",
"t",
":",
"self",
".",
"_stub",
".",
"ListClients",
"(",
"request",
",",
"timeout",
"=",
"t",
")",
")"
] | 29.166667 | 17.666667 |
def _GetCachedFileByPath(self, key_path_upper):
"""Retrieves a cached Windows Registry file for a key path.
Args:
key_path_upper (str): Windows Registry key path, in upper case with
a resolved root key alias.
Returns:
tuple: consist:
str: key path prefix
WinRegistryF... | [
"def",
"_GetCachedFileByPath",
"(",
"self",
",",
"key_path_upper",
")",
":",
"longest_key_path_prefix_upper",
"=",
"''",
"longest_key_path_prefix_length",
"=",
"len",
"(",
"longest_key_path_prefix_upper",
")",
"for",
"key_path_prefix_upper",
"in",
"self",
".",
"_registry_... | 37.103448 | 20.275862 |
def set_archive_layout_url(self, archive_id):
""" this method returns the url to set the archive layout """
url = self.api_url + '/v2/project/' + self.api_key + '/archive/' + archive_id + '/layout'
return url | [
"def",
"set_archive_layout_url",
"(",
"self",
",",
"archive_id",
")",
":",
"url",
"=",
"self",
".",
"api_url",
"+",
"'/v2/project/'",
"+",
"self",
".",
"api_key",
"+",
"'/archive/'",
"+",
"archive_id",
"+",
"'/layout'",
"return",
"url"
] | 57.25 | 21 |
def get_local_connection(logger, use_sudo=False):
"""
Helper for local connections that are sometimes needed to operate
on local hosts
"""
return get_connection(
socket.gethostname(), # cannot rely on 'localhost' here
None,
logger=logger,
threads=1,
use_sudo=... | [
"def",
"get_local_connection",
"(",
"logger",
",",
"use_sudo",
"=",
"False",
")",
":",
"return",
"get_connection",
"(",
"socket",
".",
"gethostname",
"(",
")",
",",
"# cannot rely on 'localhost' here",
"None",
",",
"logger",
"=",
"logger",
",",
"threads",
"=",
... | 26.846154 | 17.615385 |
def enhance(self, inverse=False, gamma=1.0, stretch="no",
stretch_parameters=None, **kwargs):
"""Image enhancement function. It applies **in this order** inversion,
gamma correction, and stretching to the current image, with parameters
*inverse* (see :meth:`Image.invert`), *gamma... | [
"def",
"enhance",
"(",
"self",
",",
"inverse",
"=",
"False",
",",
"gamma",
"=",
"1.0",
",",
"stretch",
"=",
"\"no\"",
",",
"stretch_parameters",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"invert",
"(",
"inverse",
")",
"if",
"stretc... | 44.5 | 14.428571 |
def clean_total_refund_amount(self):
'''
The Javascript should ensure that the hidden input is updated, but double check it here.
'''
initial = self.cleaned_data.get('initial_refund_amount', 0)
total = self.cleaned_data['total_refund_amount']
summed_refunds = sum([v for k... | [
"def",
"clean_total_refund_amount",
"(",
"self",
")",
":",
"initial",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'initial_refund_amount'",
",",
"0",
")",
"total",
"=",
"self",
".",
"cleaned_data",
"[",
"'total_refund_amount'",
"]",
"summed_refunds",
"="... | 52 | 31.777778 |
def is_empty(self):
'''Returns True if details, extent, and type are not set or
return True for ``is_empty``; returns False if any of the
fields are not empty.'''
return all(field.is_empty() for field in [self.details, self.extent]
if field is not None) \
... | [
"def",
"is_empty",
"(",
"self",
")",
":",
"return",
"all",
"(",
"field",
".",
"is_empty",
"(",
")",
"for",
"field",
"in",
"[",
"self",
".",
"details",
",",
"self",
".",
"extent",
"]",
"if",
"field",
"is",
"not",
"None",
")",
"and",
"not",
"self",
... | 48 | 18.571429 |
def users(self):
"""
Provides access to all user resources
"""
return Users(url="%s/users" % self.root,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port) | [
"def",
"users",
"(",
"self",
")",
":",
"return",
"Users",
"(",
"url",
"=",
"\"%s/users\"",
"%",
"self",
".",
"root",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"... | 35.75 | 9 |
def save_image(byteio, imgfmt):
"""Saves the specified image to disk.
Args:
byteio (bytes): image bytes to save to disk.
imgfmt (str): used as the extension of the saved file.
Returns:
str: a uuid for the saved image that can be added to the database entry.
"""
from os impo... | [
"def",
"save_image",
"(",
"byteio",
",",
"imgfmt",
")",
":",
"from",
"os",
"import",
"path",
",",
"mkdir",
"ptdir",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"project",
",",
"task",
")",
"uuid",
"=",
"str",
"(",
"uuid4",
"(",
")",
")",
"#Save the image wit... | 27.666667 | 20.333333 |
def toggle(self):
"""Toggle :obj:`ToggledFrame.interior` opened or closed."""
if self._open:
self._open = False
self.__checkbutton_var.set(False)
self.interior.grid_forget()
self._checkbutton.config(image=self._closed_image)
else:
self.... | [
"def",
"toggle",
"(",
"self",
")",
":",
"if",
"self",
".",
"_open",
":",
"self",
".",
"_open",
"=",
"False",
"self",
".",
"__checkbutton_var",
".",
"set",
"(",
"False",
")",
"self",
".",
"interior",
".",
"grid_forget",
"(",
")",
"self",
".",
"_checkb... | 40.833333 | 13.583333 |
def process_without_storing(d_vals, s_f_strm, s_f_key, output_type, outfh,
f_f_header=None, s_f_has_header=False,
missing_val=None, delim=None,
ignore_missing_keys=False,
output_unpaired=False, verbose=False)... | [
"def",
"process_without_storing",
"(",
"d_vals",
",",
"s_f_strm",
",",
"s_f_key",
",",
"output_type",
",",
"outfh",
",",
"f_f_header",
"=",
"None",
",",
"s_f_has_header",
"=",
"False",
",",
"missing_val",
"=",
"None",
",",
"delim",
"=",
"None",
",",
"ignore_... | 43.513514 | 21.324324 |
def motto(self):
"""获取用户自我介绍,由于历史原因,我还是把这个属性叫做motto吧.
:return: 用户自我介绍
:rtype: str
"""
if self.url is None:
return ''
else:
if self.soup is not None:
bar = self.soup.find(
'div', class_='title-section')
... | [
"def",
"motto",
"(",
"self",
")",
":",
"if",
"self",
".",
"url",
"is",
"None",
":",
"return",
"''",
"else",
":",
"if",
"self",
".",
"soup",
"is",
"not",
"None",
":",
"bar",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'div'",
",",
"class_",
"="... | 31.15 | 14.3 |
def deployed(name, jboss_config, salt_source=None):
'''Ensures that the given application is deployed on server.
jboss_config:
Dict with connection properties (see state description)
salt_source:
How to find the artifact to be deployed.
target_file:
Where to look... | [
"def",
"deployed",
"(",
"name",
",",
"jboss_config",
",",
"salt_source",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"\" ======================== STATE: jboss7.deployed (name: %s) \"",
",",
"name",
")",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'... | 44.055556 | 31.796296 |
def _calc_real_and_point(self):
"""
Determines the self energy -(eta/pi)**(1/2) * sum_{i=1}^{N} q_i**2
"""
fcoords = self._s.frac_coords
forcepf = 2.0 * self._sqrt_eta / sqrt(pi)
coords = self._coords
numsites = self._s.num_sites
ereal = np.empty((numsites... | [
"def",
"_calc_real_and_point",
"(",
"self",
")",
":",
"fcoords",
"=",
"self",
".",
"_s",
".",
"frac_coords",
"forcepf",
"=",
"2.0",
"*",
"self",
".",
"_sqrt_eta",
"/",
"sqrt",
"(",
"pi",
")",
"coords",
"=",
"self",
".",
"_coords",
"numsites",
"=",
"sel... | 34.791667 | 20.125 |
def rename(args):
"""
%prog rename in.gff3 switch.ids > reindexed.gff3
Change the IDs within the gff3.
"""
p = OptionParser(rename.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
ingff3, switch = args
switch = DictFile(switch)
... | [
"def",
"rename",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"rename",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
"n... | 23.777778 | 17.333333 |
def load(self, relpath, rsc=None, mode='r', useFilepath=None):
"""
Opens a file like object for reading for the given relpath.
:param relpath | <str>
:return <File> || <QFile> || None
"""
filepath = self.find(relpath, rsc, useFilepath=us... | [
"def",
"load",
"(",
"self",
",",
"relpath",
",",
"rsc",
"=",
"None",
",",
"mode",
"=",
"'r'",
",",
"useFilepath",
"=",
"None",
")",
":",
"filepath",
"=",
"self",
".",
"find",
"(",
"relpath",
",",
"rsc",
",",
"useFilepath",
"=",
"useFilepath",
")",
... | 30.52381 | 15.095238 |
def publish(branch, full_force=False):
"""Publish that branch, i.e. push it to origin"""
checkout(branch)
try:
push('--force --set-upstream origin', branch)
except ExistingReference:
if full_force:
push('origin --delete', branch)
push('--force --set-upstream origi... | [
"def",
"publish",
"(",
"branch",
",",
"full_force",
"=",
"False",
")",
":",
"checkout",
"(",
"branch",
")",
"try",
":",
"push",
"(",
"'--force --set-upstream origin'",
",",
"branch",
")",
"except",
"ExistingReference",
":",
"if",
"full_force",
":",
"push",
"... | 35.888889 | 12.888889 |
def edge_length_sum(self, terminal=True, internal=True):
'''Compute the sum of all selected edge lengths in this ``Tree``
Args:
``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal branches, ot... | [
"def",
"edge_length_sum",
"(",
"self",
",",
"terminal",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"terminal",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"leaves must be a bool\"",
")",
"if",
"not",
"isins... | 49.875 | 34.875 |
def genVector(width, height, x_mult=1, y_mult=1):
"""
Generates a map of vector lengths from the center point to each coordinate.
width - width of matrix to generate
height - height of matrix to generate
x_mult - value to scale x-axis by
y_mult - value to scale y-axis by
"""
center_x = ... | [
"def",
"genVector",
"(",
"width",
",",
"height",
",",
"x_mult",
"=",
"1",
",",
"y_mult",
"=",
"1",
")",
":",
"center_x",
"=",
"(",
"width",
"-",
"1",
")",
"/",
"2",
"center_y",
"=",
"(",
"height",
"-",
"1",
")",
"/",
"2",
"def",
"length",
"(",
... | 32.333333 | 14.555556 |
async def _clean_shutdown(self):
"""Cleanly shutdown the emulation loop."""
# Cleanly stop any other outstanding tasks not associated with tiles
remaining_tasks = []
for task in self._tasks.get(None, []):
self._logger.debug("Cancelling task at shutdown %s", task)
... | [
"async",
"def",
"_clean_shutdown",
"(",
"self",
")",
":",
"# Cleanly stop any other outstanding tasks not associated with tiles",
"remaining_tasks",
"=",
"[",
"]",
"for",
"task",
"in",
"self",
".",
"_tasks",
".",
"get",
"(",
"None",
",",
"[",
"]",
")",
":",
"sel... | 30.848485 | 21.636364 |
def open(self):
"""Opens the record file."""
if self.flag == "w":
check_call(_LIB.MXRecordIOWriterCreate(self.uri, ctypes.byref(self.handle)))
self.writable = True
elif self.flag == "r":
check_call(_LIB.MXRecordIOReaderCreate(self.uri, ctypes.byref(self.handle... | [
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"flag",
"==",
"\"w\"",
":",
"check_call",
"(",
"_LIB",
".",
"MXRecordIOWriterCreate",
"(",
"self",
".",
"uri",
",",
"ctypes",
".",
"byref",
"(",
"self",
".",
"handle",
")",
")",
")",
"self",
... | 40.583333 | 17.916667 |
def get(project, credentials=None):
"""Main Get method: Get project state, parameters, outputindex"""
user, oauth_access_token = parsecredentials(credentials)
if not Project.exists(project, user):
return withheaders(flask.make_response("Project " + project + " was not found for user ... | [
"def",
"get",
"(",
"project",
",",
"credentials",
"=",
"None",
")",
":",
"user",
",",
"oauth_access_token",
"=",
"parsecredentials",
"(",
"credentials",
")",
"if",
"not",
"Project",
".",
"exists",
"(",
"project",
",",
"user",
")",
":",
"return",
"withheade... | 80.125 | 44.583333 |
def Paraboloid(pos=(0, 0, 0), r=1, height=1, axis=(0, 0, 1), c="cyan", alpha=1, res=50):
"""
Build a paraboloid of specified height and radius `r`, centered at `pos`.
.. note::
Full volumetric expression is:
:math:`F(x,y,z)=a_0x^2+a_1y^2+a_2z^2+a_3xy+a_4yz+a_5xz+ a_6x+a_7y+a_8z+a_9`... | [
"def",
"Paraboloid",
"(",
"pos",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"r",
"=",
"1",
",",
"height",
"=",
"1",
",",
"axis",
"=",
"(",
"0",
",",
"0",
",",
"1",
")",
",",
"c",
"=",
"\"cyan\"",
",",
"alpha",
"=",
"1",
",",
"res",
"=... | 32.613636 | 15.568182 |
def notify(self):
"""
Access the Notify Twilio Domain
:returns: Notify Twilio Domain
:rtype: twilio.rest.notify.Notify
"""
if self._notify is None:
from twilio.rest.notify import Notify
self._notify = Notify(self)
return self._notify | [
"def",
"notify",
"(",
"self",
")",
":",
"if",
"self",
".",
"_notify",
"is",
"None",
":",
"from",
"twilio",
".",
"rest",
".",
"notify",
"import",
"Notify",
"self",
".",
"_notify",
"=",
"Notify",
"(",
"self",
")",
"return",
"self",
".",
"_notify"
] | 27.636364 | 8.909091 |
def _run(self):
""" Runs the interval loop. """
def get_next_interval():
start_time = time.time()
start = 0 if self.eager else 1
for count in itertools.count(start=start):
yield max(start_time + count * self.interval - time.time(), 0)
interval... | [
"def",
"_run",
"(",
"self",
")",
":",
"def",
"get_next_interval",
"(",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"start",
"=",
"0",
"if",
"self",
".",
"eager",
"else",
"1",
"for",
"count",
"in",
"itertools",
".",
"count",
"(",
"st... | 34.347826 | 16.217391 |
def getScan(self, title, peptide=None):
"""
allows random lookup
"""
if self.ra.has_key(title):
self.filename.seek(self.ra[title][0],0)
toRead = self.ra[title][1]-self.ra[title][0]
info = self.filename.read(toRead)
scan = self.parseScan(inf... | [
"def",
"getScan",
"(",
"self",
",",
"title",
",",
"peptide",
"=",
"None",
")",
":",
"if",
"self",
".",
"ra",
".",
"has_key",
"(",
"title",
")",
":",
"self",
".",
"filename",
".",
"seek",
"(",
"self",
".",
"ra",
"[",
"title",
"]",
"[",
"0",
"]",... | 30.75 | 9.75 |
def edit_distance(string1, string2):
"""
Edit distance algorithm. String1 and string2 can be either
strings or lists of strings
pip install python-Levenshtein
Args:
string1 (str or list):
string2 (str or list):
CommandLine:
python -m utool.util_alg edit_distance --show... | [
"def",
"edit_distance",
"(",
"string1",
",",
"string2",
")",
":",
"import",
"utool",
"as",
"ut",
"try",
":",
"import",
"Levenshtein",
"except",
"ImportError",
"as",
"ex",
":",
"ut",
".",
"printex",
"(",
"ex",
",",
"'pip install python-Levenshtein'",
")",
"ra... | 30.574074 | 17.092593 |
def _publish_message(self, exchange, routing_key, message, properties):
"""Publish the message to RabbitMQ
:param str exchange: The exchange to publish to
:param str routing_key: The routing key to publish with
:param str message: The message body
:param pika.BasicProperties: Th... | [
"def",
"_publish_message",
"(",
"self",
",",
"exchange",
",",
"routing_key",
",",
"message",
",",
"properties",
")",
":",
"if",
"self",
".",
"_rabbitmq_is_closed",
"or",
"not",
"self",
".",
"_rabbitmq_channel",
":",
"LOGGER",
".",
"warning",
"(",
"'Temporarily... | 46.9375 | 21.375 |
def get_value(self, constraints, expression):
"""
Ask the solver for one possible result of given expression using given set of constraints.
"""
if not issymbolic(expression):
return expression
assert isinstance(expression, (Bool, BitVec, Array))
with constrai... | [
"def",
"get_value",
"(",
"self",
",",
"constraints",
",",
"expression",
")",
":",
"if",
"not",
"issymbolic",
"(",
"expression",
")",
":",
"return",
"expression",
"assert",
"isinstance",
"(",
"expression",
",",
"(",
"Bool",
",",
"BitVec",
",",
"Array",
")",... | 41.407407 | 16.666667 |
def set_identify(on=True, duration=600, **kwargs):
'''
Request identify light
Request the identify light to turn off, on for a duration,
or on indefinitely. Other than error exceptions,
:param on: Set to True to force on or False to force off
:param duration: Set if wanting to request turn on... | [
"def",
"set_identify",
"(",
"on",
"=",
"True",
",",
"duration",
"=",
"600",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"_IpmiCommand",
"(",
"*",
"*",
"kwargs",
")",
"as",
"s",
":",
"return",
"s",
".",
"set_identify",
"(",
"on",
"=",
"on",
",",
"d... | 27.72 | 21.96 |
def _restrict_along_direction(value_and_gradients_function,
position,
direction):
"""Restricts a function in n-dimensions to a given direction.
Suppose f: R^n -> R. Then given a point x0 and a vector p0 in R^n, the
restriction of the function along that... | [
"def",
"_restrict_along_direction",
"(",
"value_and_gradients_function",
",",
"position",
",",
"direction",
")",
":",
"def",
"_restricted_func",
"(",
"t",
")",
":",
"t",
"=",
"_broadcast",
"(",
"t",
",",
"position",
")",
"pt",
"=",
"position",
"+",
"tf",
"."... | 46.833333 | 26.907407 |
def build(self, sources=None, tables=None, stage=None, force=False):
"""
:param phase:
:param stage:
:param sources: Source names or destination table names.
:return:
"""
from operator import attrgetter
from itertools import groupby
from .concurre... | [
"def",
"build",
"(",
"self",
",",
"sources",
"=",
"None",
",",
"tables",
"=",
"None",
",",
"stage",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"from",
"operator",
"import",
"attrgetter",
"from",
"itertools",
"import",
"groupby",
"from",
".",
"c... | 36.722628 | 25.875912 |
def fetch(url, fullpath):
'''
Fetch data from an URL and save it under the given target name.
'''
logger.debug("Fetching %s from %s" % (fullpath, url))
try:
tmpfile, headers = urlretrieve(url)
if os.path.exists(fullpath):
os.remove(fullpath)
shutil.move(tmpfile, ... | [
"def",
"fetch",
"(",
"url",
",",
"fullpath",
")",
":",
"logger",
".",
"debug",
"(",
"\"Fetching %s from %s\"",
"%",
"(",
"fullpath",
",",
"url",
")",
")",
"try",
":",
"tmpfile",
",",
"headers",
"=",
"urlretrieve",
"(",
"url",
")",
"if",
"os",
".",
"p... | 29.571429 | 19.428571 |
def sys_save_screenshot(name: Optional[str] = None) -> None:
"""Save a screenshot to a file.
By default this will automatically save screenshots in the working
directory.
The automatic names are formatted as screenshotNNN.png. For example:
screenshot000.png, screenshot001.png, etc. Whichever is ... | [
"def",
"sys_save_screenshot",
"(",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_sys_save_screenshot",
"(",
"_bytes",
"(",
"name",
")",
"if",
"name",
"is",
"not",
"None",
"else",
"ffi",
".",
"NULL",
")... | 33.133333 | 24.866667 |
def searchPhotos(self, title, **kwargs):
""" Search for a photo. See :func:`~plexapi.library.LibrarySection.search()` for usage. """
return self.search(libtype='photo', title=title, **kwargs) | [
"def",
"searchPhotos",
"(",
"self",
",",
"title",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"search",
"(",
"libtype",
"=",
"'photo'",
",",
"title",
"=",
"title",
",",
"*",
"*",
"kwargs",
")"
] | 68.333333 | 8.666667 |
def delete_duplicates(seq):
"""
Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | [
"def",
"delete_duplicates",
"(",
"seq",
")",
":",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"return",
"[",
"x",
"for",
"x",
"in",
"seq",
"if",
"not",
"(",
"x",
"in",
"seen",
"or",
"seen_add",
"(",
"x",
")",
")",
"]"
] | 21.285714 | 20 |
def add_tweets(self, url, last_modified, tweets):
"""Adds new tweets to the cache."""
try:
self.cache[url] = {"last_modified": last_modified, "tweets": tweets}
self.mark_updated()
return True
except TypeError:
return False | [
"def",
"add_tweets",
"(",
"self",
",",
"url",
",",
"last_modified",
",",
"tweets",
")",
":",
"try",
":",
"self",
".",
"cache",
"[",
"url",
"]",
"=",
"{",
"\"last_modified\"",
":",
"last_modified",
",",
"\"tweets\"",
":",
"tweets",
"}",
"self",
".",
"ma... | 35.875 | 16.75 |
def create(self, **attributes):
"""
Create a collection of models and persist them to the database.
:param attributes: The models attributes
:type attributes: dict
:return: mixed
"""
results = self.make(**attributes)
if self._amount == 1:
if... | [
"def",
"create",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"results",
"=",
"self",
".",
"make",
"(",
"*",
"*",
"attributes",
")",
"if",
"self",
".",
"_amount",
"==",
"1",
":",
"if",
"self",
".",
"_resolver",
":",
"results",
".",
"set_conn... | 25.916667 | 20.333333 |
def pre_filter(self):
""" Return rTorrent condition to speed up data transfer.
"""
if len(self) == 1:
return self[0].pre_filter()
else:
result = [x.pre_filter() for x in self if not isinstance(x, CompoundFilterBase)]
result = [x for x in result if x]
... | [
"def",
"pre_filter",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
")",
"==",
"1",
":",
"return",
"self",
"[",
"0",
"]",
".",
"pre_filter",
"(",
")",
"else",
":",
"result",
"=",
"[",
"x",
".",
"pre_filter",
"(",
")",
"for",
"x",
"in",
"self"... | 41.4 | 17.866667 |
def commit(self):
"Commit data to the storage."
if self._meta.path:
with open(self._meta.path, 'wb') as fd:
raw = deepcopy(self.raw)
# LAZY INDEX PROCESSING
# Save indexes only if not lazy
lazy_indexes = self.lazy_indexes # Kee... | [
"def",
"commit",
"(",
"self",
")",
":",
"if",
"self",
".",
"_meta",
".",
"path",
":",
"with",
"open",
"(",
"self",
".",
"_meta",
".",
"path",
",",
"'wb'",
")",
"as",
"fd",
":",
"raw",
"=",
"deepcopy",
"(",
"self",
".",
"raw",
")",
"# LAZY INDEX P... | 47.409091 | 13.681818 |
def has_layer(fcollection):
"""Returns true for a multi-layer dict of FeatureCollections."""
for val in six.viewvalues(fcollection):
if has_features(val):
return True
return False | [
"def",
"has_layer",
"(",
"fcollection",
")",
":",
"for",
"val",
"in",
"six",
".",
"viewvalues",
"(",
"fcollection",
")",
":",
"if",
"has_features",
"(",
"val",
")",
":",
"return",
"True",
"return",
"False"
] | 34.333333 | 11.333333 |
def _begin(self, connection, filterargs=(), escape=True):
"""
Begins an asynchronous search and returns the message id to retrieve
the results.
filterargs is an object that will be used for expansion of the filter
string. If escape is True, values in filterargs will be escaped.
... | [
"def",
"_begin",
"(",
"self",
",",
"connection",
",",
"filterargs",
"=",
"(",
")",
",",
"escape",
"=",
"True",
")",
":",
"if",
"escape",
":",
"filterargs",
"=",
"self",
".",
"_escape_filterargs",
"(",
"filterargs",
")",
"try",
":",
"filterstr",
"=",
"s... | 37.318182 | 24.590909 |
def _wipe_www_page(self, slug):
'''Remove all data in www about the page identified by slug.'''
wd = os.path.join(self._dirs['www'], slug)
if os.path.isdir(wd): # pragma: no cover
shutil.rmtree(wd) | [
"def",
"_wipe_www_page",
"(",
"self",
",",
"slug",
")",
":",
"wd",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_dirs",
"[",
"'www'",
"]",
",",
"slug",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"wd",
")",
":",
"# pragma: no cove... | 45.8 | 13.8 |
def licenses(family_directory):
"""Get a list of paths for every license
file found in a font project."""
found = []
search_paths = [family_directory]
gitroot = git_rootdir(family_directory)
if gitroot and gitroot not in search_paths:
search_paths.append(gitroot)
for directory in search_paths:
... | [
"def",
"licenses",
"(",
"family_directory",
")",
":",
"found",
"=",
"[",
"]",
"search_paths",
"=",
"[",
"family_directory",
"]",
"gitroot",
"=",
"git_rootdir",
"(",
"family_directory",
")",
"if",
"gitroot",
"and",
"gitroot",
"not",
"in",
"search_paths",
":",
... | 32.3125 | 11.25 |
def fetch_plaintext_by_subject(self, email_name):
"""
Get the plain text of an email, searching by subject.
@Params
email_name - the subject to search for
@Returns
Plaintext content of the matched email
"""
if not email_name:
raise EmailExcepti... | [
"def",
"fetch_plaintext_by_subject",
"(",
"self",
",",
"email_name",
")",
":",
"if",
"not",
"email_name",
":",
"raise",
"EmailException",
"(",
"\"Subject cannot be null\"",
")",
"results",
"=",
"self",
".",
"__imap_search",
"(",
"SUBJECT",
"=",
"email_name",
")",
... | 30.933333 | 16.266667 |
def rename_kw(old_name, old_value, new_name, new_value,
version_deprecated, version_removed):
'''Handle renamed arguments.
Parameters
----------
old_name : str
old_value
The name and value of the old argument
new_name : str
new_value
The name and value of the ... | [
"def",
"rename_kw",
"(",
"old_name",
",",
"old_value",
",",
"new_name",
",",
"new_value",
",",
"version_deprecated",
",",
"version_removed",
")",
":",
"if",
"isinstance",
"(",
"old_value",
",",
"Deprecated",
")",
":",
"return",
"new_value",
"else",
":",
"stack... | 29.68 | 22.96 |
def start_trace(reset=True, filter_func=None, time_filter_func=None):
"""Begins a trace. Setting reset to True will reset all previously recorded
trace data. filter_func needs to point to a callable function that accepts
the parameters (call_stack, module_name, class_name, func_name, full_name).
Every c... | [
"def",
"start_trace",
"(",
"reset",
"=",
"True",
",",
"filter_func",
"=",
"None",
",",
"time_filter_func",
"=",
"None",
")",
":",
"global",
"trace_filter",
"global",
"time_filter",
"if",
"reset",
":",
"reset_trace",
"(",
")",
"if",
"filter_func",
":",
"trace... | 36 | 22.916667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.