text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def FindProxies():
"""Tries to find proxies by interrogating all the user's settings.
This function is a modified urillib.getproxies_registry() from the
standard library. We just store the proxy value in the environment
for urllib to find it.
TODO(user): Iterate through all the possible values if one proxy
... | [
"def",
"FindProxies",
"(",
")",
":",
"proxies",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"100",
")",
":",
"try",
":",
"sid",
"=",
"winreg",
".",
"EnumKey",
"(",
"winreg",
".",
"HKEY_USERS",
",",
"i",
")",
"except",
"OSError",
":",... | 28.55 | 22.566667 |
def RemoveSearchProperties(self, **searchProperties) -> None:
"""
searchProperties: dict, same as searchProperties in `Control.__init__`.
"""
for key in searchProperties:
del self.searchProperties[key]
if key == 'RegexName':
self.regexName = None | [
"def",
"RemoveSearchProperties",
"(",
"self",
",",
"*",
"*",
"searchProperties",
")",
"->",
"None",
":",
"for",
"key",
"in",
"searchProperties",
":",
"del",
"self",
".",
"searchProperties",
"[",
"key",
"]",
"if",
"key",
"==",
"'RegexName'",
":",
"self",
".... | 38.875 | 9.375 |
def create_service_key(self, service_name, key_name):
"""
Create a service key for the given service.
"""
if self.has_key(service_name, key_name):
logging.warning("Reusing existing service key %s" % (key_name))
return self.get_service_key(service_name, key_name)
... | [
"def",
"create_service_key",
"(",
"self",
",",
"service_name",
",",
"key_name",
")",
":",
"if",
"self",
".",
"has_key",
"(",
"service_name",
",",
"key_name",
")",
":",
"logging",
".",
"warning",
"(",
"\"Reusing existing service key %s\"",
"%",
"(",
"key_name",
... | 35.5 | 20.071429 |
def confirm(text, default=True):
"""
Console confirmation dialog based on raw_input.
"""
if default:
legend = "[y]/n"
else:
legend = "y/[n]"
res = ""
while (res != "y") and (res != "n"):
res = raw_input(text + " ({}): ".format(legend)).lower()
if not res and d... | [
"def",
"confirm",
"(",
"text",
",",
"default",
"=",
"True",
")",
":",
"if",
"default",
":",
"legend",
"=",
"\"[y]/n\"",
"else",
":",
"legend",
"=",
"\"y/[n]\"",
"res",
"=",
"\"\"",
"while",
"(",
"res",
"!=",
"\"y\"",
")",
"and",
"(",
"res",
"!=",
"... | 24.421053 | 15.789474 |
def get_tree_members(self):
""" Retrieves all members from this node of the tree down."""
members = []
queue = deque()
queue.appendleft(self)
visited = set()
while len(queue):
node = queue.popleft()
if node not in visited:
... | [
"def",
"get_tree_members",
"(",
"self",
")",
":",
"members",
"=",
"[",
"]",
"queue",
"=",
"deque",
"(",
")",
"queue",
".",
"appendleft",
"(",
"self",
")",
"visited",
"=",
"set",
"(",
")",
"while",
"len",
"(",
"queue",
")",
":",
"node",
"=",
"queue"... | 32.764706 | 21.235294 |
def get_asset_search_session(self):
"""Gets an asset search session.
return: (osid.repository.AssetSearchSession) - an
``AssetSearchSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_asset_search()`` is ``false``
*co... | [
"def",
"get_asset_search_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_asset_search",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"AssetSearchSession",
"(",
"run... | 40.866667 | 15.066667 |
def create_from_fits(cls, fitsfile, norm_type='eflux',
hdu_scan="SCANDATA",
hdu_energies="EBOUNDS",
irow=None):
"""Create a CastroData object from a tscube FITS file.
Parameters
----------
fitsfile : str
... | [
"def",
"create_from_fits",
"(",
"cls",
",",
"fitsfile",
",",
"norm_type",
"=",
"'eflux'",
",",
"hdu_scan",
"=",
"\"SCANDATA\"",
",",
"hdu_energies",
"=",
"\"EBOUNDS\"",
",",
"irow",
"=",
"None",
")",
":",
"if",
"irow",
"is",
"not",
"None",
":",
"tab_s",
... | 33.208333 | 20.770833 |
def item_gebouw_adapter(obj, request):
"""
Adapter for rendering an object of
:class:`crabpy.gateway.crab.Gebouw` to json.
"""
return {
'id': obj.id,
'aard': {
'id': obj.aard.id,
'naam': obj.aard.naam,
'definitie': obj.aard.definitie
},
... | [
"def",
"item_gebouw_adapter",
"(",
"obj",
",",
"request",
")",
":",
"return",
"{",
"'id'",
":",
"obj",
".",
"id",
",",
"'aard'",
":",
"{",
"'id'",
":",
"obj",
".",
"aard",
".",
"id",
",",
"'naam'",
":",
"obj",
".",
"aard",
".",
"naam",
",",
"'def... | 32.394737 | 14.710526 |
def reset():
"""
Reset the timer at the current level in the hierarchy (i.e. might or
might not be the root).
Notes:
Erases timing data but preserves relationship to the hierarchy. If the
current timer level was not previously stopped, any timing data from this
timer (including... | [
"def",
"reset",
"(",
")",
":",
"if",
"f",
".",
"t",
".",
"in_loop",
":",
"raise",
"LoopError",
"(",
"\"Cannot reset a timer while it is in timed loop.\"",
")",
"f",
".",
"t",
".",
"reset",
"(",
")",
"f",
".",
"refresh_shortcuts",
"(",
")",
"return",
"f",
... | 34.217391 | 26.391304 |
def from_dicts(cls, mesh_name, vert_dict, normal_dict):
"""Returns a wavefront .obj string using pre-triangulated vertex dict and normal dict as reference."""
# Put header in string
wavefront_str = "o {name}\n".format(name=mesh_name)
# Write Vertex data from vert_dict
for wall ... | [
"def",
"from_dicts",
"(",
"cls",
",",
"mesh_name",
",",
"vert_dict",
",",
"normal_dict",
")",
":",
"# Put header in string",
"wavefront_str",
"=",
"\"o {name}\\n\"",
".",
"format",
"(",
"name",
"=",
"mesh_name",
")",
"# Write Vertex data from vert_dict",
"for",
"wal... | 40.033333 | 18.3 |
def read_union(fo, writer_schema, reader_schema=None):
"""A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union.
"""
# schema resolution
index = read_lo... | [
"def",
"read_union",
"(",
"fo",
",",
"writer_schema",
",",
"reader_schema",
"=",
"None",
")",
":",
"# schema resolution",
"index",
"=",
"read_long",
"(",
"fo",
")",
"if",
"reader_schema",
":",
"# Handle case where the reader schema is just a single type (not union)",
"i... | 44.681818 | 18.363636 |
def new(self, items:Iterator, processor:PreProcessors=None, **kwargs)->'ItemList':
"Create a new `ItemList` from `items`, keeping the same attributes."
processor = ifnone(processor, self.processor)
copy_d = {o:getattr(self,o) for o in self.copy_new}
kwargs = {**copy_d, **kwargs}
... | [
"def",
"new",
"(",
"self",
",",
"items",
":",
"Iterator",
",",
"processor",
":",
"PreProcessors",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'ItemList'",
":",
"processor",
"=",
"ifnone",
"(",
"processor",
",",
"self",
".",
"processor",
")",
"cop... | 63.333333 | 24.333333 |
def R(X, destination, a1, a2, b):
"""A single Salsa20 row operation"""
a = (X[a1] + X[a2]) & 0xffffffff
X[destination] ^= ((a << b) | (a >> (32 - b))) | [
"def",
"R",
"(",
"X",
",",
"destination",
",",
"a1",
",",
"a2",
",",
"b",
")",
":",
"a",
"=",
"(",
"X",
"[",
"a1",
"]",
"+",
"X",
"[",
"a2",
"]",
")",
"&",
"0xffffffff",
"X",
"[",
"destination",
"]",
"^=",
"(",
"(",
"a",
"<<",
"b",
")",
... | 31.8 | 12.2 |
def get_tab(self, tab_name, allow_disabled=False):
"""Returns a specific tab from this tab group.
If the tab is not allowed or not enabled this method returns ``None``.
If the tab is disabled but you wish to return it anyway, you can pass
``True`` to the allow_disabled argument.
... | [
"def",
"get_tab",
"(",
"self",
",",
"tab_name",
",",
"allow_disabled",
"=",
"False",
")",
":",
"tab",
"=",
"self",
".",
"_tabs",
".",
"get",
"(",
"tab_name",
",",
"None",
")",
"if",
"tab",
"and",
"tab",
".",
"_allowed",
"and",
"(",
"tab",
".",
"_en... | 39.333333 | 20.416667 |
def _GetNormalizedTimestamp(self):
"""Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cann... | [
"def",
"_GetNormalizedTimestamp",
"(",
"self",
")",
":",
"if",
"self",
".",
"_normalized_timestamp",
"is",
"None",
":",
"if",
"self",
".",
"_timestamp",
"is",
"not",
"None",
":",
"self",
".",
"_normalized_timestamp",
"=",
"decimal",
".",
"Decimal",
"(",
"sel... | 38.708333 | 23.666667 |
def _rt_update_docindices(self, element, docstart, docend):
"""Updates the docstart, docend, start and end attributes for the
specified element using the new limits for the docstring."""
#see how many characters have to be added/removed from the end
#of the current doc limits.
d... | [
"def",
"_rt_update_docindices",
"(",
"self",
",",
"element",
",",
"docstart",
",",
"docend",
")",
":",
"#see how many characters have to be added/removed from the end",
"#of the current doc limits.",
"delta",
"=",
"element",
".",
"docend",
"-",
"docend",
"element",
".",
... | 40.75 | 12.583333 |
def cas(key, value, old_value):
'''
Check and set a value in the minion datastore
CLI Example:
.. code-block:: bash
salt '*' data.cas <key> <value> <old_value>
'''
store = load()
if key not in store:
return False
if store[key] != old_value:
return False
s... | [
"def",
"cas",
"(",
"key",
",",
"value",
",",
"old_value",
")",
":",
"store",
"=",
"load",
"(",
")",
"if",
"key",
"not",
"in",
"store",
":",
"return",
"False",
"if",
"store",
"[",
"key",
"]",
"!=",
"old_value",
":",
"return",
"False",
"store",
"[",
... | 17.5 | 24.5 |
def check_dir(self, dirname):
"""Check and create directory
:param dirname: file name
:type dirname; str
:return: None
"""
try:
os.makedirs(dirname)
dir_stat = os.stat(dirname)
print("Created the directory: %s, stat: %s" % (dirname, d... | [
"def",
"check_dir",
"(",
"self",
",",
"dirname",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"dir_stat",
"=",
"os",
".",
"stat",
"(",
"dirname",
")",
"print",
"(",
"\"Created the directory: %s, stat: %s\"",
"%",
"(",
"dirname",
",",
... | 45.5 | 21.35 |
def p_lpartselect(self, p):
'lpartselect : identifier LBRACKET expression COLON expression RBRACKET'
p[0] = Partselect(p[1], p[3], p[5], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_lpartselect",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Partselect",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"5",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
... | 51.5 | 20 |
def is_sw_writable(self):
"""
Field is writable by software
"""
sw = self.get_property('sw')
return sw in (rdltypes.AccessType.rw, rdltypes.AccessType.rw1,
rdltypes.AccessType.w, rdltypes.AccessType.w1) | [
"def",
"is_sw_writable",
"(",
"self",
")",
":",
"sw",
"=",
"self",
".",
"get_property",
"(",
"'sw'",
")",
"return",
"sw",
"in",
"(",
"rdltypes",
".",
"AccessType",
".",
"rw",
",",
"rdltypes",
".",
"AccessType",
".",
"rw1",
",",
"rdltypes",
".",
"Access... | 32.5 | 15.25 |
def get_progress(self):
"""
Give a rough estimate of the progress done.
"""
pos = self.reader.reader.tell()
return min((pos - self.region_start) /
float(self.region_end - self.region_start),
1.0) | [
"def",
"get_progress",
"(",
"self",
")",
":",
"pos",
"=",
"self",
".",
"reader",
".",
"reader",
".",
"tell",
"(",
")",
"return",
"min",
"(",
"(",
"pos",
"-",
"self",
".",
"region_start",
")",
"/",
"float",
"(",
"self",
".",
"region_end",
"-",
"self... | 33.25 | 9.25 |
def get_package_info_from_line(tpip_pkg, line):
"""Given a line of text from metadata, extract semantic info"""
lower_line = line.lower()
try:
metadata_key, metadata_value = lower_line.split(':', 1)
except ValueError:
return
metadata_key = metadata_key.strip()
metadata_value = ... | [
"def",
"get_package_info_from_line",
"(",
"tpip_pkg",
",",
"line",
")",
":",
"lower_line",
"=",
"line",
".",
"lower",
"(",
")",
"try",
":",
"metadata_key",
",",
"metadata_value",
"=",
"lower_line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"except",
"ValueE... | 34.09375 | 21.5 |
def device_information(name, identifier):
"""Create a new DEVICE_INFO_MESSAGE."""
# pylint: disable=no-member
message = create(protobuf.DEVICE_INFO_MESSAGE)
info = message.inner()
info.uniqueIdentifier = identifier
info.name = name
info.localizedModelName = 'iPhone'
info.systemBuildVersi... | [
"def",
"device_information",
"(",
"name",
",",
"identifier",
")",
":",
"# pylint: disable=no-member",
"message",
"=",
"create",
"(",
"protobuf",
".",
"DEVICE_INFO_MESSAGE",
")",
"info",
"=",
"message",
".",
"inner",
"(",
")",
"info",
".",
"uniqueIdentifier",
"="... | 36.6 | 8.133333 |
def note_create(self, post_id, coor_x, coor_y, width, height, body):
"""Function to create a note (Requires login) (UNTESTED).
Parameters:
post_id (int):
coor_x (int): The x coordinates of the note in pixels,
with respect to the top-left corner of the i... | [
"def",
"note_create",
"(",
"self",
",",
"post_id",
",",
"coor_x",
",",
"coor_y",
",",
"width",
",",
"height",
",",
"body",
")",
":",
"params",
"=",
"{",
"'note[post_id]'",
":",
"post_id",
",",
"'note[x]'",
":",
"coor_x",
",",
"'note[y]'",
":",
"coor_y",
... | 42.272727 | 17.818182 |
def get_output_dir(self, nb):
"""Open a notebook and determine the output directory from the name"""
self.package_dir, self.package_name = self.get_package_dir_name(nb)
return join(self.package_dir, self.package_name) | [
"def",
"get_output_dir",
"(",
"self",
",",
"nb",
")",
":",
"self",
".",
"package_dir",
",",
"self",
".",
"package_name",
"=",
"self",
".",
"get_package_dir_name",
"(",
"nb",
")",
"return",
"join",
"(",
"self",
".",
"package_dir",
",",
"self",
".",
"packa... | 47.6 | 20.4 |
def transpile_modname_source_target(self, spec, modname, source, target):
"""
Calls the original version.
"""
return self.simple_transpile_modname_source_target(
spec, modname, source, target) | [
"def",
"transpile_modname_source_target",
"(",
"self",
",",
"spec",
",",
"modname",
",",
"source",
",",
"target",
")",
":",
"return",
"self",
".",
"simple_transpile_modname_source_target",
"(",
"spec",
",",
"modname",
",",
"source",
",",
"target",
")"
] | 33 | 14.142857 |
def create_server(self, admin_login, admin_password, location):
'''
Create a new Azure SQL Database server.
admin_login:
The administrator login name for the new server.
admin_password:
The administrator login password for the new server.
location:
... | [
"def",
"create_server",
"(",
"self",
",",
"admin_login",
",",
"admin_password",
",",
"location",
")",
":",
"_validate_not_none",
"(",
"'admin_login'",
",",
"admin_login",
")",
"_validate_not_none",
"(",
"'admin_password'",
",",
"admin_password",
")",
"_validate_not_no... | 34.6 | 19.64 |
def _parse_cached(html_dump):
"""Parse html string from cached html files.
Parameters
----------
html_dump : string
HTML content
Returns
-------
translations : list
Translations list.
"""
soup = BeautifulSoup(html_dump, "html.parser")
translations = []
for t... | [
"def",
"_parse_cached",
"(",
"html_dump",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"html_dump",
",",
"\"html.parser\"",
")",
"translations",
"=",
"[",
"]",
"for",
"trans",
"in",
"soup",
".",
"find_all",
"(",
"\"div\"",
",",
"class_",
"=",
"\"translation\... | 35.8125 | 19.78125 |
def get_lat_long(self, callsign, timestamp=timestamp_now):
""" Returns Latitude and Longitude for a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
dict: Containing Latitude and... | [
"def",
"get_lat_long",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"callsign_data",
"=",
"self",
".",
"get_all",
"(",
"callsign",
",",
"timestamp",
"=",
"timestamp",
")",
"return",
"{",
"const",
".",
"LATITUDE",
":",
"ca... | 36.333333 | 26.055556 |
def _parse_txtinfo(self, data):
"""
Converts the python list returned by self._txtinfo_to_python()
to a NetworkX Graph object, which is then returned.
"""
graph = self._init_graph()
for link in data:
graph.add_edge(link['source'],
li... | [
"def",
"_parse_txtinfo",
"(",
"self",
",",
"data",
")",
":",
"graph",
"=",
"self",
".",
"_init_graph",
"(",
")",
"for",
"link",
"in",
"data",
":",
"graph",
".",
"add_edge",
"(",
"link",
"[",
"'source'",
"]",
",",
"link",
"[",
"'target'",
"]",
",",
... | 35.636364 | 10 |
def get_module_files(src_directory, blacklist, list_all=False):
"""given a package directory return a list of all available python
module's files in the package and its subpackages
:type src_directory: str
:param src_directory:
path of the directory corresponding to the package
:type blackli... | [
"def",
"get_module_files",
"(",
"src_directory",
",",
"blacklist",
",",
"list_all",
"=",
"False",
")",
":",
"files",
"=",
"[",
"]",
"for",
"directory",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"src_directory",
")",
":",
"if",
"dir... | 32.885714 | 18.114286 |
def _get_partition(self, org_name, part_name=None):
"""send get partition request to the DCNM.
:param org_name: name of organization
:param part_name: name of partition
"""
if part_name is None:
part_name = self._part_name
url = self._update_part_url % (org_n... | [
"def",
"_get_partition",
"(",
"self",
",",
"org_name",
",",
"part_name",
"=",
"None",
")",
":",
"if",
"part_name",
"is",
"None",
":",
"part_name",
"=",
"self",
".",
"_part_name",
"url",
"=",
"self",
".",
"_update_part_url",
"%",
"(",
"org_name",
",",
"pa... | 39.083333 | 11.166667 |
def pipe(self, target):
"""
Pipes this Recver to *target*. *target* can either be `Sender`_ (or
`Pair`_) or a callable.
If *target* is a Sender, the two pairs are rewired so that sending on
this Recver's Sender will now be directed to the target's Recver::
sender1, ... | [
"def",
"pipe",
"(",
"self",
",",
"target",
")",
":",
"if",
"callable",
"(",
"target",
")",
":",
"sender",
",",
"recver",
"=",
"self",
".",
"hub",
".",
"pipe",
"(",
")",
"# link the two ends in the closure with a strong reference to",
"# prevent them from being gar... | 31.810345 | 20.293103 |
def draw(self, milliseconds):
"""Draws all of the objects in our world."""
cam = Ragnarok.get_world().Camera
camPos = cam.get_world_pos()
self.__sort_draw()
self.clear_backbuffer()
for obj in self.__draw_objects:
#Check to see if the object is visible to the c... | [
"def",
"draw",
"(",
"self",
",",
"milliseconds",
")",
":",
"cam",
"=",
"Ragnarok",
".",
"get_world",
"(",
")",
".",
"Camera",
"camPos",
"=",
"cam",
".",
"get_world_pos",
"(",
")",
"self",
".",
"__sort_draw",
"(",
")",
"self",
".",
"clear_backbuffer",
"... | 46.25 | 11.375 |
def redo(self):
"""Redo the last action.
This will call `redo()` on all controllers involved in this action.
"""
controllers = self.forward()
if controllers is None:
ups = ()
else:
ups = tuple([controller.redo() for
contr... | [
"def",
"redo",
"(",
"self",
")",
":",
"controllers",
"=",
"self",
".",
"forward",
"(",
")",
"if",
"controllers",
"is",
"None",
":",
"ups",
"=",
"(",
")",
"else",
":",
"ups",
"=",
"tuple",
"(",
"[",
"controller",
".",
"redo",
"(",
")",
"for",
"con... | 27.875 | 16.4375 |
def filter(args):
"""
%prog filter fastafile 100
Filter the FASTA file to contain records with size >= or <= certain cutoff.
"""
p = OptionParser(filter.__doc__)
p.add_option("--less", default=False, action="store_true",
help="filter the sizes < certain cutoff [default: >=]")
... | [
"def",
"filter",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"filter",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--less\"",
",",
"default",
"=",
"False",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"filter the sizes < cer... | 23.432432 | 20.675676 |
def _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None):
""" Helper function for _get_data that handles empty lists. """
fields = get_field_list(fields, schema)
return {'cols': _get_cols(fields, schema), 'rows': []}, 0 | [
"def",
"_get_data_from_empty_list",
"(",
"source",
",",
"fields",
"=",
"'*'",
",",
"first_row",
"=",
"0",
",",
"count",
"=",
"-",
"1",
",",
"schema",
"=",
"None",
")",
":",
"fields",
"=",
"get_field_list",
"(",
"fields",
",",
"schema",
")",
"return",
"... | 62.75 | 16.5 |
def augment_cycle(self, amount, cycle):
'''
API:
augment_cycle(self, amount, cycle):
Description:
Augments 'amount' unit of flow along cycle.
Pre:
Arcs should have 'flow' attribute.
Inputs:
amount: An integer representing the amount... | [
"def",
"augment_cycle",
"(",
"self",
",",
"amount",
",",
"cycle",
")",
":",
"index",
"=",
"0",
"k",
"=",
"len",
"(",
"cycle",
")",
"while",
"index",
"<",
"(",
"k",
"-",
"1",
")",
":",
"i",
"=",
"cycle",
"[",
"index",
"]",
"j",
"=",
"cycle",
"... | 34.735294 | 16.852941 |
def _conf(cls, opts):
"""Setup logging via ini-file from logging_conf_file option."""
logging_conf = cls.config.get('core', 'logging_conf_file', None)
if logging_conf is None:
return False
if not os.path.exists(logging_conf):
# FileNotFoundError added only in Pyt... | [
"def",
"_conf",
"(",
"cls",
",",
"opts",
")",
":",
"logging_conf",
"=",
"cls",
".",
"config",
".",
"get",
"(",
"'core'",
",",
"'logging_conf_file'",
",",
"None",
")",
"if",
"logging_conf",
"is",
"None",
":",
"return",
"False",
"if",
"not",
"os",
".",
... | 45.076923 | 24.846154 |
def frequency(self):
"""
How often the recurrence repeats.
("YEARLY", "MONTHLY", "WEEKLY", "DAILY")
"""
freqOptions = ("YEARLY", "MONTHLY", "WEEKLY", "DAILY")
if self.rule._freq < len(freqOptions):
return freqOptions[self.rule._freq]
else:
... | [
"def",
"frequency",
"(",
"self",
")",
":",
"freqOptions",
"=",
"(",
"\"YEARLY\"",
",",
"\"MONTHLY\"",
",",
"\"WEEKLY\"",
",",
"\"DAILY\"",
")",
"if",
"self",
".",
"rule",
".",
"_freq",
"<",
"len",
"(",
"freqOptions",
")",
":",
"return",
"freqOptions",
"[... | 36.8 | 12 |
def reread(self):
"""
Read configuration file and substitute references into checks conf
"""
logger.debug("Loading settings from %s",
os.path.abspath(self.filename))
conf = self.read_conf()
changed = self.creds.reread()
checks = self.parser.pa... | [
"def",
"reread",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Loading settings from %s\"",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"filename",
")",
")",
"conf",
"=",
"self",
".",
"read_conf",
"(",
")",
"changed",
"=",
"self"... | 32.5 | 12.071429 |
def parse_to_slug(words, maxlen=24):
"""
Parse a string into a slug format suitable for use in URLs and other
character restricted applications. Only utf-8 strings are supported at this
time.
:param str words: The words to parse.
:param int maxlen: The maximum length of the slug.
:return: The parsed words as a ... | [
"def",
"parse_to_slug",
"(",
"words",
",",
"maxlen",
"=",
"24",
")",
":",
"slug",
"=",
"''",
"maxlen",
"=",
"min",
"(",
"maxlen",
",",
"len",
"(",
"words",
")",
")",
"for",
"c",
"in",
"words",
":",
"if",
"len",
"(",
"slug",
")",
"==",
"maxlen",
... | 24.3 | 18.366667 |
def _make_mask(self, data, lon_str=LON_STR, lat_str=LAT_STR):
"""Construct the mask that defines a region on a given data's grid."""
mask = False
for west, east, south, north in self.mask_bounds:
if west < east:
mask_lon = (data[lon_str] > west) & (data[lon_str] < eas... | [
"def",
"_make_mask",
"(",
"self",
",",
"data",
",",
"lon_str",
"=",
"LON_STR",
",",
"lat_str",
"=",
"LAT_STR",
")",
":",
"mask",
"=",
"False",
"for",
"west",
",",
"east",
",",
"south",
",",
"north",
"in",
"self",
".",
"mask_bounds",
":",
"if",
"west"... | 48.909091 | 19.636364 |
def set_playback(self, playback):
"""Send Playback command."""
req_url = ENDPOINTS["setPlayback"].format(self._ip_address)
params = {"playback": playback}
return request(req_url, params=params) | [
"def",
"set_playback",
"(",
"self",
",",
"playback",
")",
":",
"req_url",
"=",
"ENDPOINTS",
"[",
"\"setPlayback\"",
"]",
".",
"format",
"(",
"self",
".",
"_ip_address",
")",
"params",
"=",
"{",
"\"playback\"",
":",
"playback",
"}",
"return",
"request",
"("... | 44.2 | 8.2 |
def parse_rfc3339_utc_string(rfc3339_utc_string):
"""Converts a datestamp from RFC3339 UTC to a datetime.
Args:
rfc3339_utc_string: a datetime string in RFC3339 UTC "Zulu" format
Returns:
A datetime.
"""
# The timestamp from the Google Operations are all in RFC3339 format, but
# they are sometime... | [
"def",
"parse_rfc3339_utc_string",
"(",
"rfc3339_utc_string",
")",
":",
"# The timestamp from the Google Operations are all in RFC3339 format, but",
"# they are sometimes formatted to millisconds, microseconds, sometimes",
"# nanoseconds, and sometimes only seconds:",
"# * 2016-11-14T23:05:56Z",
... | 34.017544 | 21.947368 |
def set_max_string_length(self, length=None):
"""stub"""
if self.get_max_string_length_metadata().is_read_only():
raise NoAccess()
if not self.my_osid_object_form._is_valid_cardinal(
length,
self.get_max_string_length_metadata()):
raise Inv... | [
"def",
"set_max_string_length",
"(",
"self",
",",
"length",
"=",
"None",
")",
":",
"if",
"self",
".",
"get_max_string_length_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
":",
"raise",
"NoAccess",
"(",
")",
"if",
"not",
"self",
".",
"my_osid_object_for... | 47.153846 | 14.846154 |
def rnormal(mu, tau, size=None):
"""
Random normal variates.
"""
return np.random.normal(mu, 1. / np.sqrt(tau), size) | [
"def",
"rnormal",
"(",
"mu",
",",
"tau",
",",
"size",
"=",
"None",
")",
":",
"return",
"np",
".",
"random",
".",
"normal",
"(",
"mu",
",",
"1.",
"/",
"np",
".",
"sqrt",
"(",
"tau",
")",
",",
"size",
")"
] | 25.8 | 7.4 |
def read(self, vals):
"""Read values.
Args:
vals (list): list of strings representing values
"""
i = 0
count = int(vals[i])
i += 1
for _ in range(count):
obj = GroundTemperature()
obj.read(vals[i:i + obj.field_count])
... | [
"def",
"read",
"(",
"self",
",",
"vals",
")",
":",
"i",
"=",
"0",
"count",
"=",
"int",
"(",
"vals",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"for",
"_",
"in",
"range",
"(",
"count",
")",
":",
"obj",
"=",
"GroundTemperature",
"(",
")",
"obj",
".",
... | 25 | 16.333333 |
def get_extension_attribute(self, ext_name, key):
"""
Banana banana
"""
attributes = self.extension_attributes.get(ext_name)
if not attributes:
return None
return attributes.get(key) | [
"def",
"get_extension_attribute",
"(",
"self",
",",
"ext_name",
",",
"key",
")",
":",
"attributes",
"=",
"self",
".",
"extension_attributes",
".",
"get",
"(",
"ext_name",
")",
"if",
"not",
"attributes",
":",
"return",
"None",
"return",
"attributes",
".",
"ge... | 29.375 | 10.625 |
def abs(x, context=None):
"""
Return abs(x).
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_abs,
(BigFloat._implicit_convert(x),),
context,
) | [
"def",
"abs",
"(",
"x",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_abs",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
")",
",",
"context",
",",
")... | 18.545455 | 16.727273 |
def metadefs_namespace_list(request,
filters=None,
sort_dir='asc',
sort_key='namespace',
marker=None,
paginate=False):
"""Retrieve a listing of Namespaces
:param paginate:... | [
"def",
"metadefs_namespace_list",
"(",
"request",
",",
"filters",
"=",
"None",
",",
"sort_dir",
"=",
"'asc'",
",",
"sort_key",
"=",
"'namespace'",
",",
"marker",
"=",
"None",
",",
"paginate",
"=",
"False",
")",
":",
"# Listing namespaces requires the v2 API. If no... | 40.309524 | 18.595238 |
def _get_name(self):
"""Find name of scoring function."""
if self.name is not None:
return self.name
if self.scoring_ is None:
return 'score'
if isinstance(self.scoring_, str):
return self.scoring_
if isinstance(self.scoring_, partial):
... | [
"def",
"_get_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"name",
"is",
"not",
"None",
":",
"return",
"self",
".",
"name",
"if",
"self",
".",
"scoring_",
"is",
"None",
":",
"return",
"'score'",
"if",
"isinstance",
"(",
"self",
".",
"scoring_",
",... | 37.692308 | 8.307692 |
def image_by_id(self, id):
"""
Return image with given Id
"""
if not id:
return None
return next((image for image in self.images() if image['Id'] == id),
None) | [
"def",
"image_by_id",
"(",
"self",
",",
"id",
")",
":",
"if",
"not",
"id",
":",
"return",
"None",
"return",
"next",
"(",
"(",
"image",
"for",
"image",
"in",
"self",
".",
"images",
"(",
")",
"if",
"image",
"[",
"'Id'",
"]",
"==",
"id",
")",
",",
... | 28 | 13.75 |
def attach_session(self):
"""Return ``$ tmux attach-session`` aka alias: ``$ tmux attach``."""
proc = self.cmd('attach-session', '-t%s' % self.id)
if proc.stderr:
raise exc.LibTmuxException(proc.stderr) | [
"def",
"attach_session",
"(",
"self",
")",
":",
"proc",
"=",
"self",
".",
"cmd",
"(",
"'attach-session'",
",",
"'-t%s'",
"%",
"self",
".",
"id",
")",
"if",
"proc",
".",
"stderr",
":",
"raise",
"exc",
".",
"LibTmuxException",
"(",
"proc",
".",
"stderr",... | 39 | 17 |
def __draw_cluster_item_multi_dimension(self, ax, pair, item, cluster_descr):
"""!
@brief Draw cluster chunk defined by pair coordinates in data space with dimension greater than 1.
@param[in] ax (axis): Matplotlib axis that is used to display chunk of cluster point.
@param[in] pai... | [
"def",
"__draw_cluster_item_multi_dimension",
"(",
"self",
",",
"ax",
",",
"pair",
",",
"item",
",",
"cluster_descr",
")",
":",
"index_dimension1",
"=",
"pair",
"[",
"0",
"]",
"index_dimension2",
"=",
"pair",
"[",
"1",
"]",
"if",
"cluster_descr",
".",
"data"... | 54.25 | 36.3 |
async def get_txn(self, seq_no: int) -> str:
"""
Find a transaction on the distributed ledger by its sequence number.
:param seq_no: transaction number
:return: json sequence number of transaction, null for no match
"""
LOGGER.debug('BaseAnchor.get_txn >>> seq_no: %s', ... | [
"async",
"def",
"get_txn",
"(",
"self",
",",
"seq_no",
":",
"int",
")",
"->",
"str",
":",
"LOGGER",
".",
"debug",
"(",
"'BaseAnchor.get_txn >>> seq_no: %s'",
",",
"seq_no",
")",
"rv_json",
"=",
"json",
".",
"dumps",
"(",
"{",
"}",
")",
"req_json",
"=",
... | 34.111111 | 22.444444 |
def deprecated(new_name: str):
"""
This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
"""
def decorator(func):
@wraps(func)
def new_func(*args, **kwargs):
warnings.simplefilter('a... | [
"def",
"deprecated",
"(",
"new_name",
":",
"str",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"'a... | 38.285714 | 15.428571 |
def get_all(
self, target_resource=None, target_resource_group=None, target_resource_type=None, monitor_service=None, monitor_condition=None, severity=None, smart_group_state=None, time_range=None, page_count=None, sort_by=None, sort_order=None, custom_headers=None, raw=False, **operation_config):
"... | [
"def",
"get_all",
"(",
"self",
",",
"target_resource",
"=",
"None",
",",
"target_resource_group",
"=",
"None",
",",
"target_resource_type",
"=",
"None",
",",
"monitor_service",
"=",
"None",
",",
"monitor_condition",
"=",
"None",
",",
"severity",
"=",
"None",
"... | 55.874016 | 28.661417 |
def args_as_tuple(self):
"""Return arguments as a list."""
result = ("body", )
result = result + (
self.arguments["body-transform"], self.arguments["match-type"])
if self.arguments["key-list"].startswith("["):
result = result + tuple(
tools.to_list... | [
"def",
"args_as_tuple",
"(",
"self",
")",
":",
"result",
"=",
"(",
"\"body\"",
",",
")",
"result",
"=",
"result",
"+",
"(",
"self",
".",
"arguments",
"[",
"\"body-transform\"",
"]",
",",
"self",
".",
"arguments",
"[",
"\"match-type\"",
"]",
")",
"if",
... | 40.545455 | 17.181818 |
def _fill_role_cache(self, principal, overwrite=False):
"""Fill role cache for `principal` (User or Group), in order to avoid
too many queries when checking role access with 'has_role'.
Return role_cache of `principal`
"""
if not self.app_state.use_cache:
return None... | [
"def",
"_fill_role_cache",
"(",
"self",
",",
"principal",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"app_state",
".",
"use_cache",
":",
"return",
"None",
"if",
"not",
"self",
".",
"_has_role_cache",
"(",
"principal",
")",
"or",
... | 40.5 | 16 |
def from_dict(cls, copula_dict):
"""Create a new instance from the given parameters.
Args:
copula_dict: `dict` with the parameters to replicate the copula.
Like the output of `Bivariate.to_dict`
Returns:
Bivariate: Instance of the copula defined on the param... | [
"def",
"from_dict",
"(",
"cls",
",",
"copula_dict",
")",
":",
"instance",
"=",
"cls",
"(",
"copula_dict",
"[",
"'copula_type'",
"]",
")",
"instance",
".",
"theta",
"=",
"copula_dict",
"[",
"'theta'",
"]",
"instance",
".",
"tau",
"=",
"copula_dict",
"[",
... | 34.857143 | 17.857143 |
def get_fragment(self, gp, **kwargs):
"""
Return a complete fragment for a given gp.
:param gp: A graph pattern
:return:
"""
collector = FragmentCollector(self.__host, gp)
return collector.get_fragment(**kwargs) | [
"def",
"get_fragment",
"(",
"self",
",",
"gp",
",",
"*",
"*",
"kwargs",
")",
":",
"collector",
"=",
"FragmentCollector",
"(",
"self",
".",
"__host",
",",
"gp",
")",
"return",
"collector",
".",
"get_fragment",
"(",
"*",
"*",
"kwargs",
")"
] | 32.5 | 8 |
def next(self):
"""Returns the next line from this input reader as (lineinfo, line) tuple.
Returns:
The next input from this input reader, in the form of a 2-tuple.
The first element of the tuple describes the source, it is itself
a tuple (blobkey, filenumber, byteoffset).
The second ... | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_filestream",
":",
"if",
"not",
"self",
".",
"_zip",
":",
"self",
".",
"_zip",
"=",
"zipfile",
".",
"ZipFile",
"(",
"self",
".",
"_reader",
"(",
"self",
".",
"_blob_key",
")",
")",
... | 37.815789 | 18.052632 |
def get_version(path=None, module=None):
"""Return the version string.
This function ensures that the version string complies with PEP 440.
The format of our version string is:
- for RELEASE builds:
<major>.<minor>
e.g.
0.1
2.4
- for DEVELOPME... | [
"def",
"get_version",
"(",
"path",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"# Check the module option first.",
"version",
"=",
"get_version_from_module",
"(",
"module",
")",
"if",
"version",
":",
"return",
"normalised",
"(",
"version",
")",
"# Turn pa... | 31.337838 | 19.878378 |
def is_visible(self, pos: Union[Point2, Point3, Unit]) -> bool:
""" Returns True if you have vision on a grid point. """
# more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19
assert isinstance(pos, (Point2, Point3... | [
"def",
"is_visible",
"(",
"self",
",",
"pos",
":",
"Union",
"[",
"Point2",
",",
"Point3",
",",
"Unit",
"]",
")",
"->",
"bool",
":",
"# more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19",
"ass... | 68.166667 | 24.833333 |
def money_flow(close_data, high_data, low_data, volume):
"""
Money Flow.
Formula:
MF = VOLUME * TYPICAL PRICE
"""
catch_errors.check_for_input_len_diff(
close_data, high_data, low_data, volume
)
mf = volume * tp(close_data, high_data, low_data)
return mf | [
"def",
"money_flow",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"volume",
")",
":",
"catch_errors",
".",
"check_for_input_len_diff",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"volume",
")",
"mf",
"=",
"volume",
"*",
"tp",
"("... | 24.333333 | 16.5 |
def password_enter(self, wallet, password):
"""
Enters the **password** in to **wallet**
:param wallet: Wallet to enter password for
:type wallet: str
:param password: Password to enter
:type password: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> r... | [
"def",
"password_enter",
"(",
"self",
",",
"wallet",
",",
"password",
")",
":",
"wallet",
"=",
"self",
".",
"_process_value",
"(",
"wallet",
",",
"'wallet'",
")",
"payload",
"=",
"{",
"\"wallet\"",
":",
"wallet",
",",
"\"password\"",
":",
"password",
"}",
... | 25.222222 | 21.888889 |
def tokeninfo(self, jwt):
"""Returns user profile based on the user's jwt
Validates a JSON Web Token (signature and expiration) and returns the
user information associated with the user id (sub property) of
the token.
Args:
jwt (str): User's jwt
Returns:
... | [
"def",
"tokeninfo",
"(",
"self",
",",
"jwt",
")",
":",
"warnings",
".",
"warn",
"(",
"\"/tokeninfo will be deprecated in future releases\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"post",
"(",
"url",
"=",
"'https://{}/tokeninfo'",
".",
"format",
"(... | 31.2 | 23.6 |
def tableToTsv(self, model):
"""
Takes a model class and attempts to create a table in TSV format
that can be imported into a spreadsheet program.
"""
first = True
for item in model.select():
if first:
header = "".join(
["{}... | [
"def",
"tableToTsv",
"(",
"self",
",",
"model",
")",
":",
"first",
"=",
"True",
"for",
"item",
"in",
"model",
".",
"select",
"(",
")",
":",
"if",
"first",
":",
"header",
"=",
"\"\"",
".",
"join",
"(",
"[",
"\"{}\\t\"",
".",
"format",
"(",
"x",
")... | 36 | 15.375 |
def reffs(self):
""" Get all valid reffs for every part of the CtsText
:rtype: MyCapytain.resources.texts.tei.XmlCtsCitation
"""
if not self.citation.is_set():
self.getLabel()
return [
reff for reffs in [self.getValidReff(level=i) for i in range(1, len(se... | [
"def",
"reffs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"citation",
".",
"is_set",
"(",
")",
":",
"self",
".",
"getLabel",
"(",
")",
"return",
"[",
"reff",
"for",
"reffs",
"in",
"[",
"self",
".",
"getValidReff",
"(",
"level",
"=",
"i",
"... | 35.7 | 23.3 |
def _load_certificate(location):
"""
Load a certificate from the given location.
Args:
location (str): The location to load. This can either be an HTTPS URL or an absolute file
path. This is intended to be used with PEM-encoded certificates and therefore assumes
ASCII encodi... | [
"def",
"_load_certificate",
"(",
"location",
")",
":",
"if",
"location",
".",
"startswith",
"(",
"'https://'",
")",
":",
"_log",
".",
"info",
"(",
"'Downloading x509 certificate from %s'",
",",
"location",
")",
"with",
"requests",
".",
"Session",
"(",
")",
"as... | 39.962963 | 22.407407 |
def create_tar_file(self, full_archive=False):
"""
Create tar file to be compressed
"""
tar_file_name = os.path.join(self.archive_tmp_dir, self.archive_name)
ext = "" if self.compressor == "none" else ".%s" % self.compressor
tar_file_name = tar_file_name + ".tar" + ext
... | [
"def",
"create_tar_file",
"(",
"self",
",",
"full_archive",
"=",
"False",
")",
":",
"tar_file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"archive_tmp_dir",
",",
"self",
".",
"archive_name",
")",
"ext",
"=",
"\"\"",
"if",
"self",
".",
... | 49 | 16.052632 |
def check_appt(self, complex: str, house: str, appt: str) -> bool:
"""
Check if given appartment exists in the rumetr database
"""
self.check_house(complex, house)
if '%s__%s__%s' % (complex, house, appt) in self._checked_appts:
return True
try:
s... | [
"def",
"check_appt",
"(",
"self",
",",
"complex",
":",
"str",
",",
"house",
":",
"str",
",",
"appt",
":",
"str",
")",
"->",
"bool",
":",
"self",
".",
"check_house",
"(",
"complex",
",",
"house",
")",
"if",
"'%s__%s__%s'",
"%",
"(",
"complex",
",",
... | 39.3 | 22.8 |
def submit(self, timestamp):
"""Internal instance method to submit this task for running immediately.
Does not handle any iteration, end-date, etc., processing."""
Channel(RUN_TASK_CHANNEL).send({'id':self.pk, 'ts': timestamp.timestamp()}) | [
"def",
"submit",
"(",
"self",
",",
"timestamp",
")",
":",
"Channel",
"(",
"RUN_TASK_CHANNEL",
")",
".",
"send",
"(",
"{",
"'id'",
":",
"self",
".",
"pk",
",",
"'ts'",
":",
"timestamp",
".",
"timestamp",
"(",
")",
"}",
")"
] | 65 | 13.75 |
def get(self, agentml, user=None, key=None):
"""
Evaluate and return the current active topic
:param user: The active user object
:type user: agentml.User or None
:param agentml: The active AgentML instance
:type agentml: AgentML
:param key: The user id (defau... | [
"def",
"get",
"(",
"self",
",",
"agentml",
",",
"user",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"user",
"=",
"agentml",
".",
"get_user",
"(",
"key",
")",
"if",
"key",
"else",
"user",
"if",
"not",
"user",
":",
"return",
"return",
"user",
"... | 28.1 | 16.5 |
def make_route_refresh_request(self, peer_ip, *route_families):
"""Request route-refresh for peer with `peer_ip` for given
`route_families`.
Will make route-refresh request for a given `route_family` only if such
capability is supported and if peer is in ESTABLISHED state. Else, such
... | [
"def",
"make_route_refresh_request",
"(",
"self",
",",
"peer_ip",
",",
"*",
"route_families",
")",
":",
"LOG",
".",
"debug",
"(",
"'Route refresh requested for peer %s and route families %s'",
",",
"peer_ip",
",",
"route_families",
")",
"if",
"not",
"SUPPORTED_GLOBAL_RF... | 44.393939 | 21.030303 |
def dot_special(x2d, x3d):
"""Segment-wise dot product.
This function calculates the dot product of x2d with each trial of x3d.
Parameters
----------
x2d : array, shape (p, m)
Input argument.
x3d : array, shape (t, m, n)
Segmented input data with t trials, m signals, and n samp... | [
"def",
"dot_special",
"(",
"x2d",
",",
"x3d",
")",
":",
"x3d",
"=",
"atleast_3d",
"(",
"x3d",
")",
"x2d",
"=",
"np",
".",
"atleast_2d",
"(",
"x2d",
")",
"return",
"np",
".",
"concatenate",
"(",
"[",
"x2d",
".",
"dot",
"(",
"x3d",
"[",
"i",
",",
... | 27.033333 | 20.733333 |
def chain(request):
"""shows how the XmlQuerySetChain can be used instead of @toxml decorator"""
bars = foobar_models.Bar.objects.all()
bazs = foobar_models.Baz.objects.all()
qsc = XmlQuerySetChain(bars, bazs)
return HttpResponse(tree.xml(qsc), mimetype='text/xml') | [
"def",
"chain",
"(",
"request",
")",
":",
"bars",
"=",
"foobar_models",
".",
"Bar",
".",
"objects",
".",
"all",
"(",
")",
"bazs",
"=",
"foobar_models",
".",
"Baz",
".",
"objects",
".",
"all",
"(",
")",
"qsc",
"=",
"XmlQuerySetChain",
"(",
"bars",
","... | 46.666667 | 7.666667 |
def send_command_ack(self, device_id, action):
"""Send command, wait for gateway to repond with acknowledgment."""
# serialize commands
yield from self._ready_to_send.acquire()
acknowledgement = None
try:
self._command_ack.clear()
self.send_command(device_... | [
"def",
"send_command_ack",
"(",
"self",
",",
"device_id",
",",
"action",
")",
":",
"# serialize commands",
"yield",
"from",
"self",
".",
"_ready_to_send",
".",
"acquire",
"(",
")",
"acknowledgement",
"=",
"None",
"try",
":",
"self",
".",
"_command_ack",
".",
... | 40.083333 | 17.125 |
def get_prinz_pot(nstep, x0=0., nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0):
r"""wrapper for the Prinz model generator"""
pw = PrinzModel(dt, kT, mass=mass, damping=damping)
return pw.sample(x0, nstep, nskip=nskip) | [
"def",
"get_prinz_pot",
"(",
"nstep",
",",
"x0",
"=",
"0.",
",",
"nskip",
"=",
"1",
",",
"dt",
"=",
"0.01",
",",
"kT",
"=",
"10.0",
",",
"mass",
"=",
"1.0",
",",
"damping",
"=",
"1.0",
")",
":",
"pw",
"=",
"PrinzModel",
"(",
"dt",
",",
"kT",
... | 57.25 | 15.25 |
def tcc(text: str) -> str:
"""
TCC generator, generates Thai Character Clusters
:param str text: text to be tokenized to character clusters
:return: subword (character cluster)
"""
if not text or not isinstance(text, str):
return ""
p = 0
while p < len(text):
m = PAT_TCC... | [
"def",
"tcc",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"text",
"or",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"\"\"",
"p",
"=",
"0",
"while",
"p",
"<",
"len",
"(",
"text",
")",
":",
"m",
"=",
"PAT_... | 24.333333 | 16.444444 |
def serviceViewChangerOutBox(self, limit: int = None) -> int:
"""
Service at most `limit` number of messages from the view_changer's outBox.
:return: the number of messages successfully serviced.
"""
msgCount = 0
while self.view_changer.outBox and (not limit or msgCount ... | [
"def",
"serviceViewChangerOutBox",
"(",
"self",
",",
"limit",
":",
"int",
"=",
"None",
")",
"->",
"int",
":",
"msgCount",
"=",
"0",
"while",
"self",
".",
"view_changer",
".",
"outBox",
"and",
"(",
"not",
"limit",
"or",
"msgCount",
"<",
"limit",
")",
":... | 40.875 | 20.125 |
def find_column(self, token):
""" Compute column:
- token is a token instance
"""
i = token.lexpos
while i > 0:
if self.input_data[i - 1] == '\n':
break
i -= 1
column = token.lexpos - i + 1
return column | [
"def",
"find_column",
"(",
"self",
",",
"token",
")",
":",
"i",
"=",
"token",
".",
"lexpos",
"while",
"i",
">",
"0",
":",
"if",
"self",
".",
"input_data",
"[",
"i",
"-",
"1",
"]",
"==",
"'\\n'",
":",
"break",
"i",
"-=",
"1",
"column",
"=",
"tok... | 24.75 | 13.25 |
def get_stable_entries(self, charge_to_discharge=True):
"""
Get the stable entries.
Args:
charge_to_discharge: order from most charge to most discharged
state? Default to True.
Returns:
A list of stable entries in the electrode, ordered by amount... | [
"def",
"get_stable_entries",
"(",
"self",
",",
"charge_to_discharge",
"=",
"True",
")",
":",
"list_copy",
"=",
"list",
"(",
"self",
".",
"_stable_entries",
")",
"return",
"list_copy",
"if",
"charge_to_discharge",
"else",
"list_copy",
".",
"reverse",
"(",
")"
] | 33.642857 | 20.214286 |
def _calculate_average_field_lengths(self):
"""Calculates the average document length for this index"""
accumulator = defaultdict(int)
documents_with_field = defaultdict(int)
for field_ref, length in self.field_lengths.items():
_field_ref = FieldRef.from_string(field_ref)
... | [
"def",
"_calculate_average_field_lengths",
"(",
"self",
")",
":",
"accumulator",
"=",
"defaultdict",
"(",
"int",
")",
"documents_with_field",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"field_ref",
",",
"length",
"in",
"self",
".",
"field_lengths",
".",
"items"... | 37.0625 | 15.75 |
def main(argv): # pylint: disable=W0613
'''
Main program body
'''
thin_path = os.path.join(OPTIONS.saltdir, THIN_ARCHIVE)
if os.path.isfile(thin_path):
if OPTIONS.checksum != get_hash(thin_path, OPTIONS.hashfunc):
need_deployment()
unpack_thin(thin_path)
# Salt t... | [
"def",
"main",
"(",
"argv",
")",
":",
"# pylint: disable=W0613",
"thin_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"OPTIONS",
".",
"saltdir",
",",
"THIN_ARCHIVE",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"thin_path",
")",
":",
"if",
"OPTI... | 38.459459 | 21.162162 |
def from_spec(spec):
"""Return a schema object from a spec.
A spec is either a string for a scalar type, or a list of 0 or 1 specs,
or a dictionary with two elements: {'fields': { ... }, required: [...]}.
"""
if spec == '':
return any_schema
if framework.is_str(spec):
# Scalar type
if spec not... | [
"def",
"from_spec",
"(",
"spec",
")",
":",
"if",
"spec",
"==",
"''",
":",
"return",
"any_schema",
"if",
"framework",
".",
"is_str",
"(",
"spec",
")",
":",
"# Scalar type",
"if",
"spec",
"not",
"in",
"SCALAR_TYPES",
":",
"raise",
"exceptions",
".",
"Schem... | 31.045455 | 23.363636 |
def is_inside_bounds(value, params):
"""Return ``True`` if ``value`` is contained in ``params``.
This method supports broadcasting in the sense that for
``params.ndim >= 2``, if more than one value is given, the inputs
are broadcast against each other.
Parameters
----------
value : `array-... | [
"def",
"is_inside_bounds",
"(",
"value",
",",
"params",
")",
":",
"if",
"value",
"in",
"params",
":",
"# Single parameter",
"return",
"True",
"else",
":",
"if",
"params",
".",
"ndim",
"==",
"1",
":",
"return",
"params",
".",
"contains_all",
"(",
"np",
".... | 30.365385 | 20.365385 |
def IndexOfNth(s, value, n):
"""Gets the index of Nth occurance of a given character in a string
:param str s:
Input string
:param char value:
Input char to be searched.
:param int n:
Nth occurrence of char to be searched.
:return:
Index of the Nth occurrence in the... | [
"def",
"IndexOfNth",
"(",
"s",
",",
"value",
",",
"n",
")",
":",
"remaining",
"=",
"n",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"s",
")",
")",
":",
"if",
"s",
"[",
"i",
"]",
"==",
"value",
":",
"remaining",
"-=",
"1",
"if",
"... | 22.954545 | 18.409091 |
def csv(cls,
d,
order=None,
header=None,
sort_keys=True):
"""
prints a table in csv format
:param d: A a dict with dicts of the same type.
:type d: dict
:param order:The order in which the columns are printed.
T... | [
"def",
"csv",
"(",
"cls",
",",
"d",
",",
"order",
"=",
"None",
",",
"header",
"=",
"None",
",",
"sort_keys",
"=",
"True",
")",
":",
"first_element",
"=",
"list",
"(",
"d",
")",
"[",
"0",
"]",
"def",
"_keys",
"(",
")",
":",
"return",
"list",
"("... | 28.362069 | 17.948276 |
def update_traded(self, traded_update):
""":param traded_update: [price, size]
"""
if not traded_update:
self.traded.clear()
else:
self.traded.update(traded_update) | [
"def",
"update_traded",
"(",
"self",
",",
"traded_update",
")",
":",
"if",
"not",
"traded_update",
":",
"self",
".",
"traded",
".",
"clear",
"(",
")",
"else",
":",
"self",
".",
"traded",
".",
"update",
"(",
"traded_update",
")"
] | 30.571429 | 7.571429 |
def bitsetxor(b1, b2):
"""
If b1 and b2 would be ``int`` s this would be ``b1 ^ b2`` :
>>> from py_register_machine2.engine_tools.operations import bitsetxor
>>> b1 = [1, 1, 1, 1]
>>> b2 = [1, 1, 0, 1]
>>> bitsetxor(b1, b2)
[0, 0, 1, 0]
>>> bin(0b1111 ^ 0b1101)
'0b10'
"""
res = []
for bit1, bit2 in zip(b1,... | [
"def",
"bitsetxor",
"(",
"b1",
",",
"b2",
")",
":",
"res",
"=",
"[",
"]",
"for",
"bit1",
",",
"bit2",
"in",
"zip",
"(",
"b1",
",",
"b2",
")",
":",
"res",
".",
"append",
"(",
"bit1",
"^",
"bit2",
")",
"return",
"res"
] | 21.8125 | 20.0625 |
async def modify(self, **kwargs):
'''
Corresponds to PATCH request with a resource identifier, modifying a single document in the database
'''
try:
pk = self.pk_type(kwargs['pk'])
# modify is a class method on MongoCollectionMixin
result = await self._... | [
"async",
"def",
"modify",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"pk",
"=",
"self",
".",
"pk_type",
"(",
"kwargs",
"[",
"'pk'",
"]",
")",
"# modify is a class method on MongoCollectionMixin",
"result",
"=",
"await",
"self",
".",
"_meta... | 45 | 23.285714 |
def check_sysdeps(vext_files):
"""
Check that imports in 'test_imports' succeed
otherwise display message in 'install_hints'
"""
@run_in_syspy
def run(*modules):
result = {}
for m in modules:
if m:
try:
__import__(m)
... | [
"def",
"check_sysdeps",
"(",
"vext_files",
")",
":",
"@",
"run_in_syspy",
"def",
"run",
"(",
"*",
"modules",
")",
":",
"result",
"=",
"{",
"}",
"for",
"m",
"in",
"modules",
":",
"if",
"m",
":",
"try",
":",
"__import__",
"(",
"m",
")",
"result",
"["... | 31.588235 | 15.588235 |
def _read_vector(ctx: ReaderContext) -> vector.Vector:
"""Read a vector element from the input stream."""
start = ctx.reader.advance()
assert start == "["
return _read_coll(ctx, vector.vector, "]", "vector") | [
"def",
"_read_vector",
"(",
"ctx",
":",
"ReaderContext",
")",
"->",
"vector",
".",
"Vector",
":",
"start",
"=",
"ctx",
".",
"reader",
".",
"advance",
"(",
")",
"assert",
"start",
"==",
"\"[\"",
"return",
"_read_coll",
"(",
"ctx",
",",
"vector",
".",
"v... | 43.8 | 11 |
def _get_last_node_for_prfx(self, node, key_prfx, seen_prfx):
""" get last node for the given prefix, also update `seen_prfx` to track the path already traversed
:param node: node in form of list, or BLANK_NODE
:param key_prfx: prefix to look for
:param seen_prfx: prefix already seen, u... | [
"def",
"_get_last_node_for_prfx",
"(",
"self",
",",
"node",
",",
"key_prfx",
",",
"seen_prfx",
")",
":",
"node_type",
"=",
"self",
".",
"_get_node_type",
"(",
"node",
")",
"if",
"node_type",
"==",
"NODE_TYPE_BLANK",
":",
"return",
"BLANK_NODE",
"if",
"node_typ... | 41.1 | 18.02 |
def setup_console_logger(log_level='error', log_format=None, date_format=None):
'''
Setup the console logger
'''
if is_console_configured():
logging.getLogger(__name__).warning('Console logging already configured')
return
# Remove the temporary logging handler
__remove_temp_logg... | [
"def",
"setup_console_logger",
"(",
"log_level",
"=",
"'error'",
",",
"log_format",
"=",
"None",
",",
"date_format",
"=",
"None",
")",
":",
"if",
"is_console_configured",
"(",
")",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"warning",
"(",
... | 27.897959 | 20.061224 |
def fit(self, X, y):
"""Scikit-learn required: Computes the feature importance scores from the training data.
Parameters
----------
X: array-like {n_samples, n_features}
Training instances to compute the feature importance scores from
y: array-like {n_samples}
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"self",
".",
"_X",
"=",
"X",
"# matrix of predictive variables ('independent variables')",
"self",
".",
"_y",
"=",
"y",
"# vector of values for outcome variable ('dependent variable')",
"# Set up the properties for ... | 48.171875 | 28.40625 |
def calculate_gru_output_shapes(operator):
'''
See GRU's conversion function for its output shapes.
'''
check_input_and_output_numbers(operator, input_count_range=[1, 2], output_count_range=[1, 2])
check_input_and_output_types(operator, good_input_types=[FloatTensorType])
input_shape = operator... | [
"def",
"calculate_gru_output_shapes",
"(",
"operator",
")",
":",
"check_input_and_output_numbers",
"(",
"operator",
",",
"input_count_range",
"=",
"[",
"1",
",",
"2",
"]",
",",
"output_count_range",
"=",
"[",
"1",
",",
"2",
"]",
")",
"check_input_and_output_types"... | 45.40625 | 28.21875 |
def check_name(self, name=None):
'''
Checks the plugin name and sets it accordingly.
Uses name if specified, class name if not set.
'''
if name:
self.plugin_info['check_name'] = name
if self.plugin_info['check_name'] is not None:
return self.plugi... | [
"def",
"check_name",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
":",
"self",
".",
"plugin_info",
"[",
"'check_name'",
"]",
"=",
"name",
"if",
"self",
".",
"plugin_info",
"[",
"'check_name'",
"]",
"is",
"not",
"None",
":",
"return",
... | 30.75 | 19.416667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.