text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def getOrderVectors(self):
"""
Returns a list of lists, one for each preference, of candidates ordered from most preferred
to least. Note that ties are not indicated in the returned lists. Also returns a list of
the number of times each preference is given.
"""
orderVect... | [
"def",
"getOrderVectors",
"(",
"self",
")",
":",
"orderVectors",
"=",
"[",
"]",
"for",
"preference",
"in",
"self",
".",
"preferences",
":",
"orderVectors",
".",
"append",
"(",
"preference",
".",
"getOrderVector",
"(",
")",
")",
"return",
"orderVectors"
] | 41 | 0.008677 |
def compare_conditions(self, labels1, labels2, measure_name, alpha=0.01, repeats=100, num_samples=None, plot=False, random_state=None):
""" Test for significant difference in connectivity of two sets of class labels.
Connectivity estimates are obtained by bootstrapping. Correction for multiple testing ... | [
"def",
"compare_conditions",
"(",
"self",
",",
"labels1",
",",
"labels2",
",",
"measure_name",
",",
"alpha",
"=",
"0.01",
",",
"repeats",
"=",
"100",
",",
"num_samples",
"=",
"None",
",",
"plot",
"=",
"False",
",",
"random_state",
"=",
"None",
")",
":",
... | 51.462366 | 0.00697 |
def _solve_tsp(dist, niter):
"""Solve travelling salesperson problem (TSP) by two-opt swapping.
Params
------
dist (ndarray) : distance matrix
Returns
-------
path (ndarray) : permutation of nodes in graph (rows of dist matrix)
"""
# number of nodes
N = dist.shape[0]
# ts... | [
"def",
"_solve_tsp",
"(",
"dist",
",",
"niter",
")",
":",
"# number of nodes",
"N",
"=",
"dist",
".",
"shape",
"[",
"0",
"]",
"# tsp path for quick calculation of cost",
"ii",
"=",
"np",
".",
"arange",
"(",
"N",
")",
"jj",
"=",
"np",
".",
"hstack",
"(",
... | 26.753247 | 0.000468 |
def delete_external_event(self, calendar_id, event_uid):
"""Delete an external event from the specified calendar.
:param string calendar_id: ID of calendar to delete from.
:param string event_uid: ID of event to delete.
"""
self.request_handler.delete(endpoint='calendars/%s/even... | [
"def",
"delete_external_event",
"(",
"self",
",",
"calendar_id",
",",
"event_uid",
")",
":",
"self",
".",
"request_handler",
".",
"delete",
"(",
"endpoint",
"=",
"'calendars/%s/events'",
"%",
"calendar_id",
",",
"data",
"=",
"{",
"'event_uid'",
":",
"event_uid",... | 51.857143 | 0.00813 |
def backward(ctx, grad_output):
"""
In the backward pass, we set the gradient to 1 for the winning units, and 0
for the others.
"""
indices, = ctx.saved_tensors
grad_x = torch.zeros_like(grad_output, requires_grad=True)
# Probably a better way to do it, but this is not terrible as it only l... | [
"def",
"backward",
"(",
"ctx",
",",
"grad_output",
")",
":",
"indices",
",",
"=",
"ctx",
".",
"saved_tensors",
"grad_x",
"=",
"torch",
".",
"zeros_like",
"(",
"grad_output",
",",
"requires_grad",
"=",
"True",
")",
"# Probably a better way to do it, but this is not... | 33.785714 | 0.004115 |
def validate_message_dict(self, request_body):
"""With the JSON dict that will be sent to SendGrid's API,
check the content for SendGrid API keys - throw exception if found.
:param request_body: The JSON dict that will be sent to SendGrid's
API.
... | [
"def",
"validate_message_dict",
"(",
"self",
",",
"request_body",
")",
":",
"# Handle string in edge-case",
"if",
"isinstance",
"(",
"request_body",
",",
"str",
")",
":",
"self",
".",
"validate_message_text",
"(",
"request_body",
")",
"# Default param",
"elif",
"isi... | 41.769231 | 0.0018 |
def load_existing_catalog(self, cat, **kwargs):
"""Load sources from an existing catalog object.
Parameters
----------
cat : `~fermipy.catalog.Catalog`
Catalog object.
"""
coordsys = kwargs.get('coordsys', 'CEL')
extdir = kwargs.get('extdir', self.ex... | [
"def",
"load_existing_catalog",
"(",
"self",
",",
"cat",
",",
"*",
"*",
"kwargs",
")",
":",
"coordsys",
"=",
"kwargs",
".",
"get",
"(",
"'coordsys'",
",",
"'CEL'",
")",
"extdir",
"=",
"kwargs",
".",
"get",
"(",
"'extdir'",
",",
"self",
".",
"extdir",
... | 43.4 | 0.000601 |
def value(self):
"""
Get the value of the match, using formatter if defined.
:return:
:rtype:
"""
if self._value:
return self._value
if self.formatter:
return self.formatter(self.raw)
return self.raw | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_value",
":",
"return",
"self",
".",
"_value",
"if",
"self",
".",
"formatter",
":",
"return",
"self",
".",
"formatter",
"(",
"self",
".",
"raw",
")",
"return",
"self",
".",
"raw"
] | 25.181818 | 0.006969 |
def _read_para_r1_counter(self, code, cbit, clen, *, desc, length, version):
"""Read HIP R1_COUNTER parameter.
Structure of HIP R1_COUNTER parameter [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ... | [
"def",
"_read_para_r1_counter",
"(",
"self",
",",
"code",
",",
"cbit",
",",
"clen",
",",
"*",
",",
"desc",
",",
"length",
",",
"version",
")",
":",
"if",
"clen",
"!=",
"12",
":",
"raise",
"ProtocolError",
"(",
"f'HIPv{version}: [Parano {code}] invalid format'"... | 47.333333 | 0.002654 |
def ConvCnstrMODMask(*args, **kwargs):
"""A wrapper function that dynamically defines a class derived from
one of the implementations of the Convolutional Constrained MOD
problems, and returns an object instantiated with the provided
parameters. The wrapper is designed to allow the appropriate
objec... | [
"def",
"ConvCnstrMODMask",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Extract method selection argument or set default",
"method",
"=",
"kwargs",
".",
"pop",
"(",
"'method'",
",",
"'fista'",
")",
"# Assign base class depending on method selection argument",
... | 42.955556 | 0.000506 |
def validate_term(term, so=None, method="verify"):
"""
Validate an SO term against so.obo
"""
if so is None:
so = load_GODag()
oterm = term
if term not in so.valid_names:
if "resolve" in method:
if "_" in term:
tparts = deque(term.split("_"))
... | [
"def",
"validate_term",
"(",
"term",
",",
"so",
"=",
"None",
",",
"method",
"=",
"\"verify\"",
")",
":",
"if",
"so",
"is",
"None",
":",
"so",
"=",
"load_GODag",
"(",
")",
"oterm",
"=",
"term",
"if",
"term",
"not",
"in",
"so",
".",
"valid_names",
":... | 31.333333 | 0.00129 |
def _split(self, string):
"""Iterates over the ngrams of a string (no padding).
>>> from ngram import NGram
>>> n = NGram()
>>> list(n._split("hamegg"))
['ham', 'ame', 'meg', 'egg']
"""
for i in range(len(string) - self.N + 1):
yield string[i:i + self... | [
"def",
"_split",
"(",
"self",
",",
"string",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"string",
")",
"-",
"self",
".",
"N",
"+",
"1",
")",
":",
"yield",
"string",
"[",
"i",
":",
"i",
"+",
"self",
".",
"N",
"]"
] | 31.4 | 0.006192 |
def request(self, method, url, parameters=dict()):
"""Requests wrapper function"""
# The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase
parameters = self._serializeBooleans(parameters)
headers = {'App-Key': self.apikey}
if self... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"parameters",
"=",
"dict",
"(",
")",
")",
":",
"# The requests library uses urllib, which serializes to \"True\"/\"False\" while Pingdom requires lowercase",
"parameters",
"=",
"self",
".",
"_serializeBooleans",... | 43.804348 | 0.001456 |
def key_expand(self, key):
"""
Derive public key and account number from **private key**
:param key: Private key to generate account and public key of
:type key: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.key_expand(
key="781186FB9EF17DB6E3D105655... | [
"def",
"key_expand",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"self",
".",
"_process_value",
"(",
"key",
",",
"'privatekey'",
")",
"payload",
"=",
"{",
"\"key\"",
":",
"key",
"}",
"resp",
"=",
"self",
".",
"call",
"(",
"'key_expand'",
",",
"pay... | 29.555556 | 0.006068 |
def list_nsgs_all(access_token, subscription_id):
'''List all network security groups in a subscription.
Args:
access_token (str): a valid Azure Authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of all network security groups in... | [
"def",
"list_nsgs_all",
"(",
"access_token",
",",
"subscription_id",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"get_rm_endpoint",
"(",
")",
",",
"'/subscriptions/'",
",",
"subscription_id",
",",
"'/providers/Microsoft.Network/'",
",",
"'networkSEcurity... | 41.857143 | 0.008347 |
def GetCalendarFieldValuesTuple(self):
"""Return the tuple of calendar.txt values or None if this ServicePeriod
should not be in calendar.txt ."""
if self.start_date and self.end_date:
return [getattr(self, fn) for fn in self._FIELD_NAMES] | [
"def",
"GetCalendarFieldValuesTuple",
"(",
"self",
")",
":",
"if",
"self",
".",
"start_date",
"and",
"self",
".",
"end_date",
":",
"return",
"[",
"getattr",
"(",
"self",
",",
"fn",
")",
"for",
"fn",
"in",
"self",
".",
"_FIELD_NAMES",
"]"
] | 50.6 | 0.007782 |
def getByteStatistic(self, wanInterfaceId=1, timeout=1):
"""Execute GetTotalBytesSent&GetTotalBytesReceived actions to get WAN statistics.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: a tuple of two ... | [
"def",
"getByteStatistic",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"getByteStatistic\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
".",
... | 50.0625 | 0.008578 |
def _api(fn):
"""API decorator for common tests (sessions open, etc.) and throttle
limitation (calls per second)."""
@_functools.wraps(fn)
def _fn(self, *args, **kwargs):
self._throttle_wait()
if not self._SID:
raise RuntimeError('Session closed. I... | [
"def",
"_api",
"(",
"fn",
")",
":",
"@",
"_functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"_fn",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_throttle_wait",
"(",
")",
"if",
"not",
"self",
".",
"_SID",
":",... | 40 | 0.00489 |
def get_item(self, item_id):
""" Returns a DriveItem by it's Id
:return: one item
:rtype: DriveItem
"""
if self.object_id:
# reference the current drive_id
url = self.build_url(
self._endpoints.get('get_item').format(id=self.object_id,
... | [
"def",
"get_item",
"(",
"self",
",",
"item_id",
")",
":",
"if",
"self",
".",
"object_id",
":",
"# reference the current drive_id",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'get_item'",
")",
".",
"format",
"(",... | 35.32 | 0.003308 |
def validate_ip_address(ip_address):
"""Validate the ip_address
:param ip_address: (str) IP address
:return: (bool) True if the ip_address is valid
"""
# Validate the IP address
log = logging.getLogger(mod_logger + '.validate_ip_address')
if not isinstance(ip_address, basestring):
l... | [
"def",
"validate_ip_address",
"(",
"ip_address",
")",
":",
"# Validate the IP address",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.validate_ip_address'",
")",
"if",
"not",
"isinstance",
"(",
"ip_address",
",",
"basestring",
")",
":",
"log"... | 29.666667 | 0.001088 |
def reload_glance(self, target_app, slices=None):
"""
Reloads an app's glance. Blocks as long as necessary.
:param target_app: The UUID of the app for which to reload its glance.
:type target_app: ~uuid.UUID
:param slices: The slices with which to reload the app's glance.
... | [
"def",
"reload_glance",
"(",
"self",
",",
"target_app",
",",
"slices",
"=",
"None",
")",
":",
"glance",
"=",
"AppGlance",
"(",
"version",
"=",
"1",
",",
"creation_time",
"=",
"time",
".",
"time",
"(",
")",
",",
"slices",
"=",
"(",
"slices",
"or",
"["... | 39.666667 | 0.004926 |
def assess(self, cases=None):
"""Try to sort the **cases** using the network, return the number of
misses. If **cases** is None, test all possible cases according to
the network dimensionality.
"""
if cases is None:
cases = product(range(2), repeat=self.dimension)
... | [
"def",
"assess",
"(",
"self",
",",
"cases",
"=",
"None",
")",
":",
"if",
"cases",
"is",
"None",
":",
"cases",
"=",
"product",
"(",
"range",
"(",
"2",
")",
",",
"repeat",
"=",
"self",
".",
"dimension",
")",
"misses",
"=",
"0",
"ordered",
"=",
"[",... | 39.733333 | 0.006557 |
def get_time_remaining_estimate(self):
"""
Looks through all power sources and returns total time remaining estimate
or TIME_REMAINING_UNLIMITED if ac power supply is online.
"""
all_energy_now = []
all_power_now = []
try:
type = self.power_source_type... | [
"def",
"get_time_remaining_estimate",
"(",
"self",
")",
":",
"all_energy_now",
"=",
"[",
"]",
"all_power_now",
"=",
"[",
"]",
"try",
":",
"type",
"=",
"self",
".",
"power_source_type",
"(",
")",
"if",
"type",
"==",
"common",
".",
"POWER_TYPE_AC",
":",
"if"... | 47.833333 | 0.004781 |
def openid_authorization_validator(self, request):
"""Additional validation when following the Authorization Code flow.
"""
request_info = super(HybridGrant, self).openid_authorization_validator(request)
if not request_info: # returns immediately if OAuth2.0
return request_i... | [
"def",
"openid_authorization_validator",
"(",
"self",
",",
"request",
")",
":",
"request_info",
"=",
"super",
"(",
"HybridGrant",
",",
"self",
")",
".",
"openid_authorization_validator",
"(",
"request",
")",
"if",
"not",
"request_info",
":",
"# returns immediately i... | 52.695652 | 0.002431 |
def list_files(tag='', sat_id=None, data_path=None, format_str=None):
"""Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '' and 'ascii'.
If '' is specified, the primary dat... | [
"def",
"list_files",
"(",
"tag",
"=",
"''",
",",
"sat_id",
"=",
"None",
",",
"data_path",
"=",
"None",
",",
"format_str",
"=",
"None",
")",
":",
"if",
"format_str",
"is",
"None",
"and",
"tag",
"is",
"not",
"None",
":",
"if",
"tag",
"==",
"''",
"or"... | 41.567568 | 0.000635 |
def julian_day(t: date) -> int:
"""Convert a Python datetime to a Julian day"""
# Compute the number of days from January 1, 2000 to date t
dt = t - julian_base_date
# Add the julian base number to the number of days from the julian base date to date t
return julian_base_number + dt.days | [
"def",
"julian_day",
"(",
"t",
":",
"date",
")",
"->",
"int",
":",
"# Compute the number of days from January 1, 2000 to date t",
"dt",
"=",
"t",
"-",
"julian_base_date",
"# Add the julian base number to the number of days from the julian base date to date t",
"return",
"julian_b... | 50.5 | 0.006494 |
def send_event(self, instance, message, event_type=None, time=None,
severity='info', source=None, sequence_number=None):
"""
Post a new event.
:param str instance: A Yamcs instance name.
:param str message: Event message.
:param Optional[str] event_type: Type ... | [
"def",
"send_event",
"(",
"self",
",",
"instance",
",",
"message",
",",
"event_type",
"=",
"None",
",",
"time",
"=",
"None",
",",
"severity",
"=",
"'info'",
",",
"source",
"=",
"None",
",",
"sequence_number",
"=",
"None",
")",
":",
"req",
"=",
"rest_pb... | 41.714286 | 0.002789 |
def boston(display=False):
""" Return the boston housing data in a nice package. """
d = sklearn.datasets.load_boston()
df = pd.DataFrame(data=d.data, columns=d.feature_names) # pylint: disable=E1101
return df, d.target | [
"def",
"boston",
"(",
"display",
"=",
"False",
")",
":",
"d",
"=",
"sklearn",
".",
"datasets",
".",
"load_boston",
"(",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"data",
"=",
"d",
".",
"data",
",",
"columns",
"=",
"d",
".",
"feature_names",
")",... | 38.5 | 0.012712 |
def when(self, condition, value):
"""
Evaluates a list of conditions and returns one of multiple possible result expressions.
If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions.
See :func:`pyspark.sql.functions.when` for example usage.
:param ... | [
"def",
"when",
"(",
"self",
",",
"condition",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"condition",
",",
"Column",
")",
":",
"raise",
"TypeError",
"(",
"\"condition should be a Column\"",
")",
"v",
"=",
"value",
".",
"_jc",
"if",
"isinstance... | 53.208333 | 0.003846 |
def status(config='root', num_pre=None, num_post=None):
'''
Returns a comparison between two snapshots
config
Configuration name.
num_pre
first snapshot ID to compare. Default is last snapshot
num_post
last snapshot ID to compare. Default is 0 (current state)
CLI exam... | [
"def",
"status",
"(",
"config",
"=",
"'root'",
",",
"num_pre",
"=",
"None",
",",
"num_post",
"=",
"None",
")",
":",
"try",
":",
"pre",
",",
"post",
"=",
"_get_num_interval",
"(",
"config",
",",
"num_pre",
",",
"num_post",
")",
"snapper",
".",
"CreateCo... | 34.810811 | 0.002266 |
async def SetMetricCredentials(self, creds):
'''
creds : typing.Sequence[~ApplicationMetricCredential]
Returns -> typing.Sequence[~ErrorResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Application',
request='SetMetricCr... | [
"async",
"def",
"SetMetricCredentials",
"(",
"self",
",",
"creds",
")",
":",
"# map input types to rpc msg",
"_params",
"=",
"dict",
"(",
")",
"msg",
"=",
"dict",
"(",
"type",
"=",
"'Application'",
",",
"request",
"=",
"'SetMetricCredentials'",
",",
"version",
... | 33.785714 | 0.004115 |
def _dir_additions(self):
""" add the string-like attributes from the info_axis.
If info_axis is a MultiIndex, it's first level values are used.
"""
additions = {c for c in self._info_axis.unique(level=0)[:100]
if isinstance(c, str) and c.isidentifier()}
retu... | [
"def",
"_dir_additions",
"(",
"self",
")",
":",
"additions",
"=",
"{",
"c",
"for",
"c",
"in",
"self",
".",
"_info_axis",
".",
"unique",
"(",
"level",
"=",
"0",
")",
"[",
":",
"100",
"]",
"if",
"isinstance",
"(",
"c",
",",
"str",
")",
"and",
"c",
... | 51.142857 | 0.005495 |
def _handle_tag_fire_master(self, tag, data):
'''
Handle a fire_master event
'''
if self.connected:
log.debug('Forwarding master event tag=%s', data['tag'])
self._fire_master(data['data'], data['tag'], data['events'], data['pretag']) | [
"def",
"_handle_tag_fire_master",
"(",
"self",
",",
"tag",
",",
"data",
")",
":",
"if",
"self",
".",
"connected",
":",
"log",
".",
"debug",
"(",
"'Forwarding master event tag=%s'",
",",
"data",
"[",
"'tag'",
"]",
")",
"self",
".",
"_fire_master",
"(",
"dat... | 40.428571 | 0.010381 |
def get_maxloss_rupture(dstore, loss_type):
"""
:param dstore: a DataStore instance
:param loss_type: a loss type string
:returns:
EBRupture instance corresponding to the maximum loss for the
given loss type
"""
lti = dstore['oqparam'].lti[loss_type]
ridx = dstore.get_attr('r... | [
"def",
"get_maxloss_rupture",
"(",
"dstore",
",",
"loss_type",
")",
":",
"lti",
"=",
"dstore",
"[",
"'oqparam'",
"]",
".",
"lti",
"[",
"loss_type",
"]",
"ridx",
"=",
"dstore",
".",
"get_attr",
"(",
"'rup_loss_table'",
",",
"'ridx'",
")",
"[",
"lti",
"]",... | 34.846154 | 0.002151 |
def p_expr_trig(p):
""" bexpr : math_fn bexpr %prec UMINUS
"""
p[0] = make_builtin(p.lineno(1), p[1],
make_typecast(TYPE.float_, p[2], p.lineno(1)),
{'SIN': math.sin,
'COS': math.cos,
'TAN': math.tan,
... | [
"def",
"p_expr_trig",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"make_builtin",
"(",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"p",
"[",
"1",
"]",
",",
"make_typecast",
"(",
"TYPE",
".",
"float_",
",",
"p",
"[",
"2",
"]",
",",
"p",
".",
"l... | 41.266667 | 0.00158 |
def select_icons(xmrs, left=None, relation=None, right=None):
"""
Return the list of matching ICONS for *xmrs*.
:class:`~delphin.mrs.components.IndividualConstraint` objects for
*xmrs* match if their `left` matches *left*, `relation` matches
*relation*, and `right` matches *right*. The *left*, *rel... | [
"def",
"select_icons",
"(",
"xmrs",
",",
"left",
"=",
"None",
",",
"relation",
"=",
"None",
",",
"right",
"=",
"None",
")",
":",
"icmatch",
"=",
"lambda",
"ic",
":",
"(",
"(",
"left",
"is",
"None",
"or",
"ic",
".",
"left",
"==",
"left",
")",
"and... | 39.826087 | 0.002132 |
def setSeed(self, seed):
"""Set the random seed and the numpy seed
Parameters:
--------------------------------------------------------------------
seed: random seed
"""
rand.seed(seed)
np.random.seed(seed) | [
"def",
"setSeed",
"(",
"self",
",",
"seed",
")",
":",
"rand",
".",
"seed",
"(",
"seed",
")",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")"
] | 26.555556 | 0.004049 |
def get_file_path(self, file_ref):
"""
Parameters
----------
file_ref: str
reference of file.
Available references: 'idf', 'epw', 'eio', 'eso', 'mtr', 'mtd', 'mdd', 'err', 'summary_table'
See EnergyPlus documentation for more information.
Ret... | [
"def",
"get_file_path",
"(",
"self",
",",
"file_ref",
")",
":",
"if",
"not",
"self",
".",
"exists",
"(",
"file_ref",
")",
":",
"raise",
"FileNotFoundError",
"(",
"\"File '%s' not found in simulation '%s'.\"",
"%",
"(",
"file_ref",
",",
"self",
".",
"_path",
"(... | 35.125 | 0.006932 |
def extend(validator_cls):
"""
Extend the given :class:`jsonschema.IValidator` with the Seep layer.
"""
Validator = jsonschema.validators.extend(
validator_cls, {
"properties": _properties_with_defaults(validator_cls),
}
)
class Blueprinter(Validator):
def ... | [
"def",
"extend",
"(",
"validator_cls",
")",
":",
"Validator",
"=",
"jsonschema",
".",
"validators",
".",
"extend",
"(",
"validator_cls",
",",
"{",
"\"properties\"",
":",
"_properties_with_defaults",
"(",
"validator_cls",
")",
",",
"}",
")",
"class",
"Blueprinter... | 22.611111 | 0.002358 |
def object_ref(self):
"""Return the reference of the changed object."""
return ImmutableDict(type=self.type, category_id=self.category_id, event_id=self.event_id,
session_id=self.session_id, contrib_id=self.contrib_id, subcontrib_id=self.subcontrib_id) | [
"def",
"object_ref",
"(",
"self",
")",
":",
"return",
"ImmutableDict",
"(",
"type",
"=",
"self",
".",
"type",
",",
"category_id",
"=",
"self",
".",
"category_id",
",",
"event_id",
"=",
"self",
".",
"event_id",
",",
"session_id",
"=",
"self",
".",
"sessio... | 73.5 | 0.013468 |
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 | 0.008032 |
def _parse_value(self, stats, field):
"""
Pull the specified value from the HTML contents.
Given a field, find the corresponding HTML tag for that field and parse
its value before returning the value as a string.
Parameters
----------
stats : PyQuery object
... | [
"def",
"_parse_value",
"(",
"self",
",",
"stats",
",",
"field",
")",
":",
"value",
"=",
"utils",
".",
"_parse_field",
"(",
"PLAYER_SCHEME",
",",
"stats",
",",
"field",
")",
"if",
"not",
"value",
"and",
"field",
"in",
"BOXSCORE_RETRY",
":",
"value",
"=",
... | 32.916667 | 0.00246 |
def rooms_upload(self, rid, file, **kwargs):
"""Post a message with attached file to a dedicated room."""
files = {
'file': (os.path.basename(file), open(file, 'rb'), mimetypes.guess_type(file)[0]),
}
return self.__call_api_post('rooms.upload/' + rid, kwargs=kwargs, use_json=... | [
"def",
"rooms_upload",
"(",
"self",
",",
"rid",
",",
"file",
",",
"*",
"*",
"kwargs",
")",
":",
"files",
"=",
"{",
"'file'",
":",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"file",
")",
",",
"open",
"(",
"file",
",",
"'rb'",
")",
",",
"mimet... | 55.666667 | 0.011799 |
def delete_all_eggs(self):
""" delete all the eggs in the directory specified """
path_to_delete = os.path.join(self.egg_directory, "lib", "python")
if os.path.exists(path_to_delete):
shutil.rmtree(path_to_delete) | [
"def",
"delete_all_eggs",
"(",
"self",
")",
":",
"path_to_delete",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"egg_directory",
",",
"\"lib\"",
",",
"\"python\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path_to_delete",
")",
":",
... | 49 | 0.008032 |
def serialize(self, submit=None):
"""Serialize each form field to a Payload container.
:param Submit submit: Optional `Submit` to click, if form includes
multiple submits
:return: Payload instance
"""
include_fields = prepare_fields(self.fields, self.submit_fields, ... | [
"def",
"serialize",
"(",
"self",
",",
"submit",
"=",
"None",
")",
":",
"include_fields",
"=",
"prepare_fields",
"(",
"self",
".",
"fields",
",",
"self",
".",
"submit_fields",
",",
"submit",
")",
"return",
"Payload",
".",
"from_fields",
"(",
"include_fields",... | 36.9 | 0.007937 |
def countLines(paths, exclude_files_containing=[],
exclude_folders_containing=[],
exclude_blank_lines=True,
exclude_commented_lines=True,
count_only_py_files=True):
"""
count and return lines of all *.py files in the given directory/-ies
[paths] ... | [
"def",
"countLines",
"(",
"paths",
",",
"exclude_files_containing",
"=",
"[",
"]",
",",
"exclude_folders_containing",
"=",
"[",
"]",
",",
"exclude_blank_lines",
"=",
"True",
",",
"exclude_commented_lines",
"=",
"True",
",",
"count_only_py_files",
"=",
"True",
")",... | 38.453125 | 0.002377 |
def cublasDspmv(handle, uplo, n, alpha, AP, x, incx, beta, y, incy):
"""
Matrix-vector product for real symmetric-packed matrix.
"""
status = _libcublas.cublasDspmv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
n,
... | [
"def",
"cublasDspmv",
"(",
"handle",
",",
"uplo",
",",
"n",
",",
"alpha",
",",
"AP",
",",
"x",
",",
"incx",
",",
"beta",
",",
"y",
",",
"incy",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasDspmv_v2",
"(",
"handle",
",",
"_CUBLAS_FILL_MODE",
"["... | 42.647059 | 0.002699 |
def writePatternLine(self, step_milliseconds, color, pos, led_number=0):
"""Write a color & step time color pattern line to RAM
:param step_milliseconds: how long for this pattern line to take
:param color: LED color
:param pos: color pattern line number (0-15)
:param led_number... | [
"def",
"writePatternLine",
"(",
"self",
",",
"step_milliseconds",
",",
"color",
",",
"pos",
",",
"led_number",
"=",
"0",
")",
":",
"if",
"(",
"self",
".",
"dev",
"==",
"None",
")",
":",
"return",
"''",
"self",
".",
"setLedN",
"(",
"led_number",
")",
... | 47.0625 | 0.011719 |
def can_rewind(self):
""" check if pg_rewind executable is there and that pg_controldata indicates
we have either wal_log_hints or checksums turned on
"""
# low-hanging fruit: check if pg_rewind configuration is there
if not self.config.get('use_pg_rewind'):
retur... | [
"def",
"can_rewind",
"(",
"self",
")",
":",
"# low-hanging fruit: check if pg_rewind configuration is there",
"if",
"not",
"self",
".",
"config",
".",
"get",
"(",
"'use_pg_rewind'",
")",
":",
"return",
"False",
"cmd",
"=",
"[",
"self",
".",
"_pgcommand",
"(",
"'... | 44 | 0.006954 |
def mobility(sdat, tstart=None, tend=None):
"""Plates mobility.
Compute the ratio vsurf / vrms.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if s... | [
"def",
"mobility",
"(",
"sdat",
",",
"tstart",
"=",
"None",
",",
"tend",
"=",
"None",
")",
":",
"tseries",
"=",
"sdat",
".",
"tseries_between",
"(",
"tstart",
",",
"tend",
")",
"steps",
"=",
"sdat",
".",
"steps",
"[",
"tseries",
".",
"index",
"[",
... | 39 | 0.001138 |
def get_strings(soup, tag):
"""Get all the string children from an html tag."""
tags = soup.find_all(tag)
strings = [s.string for s in tags if s.string]
return strings | [
"def",
"get_strings",
"(",
"soup",
",",
"tag",
")",
":",
"tags",
"=",
"soup",
".",
"find_all",
"(",
"tag",
")",
"strings",
"=",
"[",
"s",
".",
"string",
"for",
"s",
"in",
"tags",
"if",
"s",
".",
"string",
"]",
"return",
"strings"
] | 35.8 | 0.005464 |
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_wwn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "output")
... | [
"def",
"fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_wwn",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fcoe_get_interface",
"=",
"ET",
".",
"Element",
"(",
"\"fcoe_get_interface\"",
")",
"conf... | 50.466667 | 0.003891 |
def get_hosts_dict(self) -> Dict:
"""
Returns serialized dictionary of hosts from inventory
"""
return {
k: deserializer.inventory.InventoryElement.serialize(v).dict()
for k, v in self.hosts.items()
} | [
"def",
"get_hosts_dict",
"(",
"self",
")",
"->",
"Dict",
":",
"return",
"{",
"k",
":",
"deserializer",
".",
"inventory",
".",
"InventoryElement",
".",
"serialize",
"(",
"v",
")",
".",
"dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"hosts"... | 32.125 | 0.007576 |
def get_upload_path(finfo, sample_info, config):
""""Dry" update the file: only return the upload path
"""
try:
storage_dir = _get_storage_dir(finfo, config)
except ValueError:
return None
if finfo.get("type") == "directory":
return _get_dir_upload_path(finfo, storage_di... | [
"def",
"get_upload_path",
"(",
"finfo",
",",
"sample_info",
",",
"config",
")",
":",
"try",
":",
"storage_dir",
"=",
"_get_storage_dir",
"(",
"finfo",
",",
"config",
")",
"except",
"ValueError",
":",
"return",
"None",
"if",
"finfo",
".",
"get",
"(",
"\"typ... | 31.5 | 0.005141 |
def _remove_files(self, directory, pattern):
'''
Removes all files matching the search path
Arguments:
search_path -- The path you would like to remove, can contain wildcards
Example:
self._remove_files("output/*.html")
'''
for root, dirnames, file_names... | [
"def",
"_remove_files",
"(",
"self",
",",
"directory",
",",
"pattern",
")",
":",
"for",
"root",
",",
"dirnames",
",",
"file_names",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"for",
"file_name",
"in",
"fnmatch",
".",
"filter",
"(",
"file_names"... | 34.923077 | 0.004292 |
def _is_fd_open(self, fd):
"""
Determines if the fd is within range and in the file descr. list
:param fd: the file descriptor to check.
"""
return fd >= 0 and fd < len(self.files) and self.files[fd] is not None | [
"def",
"_is_fd_open",
"(",
"self",
",",
"fd",
")",
":",
"return",
"fd",
">=",
"0",
"and",
"fd",
"<",
"len",
"(",
"self",
".",
"files",
")",
"and",
"self",
".",
"files",
"[",
"fd",
"]",
"is",
"not",
"None"
] | 41 | 0.007968 |
def apply_command_list_template(command_list, in_path, out_path, args):
'''
Perform necessary substitutions on a command list to create a CLI-ready
list to launch a conversion or download process via system binary.
'''
replacements = {
'$IN': in_path,
'$OUT': out_path,
}
# A... | [
"def",
"apply_command_list_template",
"(",
"command_list",
",",
"in_path",
",",
"out_path",
",",
"args",
")",
":",
"replacements",
"=",
"{",
"'$IN'",
":",
"in_path",
",",
"'$OUT'",
":",
"out_path",
",",
"}",
"# Add in positional arguments ($0, $1, etc)",
"for",
"i... | 32.944444 | 0.001639 |
def voucher_code(request):
''' A view *just* for entering a voucher form. '''
VOUCHERS_FORM_PREFIX = "vouchers"
# Handle the voucher form *before* listing products.
# Products can change as vouchers are entered.
v = _handle_voucher(request, VOUCHERS_FORM_PREFIX)
voucher_form, voucher_handled =... | [
"def",
"voucher_code",
"(",
"request",
")",
":",
"VOUCHERS_FORM_PREFIX",
"=",
"\"vouchers\"",
"# Handle the voucher form *before* listing products.",
"# Products can change as vouchers are entered.",
"v",
"=",
"_handle_voucher",
"(",
"request",
",",
"VOUCHERS_FORM_PREFIX",
")",
... | 29.526316 | 0.001727 |
def generate_project(args):
"""New project."""
# Project templates path
src = os.path.join(dirname(abspath(__file__)), 'project')
project_name = args.get('<project>')
if not project_name:
logger.warning('Project name cannot be empty.')
return
# Destination project path
dst... | [
"def",
"generate_project",
"(",
"args",
")",
":",
"# Project templates path",
"src",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
"(",
"abspath",
"(",
"__file__",
")",
")",
",",
"'project'",
")",
"project_name",
"=",
"args",
".",
"get",
"(",
"'<p... | 32.42 | 0.001198 |
def prepare_data(data: Data) -> Tuple[int, bytes]:
"""
Convert a string or byte-like object to an opcode and a bytes-like object.
This function is designed for data frames.
If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes`
object encoding ``data`` in UTF-8.
If ``data`` is... | [
"def",
"prepare_data",
"(",
"data",
":",
"Data",
")",
"->",
"Tuple",
"[",
"int",
",",
"bytes",
"]",
":",
"if",
"isinstance",
"(",
"data",
",",
"str",
")",
":",
"return",
"OP_TEXT",
",",
"data",
".",
"encode",
"(",
"\"utf-8\"",
")",
"elif",
"isinstanc... | 30.961538 | 0.001205 |
def _cleanup(self):
'''
Cleanup local data.
'''
self._declare_cb = None
self._delete_cb = None
super(ExchangeClass, self)._cleanup() | [
"def",
"_cleanup",
"(",
"self",
")",
":",
"self",
".",
"_declare_cb",
"=",
"None",
"self",
".",
"_delete_cb",
"=",
"None",
"super",
"(",
"ExchangeClass",
",",
"self",
")",
".",
"_cleanup",
"(",
")"
] | 24.857143 | 0.011111 |
def replace_first_key_in_makefile(buf, key, replacement, outfile=None):
'''
Replaces first line in 'buf' matching 'key' with 'replacement'.
Optionally, writes out this new buffer into 'outfile'.
Returns: Buffer after replacement has been done
'''
regexp = re.compile(r'''
\n\s* # ... | [
"def",
"replace_first_key_in_makefile",
"(",
"buf",
",",
"key",
",",
"replacement",
",",
"outfile",
"=",
"None",
")",
":",
"regexp",
"=",
"re",
".",
"compile",
"(",
"r'''\n \\n\\s* # there might be some leading spaces\n ( # start group to return\... | 36.285714 | 0.000959 |
def get_logging_level(debug):
"""Returns logging level based on boolean"""
level = logging.INFO
if debug:
level = logging.DEBUG
return level | [
"def",
"get_logging_level",
"(",
"debug",
")",
":",
"level",
"=",
"logging",
".",
"INFO",
"if",
"debug",
":",
"level",
"=",
"logging",
".",
"DEBUG",
"return",
"level"
] | 26.5 | 0.006098 |
def __Address_lineEdit_set_ui(self):
"""
Fills **Address_lineEdit** Widget.
"""
# Adding settings key if it doesn't exists.
self.__settings.get_key(self.__settings_section, "address").isNull() and \
self.__settings.set_key(self.__settings_section, "address", self.__addre... | [
"def",
"__Address_lineEdit_set_ui",
"(",
"self",
")",
":",
"# Adding settings key if it doesn't exists.",
"self",
".",
"__settings",
".",
"get_key",
"(",
"self",
".",
"__settings_section",
",",
"\"address\"",
")",
".",
"isNull",
"(",
")",
"and",
"self",
".",
"__se... | 45.571429 | 0.010753 |
def OneOf(children, name=None, deterministic=False, random_state=None):
"""
Augmenter that always executes exactly one of its children.
dtype support::
See ``imgaug.augmenters.meta.SomeOf``.
Parameters
----------
children : list of imgaug.augmenters.meta.Augmenter
The choices ... | [
"def",
"OneOf",
"(",
"children",
",",
"name",
"=",
"None",
",",
"deterministic",
"=",
"False",
",",
"random_state",
"=",
"None",
")",
":",
"return",
"SomeOf",
"(",
"n",
"=",
"1",
",",
"children",
"=",
"children",
",",
"random_order",
"=",
"False",
",",... | 28.058824 | 0.00135 |
def datacenters(self):
"""
Gets the Datacenters API client.
Returns:
Datacenters:
"""
if not self.__datacenters:
self.__datacenters = Datacenters(self.__connection)
return self.__datacenters | [
"def",
"datacenters",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__datacenters",
":",
"self",
".",
"__datacenters",
"=",
"Datacenters",
"(",
"self",
".",
"__connection",
")",
"return",
"self",
".",
"__datacenters"
] | 25.4 | 0.007605 |
def iseof(self):
"""Check if current process streams are still open."""
succ = windll.kernel32.PeekNamedPipe(
self.conout_pipe, None, None, None, None, None
)
return not bool(succ) | [
"def",
"iseof",
"(",
"self",
")",
":",
"succ",
"=",
"windll",
".",
"kernel32",
".",
"PeekNamedPipe",
"(",
"self",
".",
"conout_pipe",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
")",
"return",
"not",
"bool",
"(",
"succ",
")"
] | 36.5 | 0.008929 |
def line_integration(image, angle, decay, sigma):
'''Integrate the image along the given angle
DIC images are the directional derivative of the underlying
image. This filter reconstructs the original image by integrating
along that direction.
image - a 2-dimensional array
angle - shear angle ... | [
"def",
"line_integration",
"(",
"image",
",",
"angle",
",",
"decay",
",",
"sigma",
")",
":",
"#",
"# Normalize the image so that the mean is zero",
"#",
"normalized",
"=",
"image",
"-",
"np",
".",
"mean",
"(",
"image",
")",
"#",
"# Rotate the image so the J direct... | 36.12069 | 0.001394 |
def check_encoding_chars(encoding_chars):
"""
Validate the given encoding chars
:type encoding_chars: ``dict``
:param encoding_chars: the encoding chars (see :func:`hl7apy.set_default_encoding_chars`)
:raises: :exc:`hl7apy.exceptions.InvalidEncodingChars` if the given encoding chars are not valid
... | [
"def",
"check_encoding_chars",
"(",
"encoding_chars",
")",
":",
"if",
"not",
"isinstance",
"(",
"encoding_chars",
",",
"collections",
".",
"MutableMapping",
")",
":",
"raise",
"InvalidEncodingChars",
"required",
"=",
"{",
"'FIELD'",
",",
"'COMPONENT'",
",",
"'SUBC... | 44.722222 | 0.00365 |
def L_sed_plate(sed_inputs=sed_dict):
"""Return the length of a single plate in the plate settler module based on
achieving the desired capture velocity
Parameters
----------
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can b... | [
"def",
"L_sed_plate",
"(",
"sed_inputs",
"=",
"sed_dict",
")",
":",
"L_sed_plate",
"=",
"(",
"(",
"sed_input",
"[",
"'plate_settlers'",
"]",
"[",
"'S'",
"]",
"*",
"(",
"(",
"sed_input",
"[",
"'tank'",
"]",
"[",
"'vel_up'",
"]",
"/",
"sed_input",
"[",
"... | 40.772727 | 0.008715 |
def get_caller_identity_arn(self):
"""Returns the ARN user or role whose credentials are used to call the API.
Returns:
(str): The ARN user or role
"""
assumed_role = self.boto_session.client('sts').get_caller_identity()['Arn']
if 'AmazonSageMaker-ExecutionRole' in a... | [
"def",
"get_caller_identity_arn",
"(",
"self",
")",
":",
"assumed_role",
"=",
"self",
".",
"boto_session",
".",
"client",
"(",
"'sts'",
")",
".",
"get_caller_identity",
"(",
")",
"[",
"'Arn'",
"]",
"if",
"'AmazonSageMaker-ExecutionRole'",
"in",
"assumed_role",
"... | 43.409091 | 0.008197 |
def create_device(args, display_types=None):
"""
Create and return device.
:type args: object
:type display_types: dict
"""
device = None
if display_types is None:
display_types = get_display_types()
if args.display in display_types.get('oled'):
import luma.oled.device
... | [
"def",
"create_device",
"(",
"args",
",",
"display_types",
"=",
"None",
")",
":",
"device",
"=",
"None",
"if",
"display_types",
"is",
"None",
":",
"display_types",
"=",
"get_display_types",
"(",
")",
"if",
"args",
".",
"display",
"in",
"display_types",
".",
... | 35.894737 | 0.001428 |
def staticmap(ctx, mapid, output, features, lat, lon, zoom, size):
"""
Generate static map images from existing Mapbox map ids.
Optionally overlay with geojson features.
$ mapbox staticmap --features features.geojson mapbox.satellite out.png
$ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 m... | [
"def",
"staticmap",
"(",
"ctx",
",",
"mapid",
",",
"output",
",",
"features",
",",
"lat",
",",
"lon",
",",
"zoom",
",",
"size",
")",
":",
"access_token",
"=",
"(",
"ctx",
".",
"obj",
"and",
"ctx",
".",
"obj",
".",
"get",
"(",
"'access_token'",
")",... | 34.133333 | 0.001899 |
def set_system_lock(cls, redis, name, timeout):
"""
Set system lock for the semaphore.
Sets a system lock that will expire in timeout seconds. This
overrides all other locks. Existing locks cannot be renewed
and no new locks will be permitted until the system lock
expire... | [
"def",
"set_system_lock",
"(",
"cls",
",",
"redis",
",",
"name",
",",
"timeout",
")",
":",
"pipeline",
"=",
"redis",
".",
"pipeline",
"(",
")",
"pipeline",
".",
"zadd",
"(",
"name",
",",
"SYSTEM_LOCK_ID",
",",
"time",
".",
"time",
"(",
")",
"+",
"tim... | 36.421053 | 0.004225 |
def visit_Attribute(self, node):
""" Compute typing for an attribute node. """
obj, path = attr_to_path(node)
# If no type is given, use a decltype
if obj.isliteral():
typename = pytype_to_ctype(obj.signature)
self.result[node] = self.builder.NamedType(typename)
... | [
"def",
"visit_Attribute",
"(",
"self",
",",
"node",
")",
":",
"obj",
",",
"path",
"=",
"attr_to_path",
"(",
"node",
")",
"# If no type is given, use a decltype",
"if",
"obj",
".",
"isliteral",
"(",
")",
":",
"typename",
"=",
"pytype_to_ctype",
"(",
"obj",
".... | 44.666667 | 0.004878 |
def fcpinfo(rh):
"""
Get fcp info and filter by the status.
Input:
Request Handle with the following properties:
function - 'GETVM'
subfunction - 'FCPINFO'
userid - userid of the virtual machine
parms['status'] - The status for filter results.
... | [
"def",
"fcpinfo",
"(",
"rh",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter changeVM.dedicate\"",
")",
"parms",
"=",
"[",
"\"-T\"",
",",
"rh",
".",
"userid",
"]",
"hideList",
"=",
"[",
"]",
"results",
"=",
"invokeSMCLI",
"(",
"rh",
",",
"\"System_WWPN... | 30.15 | 0.000803 |
def board_names(hwpack='arduino'):
"""return installed board names."""
ls = list(boards(hwpack).keys())
ls.sort()
return ls | [
"def",
"board_names",
"(",
"hwpack",
"=",
"'arduino'",
")",
":",
"ls",
"=",
"list",
"(",
"boards",
"(",
"hwpack",
")",
".",
"keys",
"(",
")",
")",
"ls",
".",
"sort",
"(",
")",
"return",
"ls"
] | 27 | 0.007194 |
def verify_registration(request):
"""
Verify registration via signature.
"""
user = process_verify_registration_data(request.data)
extra_data = None
if registration_settings.REGISTER_VERIFICATION_AUTO_LOGIN:
extra_data = perform_login(request, user)
return get_ok_response('User verif... | [
"def",
"verify_registration",
"(",
"request",
")",
":",
"user",
"=",
"process_verify_registration_data",
"(",
"request",
".",
"data",
")",
"extra_data",
"=",
"None",
"if",
"registration_settings",
".",
"REGISTER_VERIFICATION_AUTO_LOGIN",
":",
"extra_data",
"=",
"perfo... | 39.222222 | 0.00277 |
def xmoe_tr_1d():
"""Mixture of experts (16 experts).
623M Params, einsum=1.09e13
Returns:
a hparams
"""
hparams = xmoe_tr_dense_2k()
hparams.encoder_layers = ["self_att", "moe_1d"] * 4
hparams.decoder_layers = ["self_att", "enc_att", "moe_1d"] * 4
hparams.layout = "batch:batch;experts:batch"
h... | [
"def",
"xmoe_tr_1d",
"(",
")",
":",
"hparams",
"=",
"xmoe_tr_dense_2k",
"(",
")",
"hparams",
".",
"encoder_layers",
"=",
"[",
"\"self_att\"",
",",
"\"moe_1d\"",
"]",
"*",
"4",
"hparams",
".",
"decoder_layers",
"=",
"[",
"\"self_att\"",
",",
"\"enc_att\"",
",... | 23.875 | 0.02267 |
def move_vobject(self, uuid, from_project, to_project):
"""Update the project of the task with the UID uuid"""
if to_project not in self.get_filesnames():
return
uuid = uuid.split('@')[0]
with self._lock:
run(['task', 'rc.verbose=nothing', 'rc.data.location={self... | [
"def",
"move_vobject",
"(",
"self",
",",
"uuid",
",",
"from_project",
",",
"to_project",
")",
":",
"if",
"to_project",
"not",
"in",
"self",
".",
"get_filesnames",
"(",
")",
":",
"return",
"uuid",
"=",
"uuid",
".",
"split",
"(",
"'@'",
")",
"[",
"0",
... | 54 | 0.006834 |
def fbm(n, H=0.75):
"""
Generates fractional brownian motions of desired length.
Author:
Christian Thomae
References:
.. [fbm_1] https://en.wikipedia.org/wiki/Fractional_Brownian_motion#Method_1_of_simulation
Args:
n (int):
length of sequence to generate
Kwargs:
H (float):
hur... | [
"def",
"fbm",
"(",
"n",
",",
"H",
"=",
"0.75",
")",
":",
"# TODO more detailed description of fbm",
"assert",
"H",
">",
"0",
"and",
"H",
"<",
"1",
"def",
"R",
"(",
"t",
",",
"s",
")",
":",
"twoH",
"=",
"2",
"*",
"H",
"return",
"0.5",
"*",
"(",
... | 23.264706 | 0.015777 |
def update(self, value):
"Updates the progress bar to a new value."
if value <= 0.1:
value = 0
assert 0 <= value <= self.maxval
self.currval = value
if not self._need_update() or self.finished:
return
if not self.start_time:
self.start_... | [
"def",
"update",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"<=",
"0.1",
":",
"value",
"=",
"0",
"assert",
"0",
"<=",
"value",
"<=",
"self",
".",
"maxval",
"self",
".",
"currval",
"=",
"value",
"if",
"not",
"self",
".",
"_need_update",
"("... | 36.470588 | 0.003145 |
def canonical_name(sgf_name):
"""Keep filename and some date folders"""
sgf_name = os.path.normpath(sgf_name)
assert sgf_name.endswith('.sgf'), sgf_name
# Strip off '.sgf'
sgf_name = sgf_name[:-4]
# Often eval is inside a folder with the run name.
# include from folder before /eval/ if part... | [
"def",
"canonical_name",
"(",
"sgf_name",
")",
":",
"sgf_name",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"sgf_name",
")",
"assert",
"sgf_name",
".",
"endswith",
"(",
"'.sgf'",
")",
",",
"sgf_name",
"# Strip off '.sgf'",
"sgf_name",
"=",
"sgf_name",
"[",... | 33 | 0.001965 |
def refresh(self):
"""Obtain a new access token."""
grant_type = "https://oauth.reddit.com/grants/installed_client"
self._request_token(grant_type=grant_type, device_id=self._device_id) | [
"def",
"refresh",
"(",
"self",
")",
":",
"grant_type",
"=",
"\"https://oauth.reddit.com/grants/installed_client\"",
"self",
".",
"_request_token",
"(",
"grant_type",
"=",
"grant_type",
",",
"device_id",
"=",
"self",
".",
"_device_id",
")"
] | 51.5 | 0.009569 |
def on_page_layout_choice(self, event):
"""Page layout choice event handler"""
width, height = self.paper_sizes_points[event.GetString()]
self.page_width_text_ctrl.SetValue(str(width / 72.0))
self.page_height_text_ctrl.SetValue(str(height / 72.0))
event.Skip() | [
"def",
"on_page_layout_choice",
"(",
"self",
",",
"event",
")",
":",
"width",
",",
"height",
"=",
"self",
".",
"paper_sizes_points",
"[",
"event",
".",
"GetString",
"(",
")",
"]",
"self",
".",
"page_width_text_ctrl",
".",
"SetValue",
"(",
"str",
"(",
"widt... | 36.875 | 0.006623 |
def getbranchesurl(idbranch, *args, **kwargs):
"""Request Branches URL.
If idbranch is set, you'll get a response adequate for a MambuBranch object.
If not set, you'll get a response adequate for a MambuBranches object.
See mambubranch module and pydoc for further information.
Currently implemente... | [
"def",
"getbranchesurl",
"(",
"idbranch",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"getparams",
"=",
"[",
"]",
"if",
"kwargs",
":",
"try",
":",
"if",
"kwargs",
"[",
"\"fullDetails\"",
"]",
"==",
"True",
":",
"getparams",
".",
"append",
"(... | 33.666667 | 0.00401 |
def get_handler(self, *args, **options):
"""
Returns the static files serving handler wrapping the default handler,
if static files should be served. Otherwise just returns the default
handler.
"""
handler = super(Command, self).get_handler(*args, **options)
inse... | [
"def",
"get_handler",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"handler",
"=",
"super",
"(",
"Command",
",",
"self",
")",
".",
"get_handler",
"(",
"*",
"args",
",",
"*",
"*",
"options",
")",
"insecure_serving",
"=",
"options... | 40.333333 | 0.00404 |
def load_file_ui(self):
"""
Loads user chosen file(s) into **Script_Editor_tabWidget** Widget tab Model editor(s).
:return: Method success.
:rtype: bool
:note: May require user interaction.
"""
editor = self.get_current_editor()
file = editor and editor... | [
"def",
"load_file_ui",
"(",
"self",
")",
":",
"editor",
"=",
"self",
".",
"get_current_editor",
"(",
")",
"file",
"=",
"editor",
"and",
"editor",
".",
"file",
"or",
"None",
"browsedPath",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"file",
")",
"if",
... | 39.538462 | 0.006648 |
def get_google_links(limit, params, headers):
"""
function to fetch links equal to limit
every Google search result page has a start index.
every page contains 10 search results.
"""
links = []
for start_index in range(0, limit, 10):
params['start'] = start_index
resp = s.get("https://www.google.com/search"... | [
"def",
"get_google_links",
"(",
"limit",
",",
"params",
",",
"headers",
")",
":",
"links",
"=",
"[",
"]",
"for",
"start_index",
"in",
"range",
"(",
"0",
",",
"limit",
",",
"10",
")",
":",
"params",
"[",
"'start'",
"]",
"=",
"start_index",
"resp",
"="... | 32.071429 | 0.04329 |
def _parse_supl(content):
"""Parse supplemental measurements data.
Parameters
----------
content : str
Data to parse
Returns
-------
:class:`pandas.DataFrame` containing the data
"""
col_names = ['year', 'month', 'day', 'hour', '... | [
"def",
"_parse_supl",
"(",
"content",
")",
":",
"col_names",
"=",
"[",
"'year'",
",",
"'month'",
",",
"'day'",
",",
"'hour'",
",",
"'minute'",
",",
"'hourly_low_pressure'",
",",
"'hourly_low_pressure_time'",
",",
"'hourly_high_wind'",
",",
"'hourly_high_wind_directi... | 43.630435 | 0.003899 |
def get_library(lookup=True, key='exp_id'):
''' return the raw library, without parsing'''
library = None
response = requests.get(EXPFACTORY_LIBRARY)
if response.status_code == 200:
library = response.json()
if lookup is True:
return make_lookup(library,key=key)
return li... | [
"def",
"get_library",
"(",
"lookup",
"=",
"True",
",",
"key",
"=",
"'exp_id'",
")",
":",
"library",
"=",
"None",
"response",
"=",
"requests",
".",
"get",
"(",
"EXPFACTORY_LIBRARY",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"library",
"... | 35.222222 | 0.006154 |
def locked_get(self):
"""Retrieve stored credential.
Returns:
A :class:`oauth2client.Credentials` instance or `None`.
"""
filters = {self.key_name: self.key_value}
query = self.session.query(self.model_class).filter_by(**filters)
entity = query.first()
... | [
"def",
"locked_get",
"(",
"self",
")",
":",
"filters",
"=",
"{",
"self",
".",
"key_name",
":",
"self",
".",
"key_value",
"}",
"query",
"=",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"model_class",
")",
".",
"filter_by",
"(",
"*",
"*",
... | 32.529412 | 0.003515 |
def _UpdateSessionIfRequired(self, request_headers, response_result, response_headers):
"""
Updates session if necessary.
:param dict response_result:
:param dict response_headers:
:param dict response_headers
:return:
None, but updates the client sessio... | [
"def",
"_UpdateSessionIfRequired",
"(",
"self",
",",
"request_headers",
",",
"response_result",
",",
"response_headers",
")",
":",
"'''if this request was made with consistency level as session, then update\n the session'''",
"if",
"response_result",
"is",
"None",
"or",
"r... | 34.925926 | 0.007224 |
def solveConsKinkedR(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rboro,Rsave,
PermGroFac,BoroCnstArt,aXtraGrid,vFuncBool,CubicBool):
'''
Solves a single period consumption-saving problem with CRRA utility and risky
income (subject to permanent and transitory shocks), and ... | [
"def",
"solveConsKinkedR",
"(",
"solution_next",
",",
"IncomeDstn",
",",
"LivPrb",
",",
"DiscFac",
",",
"CRRA",
",",
"Rboro",
",",
"Rsave",
",",
"PermGroFac",
",",
"BoroCnstArt",
",",
"aXtraGrid",
",",
"vFuncBool",
",",
"CubicBool",
")",
":",
"solver",
"=",
... | 46.5 | 0.009543 |
def convert_selu(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert selu layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with k... | [
"def",
"convert_selu",
"(",
"params",
",",
"w_name",
",",
"scope_name",
",",
"inputs",
",",
"layers",
",",
"weights",
",",
"names",
")",
":",
"print",
"(",
"'Converting selu ...'",
")",
"if",
"names",
"==",
"'short'",
":",
"tf_name",
"=",
"'SELU'",
"+",
... | 30 | 0.001346 |
def value(self):
"""
Returns :data:`True` when the system clock reads between
:attr:`start_time` and :attr:`end_time`, and :data:`False` otherwise.
If :attr:`start_time` is greater than :attr:`end_time` (indicating a
period that crosses midnight), then this returns :data:`True` w... | [
"def",
"value",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
".",
"time",
"(",
")",
"if",
"self",
".",
"utc",
"else",
"datetime",
".",
"now",
"(",
")",
".",
"time",
"(",
")",
"if",
"self",
".",
"start_time",
"<",
"sel... | 48.357143 | 0.002899 |
def get_mx(self, tree: Union[ast.Symbol, ast.ComponentRef, ast.Expression]) -> ca.MX:
"""
We pull components and symbols from the AST on demand.
This is to ensure that parametrized vector dimensions can be resolved. Vector
dimensions need to be known at CasADi MX creation time.
... | [
"def",
"get_mx",
"(",
"self",
",",
"tree",
":",
"Union",
"[",
"ast",
".",
"Symbol",
",",
"ast",
".",
"ComponentRef",
",",
"ast",
".",
"Expression",
"]",
")",
"->",
"ca",
".",
"MX",
":",
"if",
"tree",
"not",
"in",
"self",
".",
"src",
":",
"if",
... | 43.882353 | 0.006562 |
def meth_list(args):
""" List workflows in the methods repository """
r = fapi.list_repository_methods(namespace=args.namespace,
name=args.method,
snapshotId=args.snapshot_id)
fapi._check_response_code(r, 200)
# Parse the JSON fo... | [
"def",
"meth_list",
"(",
"args",
")",
":",
"r",
"=",
"fapi",
".",
"list_repository_methods",
"(",
"namespace",
"=",
"args",
".",
"namespace",
",",
"name",
"=",
"args",
".",
"method",
",",
"snapshotId",
"=",
"args",
".",
"snapshot_id",
")",
"fapi",
".",
... | 34.944444 | 0.004644 |
def config(commands=None,
config_file=None,
template_engine='jinja',
context=None,
defaults=None,
saltenv='base',
**kwargs):
'''
Configures the Nexus switch with the specified commands.
This method is used to send configuration commands to t... | [
"def",
"config",
"(",
"commands",
"=",
"None",
",",
"config_file",
"=",
"None",
",",
"template_engine",
"=",
"'jinja'",
",",
"context",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
",",
"*",
"*",
"kwargs",
")",
":",
"initia... | 38.418367 | 0.001036 |
def failover_limitation(self):
"""Returns reason why this node can't promote or None if everything is ok."""
if not self.reachable:
return 'not reachable'
if self.tags.get('nofailover', False):
return 'not allowed to promote'
if self.watchdog_failed:
r... | [
"def",
"failover_limitation",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"reachable",
":",
"return",
"'not reachable'",
"if",
"self",
".",
"tags",
".",
"get",
"(",
"'nofailover'",
",",
"False",
")",
":",
"return",
"'not allowed to promote'",
"if",
"sel... | 40 | 0.008152 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.