text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def geo_max_distance(left, right):
"""Returns the 2-dimensional maximum distance between two geometries in
projected units. If g1 and g2 is the same geometry the function will
return the distance between the two vertices most far from each other
in that geometry
Parameters
----------
left :... | [
"def",
"geo_max_distance",
"(",
"left",
",",
"right",
")",
":",
"op",
"=",
"ops",
".",
"GeoMaxDistance",
"(",
"left",
",",
"right",
")",
"return",
"op",
".",
"to_expr",
"(",
")"
] | 27.294118 | 20.470588 |
def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Makes a best effort to watch for a key or tree change in etcd.
Returns a dict containing the new key value ( or None if the key was
deleted ), the modifiedIndex of the key, whether the key c... | [
"def",
"watch",
"(",
"key",
",",
"recurse",
"=",
"False",
",",
"profile",
"=",
"None",
",",
"timeout",
"=",
"0",
",",
"index",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"__utils__",
"[",
"'etcd_util.get_conn'",
"]",
"(",
"__opts_... | 38.956522 | 29.913043 |
def to_array(self):
"""
Serializes this KeyboardButton to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(KeyboardButton, self).to_array()
array['text'] = u(self.text) # py2: type unicode, py3: type str
if... | [
"def",
"to_array",
"(",
"self",
")",
":",
"array",
"=",
"super",
"(",
"KeyboardButton",
",",
"self",
")",
".",
"to_array",
"(",
")",
"array",
"[",
"'text'",
"]",
"=",
"u",
"(",
"self",
".",
"text",
")",
"# py2: type unicode, py3: type str",
"if",
"self",... | 37.8 | 20.466667 |
def __get_button_events(self, state, timeval=None):
"""Get the button events from xinput."""
changed_buttons = self.__detect_button_events(state)
events = self.__emulate_buttons(changed_buttons, timeval)
return events | [
"def",
"__get_button_events",
"(",
"self",
",",
"state",
",",
"timeval",
"=",
"None",
")",
":",
"changed_buttons",
"=",
"self",
".",
"__detect_button_events",
"(",
"state",
")",
"events",
"=",
"self",
".",
"__emulate_buttons",
"(",
"changed_buttons",
",",
"tim... | 49 | 15 |
def merge_lvm_data(primary, secondary, name_key):
"""
Returns a dictionary containing the set of data from primary and secondary
where values in primary will always be returned if present, and values in
secondary will only be returned if not present in primary, or if the value
in primary is `None`.
... | [
"def",
"merge_lvm_data",
"(",
"primary",
",",
"secondary",
",",
"name_key",
")",
":",
"pri_data",
"=",
"to_name_key_dict",
"(",
"primary",
",",
"name_key",
")",
"# Prime results with secondary data, to be updated with primary data",
"combined_data",
"=",
"to_name_key_dict",... | 39.217391 | 23.913043 |
def _GetRealImagArray(Array):
"""
Returns the real and imaginary components of each element in an array and returns them in 2 resulting arrays.
Parameters
----------
Array : ndarray
Input array
Returns
-------
RealArray : ndarray
The real components of the input array
... | [
"def",
"_GetRealImagArray",
"(",
"Array",
")",
":",
"ImagArray",
"=",
"_np",
".",
"array",
"(",
"[",
"num",
".",
"imag",
"for",
"num",
"in",
"Array",
"]",
")",
"RealArray",
"=",
"_np",
".",
"array",
"(",
"[",
"num",
".",
"real",
"for",
"num",
"in",... | 27.684211 | 21.263158 |
def convert_string_to_type(string_value):
"""Converts a string into a type or class
:param string_value: the string to be converted, e.g. "int"
:return: The type derived from string_value, e.g. int
"""
# If the parameter is already a type, return it
if string_value in ['None', type(None).__name... | [
"def",
"convert_string_to_type",
"(",
"string_value",
")",
":",
"# If the parameter is already a type, return it",
"if",
"string_value",
"in",
"[",
"'None'",
",",
"type",
"(",
"None",
")",
".",
"__name__",
"]",
":",
"return",
"type",
"(",
"None",
")",
"if",
"isi... | 32.631579 | 15.368421 |
def _create_pileup(bam_file, data, out_base, background):
"""Create pileup calls in the regions of interest for hg19 -> GRCh37 chromosome mapping.
"""
out_file = "%s-mpileup.txt" % out_base
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
back... | [
"def",
"_create_pileup",
"(",
"bam_file",
",",
"data",
",",
"out_base",
",",
"background",
")",
":",
"out_file",
"=",
"\"%s-mpileup.txt\"",
"%",
"out_base",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
... | 64.434783 | 25.521739 |
def gauss_jordan(A, x, b):
"""Linear equation system Ax=b by Gauss-Jordan
:param A: n by m matrix
:param x: table of size n
:param b: table of size m
:modifies: x will contain solution if any
:returns int:
0 if no solution,
1 if solution unique,
2 otherwise
:co... | [
"def",
"gauss_jordan",
"(",
"A",
",",
"x",
",",
"b",
")",
":",
"n",
"=",
"len",
"(",
"x",
")",
"m",
"=",
"len",
"(",
"b",
")",
"assert",
"len",
"(",
"A",
")",
"==",
"m",
"and",
"len",
"(",
"A",
"[",
"0",
"]",
")",
"==",
"n",
"S",
"=",
... | 28.625 | 13.65625 |
def dependencies_order_of_build(target_contract, dependencies_map):
""" Return an ordered list of contracts that is sufficient to successfully
deploy the target contract.
Note:
This function assumes that the `dependencies_map` is an acyclic graph.
"""
if not dependencies_map:
return... | [
"def",
"dependencies_order_of_build",
"(",
"target_contract",
",",
"dependencies_map",
")",
":",
"if",
"not",
"dependencies_map",
":",
"return",
"[",
"target_contract",
"]",
"if",
"target_contract",
"not",
"in",
"dependencies_map",
":",
"raise",
"ValueError",
"(",
"... | 31.741935 | 21.387097 |
def __remove_obsolete_metadata(self):
"""
Removes obsolete entries from the metadata of all stored routines.
"""
clean = {}
for key, _ in self._source_file_names.items():
if key in self._pystratum_metadata:
clean[key] = self._pystratum_metadata[key]
... | [
"def",
"__remove_obsolete_metadata",
"(",
"self",
")",
":",
"clean",
"=",
"{",
"}",
"for",
"key",
",",
"_",
"in",
"self",
".",
"_source_file_names",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
".",
"_pystratum_metadata",
":",
"clean",
"[",
... | 35 | 13.8 |
def config_present(name):
'''
Ensure a specific configuration line exists in the running config
name
config line to set
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE gro... | [
"def",
"config_present",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"matches",
"=",
"__salt__",
"[",
"'onyx.cmd'",
"]",
"(",
"'find'... | 27.333333 | 22.784314 |
def update_todo_menu(self):
"""Update todo list menu"""
editorstack = self.get_current_editorstack()
results = editorstack.get_todo_results()
self.todo_menu.clear()
filename = self.get_current_filename()
for text, line0 in results:
icon = ima.icon('todo... | [
"def",
"update_todo_menu",
"(",
"self",
")",
":",
"editorstack",
"=",
"self",
".",
"get_current_editorstack",
"(",
")",
"results",
"=",
"editorstack",
".",
"get_todo_results",
"(",
")",
"self",
".",
"todo_menu",
".",
"clear",
"(",
")",
"filename",
"=",
"self... | 45.75 | 11.916667 |
def __pop_params(self, tid):
"""
Forgets the arguments tuple for the last call to the hooked function
from this thread.
@type tid: int
@param tid: Thread global ID.
"""
stack = self.__paramStack[tid]
stack.pop()
if not stack:
del self... | [
"def",
"__pop_params",
"(",
"self",
",",
"tid",
")",
":",
"stack",
"=",
"self",
".",
"__paramStack",
"[",
"tid",
"]",
"stack",
".",
"pop",
"(",
")",
"if",
"not",
"stack",
":",
"del",
"self",
".",
"__paramStack",
"[",
"tid",
"]"
] | 27.25 | 13.916667 |
def api_path_map(self):
"""Cached dict of api_path: func."""
if self._api_path_cache is None:
self._api_path_cache = {
api_path: func
for api_path, func
in api_endpoints(self)
}
return self._api_path_cache | [
"def",
"api_path_map",
"(",
"self",
")",
":",
"if",
"self",
".",
"_api_path_cache",
"is",
"None",
":",
"self",
".",
"_api_path_cache",
"=",
"{",
"api_path",
":",
"func",
"for",
"api_path",
",",
"func",
"in",
"api_endpoints",
"(",
"self",
")",
"}",
"retur... | 32.555556 | 7.888889 |
def get_apex(self, lat, height=None):
""" Calculate apex height
Parameters
-----------
lat : (float)
Latitude in degrees
height : (float or NoneType)
Height above the surface of the earth in km or NoneType to use
reference height (default=None... | [
"def",
"get_apex",
"(",
"self",
",",
"lat",
",",
"height",
"=",
"None",
")",
":",
"lat",
"=",
"helpers",
".",
"checklat",
"(",
"lat",
",",
"name",
"=",
"'alat'",
")",
"if",
"height",
"is",
"None",
":",
"height",
"=",
"self",
".",
"refh",
"cos_lat_s... | 28.416667 | 17.75 |
def load_xml_db(self):
"""Load the Lutron database from the server."""
import urllib.request
xmlfile = urllib.request.urlopen('http://' + self._host + '/DbXmlInfo.xml')
xml_db = xmlfile.read()
xmlfile.close()
_LOGGER.info("Loaded xml db")
parser = LutronXmlDbParser(lutron=self, xml_db_str=... | [
"def",
"load_xml_db",
"(",
"self",
")",
":",
"import",
"urllib",
".",
"request",
"xmlfile",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"'http://'",
"+",
"self",
".",
"_host",
"+",
"'/DbXmlInfo.xml'",
")",
"xml_db",
"=",
"xmlfile",
".",
"read",
"... | 30.5 | 20.555556 |
def start_roles(self, service_name, deployment_name, role_names):
'''
Starts the specified virtual machines.
service_name:
The name of the service.
deployment_name:
The name of the deployment.
role_names:
The names of the roles, as an enumerab... | [
"def",
"start_roles",
"(",
"self",
",",
"service_name",
",",
"deployment_name",
",",
"role_names",
")",
":",
"_validate_not_none",
"(",
"'service_name'",
",",
"service_name",
")",
"_validate_not_none",
"(",
"'deployment_name'",
",",
"deployment_name",
")",
"_validate_... | 39.388889 | 19.277778 |
def check_node_position(
cls, parent_id, position, on_same_branch, db_session=None, *args, **kwargs
):
"""
Checks if node position for given parent is valid, raises exception if
this is not the case
:param parent_id:
:param position:
:param on_same_branch: in... | [
"def",
"check_node_position",
"(",
"cls",
",",
"parent_id",
",",
"position",
",",
"on_same_branch",
",",
"db_session",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"db_session",
"=",
"get_db_session",
"(",
"db_session",
")",
"if",
"not... | 38.416667 | 20.25 |
def _proposal_params(self, state):
"""
Proposal parameters
Calculate parameters needed for the proposal.
Inputs :
state :
x :
the present sample, the place to linearize around
f : f(x),
function value at x
J : ... | [
"def",
"_proposal_params",
"(",
"self",
",",
"state",
")",
":",
"x",
"=",
"state",
"[",
"'x'",
"]",
"f",
"=",
"state",
"[",
"'f'",
"]",
"J",
"=",
"state",
"[",
"'J'",
"]",
"JJ",
"=",
"np",
".",
"dot",
"(",
"J",
".",
"T",
",",
"J",
")",
"if"... | 28.659091 | 16.159091 |
def list_dir(self, context):
"""Return a listing of all of the functions in this context including builtins.
Args:
context (object): The context to print a directory for.
Returns:
str
"""
doc = inspect.getdoc(context)
listing = ""
listi... | [
"def",
"list_dir",
"(",
"self",
",",
"context",
")",
":",
"doc",
"=",
"inspect",
".",
"getdoc",
"(",
"context",
")",
"listing",
"=",
"\"\"",
"listing",
"+=",
"\"\\n\"",
"listing",
"+=",
"annotate",
".",
"context_name",
"(",
"context",
")",
"+",
"\"\\n\""... | 27.240741 | 20.537037 |
def encode(self, b64=False):
"""Encode the payload for transmission."""
encoded_payload = b''
for pkt in self.packets:
encoded_packet = pkt.encode(b64=b64)
packet_len = len(encoded_packet)
if b64:
encoded_payload += str(packet_len).encode('utf-... | [
"def",
"encode",
"(",
"self",
",",
"b64",
"=",
"False",
")",
":",
"encoded_payload",
"=",
"b''",
"for",
"pkt",
"in",
"self",
".",
"packets",
":",
"encoded_packet",
"=",
"pkt",
".",
"encode",
"(",
"b64",
"=",
"b64",
")",
"packet_len",
"=",
"len",
"(",... | 41.05 | 13.15 |
def get_assessment_parts_by_ids(self, assessment_part_ids):
"""Gets an ``AssessmentPartList`` corresponding to the given ``IdList``.
arg: assessment_part_ids (osid.id.IdList): the list of
``Ids`` to retrieve
return: (osid.assessment.authoring.AssessmentPartList) - the
... | [
"def",
"get_assessment_parts_by_ids",
"(",
"self",
",",
"assessment_part_ids",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resources_by_ids",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClientValidated",
... | 49.323529 | 17.941176 |
def GetMACBRepresentation(self, event):
"""Retrieves the MACB representation.
Args:
event (EventObject): event.
Returns:
str: MACB representation.
"""
data_type = getattr(event, 'data_type', None)
if not data_type:
return '....'
# The filestat parser is somewhat limited.... | [
"def",
"GetMACBRepresentation",
"(",
"self",
",",
"event",
")",
":",
"data_type",
"=",
"getattr",
"(",
"event",
",",
"'data_type'",
",",
"None",
")",
"if",
"not",
"data_type",
":",
"return",
"'....'",
"# The filestat parser is somewhat limited.",
"if",
"data_type"... | 32.514286 | 15.514286 |
def fire_event(self, event_name, service_name, default=None):
"""
Fire a data_ready, data_lost, start, or stop event on a given service.
"""
service = self.get_service(service_name)
callbacks = service.get(event_name, default)
if not callbacks:
return
... | [
"def",
"fire_event",
"(",
"self",
",",
"event_name",
",",
"service_name",
",",
"default",
"=",
"None",
")",
":",
"service",
"=",
"self",
".",
"get_service",
"(",
"service_name",
")",
"callbacks",
"=",
"service",
".",
"get",
"(",
"event_name",
",",
"default... | 38.933333 | 12.533333 |
def help_center_section_articles(self, id, locale=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles"
api_path = "/api/v2/help_center/sections/{id}/articles.json"
api_path = api_path.format(id=id)
if locale:
api_opt_path = "/api/v... | [
"def",
"help_center_section_articles",
"(",
"self",
",",
"id",
",",
"locale",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/sections/{id}/articles.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id"... | 59.25 | 24.75 |
def register(self, func):
""" Register function to templates. """
if callable(func):
self.functions[func.__name__] = func
return func | [
"def",
"register",
"(",
"self",
",",
"func",
")",
":",
"if",
"callable",
"(",
"func",
")",
":",
"self",
".",
"functions",
"[",
"func",
".",
"__name__",
"]",
"=",
"func",
"return",
"func"
] | 33 | 11.6 |
def delete(key, service=None, profile=None): # pylint: disable=W0613
'''
Get a value from the etcd service
'''
client = _get_conn(profile)
try:
client.delete(key)
return True
except Exception:
return False | [
"def",
"delete",
"(",
"key",
",",
"service",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"# pylint: disable=W0613",
"client",
"=",
"_get_conn",
"(",
"profile",
")",
"try",
":",
"client",
".",
"delete",
"(",
"key",
")",
"return",
"True",
"except",... | 24.5 | 21.3 |
def _try_pydatetime(x):
"""Try to convert to pandas objects to datetimes.
Plotly doesn't know how to handle them.
"""
try:
# for datetimeindex
x = [y.isoformat() for y in x.to_pydatetime()]
except AttributeError:
pass
try:
# for generic series
x = [y.isof... | [
"def",
"_try_pydatetime",
"(",
"x",
")",
":",
"try",
":",
"# for datetimeindex",
"x",
"=",
"[",
"y",
".",
"isoformat",
"(",
")",
"for",
"y",
"in",
"x",
".",
"to_pydatetime",
"(",
")",
"]",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"# for gen... | 24.75 | 18.25 |
def get_item_metadata(self, handle):
"""Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
... | [
"def",
"get_item_metadata",
"(",
"self",
",",
"handle",
")",
":",
"if",
"not",
"self",
".",
"_metadata_dir_exists",
"(",
")",
":",
"return",
"{",
"}",
"prefix",
"=",
"self",
".",
"_handle_to_fragment_absprefixpath",
"(",
"handle",
")",
"files",
"=",
"[",
"... | 32.423077 | 20.461538 |
def register_handler(self, callable_obj, entrypoint, methods=('GET',)):
"""Register a handler callable to a specific route.
Args:
entrypoint (str): The uri relative path.
methods (tuple): A tuple of valid method strings.
callable_obj (callable): The callable object.
... | [
"def",
"register_handler",
"(",
"self",
",",
"callable_obj",
",",
"entrypoint",
",",
"methods",
"=",
"(",
"'GET'",
",",
")",
")",
":",
"router_obj",
"=",
"Route",
".",
"wrap_callable",
"(",
"uri",
"=",
"entrypoint",
",",
"methods",
"=",
"methods",
",",
"... | 29.580645 | 20.354839 |
def license(self, license_id: str, token: dict = None, prot: str = "https") -> dict:
"""Get details about a specific license.
:param str token: API auth token
:param str license_id: license UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs).
... | [
"def",
"license",
"(",
"self",
",",
"license_id",
":",
"str",
",",
"token",
":",
"dict",
"=",
"None",
",",
"prot",
":",
"str",
"=",
"\"https\"",
")",
"->",
"dict",
":",
"# handling request parameters",
"payload",
"=",
"{",
"\"lid\"",
":",
"license_id",
"... | 30.428571 | 15.892857 |
def build_pos_grid(start, end, nstep, mesh=False):
"""
Return a grid of positions starting at X,Y given by 'start', and ending
at X,Y given by 'end'. The grid will be completely filled in X and Y by
every 'step' interval.
"""
# Build X and Y arrays
dx = end[0] - start[0]
if dx < 0:
... | [
"def",
"build_pos_grid",
"(",
"start",
",",
"end",
",",
"nstep",
",",
"mesh",
"=",
"False",
")",
":",
"# Build X and Y arrays",
"dx",
"=",
"end",
"[",
"0",
"]",
"-",
"start",
"[",
"0",
"]",
"if",
"dx",
"<",
"0",
":",
"nstart",
"=",
"end",
"end",
... | 30 | 19.84 |
def _check_all_devices_in_sync(self):
'''Wait until all devices have failover status of 'In Sync'.
:raises: UnexpectedClusterState
'''
if len(self._get_devices_by_failover_status('In Sync')) != \
len(self.devices):
msg = "Expected all devices in group to hav... | [
"def",
"_check_all_devices_in_sync",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_get_devices_by_failover_status",
"(",
"'In Sync'",
")",
")",
"!=",
"len",
"(",
"self",
".",
"devices",
")",
":",
"msg",
"=",
"\"Expected all devices in group to have 'In S... | 38.1 | 21.9 |
def create_user(self, login=None, password=None, user_name=None, envs=[], query='/users/'):
"""
`login` - Login or username for user
`password` - Plain text password for user
`user_name` - Full name of user
Create user in specified environments
"""
login = login.... | [
"def",
"create_user",
"(",
"self",
",",
"login",
"=",
"None",
",",
"password",
"=",
"None",
",",
"user_name",
"=",
"None",
",",
"envs",
"=",
"[",
"]",
",",
"query",
"=",
"'/users/'",
")",
":",
"login",
"=",
"login",
".",
"lower",
"(",
")",
"data",
... | 44.060606 | 23.878788 |
def process_docstring(app, what, name, obj, options, lines):
"""Enable markdown syntax in docstrings"""
markdown = "\n".join(lines)
# ast = cm_parser.parse(markdown)
# html = cm_renderer.render(ast)
rest = m2r(markdown)
rest.replace("\r\n", "\n")
del lines[:]
lines.extend(rest.spl... | [
"def",
"process_docstring",
"(",
"app",
",",
"what",
",",
"name",
",",
"obj",
",",
"options",
",",
"lines",
")",
":",
"markdown",
"=",
"\"\\n\"",
".",
"join",
"(",
"lines",
")",
"# ast = cm_parser.parse(markdown)",
"# html = cm_renderer.render(ast)",
"rest",
"="... | 26.5 | 17.333333 |
def read(self, domain, type_name, search_command, body=None):
"""Read entry in ThreatConnect Data Store
Args:
domain (string): One of 'local', 'organization', or 'system'.
type_name (string): This is a free form index type name. The ThreatConnect API will use
thi... | [
"def",
"read",
"(",
"self",
",",
"domain",
",",
"type_name",
",",
"search_command",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"_request",
"(",
"domain",
",",
"type_name",
",",
"search_command",
",",
"'GET'",
",",
"body",
")"
] | 47.272727 | 22.727273 |
def __parts_and_divisions(self):
"""
The parts and divisions directly part of this element.
"""
from .division import Division
from .part import Part
from .placeholder_part import PlaceholderPart
text = self.node.text
if text:
stripped_text =... | [
"def",
"__parts_and_divisions",
"(",
"self",
")",
":",
"from",
".",
"division",
"import",
"Division",
"from",
".",
"part",
"import",
"Part",
"from",
".",
"placeholder_part",
"import",
"PlaceholderPart",
"text",
"=",
"self",
".",
"node",
".",
"text",
"if",
"t... | 31.24 | 13.88 |
def get_filehandle(self):
"""Get HDF4 filehandle."""
if os.path.exists(self.filename):
self.filehandle = SD(self.filename, SDC.READ)
logger.debug("Loading dataset {}".format(self.filename))
else:
raise IOError("Path {} does not exist.".format(self.filename)) | [
"def",
"get_filehandle",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"filename",
")",
":",
"self",
".",
"filehandle",
"=",
"SD",
"(",
"self",
".",
"filename",
",",
"SDC",
".",
"READ",
")",
"logger",
".",
"debug"... | 44.571429 | 17.428571 |
def get_user(self, user_name, raw=False):
"""
Get a dictionary or object with info about the given user from the Hacker News API.
Will raise an requests.HTTPError if we got a non-200 response back.
Response parameters:
"id' -> The user's unique username. Case-sensiti... | [
"def",
"get_user",
"(",
"self",
",",
"user_name",
",",
"raw",
"=",
"False",
")",
":",
"suburl",
"=",
"\"v0/user/{}.json\"",
".",
"format",
"(",
"user_name",
")",
"try",
":",
"user_data",
"=",
"self",
".",
"_make_request",
"(",
"suburl",
")",
"except",
"r... | 54.185185 | 27.962963 |
def table(self, data2=None, dense=True):
"""
Compute the counts of values appearing in a column, or co-occurence counts between two columns.
:param H2OFrame data2: An optional single column to aggregate counts by.
:param bool dense: If True (default) then use dense representation, which... | [
"def",
"table",
"(",
"self",
",",
"data2",
"=",
"None",
",",
"dense",
"=",
"True",
")",
":",
"return",
"H2OFrame",
".",
"_expr",
"(",
"expr",
"=",
"ExprNode",
"(",
"\"table\"",
",",
"self",
",",
"data2",
",",
"dense",
")",
")",
"if",
"data2",
"is",... | 56.916667 | 35.083333 |
def build_current_graph():
"""
Read current state of SQL items from the current project state.
Returns:
(SQLStateGraph) Current project state graph.
"""
graph = SQLStateGraph()
for app_name, config in apps.app_configs.items():
try:
module = import_module(
... | [
"def",
"build_current_graph",
"(",
")",
":",
"graph",
"=",
"SQLStateGraph",
"(",
")",
"for",
"app_name",
",",
"config",
"in",
"apps",
".",
"app_configs",
".",
"items",
"(",
")",
":",
"try",
":",
"module",
"=",
"import_module",
"(",
"'.'",
".",
"join",
... | 31.608696 | 18.391304 |
def save(self, name, content, max_length=None):
"""
Saves the given content with the given name using the local
storage. If the :attr:`~queued_storage.backends.QueuedStorage.delayed`
attribute is ``True`` this will automatically call the
:meth:`~queued_storage.backends.QueuedStor... | [
"def",
"save",
"(",
"self",
",",
"name",
",",
"content",
",",
"max_length",
"=",
"None",
")",
":",
"cache_key",
"=",
"self",
".",
"get_cache_key",
"(",
"name",
")",
"cache",
".",
"set",
"(",
"cache_key",
",",
"False",
")",
"# Use a name that is available o... | 41 | 20.096774 |
def export_data(self):
"""
Get the results with the modified_data
"""
result = {}
data = self.__original_data__.copy()
data.update(self.__modified_data__)
for key, value in data.items():
if key in self.__deleted_fields__:
continue
... | [
"def",
"export_data",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"data",
"=",
"self",
".",
"__original_data__",
".",
"copy",
"(",
")",
"data",
".",
"update",
"(",
"self",
".",
"__modified_data__",
")",
"for",
"key",
",",
"value",
"in",
"data",
"... | 27.058824 | 12.823529 |
def get_ddG_results(self):
"""Parse the results from BuildModel and get the delta delta G's.
A positive ddG means that the mutation(s) is destabilzing, negative means stabilizing.
- highly stabilising (ΔΔG < −1.84 kcal/mol);
- stabilising (−1.84 kcal/mol ≤ ΔΔG < −0.92 kcal/mol)... | [
"def",
"get_ddG_results",
"(",
"self",
")",
":",
"foldx_avg_df",
"=",
"self",
".",
"df_mutation_ddG_avg",
"foldx_avg_ddG",
"=",
"{",
"}",
"results",
"=",
"foldx_avg_df",
"[",
"[",
"'Pdb'",
",",
"'total energy'",
",",
"'SD'",
"]",
"]",
".",
"T",
".",
"to_di... | 39.413793 | 25.206897 |
def shortcut(
name,
target,
arguments=None,
working_dir=None,
description=None,
icon_location=None,
force=False,
backupname=None,
makedirs=False,
user=None,
**kwargs):
'''
Create a Windows shortcut
If the file already e... | [
"def",
"shortcut",
"(",
"name",
",",
"target",
",",
"arguments",
"=",
"None",
",",
"working_dir",
"=",
"None",
",",
"description",
"=",
"None",
",",
"icon_location",
"=",
"None",
",",
"force",
"=",
"False",
",",
"backupname",
"=",
"None",
",",
"makedirs"... | 38.46063 | 20.34252 |
def wcs_to_axes(w, npix):
"""Generate a sequence of bin edge vectors corresponding to the
axes of a WCS object."""
npix = npix[::-1]
x = np.linspace(-(npix[0]) / 2., (npix[0]) / 2.,
npix[0] + 1) * np.abs(w.wcs.cdelt[0])
y = np.linspace(-(npix[1]) / 2., (npix[1]) / 2.,
... | [
"def",
"wcs_to_axes",
"(",
"w",
",",
"npix",
")",
":",
"npix",
"=",
"npix",
"[",
":",
":",
"-",
"1",
"]",
"x",
"=",
"np",
".",
"linspace",
"(",
"-",
"(",
"npix",
"[",
"0",
"]",
")",
"/",
"2.",
",",
"(",
"npix",
"[",
"0",
"]",
")",
"/",
... | 29.05 | 22.3 |
def p_casecontent_condition_single(self, p):
'casecontent_condition : casecontent_condition COMMA expression'
p[0] = p[1] + (p[3],)
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_casecontent_condition_single",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"(",
"p",
"[",
"3",
"]",
",",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 45.25 | 12.75 |
def debye_E_single(x):
"""
calculate Debye energy using old fortran routine
:params x: Debye x value
:return: Debye energy
"""
# make the function handles both scalar and array
if ((x > 0.0) & (x <= 0.1)):
result = 1. - 0.375 * x + x * x * \
(0.05 - (5.952380953e-4) * x ... | [
"def",
"debye_E_single",
"(",
"x",
")",
":",
"# make the function handles both scalar and array",
"if",
"(",
"(",
"x",
">",
"0.0",
")",
"&",
"(",
"x",
"<=",
"0.1",
")",
")",
":",
"result",
"=",
"1.",
"-",
"0.375",
"*",
"x",
"+",
"x",
"*",
"x",
"*",
... | 34.394737 | 13.342105 |
def GetConsoleTitle() -> str:
"""
GetConsoleTitle from Win32.
Return str.
"""
arrayType = ctypes.c_wchar * MAX_PATH
values = arrayType()
ctypes.windll.kernel32.GetConsoleTitleW(values, MAX_PATH)
return values.value | [
"def",
"GetConsoleTitle",
"(",
")",
"->",
"str",
":",
"arrayType",
"=",
"ctypes",
".",
"c_wchar",
"*",
"MAX_PATH",
"values",
"=",
"arrayType",
"(",
")",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"GetConsoleTitleW",
"(",
"values",
",",
"MAX_PATH",
")",... | 26.444444 | 11.111111 |
def init_dict(data, index, columns, dtype=None):
"""
Segregate Series based on type and coerce into matrices.
Needs to handle a lot of exceptional cases.
"""
if columns is not None:
from pandas.core.series import Series
arrays = Series(data, index=columns, dtype=object)
data_... | [
"def",
"init_dict",
"(",
"data",
",",
"index",
",",
"columns",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"columns",
"is",
"not",
"None",
":",
"from",
"pandas",
".",
"core",
".",
"series",
"import",
"Series",
"arrays",
"=",
"Series",
"(",
"data",
","... | 38.810811 | 16.378378 |
def sid(self, spec):
"""Convert the given search specifier into a search-id (sid)."""
if spec.startswith('@'):
index = int(spec[1:])
jobs = self.service.jobs.list()
if index < len(jobs):
return jobs[index].sid
return spec | [
"def",
"sid",
"(",
"self",
",",
"spec",
")",
":",
"if",
"spec",
".",
"startswith",
"(",
"'@'",
")",
":",
"index",
"=",
"int",
"(",
"spec",
"[",
"1",
":",
"]",
")",
"jobs",
"=",
"self",
".",
"service",
".",
"jobs",
".",
"list",
"(",
")",
"if",... | 36.25 | 8.5 |
def start(self):
"""
Starts the Service.
:Exceptions:
- WebDriverException : Raised either when it can't start the service
or when it can't connect to the service
"""
try:
cmd = [self.path]
cmd.extend(self.command_line_args())
... | [
"def",
"start",
"(",
"self",
")",
":",
"try",
":",
"cmd",
"=",
"[",
"self",
".",
"path",
"]",
"cmd",
".",
"extend",
"(",
"self",
".",
"command_line_args",
"(",
")",
")",
"self",
".",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"e... | 40.136364 | 19.5 |
def _update_redundancy_routers(self, context, updated_router,
update_specification, requested_ha_settings,
updated_router_db, gateway_changed):
"""To be called in update_router() AFTER router has been
updated in DB.
"""
... | [
"def",
"_update_redundancy_routers",
"(",
"self",
",",
"context",
",",
"updated_router",
",",
"update_specification",
",",
"requested_ha_settings",
",",
"updated_router_db",
",",
"gateway_changed",
")",
":",
"router_requested",
"=",
"update_specification",
"[",
"'router'"... | 55.988889 | 20.222222 |
def _partition_tasks(worker):
"""
Takes a worker and sorts out tasks based on their status.
Still_pending_not_ext is only used to get upstream_failure, upstream_missing_dependency and run_by_other_worker
"""
task_history = worker._add_task_history
pending_tasks = {task for(task, status, ext) in ... | [
"def",
"_partition_tasks",
"(",
"worker",
")",
":",
"task_history",
"=",
"worker",
".",
"_add_task_history",
"pending_tasks",
"=",
"{",
"task",
"for",
"(",
"task",
",",
"status",
",",
"ext",
")",
"in",
"task_history",
"if",
"status",
"==",
"'PENDING'",
"}",
... | 69.28 | 36.8 |
def get_port_profile_for_intf_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_for_intf = ET.Element("get_port_profile_for_intf")
config = get_port_profile_for_intf
input = ET.SubElement(get_port_profile_for_intf,... | [
"def",
"get_port_profile_for_intf_input_rbridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_port_profile_for_intf",
"=",
"ET",
".",
"Element",
"(",
"\"get_port_profile_for_intf\"",
")",
"co... | 43 | 14.916667 |
def _schedule_sending_init_updates(self):
"""Setup timer for sending best-paths for all other address-families
that qualify.
Setup timer for sending initial updates to peer.
"""
def _enqueue_non_rtc_init_updates():
LOG.debug('Scheduled queuing of initial Non-RTC UPD... | [
"def",
"_schedule_sending_init_updates",
"(",
"self",
")",
":",
"def",
"_enqueue_non_rtc_init_updates",
"(",
")",
":",
"LOG",
".",
"debug",
"(",
"'Scheduled queuing of initial Non-RTC UPDATEs'",
")",
"tm",
"=",
"self",
".",
"_core_service",
".",
"table_manager",
"self... | 41.2 | 15.16 |
def split(self, string, maxsplit=0):
"""Split string by the occurrences of pattern."""
splitlist = []
state = _State(string, 0, sys.maxint, self.flags)
n = 0
last = state.start
while not maxsplit or n < maxsplit:
state.reset()
state.string_position... | [
"def",
"split",
"(",
"self",
",",
"string",
",",
"maxsplit",
"=",
"0",
")",
":",
"splitlist",
"=",
"[",
"]",
"state",
"=",
"_State",
"(",
"string",
",",
"0",
",",
"sys",
".",
"maxint",
",",
"self",
".",
"flags",
")",
"n",
"=",
"0",
"last",
"=",... | 40.444444 | 14.185185 |
def _get_format(self, token):
""" Returns a QTextCharFormat for token or None.
"""
if token in self._formats:
return self._formats[token]
result = self._get_format_from_style(token, self._style)
self._formats[token] = result
return result | [
"def",
"_get_format",
"(",
"self",
",",
"token",
")",
":",
"if",
"token",
"in",
"self",
".",
"_formats",
":",
"return",
"self",
".",
"_formats",
"[",
"token",
"]",
"result",
"=",
"self",
".",
"_get_format_from_style",
"(",
"token",
",",
"self",
".",
"_... | 29.1 | 14.4 |
def connect(self, opt):
"""This sets up the tokens we expect to see in a way
that hvac also expects."""
if not self._kwargs['verify']:
LOG.warning('Skipping SSL Validation!')
self.version = self.server_version()
self.token = self.init_token()
my_token = self.... | [
"def",
"connect",
"(",
"self",
",",
"opt",
")",
":",
"if",
"not",
"self",
".",
"_kwargs",
"[",
"'verify'",
"]",
":",
"LOG",
".",
"warning",
"(",
"'Skipping SSL Validation!'",
")",
"self",
".",
"version",
"=",
"self",
".",
"server_version",
"(",
")",
"s... | 35.078947 | 16.763158 |
def clique(graph, id):
""" Returns the largest possible clique for the node with given id.
"""
clique = [id]
for n in graph.nodes:
friend = True
for id in clique:
if n.id == id or graph.edge(n.id, id) == None:
friend = False
break
... | [
"def",
"clique",
"(",
"graph",
",",
"id",
")",
":",
"clique",
"=",
"[",
"id",
"]",
"for",
"n",
"in",
"graph",
".",
"nodes",
":",
"friend",
"=",
"True",
"for",
"id",
"in",
"clique",
":",
"if",
"n",
".",
"id",
"==",
"id",
"or",
"graph",
".",
"e... | 23.4375 | 18.6875 |
def num_to_var_int(x):
"""
(bitcoin-specific): convert an integer into a variable-length integer
"""
x = int(x)
if x < 253:
return from_int_to_byte(x)
elif x < 65536:
return from_int_to_byte(253) + encode(x, 256, 2)[::-1]
elif x < 4294967296:
return from_int_to_byte... | [
"def",
"num_to_var_int",
"(",
"x",
")",
":",
"x",
"=",
"int",
"(",
"x",
")",
"if",
"x",
"<",
"253",
":",
"return",
"from_int_to_byte",
"(",
"x",
")",
"elif",
"x",
"<",
"65536",
":",
"return",
"from_int_to_byte",
"(",
"253",
")",
"+",
"encode",
"(",... | 25.625 | 22.625 |
def delete_saved_sandbox(self, context, delete_saved_apps, cancellation_context):
"""
Delete a saved sandbox, along with any vms associated with it
:param ResourceCommandContext context:
:param list[DeleteSavedApp] delete_saved_apps:
:param CancellationContext cancellation_contex... | [
"def",
"delete_saved_sandbox",
"(",
"self",
",",
"context",
",",
"delete_saved_apps",
",",
"cancellation_context",
")",
":",
"connection",
"=",
"self",
".",
"command_wrapper",
".",
"execute_command_with_connection",
"(",
"context",
",",
"self",
".",
"delete_saved_sand... | 60.461538 | 24.923077 |
def datasets(self):
"""A mapping from dataset numbers to datasets in this list"""
return {key: val['ds'] for key, val in six.iteritems(
self._get_ds_descriptions(self.array_info(ds_description=['ds'])))} | [
"def",
"datasets",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"val",
"[",
"'ds'",
"]",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_get_ds_descriptions",
"(",
"self",
".",
"array_info",
"(",
"ds_description",
"=",... | 57 | 20.25 |
def make_var_string(string):
"""
Make a var-string (a var-int with the length, concatenated with the data)
Return the hex-encoded string
"""
s = None
if isinstance(string, str) and re.match('^[0-9a-fA-F]*$', string):
# convert from hex to bin, safely
s = binascii.unhexlify(string... | [
"def",
"make_var_string",
"(",
"string",
")",
":",
"s",
"=",
"None",
"if",
"isinstance",
"(",
"string",
",",
"str",
")",
"and",
"re",
".",
"match",
"(",
"'^[0-9a-fA-F]*$'",
",",
"string",
")",
":",
"# convert from hex to bin, safely",
"s",
"=",
"binascii",
... | 29.714286 | 16 |
def mid_point(self):
'''
Returns the midpoint of the arc as a 1x2 numpy array.
'''
midpoint_angle = self.from_angle + self.sign*self.length_degrees() / 2
return self.angle_as_point(midpoint_angle) | [
"def",
"mid_point",
"(",
"self",
")",
":",
"midpoint_angle",
"=",
"self",
".",
"from_angle",
"+",
"self",
".",
"sign",
"*",
"self",
".",
"length_degrees",
"(",
")",
"/",
"2",
"return",
"self",
".",
"angle_as_point",
"(",
"midpoint_angle",
")"
] | 38.5 | 24.5 |
def _http_get(self, url, query):
"""
Performs the HTTP GET Request.
"""
if not self.authorization_as_header:
query.update({'access_token': self.access_token})
response = None
self._normalize_query(query)
kwargs = {
'params': query,
... | [
"def",
"_http_get",
"(",
"self",
",",
"url",
",",
"query",
")",
":",
"if",
"not",
"self",
".",
"authorization_as_header",
":",
"query",
".",
"update",
"(",
"{",
"'access_token'",
":",
"self",
".",
"access_token",
"}",
")",
"response",
"=",
"None",
"self"... | 22.137931 | 19.793103 |
def DeriveReportKey(cls, root_key, report_id, sent_timestamp):
"""Derive a standard one time use report signing key.
The standard method is HMAC-SHA256(root_key, MAGIC_NUMBER || report_id || sent_timestamp)
where MAGIC_NUMBER is 0x00000002 and all integers are in little endian.
"""
... | [
"def",
"DeriveReportKey",
"(",
"cls",
",",
"root_key",
",",
"report_id",
",",
"sent_timestamp",
")",
":",
"signed_data",
"=",
"struct",
".",
"pack",
"(",
"\"<LLL\"",
",",
"AuthProvider",
".",
"ReportKeyMagic",
",",
"report_id",
",",
"sent_timestamp",
")",
"hma... | 47.090909 | 29.636364 |
def args(self):
"""Create args from function parameters."""
params = self.parameters
args = OrderedDict()
# This will be overridden if the command explicitly defines an
# arg named help.
args['help'] = HelpArg(command=self)
normalize_name = self.normalize_name
... | [
"def",
"args",
"(",
"self",
")",
":",
"params",
"=",
"self",
".",
"parameters",
"args",
"=",
"OrderedDict",
"(",
")",
"# This will be overridden if the command explicitly defines an",
"# arg named help.",
"args",
"[",
"'help'",
"]",
"=",
"HelpArg",
"(",
"command",
... | 35.655556 | 15.244444 |
def _parse_sequences(ilines, expect_qlen):
"""Parse the sequences in the current block.
Sequence looks like:
$3=227(209):
>gi|15606894|ref|NP_214275.1| {|2(244)|<Aquificae(B)>}DNA polymerase III gamma subunit [Aquifex aeolicus VF5] >gi|2984127|gb|AAC07663.1| DNA polymerase III gamma subunit [Aquifex ... | [
"def",
"_parse_sequences",
"(",
"ilines",
",",
"expect_qlen",
")",
":",
"while",
"True",
":",
"first",
"=",
"next",
"(",
"ilines",
")",
"if",
"first",
".",
"startswith",
"(",
"'_'",
")",
"and",
"first",
".",
"endswith",
"(",
"'].'",
")",
":",
"# End of... | 39.8125 | 21.921875 |
def extract_fields(d, fields, delimiter='|'):
""" get values out of an object ``d`` for saving to a csv """
rd = {}
for f in fields:
v = d.get(f, None)
if isinstance(v, (str, unicode)):
v = v.encode('utf8')
elif isinstance(v, list):
v = delimiter.join(v)
... | [
"def",
"extract_fields",
"(",
"d",
",",
"fields",
",",
"delimiter",
"=",
"'|'",
")",
":",
"rd",
"=",
"{",
"}",
"for",
"f",
"in",
"fields",
":",
"v",
"=",
"d",
".",
"get",
"(",
"f",
",",
"None",
")",
"if",
"isinstance",
"(",
"v",
",",
"(",
"st... | 30.545455 | 12.818182 |
def predict(self, h=5, oos_data=None, intervals=False, **kwargs):
""" Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
oos_data : pd.DataFrame
Data for the variables to b... | [
"def",
"predict",
"(",
"self",
",",
"h",
"=",
"5",
",",
"oos_data",
"=",
"None",
",",
"intervals",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
"estimated",
"is",
"False",
":",
"raise",
"Exception",
"("... | 47.88172 | 30.043011 |
def get(path):
"""Read an object from file"""
try:
import cPickle as pickle
except:
import pickle
with open(path, 'rb') as file:
return pickle.load(file) | [
"def",
"get",
"(",
"path",
")",
":",
"try",
":",
"import",
"cPickle",
"as",
"pickle",
"except",
":",
"import",
"pickle",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"file",
":",
"return",
"pickle",
".",
"load",
"(",
"file",
")"
] | 20.666667 | 18.666667 |
def variable_length_to_fixed_length_categorical(
self, left_edge=4, right_edge=4, max_length=15):
"""
Encode variable-length sequences using a fixed-length encoding designed
for preserving the anchor positions of class I peptides.
The sequences must be of length at l... | [
"def",
"variable_length_to_fixed_length_categorical",
"(",
"self",
",",
"left_edge",
"=",
"4",
",",
"right_edge",
"=",
"4",
",",
"max_length",
"=",
"15",
")",
":",
"cache_key",
"=",
"(",
"\"fixed_length_categorical\"",
",",
"left_edge",
",",
"right_edge",
",",
"... | 36.085714 | 19.057143 |
def to_list_of_dicts(self, **kwargs):
"""
Convert the :class:`ParameterSet` to a list of the dictionary representation
of each :class:`Parameter`
:return: list of dicts
"""
if kwargs:
return self.filter(**kwargs).to_list_of_dicts()
return [param.to_di... | [
"def",
"to_list_of_dicts",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
":",
"return",
"self",
".",
"filter",
"(",
"*",
"*",
"kwargs",
")",
".",
"to_list_of_dicts",
"(",
")",
"return",
"[",
"param",
".",
"to_dict",
"(",
")",
"for",... | 34.2 | 16.2 |
def _get_keys_defdict(self):
'''Get the keys and the default dictionary of the given function's
arguments
'''
# inspect argspecs
argspec = inspect.getargspec(self.func)
keys, defvals = argspec.args, argspec.defaults
# convert to (list_of_argkeys, dict_of_default_... | [
"def",
"_get_keys_defdict",
"(",
"self",
")",
":",
"# inspect argspecs",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"self",
".",
"func",
")",
"keys",
",",
"defvals",
"=",
"argspec",
".",
"args",
",",
"argspec",
".",
"defaults",
"# convert to (list_of_a... | 32.222222 | 16.777778 |
def is_xml(text):
"""
Helper function. Lightweight test if response is an XML doc
"""
# BOM_UTF8 is an UTF-8 byte order mark which may precede the XML from an Exchange server
bom_len = len(BOM_UTF8)
if text[:bom_len] == BOM_UTF8:
return text[bom_len:bom_len + 5] == b'<?xml'
return te... | [
"def",
"is_xml",
"(",
"text",
")",
":",
"# BOM_UTF8 is an UTF-8 byte order mark which may precede the XML from an Exchange server",
"bom_len",
"=",
"len",
"(",
"BOM_UTF8",
")",
"if",
"text",
"[",
":",
"bom_len",
"]",
"==",
"BOM_UTF8",
":",
"return",
"text",
"[",
"bo... | 36.666667 | 15.333333 |
def get_samples(self, sample_count):
"""
Fetch a number of samples from self.wave_cache
Args:
sample_count (int): Number of samples to fetch
Returns: ndarray
"""
if self.amplitude.value <= 0:
return None
# Build samples by rolling the per... | [
"def",
"get_samples",
"(",
"self",
",",
"sample_count",
")",
":",
"if",
"self",
".",
"amplitude",
".",
"value",
"<=",
"0",
":",
"return",
"None",
"# Build samples by rolling the period cache through the buffer",
"rolled_array",
"=",
"numpy",
".",
"roll",
"(",
"sel... | 44.48 | 18.72 |
def server(self, parsed_args):
"""Server."""
server_args = vars(self)
server_args['bind_addr'] = parsed_args['bind_addr']
if parsed_args.max is not None:
server_args['maxthreads'] = parsed_args.max
if parsed_args.numthreads is not None:
server_args['minthr... | [
"def",
"server",
"(",
"self",
",",
"parsed_args",
")",
":",
"server_args",
"=",
"vars",
"(",
"self",
")",
"server_args",
"[",
"'bind_addr'",
"]",
"=",
"parsed_args",
"[",
"'bind_addr'",
"]",
"if",
"parsed_args",
".",
"max",
"is",
"not",
"None",
":",
"ser... | 43.444444 | 9.777778 |
def get_work_units(self, work_spec_name, work_unit_keys=None,
state=None, limit=None, start=None):
'''Get (key, value) pairs for work units.
If `state` is not :const:`None`, then it should be one of
the string state constants, and this function will return
a list ... | [
"def",
"get_work_units",
"(",
"self",
",",
"work_spec_name",
",",
"work_unit_keys",
"=",
"None",
",",
"state",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"start",
"=",
"None",
")",
":",
"if",
"work_unit_keys",
"is",
"not",
"None",
":",
"raise",
"NotImp... | 49.019231 | 20.788462 |
def first_consumed_mesh(self):
"""The first consumed mesh.
:return: the first consumed mesh
:rtype: knittingpattern.Mesh.Mesh
:raises IndexError: if no mesh is consumed
.. seealso:: :attr:`number_of_consumed_meshes`
"""
for instruction in self.instructions:
... | [
"def",
"first_consumed_mesh",
"(",
"self",
")",
":",
"for",
"instruction",
"in",
"self",
".",
"instructions",
":",
"if",
"instruction",
".",
"consumes_meshes",
"(",
")",
":",
"return",
"instruction",
".",
"first_consumed_mesh",
"raise",
"IndexError",
"(",
"\"{} ... | 35.923077 | 12.384615 |
def _makeTags(tagStr, xml):
"""Internal helper to construct opening and closing tag expressions, given a tag name"""
if isinstance(tagStr,basestring):
resname = tagStr
tagStr = Keyword(tagStr, caseless=not xml)
else:
resname = tagStr.name
tagAttrName = Word(alphas,alphan... | [
"def",
"_makeTags",
"(",
"tagStr",
",",
"xml",
")",
":",
"if",
"isinstance",
"(",
"tagStr",
",",
"basestring",
")",
":",
"resname",
"=",
"tagStr",
"tagStr",
"=",
"Keyword",
"(",
"tagStr",
",",
"caseless",
"=",
"not",
"xml",
")",
"else",
":",
"resname",... | 56.25 | 31.642857 |
def downgrade():
"""alexm: i believe this method is never called"""
with op.batch_alter_table(t2_name) as batch_op:
batch_op.drop_column('do_not_use')
with op.batch_alter_table(t1_name) as batch_op:
batch_op.drop_column('enabled') | [
"def",
"downgrade",
"(",
")",
":",
"with",
"op",
".",
"batch_alter_table",
"(",
"t2_name",
")",
"as",
"batch_op",
":",
"batch_op",
".",
"drop_column",
"(",
"'do_not_use'",
")",
"with",
"op",
".",
"batch_alter_table",
"(",
"t1_name",
")",
"as",
"batch_op",
... | 36.142857 | 12.714286 |
def extract_energy(rate, sig):
""" Extracts the energy of frames. """
mfcc = python_speech_features.mfcc(sig, rate, appendEnergy=True)
energy_row_vec = mfcc[:, 0]
energy_col_vec = energy_row_vec[:, np.newaxis]
return energy_col_vec | [
"def",
"extract_energy",
"(",
"rate",
",",
"sig",
")",
":",
"mfcc",
"=",
"python_speech_features",
".",
"mfcc",
"(",
"sig",
",",
"rate",
",",
"appendEnergy",
"=",
"True",
")",
"energy_row_vec",
"=",
"mfcc",
"[",
":",
",",
"0",
"]",
"energy_col_vec",
"=",... | 35.142857 | 16 |
def list_all_shipping_methods(cls, **kwargs):
"""List ShippingMethods
Return a list of ShippingMethods
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_shipping_methods(async=True)
... | [
"def",
"list_all_shipping_methods",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_list_all_shipping_methods_with_http_info... | 38.478261 | 15.173913 |
def target(self):
"""
Target the current space for any forthcoming Cloud Foundry
operations.
"""
# MAINT: I don't like this, but will deal later
os.environ['PREDIX_SPACE_GUID'] = self.guid
os.environ['PREDIX_SPACE_NAME'] = self.name
os.environ['PREDIX_ORGA... | [
"def",
"target",
"(",
"self",
")",
":",
"# MAINT: I don't like this, but will deal later",
"os",
".",
"environ",
"[",
"'PREDIX_SPACE_GUID'",
"]",
"=",
"self",
".",
"guid",
"os",
".",
"environ",
"[",
"'PREDIX_SPACE_NAME'",
"]",
"=",
"self",
".",
"name",
"os",
"... | 40.5 | 15.1 |
def save(self):
"""
Creates / updates a row.
This is a blind insert call.
All validation and cleaning needs to happen
prior to calling this.
"""
if self.instance is None:
raise CQLEngineException("DML Query intance attribute is None")
assert ty... | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"instance",
"is",
"None",
":",
"raise",
"CQLEngineException",
"(",
"\"DML Query intance attribute is None\"",
")",
"assert",
"type",
"(",
"self",
".",
"instance",
")",
"==",
"self",
".",
"model",
"null... | 50.738095 | 23.261905 |
def press(self, coordinate, success=None):
"""Success must be given as a tuple of a (coordinate, timeout).
Use (coordinate,) if you want to use the default timeout."""
if isinstance(coordinate, WebElement):
coordinate.click()
else:
self.get_element(coordinate).cli... | [
"def",
"press",
"(",
"self",
",",
"coordinate",
",",
"success",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"coordinate",
",",
"WebElement",
")",
":",
"coordinate",
".",
"click",
"(",
")",
"else",
":",
"self",
".",
"get_element",
"(",
"coordinate",
... | 43.888889 | 7.555556 |
def srem(self, key, member, *members):
"""Remove one or more members from a set."""
return self.execute(b'SREM', key, member, *members) | [
"def",
"srem",
"(",
"self",
",",
"key",
",",
"member",
",",
"*",
"members",
")",
":",
"return",
"self",
".",
"execute",
"(",
"b'SREM'",
",",
"key",
",",
"member",
",",
"*",
"members",
")"
] | 49.666667 | 7 |
def get_data_or_404(model, instance_id, kind=''):
"""Wrap `get_data`, when missing data, raise BadRequest.
"""
data = get_data(model, instance_id, kind)
if not data:
return abort(404)
return data | [
"def",
"get_data_or_404",
"(",
"model",
",",
"instance_id",
",",
"kind",
"=",
"''",
")",
":",
"data",
"=",
"get_data",
"(",
"model",
",",
"instance_id",
",",
"kind",
")",
"if",
"not",
"data",
":",
"return",
"abort",
"(",
"404",
")",
"return",
"data"
] | 24.111111 | 17.555556 |
def cfg_(self,cfg=None):
"""
Getter/Setter of configuration data. This can be used
to update and modify the configuration file on the system
by new applications.
"""
if cfg is None:
cfg = self._cfg
else:
self._cfg = cfg
self.overlay... | [
"def",
"cfg_",
"(",
"self",
",",
"cfg",
"=",
"None",
")",
":",
"if",
"cfg",
"is",
"None",
":",
"cfg",
"=",
"self",
".",
"_cfg",
"else",
":",
"self",
".",
"_cfg",
"=",
"cfg",
"self",
".",
"overlay_load",
"(",
")",
"return",
"cfg"
] | 27.916667 | 14.916667 |
def Extra(self):
"""
Returns any `V`, `P`, `DOI` or `misc` values as a string. These are all the values not returned by [ID()](#metaknowledge.citation.Citation.ID), they are separated by `' ,'`.
# Returns
`str`
> A string containing the data not in the ID of the `Citation`.
... | [
"def",
"Extra",
"(",
"self",
")",
":",
"extraTags",
"=",
"[",
"'V'",
",",
"'P'",
",",
"'DOI'",
",",
"'misc'",
"]",
"retVal",
"=",
"\"\"",
"for",
"tag",
"in",
"extraTags",
":",
"if",
"getattr",
"(",
"self",
",",
"tag",
")",
":",
"retVal",
"+=",
"g... | 31.210526 | 25.526316 |
def update(self, **kwargs):
"""
Overrides update to concatenate streamed data up to defined length.
"""
data = kwargs.get('data')
if data is not None:
if (util.pd and isinstance(data, util.pd.DataFrame) and
list(data.columns) != list(self.data.columns)... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"kwargs",
".",
"get",
"(",
"'data'",
")",
"if",
"data",
"is",
"not",
"None",
":",
"if",
"(",
"util",
".",
"pd",
"and",
"isinstance",
"(",
"data",
",",
"util",
".",
"p... | 40 | 12.923077 |
def exit(self):
"""Overwrite the exit method to close threads."""
if self._thread is not None:
self._thread.stop()
# Call the father class
super(Plugin, self).exit() | [
"def",
"exit",
"(",
"self",
")",
":",
"if",
"self",
".",
"_thread",
"is",
"not",
"None",
":",
"self",
".",
"_thread",
".",
"stop",
"(",
")",
"# Call the father class",
"super",
"(",
"Plugin",
",",
"self",
")",
".",
"exit",
"(",
")"
] | 34 | 8.833333 |
def is_title(p):
"""
Certain p tags are denoted as ``Title`` tags. This function will return
True if the passed in p tag is considered a title.
"""
w_namespace = get_namespace(p, 'w')
styles = p.xpath('.//w:pStyle', namespaces=p.nsmap)
if len(styles) == 0:
return False
style = st... | [
"def",
"is_title",
"(",
"p",
")",
":",
"w_namespace",
"=",
"get_namespace",
"(",
"p",
",",
"'w'",
")",
"styles",
"=",
"p",
".",
"xpath",
"(",
"'.//w:pStyle'",
",",
"namespaces",
"=",
"p",
".",
"nsmap",
")",
"if",
"len",
"(",
"styles",
")",
"==",
"0... | 33.818182 | 14.363636 |
def _fsic_queuing_calc(fsic1, fsic2):
"""
We set the lower counter between two same instance ids.
If an instance_id exists in one fsic but not the other we want to give that counter a value of 0.
:param fsic1: dictionary containing (instance_id, counter) pairs
:param fsic2: dictionary containing (i... | [
"def",
"_fsic_queuing_calc",
"(",
"fsic1",
",",
"fsic2",
")",
":",
"return",
"{",
"instance",
":",
"fsic2",
".",
"get",
"(",
"instance",
",",
"0",
")",
"for",
"instance",
",",
"counter",
"in",
"six",
".",
"iteritems",
"(",
"fsic1",
")",
"if",
"fsic2",
... | 56 | 31.2 |
def getDomainFromUrl(self, url):
"""
Extracting the domain from the URL.
:return: domain as a string.
"""
try:
domain = re.findall( self.domainRegexp, url )[0]
except Exception, e:
errMsg = "ERROR. Something happened when tryin... | [
"def",
"getDomainFromUrl",
"(",
"self",
",",
"url",
")",
":",
"try",
":",
"domain",
"=",
"re",
".",
"findall",
"(",
"self",
".",
"domainRegexp",
",",
"url",
")",
"[",
"0",
"]",
"except",
"Exception",
",",
"e",
":",
"errMsg",
"=",
"\"ERROR. Something ha... | 43 | 25.153846 |
def _convert_for_reindex(self, key, axis=None):
"""
Transform a list of keys into a new array ready to be used as axis of
the object we return (e.g. including NaNs).
Parameters
----------
key : list-like
Target labels
axis: int
Where the i... | [
"def",
"_convert_for_reindex",
"(",
"self",
",",
"key",
",",
"axis",
"=",
"None",
")",
":",
"if",
"axis",
"is",
"None",
":",
"axis",
"=",
"self",
".",
"axis",
"or",
"0",
"labels",
"=",
"self",
".",
"obj",
".",
"_get_axis",
"(",
"axis",
")",
"if",
... | 28.666667 | 18.142857 |
def _ep_active(self):
"""Both ends of the Endpoint have become active."""
LOG.debug("Connection is up")
if self._handler:
with self._callback_lock:
self._handler.connection_active(self) | [
"def",
"_ep_active",
"(",
"self",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Connection is up\"",
")",
"if",
"self",
".",
"_handler",
":",
"with",
"self",
".",
"_callback_lock",
":",
"self",
".",
"_handler",
".",
"connection_active",
"(",
"self",
")"
] | 38.666667 | 8.833333 |
def FileHashIndexQuery(self, subject, target_prefix, limit=100):
"""Search the index for matches starting with target_prefix.
Args:
subject: The index to use. Should be a urn that points to the sha256
namespace.
target_prefix: The prefix to match against the index.
limit: Either a... | [
"def",
"FileHashIndexQuery",
"(",
"self",
",",
"subject",
",",
"target_prefix",
",",
"limit",
"=",
"100",
")",
":",
"if",
"isinstance",
"(",
"limit",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"start",
",",
"length",
"=",
"limit",
"# pylint: disable=... | 32.034483 | 24.068966 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.