text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def dot2svg(dot):
# type: (str) -> str
""" Render Graphviz data to SVG """
svg = graphviz.Source(dot).pipe(format='svg').decode('utf8') # type: str
# strip doctype and xml declaration
svg = svg[svg.index('<svg'):]
return svg | [
"def",
"dot2svg",
"(",
"dot",
")",
":",
"# type: (str) -> str",
"svg",
"=",
"graphviz",
".",
"Source",
"(",
"dot",
")",
".",
"pipe",
"(",
"format",
"=",
"'svg'",
")",
".",
"decode",
"(",
"'utf8'",
")",
"# type: str",
"# strip doctype and xml declaration",
"s... | 34.714286 | 15.714286 |
def getAllCols(self, sddsfile=None):
""" get all available column names from sddsfile
:param sddsfile: sdds file name, if not given, rollback to the one that from ``__init__()``
:return: all sdds data column names
:rtype: list
:Example:
>>> dh = DataExtracter('test.out... | [
"def",
"getAllCols",
"(",
"self",
",",
"sddsfile",
"=",
"None",
")",
":",
"if",
"SDDS_",
":",
"if",
"sddsfile",
"is",
"not",
"None",
":",
"sddsobj",
"=",
"sdds",
".",
"SDDS",
"(",
"2",
")",
"sddsobj",
".",
"load",
"(",
"sddsfile",
")",
"else",
":",... | 38.62963 | 18.888889 |
def validate_params(request):
"""Validate request params."""
if 'params' in request:
correct_params = isinstance(request['params'], (list, dict))
error = 'Incorrect parameter values'
assert correct_params, error | [
"def",
"validate_params",
"(",
"request",
")",
":",
"if",
"'params'",
"in",
"request",
":",
"correct_params",
"=",
"isinstance",
"(",
"request",
"[",
"'params'",
"]",
",",
"(",
"list",
",",
"dict",
")",
")",
"error",
"=",
"'Incorrect parameter values'",
"ass... | 34 | 14.285714 |
def _handle_api_result(result: Optional[Dict[str, Any]]) -> Any:
"""
Retrieve 'data' field from the API result object.
:param result: API result that received from HTTP API
:return: the 'data' field in result object
:raise ActionFailed: the 'status' field is 'failed'
"""
if isinstance(resul... | [
"def",
"_handle_api_result",
"(",
"result",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
")",
"->",
"Any",
":",
"if",
"isinstance",
"(",
"result",
",",
"dict",
")",
":",
"if",
"result",
".",
"get",
"(",
"'status'",
")",
"==",
"'f... | 38.25 | 12.916667 |
def start(self):
'''
Turn on the master server components
'''
self._pre_flight()
log.info('salt-master is starting as user \'%s\'', salt.utils.user.get_user())
enable_sigusr1_handler()
enable_sigusr2_handler()
self.__set_max_open_files()
# Reset... | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_pre_flight",
"(",
")",
"log",
".",
"info",
"(",
"'salt-master is starting as user \\'%s\\''",
",",
"salt",
".",
"utils",
".",
"user",
".",
"get_user",
"(",
")",
")",
"enable_sigusr1_handler",
"(",
")",
... | 46.372093 | 24.55814 |
def highlightBlock(self, text):
"""Apply syntax highlighting to the given block of text.
"""
# Do other syntax formatting
for expression, nth, format in self.rules:
index = expression.indexIn(text, 0)
while index >= 0:
# We actually want t... | [
"def",
"highlightBlock",
"(",
"self",
",",
"text",
")",
":",
"# Do other syntax formatting\r",
"for",
"expression",
",",
"nth",
",",
"format",
"in",
"self",
".",
"rules",
":",
"index",
"=",
"expression",
".",
"indexIn",
"(",
"text",
",",
"0",
")",
"while",... | 39.5 | 15.65 |
def write_gdf(gdf, fname):
"""
Fast line-by-line gdf-file write function
Parameters
----------
gdf : numpy.ndarray
Column 0 is gids, columns 1: are values.
fname : str
Path to gdf-file.
Returns
-------
None
"""
gdf_file = open(fname, '... | [
"def",
"write_gdf",
"(",
"gdf",
",",
"fname",
")",
":",
"gdf_file",
"=",
"open",
"(",
"fname",
",",
"'w'",
")",
"for",
"line",
"in",
"gdf",
":",
"for",
"i",
"in",
"np",
".",
"arange",
"(",
"len",
"(",
"line",
")",
")",
":",
"gdf_file",
".",
"wr... | 18.28 | 20.68 |
def onConnect(self, client, userdata, flags, rc):
"""!
The callback for when the client receives a CONNACK response from the server.
@param client
@param userdata
@param flags
@param rc
"""
for sub in self.subsciption:
(result, mid) = self.cli... | [
"def",
"onConnect",
"(",
"self",
",",
"client",
",",
"userdata",
",",
"flags",
",",
"rc",
")",
":",
"for",
"sub",
"in",
"self",
".",
"subsciption",
":",
"(",
"result",
",",
"mid",
")",
"=",
"self",
".",
"client",
".",
"subscribe",
"(",
"sub",
")"
] | 29.818182 | 17.363636 |
def __rubberband(y, sr, **kwargs):
'''Execute rubberband
Parameters
----------
y : np.ndarray [shape=(n,) or (n, c)]
Audio time series, either single or multichannel
sr : int > 0
sampling rate of y
**kwargs
keyword arguments to rubberband
Returns
-------
y... | [
"def",
"__rubberband",
"(",
"y",
",",
"sr",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"sr",
">",
"0",
"# Get the input and output tempfile",
"fd",
",",
"infile",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"'.wav'",
")",
"os",
".",
"close",
... | 23.84127 | 22.190476 |
def uint8_3(self, val1, val2, val3):
"""append a frame containing 3 uint8"""
try:
self.msg += [pack("BBB", val1, val2, val3)]
except struct.error:
raise ValueError("Expected uint8")
return self | [
"def",
"uint8_3",
"(",
"self",
",",
"val1",
",",
"val2",
",",
"val3",
")",
":",
"try",
":",
"self",
".",
"msg",
"+=",
"[",
"pack",
"(",
"\"BBB\"",
",",
"val1",
",",
"val2",
",",
"val3",
")",
"]",
"except",
"struct",
".",
"error",
":",
"raise",
... | 34.714286 | 12.285714 |
def add_suffix(filename, suffix):
"""
ADD suffix TO THE filename (NOT INCLUDING THE FILE EXTENSION)
"""
path = filename.split("/")
parts = path[-1].split(".")
i = max(len(parts) - 2, 0)
parts[i] = parts[i] + suffix
path[-1] = ".".join(parts)
return... | [
"def",
"add_suffix",
"(",
"filename",
",",
"suffix",
")",
":",
"path",
"=",
"filename",
".",
"split",
"(",
"\"/\"",
")",
"parts",
"=",
"path",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"\".\"",
")",
"i",
"=",
"max",
"(",
"len",
"(",
"parts",
")",
... | 32.6 | 7.4 |
def SetFillStyle(self, style):
"""
*style* may be any fill style understood by ROOT or matplotlib.
For full documentation of accepted *style* arguments, see
:class:`rootpy.plotting.style.FillStyle`.
"""
self._fillstyle = FillStyle(style)
if isinstance(self, ROOT.... | [
"def",
"SetFillStyle",
"(",
"self",
",",
"style",
")",
":",
"self",
".",
"_fillstyle",
"=",
"FillStyle",
"(",
"style",
")",
"if",
"isinstance",
"(",
"self",
",",
"ROOT",
".",
"TAttFill",
")",
":",
"ROOT",
".",
"TAttFill",
".",
"SetFillStyle",
"(",
"sel... | 39.1 | 14.9 |
def get_user_pubkeys(users):
'''
Retrieve a set of public keys from GitHub for the specified list of users.
Expects input in list format. Optionally, a value in the list may be a dict
whose value is a list of key IDs to be returned. If this is not done, then
all keys will be returned.
Some exam... | [
"def",
"get_user_pubkeys",
"(",
"users",
")",
":",
"if",
"not",
"isinstance",
"(",
"users",
",",
"list",
")",
":",
"return",
"{",
"'Error'",
":",
"'A list of users is expected'",
"}",
"ret",
"=",
"{",
"}",
"for",
"user",
"in",
"users",
":",
"key_ids",
"=... | 26.423077 | 23.038462 |
def update_product(product_id, **kwargs):
"""
Update a Product with new information
"""
content = update_product_raw(product_id, **kwargs)
if content:
return utils.format_json(content) | [
"def",
"update_product",
"(",
"product_id",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"update_product_raw",
"(",
"product_id",
",",
"*",
"*",
"kwargs",
")",
"if",
"content",
":",
"return",
"utils",
".",
"format_json",
"(",
"content",
")"
] | 29.428571 | 6 |
def get_service_reference(self, clazz, ldap_filter=None):
# type: (Optional[str], Optional[str]) -> Optional[ServiceReference]
"""
Returns a ServiceReference object for a service that implements and
was registered under the specified class
:param clazz: The class name with which... | [
"def",
"get_service_reference",
"(",
"self",
",",
"clazz",
",",
"ldap_filter",
"=",
"None",
")",
":",
"# type: (Optional[str], Optional[str]) -> Optional[ServiceReference]",
"result",
"=",
"self",
".",
"__framework",
".",
"find_service_references",
"(",
"clazz",
",",
"l... | 38.647059 | 19.352941 |
def getdarkcurrent(self,extver):
"""
Return the dark current for the ACS detector. This value
will be contained within an instrument specific keyword.
The value in the image header will be converted to units
of electrons.
Returns
-------
darkcurrent: flo... | [
"def",
"getdarkcurrent",
"(",
"self",
",",
"extver",
")",
":",
"darkcurrent",
"=",
"0.",
"try",
":",
"darkcurrent",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"extver",
"]",
".",
"header",
"[",
"'MEANDARK'",
"]",
"except",
":",
"s... | 43.16129 | 24.580645 |
def invoke(client, method, **kwargs):
"""Invoke a method on the underlying soap service."""
try:
# Proxy the method to the suds service
result = getattr(client.service, method)(**kwargs)
except AttributeError:
logger.critical("Unknown method: %s", method)
raise
except URL... | [
"def",
"invoke",
"(",
"client",
",",
"method",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# Proxy the method to the suds service",
"result",
"=",
"getattr",
"(",
"client",
".",
"service",
",",
"method",
")",
"(",
"*",
"*",
"kwargs",
")",
"except",
"... | 36.916667 | 16.722222 |
def _pelita_member_filter(parent_name, item_names):
"""
Filter a list of autodoc items for which to generate documentation.
Include only imports that come from the documented module or its
submodules.
"""
filtered_names = []
if parent_name not in sys.modules:
return item_names
... | [
"def",
"_pelita_member_filter",
"(",
"parent_name",
",",
"item_names",
")",
":",
"filtered_names",
"=",
"[",
"]",
"if",
"parent_name",
"not",
"in",
"sys",
".",
"modules",
":",
"return",
"item_names",
"module",
"=",
"sys",
".",
"modules",
"[",
"parent_name",
... | 28.181818 | 20.727273 |
def slice_sequence(self,start,end,directionless=False):
"""Slice the mapping by the position in the sequence
First coordinate is 0-indexed start
Second coordinate is 1-indexed finish
"""
if end > self.length: end = self.length
if start < 0: start = 0
if not directionless and s... | [
"def",
"slice_sequence",
"(",
"self",
",",
"start",
",",
"end",
",",
"directionless",
"=",
"False",
")",
":",
"if",
"end",
">",
"self",
".",
"length",
":",
"end",
"=",
"self",
".",
"length",
"if",
"start",
"<",
"0",
":",
"start",
"=",
"0",
"if",
... | 27.194444 | 14.611111 |
def _collect_variable_renaming(
cls, expression: Expression, position: List[int]=None, variables: Dict[str, str]=None
) -> Dict[str, str]:
"""Return renaming for the variables in the expression.
The variable names are generated according to the position of the variable in the expression... | [
"def",
"_collect_variable_renaming",
"(",
"cls",
",",
"expression",
":",
"Expression",
",",
"position",
":",
"List",
"[",
"int",
"]",
"=",
"None",
",",
"variables",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
... | 47.814815 | 24.185185 |
def clean_whitespace(self, tree):
"""
Cleans up whitespace around block open and close tags if they are the
only thing on the line
:param tree:
The AST - will be modified in place
"""
pointer = 0
end = len(tree)
while pointer < end:
... | [
"def",
"clean_whitespace",
"(",
"self",
",",
"tree",
")",
":",
"pointer",
"=",
"0",
"end",
"=",
"len",
"(",
"tree",
")",
"while",
"pointer",
"<",
"end",
":",
"piece",
"=",
"tree",
"[",
"pointer",
"]",
"if",
"piece",
"[",
"0",
"]",
"==",
"'block'",
... | 43.95 | 19.25 |
def show_nontab_menu(self, event):
"""Show the context menu assigned to nontabs section."""
menu = self.main.createPopupMenu()
menu.exec_(self.dock_tabbar.mapToGlobal(event.pos())) | [
"def",
"show_nontab_menu",
"(",
"self",
",",
"event",
")",
":",
"menu",
"=",
"self",
".",
"main",
".",
"createPopupMenu",
"(",
")",
"menu",
".",
"exec_",
"(",
"self",
".",
"dock_tabbar",
".",
"mapToGlobal",
"(",
"event",
".",
"pos",
"(",
")",
")",
")... | 50.25 | 7.25 |
def plot_drawdown_periods(returns, top=10, ax=None, **kwargs):
"""
Plots cumulative returns highlighting top drawdown periods.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
top : i... | [
"def",
"plot_drawdown_periods",
"(",
"returns",
",",
"top",
"=",
"10",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"y_axis_formatter",
"=",
"FuncFormatter",
"(",
... | 31.078431 | 17.431373 |
def invoked(self, ctx):
"""
Guacamole method used by the command ingredient.
:param ctx:
The guacamole context object. Context provides access to all
features of guacamole. The argparse ingredient adds the ``args``
attribute to it. That attribute contains the... | [
"def",
"invoked",
"(",
"self",
",",
"ctx",
")",
":",
"print",
"(",
"\"{} + {} = {}\"",
".",
"format",
"(",
"ctx",
".",
"args",
".",
"x",
",",
"ctx",
".",
"args",
".",
"y",
",",
"ctx",
".",
"args",
".",
"x",
"+",
"ctx",
".",
"args",
".",
"y",
... | 37.941176 | 18.647059 |
def getItems(self, sort=False, reverse=False, selector=None):
""" #TODO: docstring
"""
selector = (lambda fgi: fgi.isValid) if selector is None else selector
_container = {'_': self.container}
return _getItems(_container, '_', sort, reverse, selector) | [
"def",
"getItems",
"(",
"self",
",",
"sort",
"=",
"False",
",",
"reverse",
"=",
"False",
",",
"selector",
"=",
"None",
")",
":",
"selector",
"=",
"(",
"lambda",
"fgi",
":",
"fgi",
".",
"isValid",
")",
"if",
"selector",
"is",
"None",
"else",
"selector... | 47.833333 | 14.666667 |
def predict(self, times):
"""
Predict the {0} at certain point in time. Uses a linear interpolation if
points in time are not in the index.
Parameters
----------
times: a scalar or an array of times to predict the value of {0} at.
Returns
-------
... | [
"def",
"predict",
"(",
"self",
",",
"times",
")",
":",
"if",
"callable",
"(",
"self",
".",
"_estimation_method",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"self",
".",
"_estimation_method",
"(",
"_to_array",
"(",
"times",
")",
")",
",",
"index",
... | 42.555556 | 26.777778 |
def extend_safe(target, source):
"""
Extends source list to target list only if elements doesn't exists in target list.
:param target:
:type target: list
:param source:
:type source: list
"""
for elt in source:
if elt not in target:
target.append(elt) | [
"def",
"extend_safe",
"(",
"target",
",",
"source",
")",
":",
"for",
"elt",
"in",
"source",
":",
"if",
"elt",
"not",
"in",
"target",
":",
"target",
".",
"append",
"(",
"elt",
")"
] | 26.636364 | 15.727273 |
def set_dhw_on(self, until=None):
"""Sets the DHW on until a given time, or permanently."""
if until is None:
data = {"Mode": "PermanentOverride",
"State": "On",
"UntilTime": None}
else:
data = {"Mode": "TemporaryOverride",
... | [
"def",
"set_dhw_on",
"(",
"self",
",",
"until",
"=",
"None",
")",
":",
"if",
"until",
"is",
"None",
":",
"data",
"=",
"{",
"\"Mode\"",
":",
"\"PermanentOverride\"",
",",
"\"State\"",
":",
"\"On\"",
",",
"\"UntilTime\"",
":",
"None",
"}",
"else",
":",
"... | 36.25 | 13.5 |
def default_facets_factory(search, index):
"""Add a default facets to query.
:param search: Basic search object.
:param index: Index name.
:returns: A tuple containing the new search object and a dictionary with
all fields and values used.
"""
urlkwargs = MultiDict()
facets = curre... | [
"def",
"default_facets_factory",
"(",
"search",
",",
"index",
")",
":",
"urlkwargs",
"=",
"MultiDict",
"(",
")",
"facets",
"=",
"current_app",
".",
"config",
"[",
"'RECORDS_REST_FACETS'",
"]",
".",
"get",
"(",
"index",
")",
"if",
"facets",
"is",
"not",
"No... | 29.72 | 19 |
def contains_list(longer, shorter):
"""Check if longer list starts with shorter list"""
if len(longer) <= len(shorter):
return False
for a, b in zip(shorter, longer):
if a != b:
return False
return True | [
"def",
"contains_list",
"(",
"longer",
",",
"shorter",
")",
":",
"if",
"len",
"(",
"longer",
")",
"<=",
"len",
"(",
"shorter",
")",
":",
"return",
"False",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"shorter",
",",
"longer",
")",
":",
"if",
"a",
"!=... | 29.875 | 12 |
def add_labels_to_pr(repo: GithubRepository,
pull_id: int,
*labels: str,
override_token: str = None) -> None:
"""
References:
https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue
"""
url = ("https://api.github.com/re... | [
"def",
"add_labels_to_pr",
"(",
"repo",
":",
"GithubRepository",
",",
"pull_id",
":",
"int",
",",
"*",
"labels",
":",
"str",
",",
"override_token",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"url",
"=",
"(",
"\"https://api.github.com/repos/{}/{}/issues/{... | 41.736842 | 15.210526 |
async def sync_all_new_events(self, sync_all_new_events_request):
"""List all events occurring at or after a timestamp."""
response = hangouts_pb2.SyncAllNewEventsResponse()
await self._pb_request('conversations/syncallnewevents',
sync_all_new_events_request, respo... | [
"async",
"def",
"sync_all_new_events",
"(",
"self",
",",
"sync_all_new_events_request",
")",
":",
"response",
"=",
"hangouts_pb2",
".",
"SyncAllNewEventsResponse",
"(",
")",
"await",
"self",
".",
"_pb_request",
"(",
"'conversations/syncallnewevents'",
",",
"sync_all_new... | 57.166667 | 18.833333 |
def load_yaml_config(self, conf):
"""Load a YAML configuration file and recursively update the overall configuration."""
with open(conf) as fd:
self.config = recursive_dict_update(self.config, yaml.load(fd, Loader=UnsafeLoader)) | [
"def",
"load_yaml_config",
"(",
"self",
",",
"conf",
")",
":",
"with",
"open",
"(",
"conf",
")",
"as",
"fd",
":",
"self",
".",
"config",
"=",
"recursive_dict_update",
"(",
"self",
".",
"config",
",",
"yaml",
".",
"load",
"(",
"fd",
",",
"Loader",
"="... | 63.25 | 18.25 |
def first_items(self, index):
"""Meant to reproduce the results of the following
grouper = pandas.Grouper(...)
first_items = pd.Series(np.arange(len(index)),
index).groupby(grouper).first()
with index being a CFTimeIndex instead of a DatetimeIndex.
... | [
"def",
"first_items",
"(",
"self",
",",
"index",
")",
":",
"datetime_bins",
",",
"labels",
"=",
"_get_time_bins",
"(",
"index",
",",
"self",
".",
"freq",
",",
"self",
".",
"closed",
",",
"self",
".",
"label",
",",
"self",
".",
"base",
")",
"if",
"sel... | 39.645161 | 18.774194 |
def get(self, *args, **kwargs):
"""Handle reading of the model
:param args:
:param kwargs:
"""
# Create the model and fetch its data
self.model = self.get_model(kwargs.get('id'))
result = yield self.model.fetch()
# If model is not found, return 404
... | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Create the model and fetch its data",
"self",
".",
"model",
"=",
"self",
".",
"get_model",
"(",
"kwargs",
".",
"get",
"(",
"'id'",
")",
")",
"result",
"=",
"yield",
"sel... | 27.461538 | 15.115385 |
def copy_and_disconnect_tree(root, machine):
"""Copy a RoutingTree (containing nothing but RoutingTrees), disconnecting
nodes which are not connected in the machine.
Note that if a dead chip is part of the input RoutingTree, no corresponding
node will be included in the copy. The assumption behind this... | [
"def",
"copy_and_disconnect_tree",
"(",
"root",
",",
"machine",
")",
":",
"new_root",
"=",
"None",
"# Lookup for copied routing tree {(x, y): RoutingTree, ...}",
"new_lookup",
"=",
"{",
"}",
"# List of missing connections in the copied routing tree [(new_parent,",
"# new_child), ..... | 41.578947 | 21.881579 |
def update_distribution(
name,
config,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Update the config (and optionally tags) for the CloudFront distribution with the given name.
name
Name of the CloudFront distribution
config
Configurati... | [
"def",
"update_distribution",
"(",
"name",
",",
"config",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
")",
":",
"### FIXME - BUG. This function can NEVER work as... | 27.311321 | 21.613208 |
def _BuildFindSpecsFromFileSourcePath(
self, source_path, path_separator, environment_variables, user_accounts):
"""Builds find specifications from a file source type.
Args:
source_path (str): file system path defined by the source.
path_separator (str): file system path segment separator.
... | [
"def",
"_BuildFindSpecsFromFileSourcePath",
"(",
"self",
",",
"source_path",
",",
"path_separator",
",",
"environment_variables",
",",
"user_accounts",
")",
":",
"find_specs",
"=",
"[",
"]",
"for",
"path_glob",
"in",
"path_helper",
".",
"PathHelper",
".",
"ExpandRec... | 36.639344 | 22.262295 |
def init(self, ctxt, step_addr):
"""
Initialize the item. This calls the class constructor with the
appropriate arguments and returns the initialized object.
:param ctxt: The context object.
:param step_addr: The address of the step in the test
configu... | [
"def",
"init",
"(",
"self",
",",
"ctxt",
",",
"step_addr",
")",
":",
"return",
"self",
".",
"cls",
"(",
"ctxt",
",",
"self",
".",
"name",
",",
"self",
".",
"conf",
",",
"step_addr",
")"
] | 35.727273 | 17 |
def first_order_markov_process(t, variance, time_scale, rseed=None):
"""
Generates a correlated noise vector using a multivariate normal
random number generator with zero mean and covariance
Sigma_ij = s^2 exp(-|t_i - t_j|/l),
where s is the variance and l is the time scale.
The P... | [
"def",
"first_order_markov_process",
"(",
"t",
",",
"variance",
",",
"time_scale",
",",
"rseed",
"=",
"None",
")",
":",
"if",
"variance",
"<",
"0.0",
":",
"raise",
"ValueError",
"(",
"\"Variance must be positive\"",
")",
"if",
"time_scale",
"<",
"0.0",
":",
... | 30.428571 | 20.183673 |
def _solution_factory(self, basis_kwargs, coefs_array, nodes, problem, result):
"""
Construct a representation of the solution to the boundary value problem.
Parameters
----------
basis_kwargs : dict(str : )
coefs_array : numpy.ndarray
problem : TwoPointBVPLike
... | [
"def",
"_solution_factory",
"(",
"self",
",",
"basis_kwargs",
",",
"coefs_array",
",",
"nodes",
",",
"problem",
",",
"result",
")",
":",
"soln_coefs",
"=",
"self",
".",
"_array_to_list",
"(",
"coefs_array",
",",
"problem",
".",
"number_odes",
")",
"soln_derivs... | 40.88 | 24.48 |
def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 1:
return self.print_help()
audio_file_path = self.actual_arguments[0]
if not self.check_input_file(audio_file_path):... | [
"def",
"perform_command",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"actual_arguments",
")",
"<",
"1",
":",
"return",
"self",
".",
"print_help",
"(",
")",
"audio_file_path",
"=",
"self",
".",
"actual_arguments",
"[",
"0",
"]",
"if",
"not",
... | 43.333333 | 23.333333 |
def get_log(self):
"""Gets the ``Log`` at this node.
return: (osid.logging.Log) - the log represented by this node
*compliance: mandatory -- This method must be implemented.*
"""
if self._lookup_session is None:
mgr = get_provider_manager('LOGGING', runtime=self._ru... | [
"def",
"get_log",
"(",
"self",
")",
":",
"if",
"self",
".",
"_lookup_session",
"is",
"None",
":",
"mgr",
"=",
"get_provider_manager",
"(",
"'LOGGING'",
",",
"runtime",
"=",
"self",
".",
"_runtime",
",",
"proxy",
"=",
"self",
".",
"_proxy",
")",
"self",
... | 45.636364 | 26.727273 |
def find(self, pkg, flag):
"""Start to find packages and print
"""
print("\nPackages with name matching [ {0}{1}{2} ]\n".format(
self.cyan, ", ".join(pkg), self.endc))
Msg().template(78)
print("| {0} {1}{2}{3}".format("Repository", "Package", " " * 54,
... | [
"def",
"find",
"(",
"self",
",",
"pkg",
",",
"flag",
")",
":",
"print",
"(",
"\"\\nPackages with name matching [ {0}{1}{2} ]\\n\"",
".",
"format",
"(",
"self",
".",
"cyan",
",",
"\", \"",
".",
"join",
"(",
"pkg",
")",
",",
"self",
".",
"endc",
")",
")",
... | 46.944444 | 13.166667 |
def validate(self, tracking_number):
"Return True if this is a valid USPS tracking number."
tracking_num = tracking_number[:-1].replace(' ', '')
odd_total = 0
even_total = 0
for ii, digit in enumerate(tracking_num):
if ii % 2:
odd_total += int(digit)
... | [
"def",
"validate",
"(",
"self",
",",
"tracking_number",
")",
":",
"tracking_num",
"=",
"tracking_number",
"[",
":",
"-",
"1",
"]",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"odd_total",
"=",
"0",
"even_total",
"=",
"0",
"for",
"ii",
",",
"digit",
"... | 39.923077 | 12.692308 |
def standard_reader_routine(reader, filename, attrs=None):
"""Use a given reader from the ``READERS`` mapping in the common VTK reading
pipeline routine.
Parameters
----------
reader : vtkReader
Any instantiated VTK reader class
filename : str
The string filename to the data fi... | [
"def",
"standard_reader_routine",
"(",
"reader",
",",
"filename",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"attrs",
"is",
"None",
":",
"attrs",
"=",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"attrs",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
... | 32.885714 | 19.428571 |
def _inherit_data(self):
"""
Inherits the data from the parent.
"""
LOG.debug("'%s' inheriting data from '%s'" % (self.get_name(),
self.parent.get_name()),
extra=dict(data=self.parent.data))
self.set_data(**s... | [
"def",
"_inherit_data",
"(",
"self",
")",
":",
"LOG",
".",
"debug",
"(",
"\"'%s' inheriting data from '%s'\"",
"%",
"(",
"self",
".",
"get_name",
"(",
")",
",",
"self",
".",
"parent",
".",
"get_name",
"(",
")",
")",
",",
"extra",
"=",
"dict",
"(",
"dat... | 41.125 | 12.375 |
def get_max_runs(x) -> np.array:
"""
Given a list of numbers, return a NumPy array of pairs
(start index, end index + 1) of the runs of max value.
Example::
>>> get_max_runs([7, 1, 2, 7, 7, 1, 2])
array([[0, 1],
[3, 5]])
Assume x is not empty.
Recipe comes from
... | [
"def",
"get_max_runs",
"(",
"x",
")",
"->",
"np",
".",
"array",
":",
"# Get 0-1 array where 1 marks the max values of x",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"m",
"=",
"np",
".",
"max",
"(",
"x",
")",
"y",
"=",
"(",
"x",
"==",
"m",
")",
"*... | 31.884615 | 17.884615 |
def _reliure_worker(wnum, Qin, Qout, pipeline, options={}):
""" a worker used by :func:`run_parallel`
"""
#pipeline = get_pipeline()
logger = logging.getLogger("reliure.run_parallel.worker#%s" % wnum)
logger.debug("worker created")
if options is None:
options = {}
while True:
... | [
"def",
"_reliure_worker",
"(",
"wnum",
",",
"Qin",
",",
"Qout",
",",
"pipeline",
",",
"options",
"=",
"{",
"}",
")",
":",
"#pipeline = get_pipeline()",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"reliure.run_parallel.worker#%s\"",
"%",
"wnum",
")",
"lo... | 40.8 | 17.866667 |
def _download_rtd_zip(rtd_version=None, **kwargs):
"""
Download and extract HTML ZIP from RTD to installed doc data path.
Download is skipped if content already exists.
Parameters
----------
rtd_version : str or `None`
RTD version to download; e.g., "latest", "stable", or "v2.6.0".
... | [
"def",
"_download_rtd_zip",
"(",
"rtd_version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# https://github.com/ejeschke/ginga/pull/451#issuecomment-298403134",
"if",
"not",
"toolkit",
".",
"family",
".",
"startswith",
"(",
"'qt'",
")",
":",
"raise",
"ValueErr... | 34.016393 | 21.229508 |
def concat(*cols):
"""
Concatenates multiple input columns together into a single column.
The function works with strings, binary and compatible array columns.
>>> df = spark.createDataFrame([('abcd','123')], ['s', 'd'])
>>> df.select(concat(df.s, df.d).alias('s')).collect()
[Row(s=u'abcd123')]... | [
"def",
"concat",
"(",
"*",
"cols",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"return",
"Column",
"(",
"sc",
".",
"_jvm",
".",
"functions",
".",
"concat",
"(",
"_to_seq",
"(",
"sc",
",",
"cols",
",",
"_to_java_column",
")",
")",
... | 43.333333 | 23.6 |
def sina_download_by_vkey(vkey, title=None, output_dir='.', merge=True, info_only=False):
"""Downloads a Sina video by its unique vkey.
http://video.sina.com/
"""
url = 'http://video.sina.com/v/flvideo/%s_0.flv' % vkey
type, ext, size = url_info(url)
print_info(site_info, title, 'flv', size)
... | [
"def",
"sina_download_by_vkey",
"(",
"vkey",
",",
"title",
"=",
"None",
",",
"output_dir",
"=",
"'.'",
",",
"merge",
"=",
"True",
",",
"info_only",
"=",
"False",
")",
":",
"url",
"=",
"'http://video.sina.com/v/flvideo/%s_0.flv'",
"%",
"vkey",
"type",
",",
"e... | 38.090909 | 21.727273 |
def user_list(self, userid, cur_p=''):
'''
List the entities of the user.
'''
current_page_number = int(cur_p) if cur_p else 1
current_page_number = 1 if current_page_number < 1 else current_page_number
kwd = {
'current_page': current_page_number
}
... | [
"def",
"user_list",
"(",
"self",
",",
"userid",
",",
"cur_p",
"=",
"''",
")",
":",
"current_page_number",
"=",
"int",
"(",
"cur_p",
")",
"if",
"cur_p",
"else",
"1",
"current_page_number",
"=",
"1",
"if",
"current_page_number",
"<",
"1",
"else",
"current_pa... | 34.277778 | 23.277778 |
def pluralize(singular):
"""Convert singular word to its plural form.
Args:
singular: A word in its singular form.
Returns:
The word in its plural form.
"""
if singular in UNCOUNTABLES:
return singular
for i in IRREGULAR:
if i[0] == singular:
return ... | [
"def",
"pluralize",
"(",
"singular",
")",
":",
"if",
"singular",
"in",
"UNCOUNTABLES",
":",
"return",
"singular",
"for",
"i",
"in",
"IRREGULAR",
":",
"if",
"i",
"[",
"0",
"]",
"==",
"singular",
":",
"return",
"i",
"[",
"1",
"]",
"for",
"i",
"in",
"... | 25.117647 | 14.941176 |
def format_number(col, d):
"""
Formats the number X to a format like '#,--#,--#.--', rounded to d decimal places
with HALF_EVEN round mode, and returns the result as a string.
:param col: the column name of the numeric value to be formatted
:param d: the N decimal places
>>> spark.createDataFr... | [
"def",
"format_number",
"(",
"col",
",",
"d",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"return",
"Column",
"(",
"sc",
".",
"_jvm",
".",
"functions",
".",
"format_number",
"(",
"_to_java_column",
"(",
"col",
")",
",",
"d",
")",
"... | 40.615385 | 23.846154 |
def get_tags(self, rev=None):
"""
Return the tags for the current revision as a set
"""
rev = rev or 'HEAD'
return set(self._invoke('tag', '--points-at', rev).splitlines()) | [
"def",
"get_tags",
"(",
"self",
",",
"rev",
"=",
"None",
")",
":",
"rev",
"=",
"rev",
"or",
"'HEAD'",
"return",
"set",
"(",
"self",
".",
"_invoke",
"(",
"'tag'",
",",
"'--points-at'",
",",
"rev",
")",
".",
"splitlines",
"(",
")",
")"
] | 29.5 | 11.166667 |
def get_platform_by_name(self, name, for_target=None):
"""Finds the platform with the given name.
If the name is empty or None, returns the default platform.
If not platform with the given name is defined, raises an error.
:param str name: name of the platform.
:param JvmTarget for_target: optional... | [
"def",
"get_platform_by_name",
"(",
"self",
",",
"name",
",",
"for_target",
"=",
"None",
")",
":",
"if",
"not",
"name",
":",
"return",
"self",
".",
"default_platform",
"if",
"name",
"not",
"in",
"self",
".",
"platforms_by_name",
":",
"raise",
"self",
".",
... | 43.5625 | 15.625 |
def RoundToSeconds(cls, timestamp):
"""Takes a timestamp value and rounds it to a second precision."""
leftovers = timestamp % definitions.MICROSECONDS_PER_SECOND
scrubbed = timestamp - leftovers
rounded = round(float(leftovers) / definitions.MICROSECONDS_PER_SECOND)
return int(scrubbed + rounded *... | [
"def",
"RoundToSeconds",
"(",
"cls",
",",
"timestamp",
")",
":",
"leftovers",
"=",
"timestamp",
"%",
"definitions",
".",
"MICROSECONDS_PER_SECOND",
"scrubbed",
"=",
"timestamp",
"-",
"leftovers",
"rounded",
"=",
"round",
"(",
"float",
"(",
"leftovers",
")",
"/... | 50.142857 | 19.857143 |
def heightmap_add_hill(
hm: np.ndarray, x: float, y: float, radius: float, height: float
) -> None:
"""Add a hill (a half spheroid) at given position.
If height == radius or -radius, the hill is a half-sphere.
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
... | [
"def",
"heightmap_add_hill",
"(",
"hm",
":",
"np",
".",
"ndarray",
",",
"x",
":",
"float",
",",
"y",
":",
"float",
",",
"radius",
":",
"float",
",",
"height",
":",
"float",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_heightmap_add_hill",
"(",
"_heightmap... | 41.533333 | 23.866667 |
def on_connect(self, client, userdata, flags, result_code):
""" Callback when the MQTT client is connected.
:param client: the client being connected.
:param userdata: unused.
:param flags: unused.
:param result_code: result code.
"""
self.log_info("Connected wit... | [
"def",
"on_connect",
"(",
"self",
",",
"client",
",",
"userdata",
",",
"flags",
",",
"result_code",
")",
":",
"self",
".",
"log_info",
"(",
"\"Connected with result code {}\"",
".",
"format",
"(",
"result_code",
")",
")",
"self",
".",
"state_handler",
".",
"... | 40.1 | 13.3 |
def on_task_status(self, task):
"""Ignore not processing error in interactive mode"""
if not self.interactive:
super(OneScheduler, self).on_task_status(task)
try:
procesok = task['track']['process']['ok']
except KeyError as e:
logger.error("Bad status... | [
"def",
"on_task_status",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"self",
".",
"interactive",
":",
"super",
"(",
"OneScheduler",
",",
"self",
")",
".",
"on_task_status",
"(",
"task",
")",
"try",
":",
"procesok",
"=",
"task",
"[",
"'track'",
"]"... | 41.347826 | 19.73913 |
def hideEvent(self, event):
"""
Sets the visible state for this widget. If it is the first time this
widget will be visible, the initialized signal will be emitted.
:param state | <bool>
"""
super(XView, self).hideEvent(event)
# record the ... | [
"def",
"hideEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"XView",
",",
"self",
")",
".",
"hideEvent",
"(",
"event",
")",
"# record the visible state for this widget to be separate of Qt's",
"# system to know if this view WILL be visible or not once the ",
"# s... | 40.722222 | 17.722222 |
def validateInt(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
min=None, max=None, lessThan=None, greaterThan=None, excMsg=None):
"""Raises ValidationException if value is not a int.
Returns value, so it can be used inline in an expression:
print(2 + vali... | [
"def",
"validateInt",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
",",
"lessThan",
"=",
"None",
",",
... | 60.783784 | 38.486486 |
def get_identity(self, subject_id, entities=None,
check_not_on_or_after=True):
""" Get all the identity information that has been received and
are still valid about the subject.
:param subject_id: The identifier of the subject
:param entities: The identifiers of the... | [
"def",
"get_identity",
"(",
"self",
",",
"subject_id",
",",
"entities",
"=",
"None",
",",
"check_not_on_or_after",
"=",
"True",
")",
":",
"res",
"=",
"{",
"}",
"oldees",
"=",
"[",
"]",
"if",
"not",
"entities",
":",
"for",
"item",
"in",
"self",
".",
"... | 39.288889 | 16.666667 |
def loss(loss_value):
"""Calculates aggregated mean loss."""
total_loss = tf.Variable(0.0, False)
loss_count = tf.Variable(0, False)
total_loss_update = tf.assign_add(total_loss, loss_value)
loss_count_update = tf.assign_add(loss_count, 1)
loss_op = total_loss / tf.cast(loss_count, tf.float32)
return [tot... | [
"def",
"loss",
"(",
"loss_value",
")",
":",
"total_loss",
"=",
"tf",
".",
"Variable",
"(",
"0.0",
",",
"False",
")",
"loss_count",
"=",
"tf",
".",
"Variable",
"(",
"0",
",",
"False",
")",
"total_loss_update",
"=",
"tf",
".",
"assign_add",
"(",
"total_l... | 44.5 | 10.75 |
def _array2cstr(arr):
""" Serializes a numpy array to a compressed base64 string """
out = StringIO()
np.save(out, arr)
return b64encode(out.getvalue()) | [
"def",
"_array2cstr",
"(",
"arr",
")",
":",
"out",
"=",
"StringIO",
"(",
")",
"np",
".",
"save",
"(",
"out",
",",
"arr",
")",
"return",
"b64encode",
"(",
"out",
".",
"getvalue",
"(",
")",
")"
] | 32.8 | 12.4 |
def close(self):
"""Closes the serial port."""
if self.pyb and self.pyb.serial:
self.pyb.serial.close()
self.pyb = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"pyb",
"and",
"self",
".",
"pyb",
".",
"serial",
":",
"self",
".",
"pyb",
".",
"serial",
".",
"close",
"(",
")",
"self",
".",
"pyb",
"=",
"None"
] | 30.2 | 9.2 |
def copy_dependency_images(tile):
"""Copy all documentation from dependencies into build/output/doc folder"""
env = Environment(tools=[])
outputbase = os.path.join('build', 'output')
depbase = os.path.join('build', 'deps')
for dep in tile.dependencies:
depdir = os.path.join(depbase, dep['u... | [
"def",
"copy_dependency_images",
"(",
"tile",
")",
":",
"env",
"=",
"Environment",
"(",
"tools",
"=",
"[",
"]",
")",
"outputbase",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'build'",
",",
"'output'",
")",
"depbase",
"=",
"os",
".",
"path",
".",
"joi... | 38.222222 | 17.277778 |
def transform(self, X, y=None, copy=None):
"""
Perform standardization by centering and scaling using the parameters.
:param X: Data matrix to scale.
:type X: numpy.ndarray, shape [n_samples, n_features]
:param y: Passthrough for scikit-learn ``Pipeline`` compatibility.
... | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"copy",
"=",
"None",
")",
":",
"check_is_fitted",
"(",
"self",
",",
"'scale_'",
")",
"copy",
"=",
"copy",
"if",
"copy",
"is",
"not",
"None",
"else",
"self",
".",
"copy",
"X",
... | 38.03125 | 18.46875 |
def export(self):
"""
Make the actual request to the Import API (exporting is part of the
Import API) to export a map visualization as a .carto file
:return: A URL pointing to the .carto file
:rtype: str
:raise: CartoException
.. warning:: Non-public API. It ma... | [
"def",
"export",
"(",
"self",
")",
":",
"export_job",
"=",
"ExportJob",
"(",
"self",
".",
"client",
",",
"self",
".",
"get_id",
"(",
")",
")",
"export_job",
".",
"run",
"(",
")",
"export_job",
".",
"refresh",
"(",
")",
"count",
"=",
"0",
"while",
"... | 38.921053 | 26.868421 |
def random_numbers(n):
"""
Generate a random string from 0-9
:param n: length of the string
:return: the random string
"""
return ''.join(random.SystemRandom().choice(string.digits) for _ in range(n)) | [
"def",
"random_numbers",
"(",
"n",
")",
":",
"return",
"''",
".",
"join",
"(",
"random",
".",
"SystemRandom",
"(",
")",
".",
"choice",
"(",
"string",
".",
"digits",
")",
"for",
"_",
"in",
"range",
"(",
"n",
")",
")"
] | 31.142857 | 11.142857 |
def _compute_and_transfer_to_final_run(self, process_name, start_timeperiod, end_timeperiod, job_record):
""" method computes new unit_of_work and transfers the job to STATE_FINAL_RUN
it also shares _fuzzy_ DuplicateKeyError logic from _compute_and_transfer_to_progress method"""
source_collectio... | [
"def",
"_compute_and_transfer_to_final_run",
"(",
"self",
",",
"process_name",
",",
"start_timeperiod",
",",
"end_timeperiod",
",",
"job_record",
")",
":",
"source_collection_name",
"=",
"context",
".",
"process_context",
"[",
"process_name",
"]",
".",
"source",
"star... | 73.454545 | 32.909091 |
def start(self):
"""Open sockets to the server and start threads"""
if not self.writeThread.isAlive() and not self.readThread.isAlive():
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client.connect(self.ADDR)
self.running = True
self... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"writeThread",
".",
"isAlive",
"(",
")",
"and",
"not",
"self",
".",
"readThread",
".",
"isAlive",
"(",
")",
":",
"self",
".",
"client",
"=",
"socket",
".",
"socket",
"(",
"socket",
".... | 46.125 | 14.375 |
def get_file_array(self, start, end):
"""Return a list of filenames between and including start and end.
Parameters
----------
start: array_like or single string
filenames for start of returned filelist
stop: array_like or single string
... | [
"def",
"get_file_array",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"if",
"hasattr",
"(",
"start",
",",
"'__iter__'",
")",
"&",
"hasattr",
"(",
"end",
",",
"'__iter__'",
")",
":",
"files",
"=",
"[",
"]",
"for",
"(",
"sta",
",",
"stp",
")",
... | 37.433333 | 15.466667 |
def set_index(self, index):
"""Set or reset the index.
Parameters
----------
index : string or pair of strings, optional
Names of columns to use for positional index, e.g., 'POS' if table
contains a 'POS' column and records from a single
chromosome/co... | [
"def",
"set_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"is",
"None",
":",
"pass",
"elif",
"isinstance",
"(",
"index",
",",
"str",
")",
":",
"index",
"=",
"SortedIndex",
"(",
"self",
"[",
"index",
"]",
",",
"copy",
"=",
"False",
")"... | 39.956522 | 20.695652 |
def _get_html_response(url, session):
# type: (str, PipSession) -> Response
"""Access an HTML page with GET, and return the response.
This consists of three parts:
1. If the URL looks suspiciously like an archive, send a HEAD first to
check the Content-Type is HTML, to avoid downloading a large... | [
"def",
"_get_html_response",
"(",
"url",
",",
"session",
")",
":",
"# type: (str, PipSession) -> Response",
"if",
"_is_url_like_archive",
"(",
"url",
")",
":",
"_ensure_html_response",
"(",
"url",
",",
"session",
"=",
"session",
")",
"logger",
".",
"debug",
"(",
... | 42.387755 | 21.693878 |
def _propagate_down(self, handle, target_id):
"""
For DEL_ROUTE, we additionally want to broadcast the message to any
stream that has ever communicated with the disconnecting ID, so
core.py's :meth:`mitogen.core.Router._on_del_route` can turn the
message into a disconnect event.
... | [
"def",
"_propagate_down",
"(",
"self",
",",
"handle",
",",
"target_id",
")",
":",
"for",
"stream",
"in",
"self",
".",
"router",
".",
"get_streams",
"(",
")",
":",
"if",
"target_id",
"in",
"stream",
".",
"egress_ids",
"and",
"(",
"(",
"self",
".",
"pare... | 45.444444 | 18.333333 |
def vera_request(self, **kwargs):
"""Perfom a vera_request for this scene."""
request_payload = {
'output_format': 'json',
'SceneNum': self.scene_id,
}
request_payload.update(kwargs)
return self.vera_controller.data_request(request_payload) | [
"def",
"vera_request",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"request_payload",
"=",
"{",
"'output_format'",
":",
"'json'",
",",
"'SceneNum'",
":",
"self",
".",
"scene_id",
",",
"}",
"request_payload",
".",
"update",
"(",
"kwargs",
")",
"return",... | 33 | 13.777778 |
def instantiate_for_read_and_search(handle_server_url, reverselookup_username, reverselookup_password, **config):
'''
Initialize client with read access and with search function.
:param handle_server_url: The URL of the Handle Server. May be None
(then, the default 'https://hdl.hand... | [
"def",
"instantiate_for_read_and_search",
"(",
"handle_server_url",
",",
"reverselookup_username",
",",
"reverselookup_password",
",",
"*",
"*",
"config",
")",
":",
"if",
"handle_server_url",
"is",
"None",
"and",
"'reverselookup_baseuri'",
"not",
"in",
"config",
".",
... | 48.296296 | 28.814815 |
def airing_today(self, **kwargs):
"""
Get the list of TV shows that air today. Without a specified timezone,
this query defaults to EST (Eastern Time UTC-05:00).
Args:
page: (optional) Minimum 1, maximum 1000.
language: (optional) ISO 639 code.
timezo... | [
"def",
"airing_today",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"'airing_today'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs_to_values",
"(",
"... | 34.166667 | 19.055556 |
def write_config_file_value(key, value):
"""
Writes an environment variable configuration to the current
config file. This will be read in on the next restart.
The config file is created if not present.
Note: The variables will not take effect until after restart.
"""
filename = get_confi... | [
"def",
"write_config_file_value",
"(",
"key",
",",
"value",
")",
":",
"filename",
"=",
"get_config_file",
"(",
")",
"config",
"=",
"_ConfigParser",
".",
"SafeConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"filename",
")",
"__section",
"=",
"\"Environment... | 26.565217 | 17.869565 |
def shared_databases(self):
"""
Retrieves a list containing the names of databases shared
with this account.
:returns: List of database names
"""
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'shared_databases'))
resp = self.r_session.g... | [
"def",
"shared_databases",
"(",
"self",
")",
":",
"endpoint",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"server_url",
",",
"'_api'",
",",
"'v2'",
",",
"'user'",
",",
"'shared_databases'",
")",
")",
"resp",
"=",
"self",
".",
"r_session",
".",
"get... | 34.076923 | 11.923077 |
def _is_auto_field(self, cursor, table_name, column_name):
"""
Checks whether column is Identity
"""
# COLUMNPROPERTY: http://msdn2.microsoft.com/en-us/library/ms174968.aspx
#from django.db import connection
#cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsId... | [
"def",
"_is_auto_field",
"(",
"self",
",",
"cursor",
",",
"table_name",
",",
"column_name",
")",
":",
"# COLUMNPROPERTY: http://msdn2.microsoft.com/en-us/library/ms174968.aspx",
"#from django.db import connection",
"#cursor.execute(\"SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsIdentity')... | 50.25 | 22.083333 |
def hybrid_meco_velocity(m1, m2, chi1, chi2, qm1=None, qm2=None):
"""Return the velocity of the hybrid MECO
Parameters
----------
m1 : float
Mass of the primary object in solar masses.
m2 : float
Mass of the secondary object in solar masses.
chi1: float
Dimensionless spi... | [
"def",
"hybrid_meco_velocity",
"(",
"m1",
",",
"m2",
",",
"chi1",
",",
"chi2",
",",
"qm1",
"=",
"None",
",",
"qm2",
"=",
"None",
")",
":",
"if",
"qm1",
"is",
"None",
":",
"qm1",
"=",
"1",
"if",
"qm2",
"is",
"None",
":",
"qm2",
"=",
"1",
"# Set ... | 30.837838 | 21.216216 |
def _getBlobFromURL(cls, url, exists=False):
"""
Gets the blob specified by the url.
caution: makes no api request. blob may not ACTUALLY exist
:param urlparse.ParseResult url: the URL
:param bool exists: if True, then syncs local blob object with cloud
and raises exce... | [
"def",
"_getBlobFromURL",
"(",
"cls",
",",
"url",
",",
"exists",
"=",
"False",
")",
":",
"bucketName",
"=",
"url",
".",
"netloc",
"fileName",
"=",
"url",
".",
"path",
"# remove leading '/', which can cause problems if fileName is a path",
"if",
"fileName",
".",
"s... | 31.774194 | 18.225806 |
def tags(self):
"""Access the auxillary data here"""
if self._tags: return self._tags
tags = {}
if not tags: return {}
for m in [[y.group(1),y.group(2),y.group(3)] for y in [re.match('([^:]{2,2}):([^:]):(.+)$',x) for x in self.entries.optional_fields.split("\t")]]:
if m[1] == 'i': m[2] ... | [
"def",
"tags",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tags",
":",
"return",
"self",
".",
"_tags",
"tags",
"=",
"{",
"}",
"if",
"not",
"tags",
":",
"return",
"{",
"}",
"for",
"m",
"in",
"[",
"[",
"y",
".",
"group",
"(",
"1",
")",
",",
"... | 41.181818 | 19.818182 |
def clized_default_shorts(p1, p2,
first_option='default_value',
second_option=5,
third_option=[4, 3],
last_option=False):
"""Help docstring
"""
print('%s %s %s %s %s %s' % (p1, p2, first_option, second_op... | [
"def",
"clized_default_shorts",
"(",
"p1",
",",
"p2",
",",
"first_option",
"=",
"'default_value'",
",",
"second_option",
"=",
"5",
",",
"third_option",
"=",
"[",
"4",
",",
"3",
"]",
",",
"last_option",
"=",
"False",
")",
":",
"print",
"(",
"'%s %s %s %s %s... | 43.25 | 11.5 |
def get_kgXref_hg19(self):
""" Get UCSC kgXref table for Build 37.
Returns
-------
pandas.DataFrame
kgXref table if loading was successful, else None
"""
if self._kgXref_hg19 is None:
self._kgXref_hg19 = self._load_kgXref(self._get_path_kgXref_hg1... | [
"def",
"get_kgXref_hg19",
"(",
"self",
")",
":",
"if",
"self",
".",
"_kgXref_hg19",
"is",
"None",
":",
"self",
".",
"_kgXref_hg19",
"=",
"self",
".",
"_load_kgXref",
"(",
"self",
".",
"_get_path_kgXref_hg19",
"(",
")",
")",
"return",
"self",
".",
"_kgXref_... | 28.916667 | 19.25 |
def _set_protobuf_value(value_pb, val):
"""Assign 'val' to the correct subfield of 'value_pb'.
The Protobuf API uses different attribute names based on value types
rather than inferring the type.
Some value types (entities, keys, lists) cannot be directly
assigned; this function handles them corre... | [
"def",
"_set_protobuf_value",
"(",
"value_pb",
",",
"val",
")",
":",
"attr",
",",
"val",
"=",
"_pb_attr_value",
"(",
"val",
")",
"if",
"attr",
"==",
"\"key_value\"",
":",
"value_pb",
".",
"key_value",
".",
"CopyFrom",
"(",
"val",
")",
"elif",
"attr",
"==... | 38.684211 | 14.026316 |
def eqdate(y):
"""
Like eq but compares datetime with y,m,d tuple.
Also accepts magic string 'TODAY'.
"""
y = datetime.date.today() if y == 'TODAY' else datetime.date(*y)
return lambda x: x == y | [
"def",
"eqdate",
"(",
"y",
")",
":",
"y",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"if",
"y",
"==",
"'TODAY'",
"else",
"datetime",
".",
"date",
"(",
"*",
"y",
")",
"return",
"lambda",
"x",
":",
"x",
"==",
"y"
] | 30.285714 | 11.428571 |
def _default_ising_beta_range(h, J):
"""Determine the starting and ending beta from h J
Args:
h (dict)
J (dict)
Assume each variable in J is also in h.
We use the minimum bias to give a lower bound on the minimum energy gap, such at the
final sweeps we are highly likely to settle... | [
"def",
"_default_ising_beta_range",
"(",
"h",
",",
"J",
")",
":",
"# Get nonzero, absolute biases",
"abs_h",
"=",
"[",
"abs",
"(",
"hh",
")",
"for",
"hh",
"in",
"h",
".",
"values",
"(",
")",
"if",
"hh",
"!=",
"0",
"]",
"abs_J",
"=",
"[",
"abs",
"(",
... | 38.9375 | 24.083333 |
def async_or_eager(self, **options):
"""
Attempt to call self.apply_async, or if that fails because of a problem
with the broker, run the task eagerly and return an EagerResult.
"""
args = options.pop("args", None)
kwargs = options.pop("kwargs", None)
possible_bro... | [
"def",
"async_or_eager",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"args",
"=",
"options",
".",
"pop",
"(",
"\"args\"",
",",
"None",
")",
"kwargs",
"=",
"options",
".",
"pop",
"(",
"\"kwargs\"",
",",
"None",
")",
"possible_broker_errors",
"=",
"... | 44.166667 | 14.666667 |
def DirContains(self,f) :
""" Matches dirs that have a child that matches filter f"""
def match(fsNode) :
if not fsNode.isdir() : return False
for c in fsNode.children() :
if f(c) : return True
return False
return self.make_return(match) | [
"def",
"DirContains",
"(",
"self",
",",
"f",
")",
":",
"def",
"match",
"(",
"fsNode",
")",
":",
"if",
"not",
"fsNode",
".",
"isdir",
"(",
")",
":",
"return",
"False",
"for",
"c",
"in",
"fsNode",
".",
"children",
"(",
")",
":",
"if",
"f",
"(",
"... | 38.375 | 7.25 |
def _time_to_expiry(expires):
"""
Determines the seconds until a HTTP header "Expires" timestamp
:param expires: HTTP response "Expires" header
:return: seconds until "Expires" time
"""
try:
expires_dt = datetime.strptime(str(expires), '%a, %d %b %Y %H:%M:%S %... | [
"def",
"_time_to_expiry",
"(",
"expires",
")",
":",
"try",
":",
"expires_dt",
"=",
"datetime",
".",
"strptime",
"(",
"str",
"(",
"expires",
")",
",",
"'%a, %d %b %Y %H:%M:%S %Z'",
")",
"delta",
"=",
"expires_dt",
"-",
"datetime",
".",
"utcnow",
"(",
")",
"... | 37 | 15.333333 |
def take_action(self, production_rule: str) -> 'GrammarStatelet':
"""
Takes an action in the current grammar state, returning a new grammar state with whatever
updates are necessary. The production rule is assumed to be formatted as "LHS -> RHS".
This will update the non-terminal stack... | [
"def",
"take_action",
"(",
"self",
",",
"production_rule",
":",
"str",
")",
"->",
"'GrammarStatelet'",
":",
"left_side",
",",
"right_side",
"=",
"production_rule",
".",
"split",
"(",
"' -> '",
")",
"assert",
"self",
".",
"_nonterminal_stack",
"[",
"-",
"1",
... | 52.057143 | 31.428571 |
def user_can_add_attachments(self):
"""Checks if the current logged in user is allowed to add attachments
"""
if not self.global_attachments_allowed():
return False
context = self.context
pm = api.get_tool("portal_membership")
return pm.checkPermission(AddAtta... | [
"def",
"user_can_add_attachments",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"global_attachments_allowed",
"(",
")",
":",
"return",
"False",
"context",
"=",
"self",
".",
"context",
"pm",
"=",
"api",
".",
"get_tool",
"(",
"\"portal_membership\"",
")",
... | 41.125 | 7.875 |
def _get_timestamp_tuple(ts):
"""
Internal method to get a timestamp tuple from a value.
Handles input being a datetime or a Timestamp.
"""
if isinstance(ts, datetime.datetime):
return Timestamp.from_datetime(ts).tuple()
elif isinstance(ts, Timestamp):
return ts
raise... | [
"def",
"_get_timestamp_tuple",
"(",
"ts",
")",
":",
"if",
"isinstance",
"(",
"ts",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"Timestamp",
".",
"from_datetime",
"(",
"ts",
")",
".",
"tuple",
"(",
")",
"elif",
"isinstance",
"(",
"ts",
",",
"T... | 36.4 | 10 |
def check_membership(self, groups):
''' Allows for objects with no required groups '''
if not groups or groups == ['']:
return True
if self.request.user.is_superuser:
return True
user_groups = self.request.user.groups.values_list("name", flat=True)
... | [
"def",
"check_membership",
"(",
"self",
",",
"groups",
")",
":",
"if",
"not",
"groups",
"or",
"groups",
"==",
"[",
"''",
"]",
":",
"return",
"True",
"if",
"self",
".",
"request",
".",
"user",
".",
"is_superuser",
":",
"return",
"True",
"user_groups",
"... | 45.25 | 14.25 |
def _header(self):
"""
Default html header
"""
html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Report</title>
"""
if "bokeh" in self.report_engines:
html += self.bokeh_header_()
if "altair" in self.report_engines:... | [
"def",
"_header",
"(",
"self",
")",
":",
"html",
"=",
"\"\"\"\n\t\t<!DOCTYPE html>\n\t\t<html lang=\"en\">\n\t\t<head>\n\t\t\t<meta charset=\"utf-8\">\n\t\t\t<title>Report</title>\n\t\t\"\"\"",
"if",
"\"bokeh\"",
"in",
"self",
".",
"report_engines",
":",
"html",
"+=",
"self",
"... | 22.454545 | 10.863636 |
def update_shelf(self, shelf_id, shelf_data):
"""
修改货架
:param shelf_id: 货架ID
:param shelf_data: 货架详情
:return: 返回的 JSON 数据包
"""
shelf_data['shelf_id'] = shelf_id
return self._post(
'merchant/shelf/mod',
data=shelf_data
) | [
"def",
"update_shelf",
"(",
"self",
",",
"shelf_id",
",",
"shelf_data",
")",
":",
"shelf_data",
"[",
"'shelf_id'",
"]",
"=",
"shelf_id",
"return",
"self",
".",
"_post",
"(",
"'merchant/shelf/mod'",
",",
"data",
"=",
"shelf_data",
")"
] | 23.384615 | 13.076923 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.