text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def zext(self, num):
"""Zero-extend this farray by *num* bits.
Returns a new farray.
"""
zero = self.ftype.box(0)
return self.__class__(self._items + [zero] * num, ftype=self.ftype) | [
"def",
"zext",
"(",
"self",
",",
"num",
")",
":",
"zero",
"=",
"self",
".",
"ftype",
".",
"box",
"(",
"0",
")",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"_items",
"+",
"[",
"zero",
"]",
"*",
"num",
",",
"ftype",
"=",
"self",
".",
"ftype",
")"
] | 30.857143 | 16.285714 |
def get_sub_accounts(self, account_id, params={}):
"""
Return list of subaccounts within the account with the passed
canvas id.
https://canvas.instructure.com/doc/api/accounts.html#method.accounts.sub_accounts
"""
url = ACCOUNTS_API.format(account_id) + "/sub_accounts"
accounts = []
for datum in self._get_paged_resource(url, params=params):
accounts.append(CanvasAccount(data=datum))
return accounts | [
"def",
"get_sub_accounts",
"(",
"self",
",",
"account_id",
",",
"params",
"=",
"{",
"}",
")",
":",
"url",
"=",
"ACCOUNTS_API",
".",
"format",
"(",
"account_id",
")",
"+",
"\"/sub_accounts\"",
"accounts",
"=",
"[",
"]",
"for",
"datum",
"in",
"self",
".",
"_get_paged_resource",
"(",
"url",
",",
"params",
"=",
"params",
")",
":",
"accounts",
".",
"append",
"(",
"CanvasAccount",
"(",
"data",
"=",
"datum",
")",
")",
"return",
"accounts"
] | 33.928571 | 23.5 |
def stream_copy(source, destination, chunk_size=512 * 1024):
"""Copy all data from the source stream into the destination stream in chunks
of size chunk_size
:return: amount of bytes written"""
br = 0
while True:
chunk = source.read(chunk_size)
destination.write(chunk)
br += len(chunk)
if len(chunk) < chunk_size:
break
# END reading output stream
return br | [
"def",
"stream_copy",
"(",
"source",
",",
"destination",
",",
"chunk_size",
"=",
"512",
"*",
"1024",
")",
":",
"br",
"=",
"0",
"while",
"True",
":",
"chunk",
"=",
"source",
".",
"read",
"(",
"chunk_size",
")",
"destination",
".",
"write",
"(",
"chunk",
")",
"br",
"+=",
"len",
"(",
"chunk",
")",
"if",
"len",
"(",
"chunk",
")",
"<",
"chunk_size",
":",
"break",
"# END reading output stream",
"return",
"br"
] | 29.857143 | 15.857143 |
def publictypes(self):
""" get all public types """
for t in self.wsdl.schema.types.values():
if t in self.params:
continue
if t in self.types:
continue
item = (t, t)
self.types.append(item)
self.types.sort(key=lambda x: x[0].name) | [
"def",
"publictypes",
"(",
"self",
")",
":",
"for",
"t",
"in",
"self",
".",
"wsdl",
".",
"schema",
".",
"types",
".",
"values",
"(",
")",
":",
"if",
"t",
"in",
"self",
".",
"params",
":",
"continue",
"if",
"t",
"in",
"self",
".",
"types",
":",
"continue",
"item",
"=",
"(",
"t",
",",
"t",
")",
"self",
".",
"types",
".",
"append",
"(",
"item",
")",
"self",
".",
"types",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
".",
"name",
")"
] | 32.6 | 10.4 |
def portfolio_value(portfolio, date, price='close'):
"""Total value of a portfolio (dict mapping symbols to numbers of shares)
$CASH used as symbol for USD
"""
value = 0.0
for (sym, sym_shares) in portfolio.iteritems():
sym_price = None
if sym_shares:
sym_price = get_price(symbol=sym, date=date, price=price)
# print sym, sym_shares, sym_price
# print last_date, k, price
if sym_price != None:
if np.isnan(sym_price):
print 'Invalid price, shares, value, total: ', sym_price, sym_shares, (float(sym_shares) * float(sym_price)) if sym_shares and sym_price else 'Invalid', value
if sym_shares:
return float('nan')
else:
# print ('{0} shares of {1} = {2} * {3} = {4}'.format(sym_shares, sym, sym_shares, sym_price, sym_shares * sym_price))
value += sym_shares * sym_price
# print 'new price, value = {0}, {1}'.format(sym_price, value)
return value | [
"def",
"portfolio_value",
"(",
"portfolio",
",",
"date",
",",
"price",
"=",
"'close'",
")",
":",
"value",
"=",
"0.0",
"for",
"(",
"sym",
",",
"sym_shares",
")",
"in",
"portfolio",
".",
"iteritems",
"(",
")",
":",
"sym_price",
"=",
"None",
"if",
"sym_shares",
":",
"sym_price",
"=",
"get_price",
"(",
"symbol",
"=",
"sym",
",",
"date",
"=",
"date",
",",
"price",
"=",
"price",
")",
"# print sym, sym_shares, sym_price",
"# print last_date, k, price",
"if",
"sym_price",
"!=",
"None",
":",
"if",
"np",
".",
"isnan",
"(",
"sym_price",
")",
":",
"print",
"'Invalid price, shares, value, total: '",
",",
"sym_price",
",",
"sym_shares",
",",
"(",
"float",
"(",
"sym_shares",
")",
"*",
"float",
"(",
"sym_price",
")",
")",
"if",
"sym_shares",
"and",
"sym_price",
"else",
"'Invalid'",
",",
"value",
"if",
"sym_shares",
":",
"return",
"float",
"(",
"'nan'",
")",
"else",
":",
"# print ('{0} shares of {1} = {2} * {3} = {4}'.format(sym_shares, sym, sym_shares, sym_price, sym_shares * sym_price))",
"value",
"+=",
"sym_shares",
"*",
"sym_price",
"# print 'new price, value = {0}, {1}'.format(sym_price, value)",
"return",
"value"
] | 46.590909 | 23.318182 |
def partitionBy(*cols):
"""
Creates a :class:`WindowSpec` with the partitioning defined.
"""
sc = SparkContext._active_spark_context
jspec = sc._jvm.org.apache.spark.sql.expressions.Window.partitionBy(_to_java_cols(cols))
return WindowSpec(jspec) | [
"def",
"partitionBy",
"(",
"*",
"cols",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"jspec",
"=",
"sc",
".",
"_jvm",
".",
"org",
".",
"apache",
".",
"spark",
".",
"sql",
".",
"expressions",
".",
"Window",
".",
"partitionBy",
"(",
"_to_java_cols",
"(",
"cols",
")",
")",
"return",
"WindowSpec",
"(",
"jspec",
")"
] | 41.142857 | 16.571429 |
def AsDict(self, dt=True):
"""
A dict representation of this Shake instance.
The return value uses the same key names as the JSON representation.
Return:
A dict representing this Shake instance
"""
data = {}
if self.id:
data['id'] = self.id
if self.name:
data['name'] = self.name
if self.owner:
data['owner'] = self.owner.AsDict()
if self.url:
data['url'] = self.url
if self.thumbnail_url:
data['thumbnail_url'] = self.thumbnail_url
if self.description:
data['description'] = self.description
if self.type:
data['type'] = self.type
if dt:
if self.created_at:
data['created_at'] = self.created_at
if self.updated_at:
data['updated_at'] = self.updated_at
else:
if self.created_at:
data['created_at'] = self.created_at_iso
if self.updated_at:
data['updated_at'] = self.updated_at_iso
return data | [
"def",
"AsDict",
"(",
"self",
",",
"dt",
"=",
"True",
")",
":",
"data",
"=",
"{",
"}",
"if",
"self",
".",
"id",
":",
"data",
"[",
"'id'",
"]",
"=",
"self",
".",
"id",
"if",
"self",
".",
"name",
":",
"data",
"[",
"'name'",
"]",
"=",
"self",
".",
"name",
"if",
"self",
".",
"owner",
":",
"data",
"[",
"'owner'",
"]",
"=",
"self",
".",
"owner",
".",
"AsDict",
"(",
")",
"if",
"self",
".",
"url",
":",
"data",
"[",
"'url'",
"]",
"=",
"self",
".",
"url",
"if",
"self",
".",
"thumbnail_url",
":",
"data",
"[",
"'thumbnail_url'",
"]",
"=",
"self",
".",
"thumbnail_url",
"if",
"self",
".",
"description",
":",
"data",
"[",
"'description'",
"]",
"=",
"self",
".",
"description",
"if",
"self",
".",
"type",
":",
"data",
"[",
"'type'",
"]",
"=",
"self",
".",
"type",
"if",
"dt",
":",
"if",
"self",
".",
"created_at",
":",
"data",
"[",
"'created_at'",
"]",
"=",
"self",
".",
"created_at",
"if",
"self",
".",
"updated_at",
":",
"data",
"[",
"'updated_at'",
"]",
"=",
"self",
".",
"updated_at",
"else",
":",
"if",
"self",
".",
"created_at",
":",
"data",
"[",
"'created_at'",
"]",
"=",
"self",
".",
"created_at_iso",
"if",
"self",
".",
"updated_at",
":",
"data",
"[",
"'updated_at'",
"]",
"=",
"self",
".",
"updated_at_iso",
"return",
"data"
] | 28.842105 | 17.368421 |
def show2(self):
"""
Rebuild the TLS packet with the same context, and then .show() it.
We need self.__class__ to call the subclass in a dynamic way.
Howether we do not want the tls_session.{r,w}cs.seq_num to be updated.
We have to bring back the init states (it's possible the cipher context
has been updated because of parsing) but also to keep the current state
and restore it afterwards (the raw() call may also update the states).
"""
s = self.tls_session
rcs_snap = s.rcs.snapshot()
wcs_snap = s.wcs.snapshot()
s.rcs = self.rcs_snap_init
built_packet = raw(self)
s.frozen = True
self.__class__(built_packet, tls_session=s).show()
s.frozen = False
s.rcs = rcs_snap
s.wcs = wcs_snap | [
"def",
"show2",
"(",
"self",
")",
":",
"s",
"=",
"self",
".",
"tls_session",
"rcs_snap",
"=",
"s",
".",
"rcs",
".",
"snapshot",
"(",
")",
"wcs_snap",
"=",
"s",
".",
"wcs",
".",
"snapshot",
"(",
")",
"s",
".",
"rcs",
"=",
"self",
".",
"rcs_snap_init",
"built_packet",
"=",
"raw",
"(",
"self",
")",
"s",
".",
"frozen",
"=",
"True",
"self",
".",
"__class__",
"(",
"built_packet",
",",
"tls_session",
"=",
"s",
")",
".",
"show",
"(",
")",
"s",
".",
"frozen",
"=",
"False",
"s",
".",
"rcs",
"=",
"rcs_snap",
"s",
".",
"wcs",
"=",
"wcs_snap"
] | 35.304348 | 22.608696 |
def distance(p0, p1, deg=True, r=r_earth_mean):
"""
Return the distance between two points on the surface of the Earth.
Parameters
----------
p0 : point-like (or array of point-like) [longitude, latitude] objects
p1 : point-like (or array of point-like) [longitude, latitude] objects
deg : bool, optional (default True)
indicates if p0 and p1 are specified in degrees
r : float, optional (default r_earth_mean)
radius of the sphere
Returns
-------
d : float
Reference
---------
http://www.movable-type.co.uk/scripts/latlong.html - Distance
Note: Spherical earth model. By default uses radius of 6371.0 km.
"""
single, (p0, p1) = _to_arrays((p0, 2), (p1, 2))
if deg:
p0 = np.radians(p0)
p1 = np.radians(p1)
lon0, lat0 = p0[:,0], p0[:,1]
lon1, lat1 = p1[:,0], p1[:,1]
# h_x used to denote haversine(x): sin^2(x / 2)
h_dlat = sin((lat1 - lat0) / 2.0) ** 2
h_dlon = sin((lon1 - lon0) / 2.0) ** 2
h_angle = h_dlat + cos(lat0) * cos(lat1) * h_dlon
angle = 2.0 * arcsin(sqrt(h_angle))
d = r * angle
if single:
d = d[0]
return d | [
"def",
"distance",
"(",
"p0",
",",
"p1",
",",
"deg",
"=",
"True",
",",
"r",
"=",
"r_earth_mean",
")",
":",
"single",
",",
"(",
"p0",
",",
"p1",
")",
"=",
"_to_arrays",
"(",
"(",
"p0",
",",
"2",
")",
",",
"(",
"p1",
",",
"2",
")",
")",
"if",
"deg",
":",
"p0",
"=",
"np",
".",
"radians",
"(",
"p0",
")",
"p1",
"=",
"np",
".",
"radians",
"(",
"p1",
")",
"lon0",
",",
"lat0",
"=",
"p0",
"[",
":",
",",
"0",
"]",
",",
"p0",
"[",
":",
",",
"1",
"]",
"lon1",
",",
"lat1",
"=",
"p1",
"[",
":",
",",
"0",
"]",
",",
"p1",
"[",
":",
",",
"1",
"]",
"# h_x used to denote haversine(x): sin^2(x / 2)",
"h_dlat",
"=",
"sin",
"(",
"(",
"lat1",
"-",
"lat0",
")",
"/",
"2.0",
")",
"**",
"2",
"h_dlon",
"=",
"sin",
"(",
"(",
"lon1",
"-",
"lon0",
")",
"/",
"2.0",
")",
"**",
"2",
"h_angle",
"=",
"h_dlat",
"+",
"cos",
"(",
"lat0",
")",
"*",
"cos",
"(",
"lat1",
")",
"*",
"h_dlon",
"angle",
"=",
"2.0",
"*",
"arcsin",
"(",
"sqrt",
"(",
"h_angle",
")",
")",
"d",
"=",
"r",
"*",
"angle",
"if",
"single",
":",
"d",
"=",
"d",
"[",
"0",
"]",
"return",
"d"
] | 26.534884 | 22.209302 |
def transit_delete_key(self, name, mount_point='transit'):
"""DELETE /<mount_point>/keys/<name>
:param name:
:type name:
:param mount_point:
:type mount_point:
:return:
:rtype:
"""
url = '/v1/{0}/keys/{1}'.format(mount_point, name)
return self._adapter.delete(url) | [
"def",
"transit_delete_key",
"(",
"self",
",",
"name",
",",
"mount_point",
"=",
"'transit'",
")",
":",
"url",
"=",
"'/v1/{0}/keys/{1}'",
".",
"format",
"(",
"mount_point",
",",
"name",
")",
"return",
"self",
".",
"_adapter",
".",
"delete",
"(",
"url",
")"
] | 27.833333 | 16.083333 |
def multivariate_normal(random, mean, cov):
"""
Draw random samples from a multivariate normal distribution.
Parameters
----------
random : np.random.RandomState instance
Random state.
mean : array_like
Mean of the n-dimensional distribution.
cov : array_like
Covariance matrix of the distribution. It must be symmetric and
positive-definite for proper sampling.
Returns
-------
out : ndarray
The drawn sample.
"""
from numpy.linalg import cholesky
L = cholesky(cov)
return L @ random.randn(L.shape[0]) + mean | [
"def",
"multivariate_normal",
"(",
"random",
",",
"mean",
",",
"cov",
")",
":",
"from",
"numpy",
".",
"linalg",
"import",
"cholesky",
"L",
"=",
"cholesky",
"(",
"cov",
")",
"return",
"L",
"@",
"random",
".",
"randn",
"(",
"L",
".",
"shape",
"[",
"0",
"]",
")",
"+",
"mean"
] | 25.478261 | 18.608696 |
def get_user_profile(self, user_id):
"""
Get user profile.
Returns user profile data, including user id, name, and profile pic.
When requesting the profile for the user accessing the API, the user's
calendar feed URL will be returned as well.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - user_id
"""ID"""
path["user_id"] = user_id
self.logger.debug("GET /api/v1/users/{user_id}/profile with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/users/{user_id}/profile".format(**path), data=data, params=params, single_item=True) | [
"def",
"get_user_profile",
"(",
"self",
",",
"user_id",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - user_id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"user_id\"",
"]",
"=",
"user_id",
"self",
".",
"logger",
".",
"debug",
"(",
"\"GET /api/v1/users/{user_id}/profile with query params: {params} and form data: {data}\"",
".",
"format",
"(",
"params",
"=",
"params",
",",
"data",
"=",
"data",
",",
"*",
"*",
"path",
")",
")",
"return",
"self",
".",
"generic_request",
"(",
"\"GET\"",
",",
"\"/api/v1/users/{user_id}/profile\"",
".",
"format",
"(",
"*",
"*",
"path",
")",
",",
"data",
"=",
"data",
",",
"params",
"=",
"params",
",",
"single_item",
"=",
"True",
")"
] | 39.052632 | 28.368421 |
def put_user_policy(self, user_name, policy_name, policy_json):
"""
Adds or updates the specified policy document for the specified user.
:type user_name: string
:param user_name: The name of the user the policy is associated with.
:type policy_name: string
:param policy_name: The policy document to get.
:type policy_json: string
:param policy_json: The policy document.
"""
params = {'UserName' : user_name,
'PolicyName' : policy_name,
'PolicyDocument' : policy_json}
return self.get_response('PutUserPolicy', params, verb='POST') | [
"def",
"put_user_policy",
"(",
"self",
",",
"user_name",
",",
"policy_name",
",",
"policy_json",
")",
":",
"params",
"=",
"{",
"'UserName'",
":",
"user_name",
",",
"'PolicyName'",
":",
"policy_name",
",",
"'PolicyDocument'",
":",
"policy_json",
"}",
"return",
"self",
".",
"get_response",
"(",
"'PutUserPolicy'",
",",
"params",
",",
"verb",
"=",
"'POST'",
")"
] | 36.222222 | 18.888889 |
def to_bigquery_field(self, name_case=DdlParseBase.NAME_CASE.original):
"""Generate BigQuery JSON field define"""
col_name = self.get_name(name_case)
mode = self.bigquery_mode
if self.array_dimensional <= 1:
# no or one dimensional array data type
type = self.bigquery_legacy_data_type
else:
# multiple dimensional array data type
type = "RECORD"
fields = OrderedDict()
fields_cur = fields
for i in range(1, self.array_dimensional):
is_last = True if i == self.array_dimensional - 1 else False
fields_cur['fields'] = [OrderedDict()]
fields_cur = fields_cur['fields'][0]
fields_cur['name'] = "dimension_{}".format(i)
fields_cur['type'] = self.bigquery_legacy_data_type if is_last else "RECORD"
fields_cur['mode'] = self.bigquery_mode if is_last else "REPEATED"
col = OrderedDict()
col['name'] = col_name
col['type'] = type
col['mode'] = mode
if self.array_dimensional > 1:
col['fields'] = fields['fields']
return json.dumps(col) | [
"def",
"to_bigquery_field",
"(",
"self",
",",
"name_case",
"=",
"DdlParseBase",
".",
"NAME_CASE",
".",
"original",
")",
":",
"col_name",
"=",
"self",
".",
"get_name",
"(",
"name_case",
")",
"mode",
"=",
"self",
".",
"bigquery_mode",
"if",
"self",
".",
"array_dimensional",
"<=",
"1",
":",
"# no or one dimensional array data type",
"type",
"=",
"self",
".",
"bigquery_legacy_data_type",
"else",
":",
"# multiple dimensional array data type",
"type",
"=",
"\"RECORD\"",
"fields",
"=",
"OrderedDict",
"(",
")",
"fields_cur",
"=",
"fields",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"self",
".",
"array_dimensional",
")",
":",
"is_last",
"=",
"True",
"if",
"i",
"==",
"self",
".",
"array_dimensional",
"-",
"1",
"else",
"False",
"fields_cur",
"[",
"'fields'",
"]",
"=",
"[",
"OrderedDict",
"(",
")",
"]",
"fields_cur",
"=",
"fields_cur",
"[",
"'fields'",
"]",
"[",
"0",
"]",
"fields_cur",
"[",
"'name'",
"]",
"=",
"\"dimension_{}\"",
".",
"format",
"(",
"i",
")",
"fields_cur",
"[",
"'type'",
"]",
"=",
"self",
".",
"bigquery_legacy_data_type",
"if",
"is_last",
"else",
"\"RECORD\"",
"fields_cur",
"[",
"'mode'",
"]",
"=",
"self",
".",
"bigquery_mode",
"if",
"is_last",
"else",
"\"REPEATED\"",
"col",
"=",
"OrderedDict",
"(",
")",
"col",
"[",
"'name'",
"]",
"=",
"col_name",
"col",
"[",
"'type'",
"]",
"=",
"type",
"col",
"[",
"'mode'",
"]",
"=",
"mode",
"if",
"self",
".",
"array_dimensional",
">",
"1",
":",
"col",
"[",
"'fields'",
"]",
"=",
"fields",
"[",
"'fields'",
"]",
"return",
"json",
".",
"dumps",
"(",
"col",
")"
] | 33.771429 | 21.285714 |
def set_application_parameters(self, application_id, framework_type, repository_url):
"""
Sets parameters for the Hybrid Analysis Mapping ThreadFix functionality.
:param application_id: Application identifier.
:param framework_type: The web framework the app was built on. ('None', 'DETECT', 'JSP', 'SPRING_MVC')
:param repository_url: The git repository where the source code for the application can be found.
"""
params = {
'frameworkType': framework_type,
'repositoryUrl': repository_url
}
return self._request('POST', 'rest/applications/' + str(application_id) + '/setParameters', params) | [
"def",
"set_application_parameters",
"(",
"self",
",",
"application_id",
",",
"framework_type",
",",
"repository_url",
")",
":",
"params",
"=",
"{",
"'frameworkType'",
":",
"framework_type",
",",
"'repositoryUrl'",
":",
"repository_url",
"}",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'rest/applications/'",
"+",
"str",
"(",
"application_id",
")",
"+",
"'/setParameters'",
",",
"params",
")"
] | 56.416667 | 30.083333 |
def getCmdParams(cmd, request, **fields):
"""Update or fill the fields parameters depending on command code. Both cmd and drAppId can be provided # noqa: E501
in string or int format."""
drCode = None
params = None
drAppId = None
# Fetch the parameters if cmd is found in dict
if isinstance(cmd, int):
drCode = cmd # Enable to craft commands with non standard code
if cmd in DR_cmd_def:
params = DR_cmd_def[drCode]
else:
params = ('Unknown', 'UK', {0: (128, 0)})
warning(
'No Diameter command with code %d found in DR_cmd_def dictionary' % # noqa: E501
cmd)
else: # Assume command is a string
if len(cmd) > 3: # Assume full command name given
fpos = 0
else: # Assume abbreviated name is given and take only the first two letters # noqa: E501
cmd = cmd[:2]
fpos = 1
for k, f in DR_cmd_def.items():
if f[fpos][:len(
cmd)] == cmd: # Accept only a prefix of the full name
drCode = k
params = f
break
if not drCode:
warning(
'Diameter command with name %s not found in DR_cmd_def dictionary.' % # noqa: E501
cmd)
return (fields, 'Unknown')
# The drCode is set/overridden in any case
fields['drCode'] = drCode
# Processing of drAppId
if 'drAppId' in fields:
val = fields['drAppId']
if isinstance(val, str): # Translate into application Id code
found = False
for k, v in six.iteritems(AppIDsEnum):
if v.find(val) != -1:
drAppId = k
fields['drAppId'] = drAppId
found = True
break
if not found:
del(fields['drAppId'])
warning(
'Application ID with name %s not found in AppIDsEnum dictionary.' % # noqa: E501
val)
return (fields, 'Unknown')
else: # Assume type is int
drAppId = val
else: # Application Id shall be taken from the params found based on cmd
drAppId = next(iter(params[2])) # The first record is taken
fields['drAppId'] = drAppId
# Set the command name
name = request and params[0] + '-Request' or params[0] + '-Answer'
# Processing of flags (only if not provided manually)
if 'drFlags' not in fields:
if drAppId in params[2]:
flags = params[2][drAppId]
fields['drFlags'] = request and flags[0] or flags[1]
return (fields, name) | [
"def",
"getCmdParams",
"(",
"cmd",
",",
"request",
",",
"*",
"*",
"fields",
")",
":",
"drCode",
"=",
"None",
"params",
"=",
"None",
"drAppId",
"=",
"None",
"# Fetch the parameters if cmd is found in dict",
"if",
"isinstance",
"(",
"cmd",
",",
"int",
")",
":",
"drCode",
"=",
"cmd",
"# Enable to craft commands with non standard code",
"if",
"cmd",
"in",
"DR_cmd_def",
":",
"params",
"=",
"DR_cmd_def",
"[",
"drCode",
"]",
"else",
":",
"params",
"=",
"(",
"'Unknown'",
",",
"'UK'",
",",
"{",
"0",
":",
"(",
"128",
",",
"0",
")",
"}",
")",
"warning",
"(",
"'No Diameter command with code %d found in DR_cmd_def dictionary'",
"%",
"# noqa: E501",
"cmd",
")",
"else",
":",
"# Assume command is a string",
"if",
"len",
"(",
"cmd",
")",
">",
"3",
":",
"# Assume full command name given",
"fpos",
"=",
"0",
"else",
":",
"# Assume abbreviated name is given and take only the first two letters # noqa: E501",
"cmd",
"=",
"cmd",
"[",
":",
"2",
"]",
"fpos",
"=",
"1",
"for",
"k",
",",
"f",
"in",
"DR_cmd_def",
".",
"items",
"(",
")",
":",
"if",
"f",
"[",
"fpos",
"]",
"[",
":",
"len",
"(",
"cmd",
")",
"]",
"==",
"cmd",
":",
"# Accept only a prefix of the full name",
"drCode",
"=",
"k",
"params",
"=",
"f",
"break",
"if",
"not",
"drCode",
":",
"warning",
"(",
"'Diameter command with name %s not found in DR_cmd_def dictionary.'",
"%",
"# noqa: E501",
"cmd",
")",
"return",
"(",
"fields",
",",
"'Unknown'",
")",
"# The drCode is set/overridden in any case",
"fields",
"[",
"'drCode'",
"]",
"=",
"drCode",
"# Processing of drAppId",
"if",
"'drAppId'",
"in",
"fields",
":",
"val",
"=",
"fields",
"[",
"'drAppId'",
"]",
"if",
"isinstance",
"(",
"val",
",",
"str",
")",
":",
"# Translate into application Id code",
"found",
"=",
"False",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"AppIDsEnum",
")",
":",
"if",
"v",
".",
"find",
"(",
"val",
")",
"!=",
"-",
"1",
":",
"drAppId",
"=",
"k",
"fields",
"[",
"'drAppId'",
"]",
"=",
"drAppId",
"found",
"=",
"True",
"break",
"if",
"not",
"found",
":",
"del",
"(",
"fields",
"[",
"'drAppId'",
"]",
")",
"warning",
"(",
"'Application ID with name %s not found in AppIDsEnum dictionary.'",
"%",
"# noqa: E501",
"val",
")",
"return",
"(",
"fields",
",",
"'Unknown'",
")",
"else",
":",
"# Assume type is int",
"drAppId",
"=",
"val",
"else",
":",
"# Application Id shall be taken from the params found based on cmd",
"drAppId",
"=",
"next",
"(",
"iter",
"(",
"params",
"[",
"2",
"]",
")",
")",
"# The first record is taken",
"fields",
"[",
"'drAppId'",
"]",
"=",
"drAppId",
"# Set the command name",
"name",
"=",
"request",
"and",
"params",
"[",
"0",
"]",
"+",
"'-Request'",
"or",
"params",
"[",
"0",
"]",
"+",
"'-Answer'",
"# Processing of flags (only if not provided manually)",
"if",
"'drFlags'",
"not",
"in",
"fields",
":",
"if",
"drAppId",
"in",
"params",
"[",
"2",
"]",
":",
"flags",
"=",
"params",
"[",
"2",
"]",
"[",
"drAppId",
"]",
"fields",
"[",
"'drFlags'",
"]",
"=",
"request",
"and",
"flags",
"[",
"0",
"]",
"or",
"flags",
"[",
"1",
"]",
"return",
"(",
"fields",
",",
"name",
")"
] | 41.107692 | 16.938462 |
def disassemble_all(bytecode, pc=0, fork=DEFAULT_FORK):
""" Disassemble all instructions in bytecode
:param bytecode: an evm bytecode (binary)
:type bytecode: str | bytes | bytearray | iterator
:param pc: program counter of the first instruction(optional)
:type pc: int
:param fork: fork name (optional)
:type fork: str
:return: An generator of Instruction objects
:rtype: list[Instruction]
Example use::
>>> for inst in disassemble_all(bytecode):
... print(instr)
...
PUSH1 0x60
PUSH1 0x40
MSTORE
PUSH1 0x2
PUSH2 0x108
PUSH1 0x0
POP
SSTORE
PUSH1 0x40
MLOAD
"""
if isinstance(bytecode, bytes):
bytecode = bytearray(bytecode)
if isinstance(bytecode, str):
bytecode = bytearray(bytecode.encode('latin-1'))
bytecode = iter(bytecode)
while True:
instr = disassemble_one(bytecode, pc=pc, fork=fork)
if not instr:
return
pc += instr.size
yield instr | [
"def",
"disassemble_all",
"(",
"bytecode",
",",
"pc",
"=",
"0",
",",
"fork",
"=",
"DEFAULT_FORK",
")",
":",
"if",
"isinstance",
"(",
"bytecode",
",",
"bytes",
")",
":",
"bytecode",
"=",
"bytearray",
"(",
"bytecode",
")",
"if",
"isinstance",
"(",
"bytecode",
",",
"str",
")",
":",
"bytecode",
"=",
"bytearray",
"(",
"bytecode",
".",
"encode",
"(",
"'latin-1'",
")",
")",
"bytecode",
"=",
"iter",
"(",
"bytecode",
")",
"while",
"True",
":",
"instr",
"=",
"disassemble_one",
"(",
"bytecode",
",",
"pc",
"=",
"pc",
",",
"fork",
"=",
"fork",
")",
"if",
"not",
"instr",
":",
"return",
"pc",
"+=",
"instr",
".",
"size",
"yield",
"instr"
] | 26.116279 | 19.488372 |
def open(self, options=None, mimetype='application/octet-stream'):
"""
open: return a file like object for self.
The method can be used with the 'with' statment.
"""
return self.connection.open(self, options, mimetype) | [
"def",
"open",
"(",
"self",
",",
"options",
"=",
"None",
",",
"mimetype",
"=",
"'application/octet-stream'",
")",
":",
"return",
"self",
".",
"connection",
".",
"open",
"(",
"self",
",",
"options",
",",
"mimetype",
")"
] | 42.166667 | 11.833333 |
def set_server_handler(self, handler_func, name=None, header_filter=None, alias=None, interval=0.5):
"""Sets an automatic handler for the type of message template currently loaded.
This feature allows users to set a python handler function which is called
automatically by the Rammbock message queue when message matches the expected
template. The optional name argument defines the server node to which the
handler will be bound. Otherwise the default server will be used.
The header_filter defines which header field will be used to identify the
message defined in template. (Otherwise all incoming messages will match!)
The interval defines the interval in seconds on which the handler will
be called on background. By default the incoming messages are checked
every 0.5 seconds.
The alias is the alias for the connection. By default the current active
connection will be used.
The handler function will be called with two arguments: the rammbock library
instance and the received message.
Example:
| Load template | SomeMessage |
| Set server handler | my_module.respond_to_sample | messageType |
my_module.py:
| def respond_to_sample(rammbock, msg):
| rammbock.save_template("__backup_template", unlocked=True)
| try:
| rammbock.load_template("sample response")
| rammbock.server_sends_message()
| finally:
| rammbock.load_template("__backup_template")
"""
msg_template = self._get_message_template()
server, server_name = self._servers.get_with_name(name)
server.set_handler(msg_template, handler_func, header_filter=header_filter, alias=alias, interval=interval) | [
"def",
"set_server_handler",
"(",
"self",
",",
"handler_func",
",",
"name",
"=",
"None",
",",
"header_filter",
"=",
"None",
",",
"alias",
"=",
"None",
",",
"interval",
"=",
"0.5",
")",
":",
"msg_template",
"=",
"self",
".",
"_get_message_template",
"(",
")",
"server",
",",
"server_name",
"=",
"self",
".",
"_servers",
".",
"get_with_name",
"(",
"name",
")",
"server",
".",
"set_handler",
"(",
"msg_template",
",",
"handler_func",
",",
"header_filter",
"=",
"header_filter",
",",
"alias",
"=",
"alias",
",",
"interval",
"=",
"interval",
")"
] | 49 | 29.324324 |
def _add_kwarg_datasets(datasets, kwargs):
"""Add data sets of the given kwargs.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicode` to varies
"""
for test_method_suffix, dataset in six.iteritems(kwargs):
datasets[test_method_suffix] = dataset | [
"def",
"_add_kwarg_datasets",
"(",
"datasets",
",",
"kwargs",
")",
":",
"for",
"test_method_suffix",
",",
"dataset",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
")",
":",
"datasets",
"[",
"test_method_suffix",
"]",
"=",
"dataset"
] | 28.928571 | 13.928571 |
def svg_polygon(coordinates, color):
"""
Create an svg triangle for the stationary heatmap.
Parameters
----------
coordinates: list
The coordinates defining the polygon
color: string
RGB color value e.g. #26ffd1
Returns
-------
string, the svg string for the polygon
"""
coord_str = []
for c in coordinates:
coord_str.append(",".join(map(str, c)))
coord_str = " ".join(coord_str)
polygon = '<polygon points="%s" style="fill:%s;stroke:%s;stroke-width:0"/>\n' % (coord_str, color, color)
return polygon | [
"def",
"svg_polygon",
"(",
"coordinates",
",",
"color",
")",
":",
"coord_str",
"=",
"[",
"]",
"for",
"c",
"in",
"coordinates",
":",
"coord_str",
".",
"append",
"(",
"\",\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"c",
")",
")",
")",
"coord_str",
"=",
"\" \"",
".",
"join",
"(",
"coord_str",
")",
"polygon",
"=",
"'<polygon points=\"%s\" style=\"fill:%s;stroke:%s;stroke-width:0\"/>\\n'",
"%",
"(",
"coord_str",
",",
"color",
",",
"color",
")",
"return",
"polygon"
] | 25.727273 | 20 |
def luhn_checksum(number, chars=DIGITS):
'''
Calculates the Luhn checksum for `number`
:param number: string or int
:param chars: string
>>> luhn_checksum(1234)
4
'''
length = len(chars)
number = [chars.index(n) for n in reversed(str(number))]
return (
sum(number[::2]) +
sum(sum(divmod(i * 2, length)) for i in number[1::2])
) % length | [
"def",
"luhn_checksum",
"(",
"number",
",",
"chars",
"=",
"DIGITS",
")",
":",
"length",
"=",
"len",
"(",
"chars",
")",
"number",
"=",
"[",
"chars",
".",
"index",
"(",
"n",
")",
"for",
"n",
"in",
"reversed",
"(",
"str",
"(",
"number",
")",
")",
"]",
"return",
"(",
"sum",
"(",
"number",
"[",
":",
":",
"2",
"]",
")",
"+",
"sum",
"(",
"sum",
"(",
"divmod",
"(",
"i",
"*",
"2",
",",
"length",
")",
")",
"for",
"i",
"in",
"number",
"[",
"1",
":",
":",
"2",
"]",
")",
")",
"%",
"length"
] | 22.529412 | 22.882353 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ChannelContext for this ChannelInstance
:rtype: twilio.rest.chat.v1.service.channel.ChannelContext
"""
if self._context is None:
self._context = ChannelContext(
self._version,
service_sid=self._solution['service_sid'],
sid=self._solution['sid'],
)
return self._context | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"ChannelContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
")",
"return",
"self",
".",
"_context"
] | 38.2 | 17.933333 |
def _make_load_template(self):
"""
Return a function that loads a template by name.
"""
loader = self._make_loader()
def load_template(template_name):
return loader.load_name(template_name)
return load_template | [
"def",
"_make_load_template",
"(",
"self",
")",
":",
"loader",
"=",
"self",
".",
"_make_loader",
"(",
")",
"def",
"load_template",
"(",
"template_name",
")",
":",
"return",
"loader",
".",
"load_name",
"(",
"template_name",
")",
"return",
"load_template"
] | 23.909091 | 15.727273 |
def fn_getdatetime_list(fn):
"""Extract all datetime strings from input filename
"""
#Want to split last component
fn = os.path.split(os.path.splitext(fn)[0])[-1]
import re
#WV01_12JUN152223255-P1BS_R1C1-102001001B3B9800__WV01_12JUN152224050-P1BS_R1C1-102001001C555C00-DEM_4x.tif
#Need to parse above with month name
#Note: made this more restrictive to avoid false matches:
#'20130304_1510_1030010020770600_1030010020CEAB00-DEM_4x'
#This is a problem, b/c 2015/17/00:
#WV02_20130315_10300100207D5600_1030010020151700
#This code should be obsolete before 2019
#Assume new filenames
#fn = fn[0:13]
#Use cascading re find to pull out timestamps
#Note: Want to be less restrictive here - could have a mix of YYYYMMDD_HHMM, YYYYMMDD and YYYY in filename
#Should probably search for all possibilities, then prune
#NOTE: these don't include seconds in the time
#NOTE: could have 20130304_1510__20130304__whatever in filename
#The current approach will only catch the first datetime
dstr = None
out = None
#20180101_1200 or 20180101T1200
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])[_T](?:0[0-9]|1[0-9]|2[0-3])[0-5][0-9]', fn)
#201801011200
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])(?:0[0-9]|1[0-9]|2[0-3])[0-5][0-9]', fn)
#20180101
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])(?:$|_|-)', fn)
#This should pick up dates separated by a dash
#dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])', fn)
#2018.609990
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9]\.[0-9][0-9][0-9]*(?:$|_|-)', fn)
dstr = [d.lstrip('_').rstrip('_') for d in dstr]
dstr = [d.lstrip('-').rstrip('-') for d in dstr]
out = [decyear2dt(float(s)) for s in dstr]
dstr = None
#2018
if not dstr:
dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:$|_|-)', fn)
#This is for USGS archive filenames
if not dstr:
dstr = re.findall(r'[0-3][0-9][a-z][a-z][a-z][0-9][0-9]', fn)
#This is USGS archive format
if dstr:
out = [datetime.strptime(s, '%d%b%y') for s in dstr][0]
dstr = None
if dstr:
#This is a hack to remove peripheral underscores and dashes
dstr = [d.lstrip('_').rstrip('_') for d in dstr]
dstr = [d.lstrip('-').rstrip('-') for d in dstr]
#This returns an empty list of nothing is found
out = [strptime_fuzzy(s) for s in dstr]
return out | [
"def",
"fn_getdatetime_list",
"(",
"fn",
")",
":",
"#Want to split last component",
"fn",
"=",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"fn",
")",
"[",
"0",
"]",
")",
"[",
"-",
"1",
"]",
"import",
"re",
"#WV01_12JUN152223255-P1BS_R1C1-102001001B3B9800__WV01_12JUN152224050-P1BS_R1C1-102001001C555C00-DEM_4x.tif",
"#Need to parse above with month name ",
"#Note: made this more restrictive to avoid false matches:",
"#'20130304_1510_1030010020770600_1030010020CEAB00-DEM_4x'",
"#This is a problem, b/c 2015/17/00:",
"#WV02_20130315_10300100207D5600_1030010020151700",
"#This code should be obsolete before 2019 ",
"#Assume new filenames",
"#fn = fn[0:13]",
"#Use cascading re find to pull out timestamps",
"#Note: Want to be less restrictive here - could have a mix of YYYYMMDD_HHMM, YYYYMMDD and YYYY in filename",
"#Should probably search for all possibilities, then prune ",
"#NOTE: these don't include seconds in the time",
"#NOTE: could have 20130304_1510__20130304__whatever in filename",
"#The current approach will only catch the first datetime ",
"dstr",
"=",
"None",
"out",
"=",
"None",
"#20180101_1200 or 20180101T1200",
"dstr",
"=",
"re",
".",
"findall",
"(",
"r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])[_T](?:0[0-9]|1[0-9]|2[0-3])[0-5][0-9]'",
",",
"fn",
")",
"#201801011200",
"if",
"not",
"dstr",
":",
"dstr",
"=",
"re",
".",
"findall",
"(",
"r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])(?:0[0-9]|1[0-9]|2[0-3])[0-5][0-9]'",
",",
"fn",
")",
"#20180101",
"if",
"not",
"dstr",
":",
"dstr",
"=",
"re",
".",
"findall",
"(",
"r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])(?:$|_|-)'",
",",
"fn",
")",
"#This should pick up dates separated by a dash",
"#dstr = re.findall(r'(?:^|_|-)(?:19|20)[0-9][0-9](?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])', fn)",
"#2018.609990",
"if",
"not",
"dstr",
":",
"dstr",
"=",
"re",
".",
"findall",
"(",
"r'(?:^|_|-)(?:19|20)[0-9][0-9]\\.[0-9][0-9][0-9]*(?:$|_|-)'",
",",
"fn",
")",
"dstr",
"=",
"[",
"d",
".",
"lstrip",
"(",
"'_'",
")",
".",
"rstrip",
"(",
"'_'",
")",
"for",
"d",
"in",
"dstr",
"]",
"dstr",
"=",
"[",
"d",
".",
"lstrip",
"(",
"'-'",
")",
".",
"rstrip",
"(",
"'-'",
")",
"for",
"d",
"in",
"dstr",
"]",
"out",
"=",
"[",
"decyear2dt",
"(",
"float",
"(",
"s",
")",
")",
"for",
"s",
"in",
"dstr",
"]",
"dstr",
"=",
"None",
"#2018",
"if",
"not",
"dstr",
":",
"dstr",
"=",
"re",
".",
"findall",
"(",
"r'(?:^|_|-)(?:19|20)[0-9][0-9](?:$|_|-)'",
",",
"fn",
")",
"#This is for USGS archive filenames",
"if",
"not",
"dstr",
":",
"dstr",
"=",
"re",
".",
"findall",
"(",
"r'[0-3][0-9][a-z][a-z][a-z][0-9][0-9]'",
",",
"fn",
")",
"#This is USGS archive format",
"if",
"dstr",
":",
"out",
"=",
"[",
"datetime",
".",
"strptime",
"(",
"s",
",",
"'%d%b%y'",
")",
"for",
"s",
"in",
"dstr",
"]",
"[",
"0",
"]",
"dstr",
"=",
"None",
"if",
"dstr",
":",
"#This is a hack to remove peripheral underscores and dashes",
"dstr",
"=",
"[",
"d",
".",
"lstrip",
"(",
"'_'",
")",
".",
"rstrip",
"(",
"'_'",
")",
"for",
"d",
"in",
"dstr",
"]",
"dstr",
"=",
"[",
"d",
".",
"lstrip",
"(",
"'-'",
")",
".",
"rstrip",
"(",
"'-'",
")",
"for",
"d",
"in",
"dstr",
"]",
"#This returns an empty list of nothing is found",
"out",
"=",
"[",
"strptime_fuzzy",
"(",
"s",
")",
"for",
"s",
"in",
"dstr",
"]",
"return",
"out"
] | 47.175439 | 24.54386 |
def set_context(self, definition: Definition, explanation: str) -> None:
"""Set the source code context for this error."""
self.definition = definition
self.explanation = explanation | [
"def",
"set_context",
"(",
"self",
",",
"definition",
":",
"Definition",
",",
"explanation",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"definition",
"=",
"definition",
"self",
".",
"explanation",
"=",
"explanation"
] | 50.75 | 9.5 |
def reboot(name, call=None):
'''
Reboot a VM.
.. versionadded:: 2016.3.0
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot my-vm
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
log.info('Rebooting node %s', name)
return vm_action(name, kwargs={'action': 'reboot'}, call=call) | [
"def",
"reboot",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The start action must be called with -a or --action.'",
")",
"log",
".",
"info",
"(",
"'Rebooting node %s'",
",",
"name",
")",
"return",
"vm_action",
"(",
"name",
",",
"kwargs",
"=",
"{",
"'action'",
":",
"'reboot'",
"}",
",",
"call",
"=",
"call",
")"
] | 19.347826 | 25.173913 |
def has_no_error(
state,
incorrect_msg="Have a look at the console: your code contains an error. Fix it and try again!",
):
"""Check whether the submission did not generate a runtime error.
If all SCTs for an exercise pass, before marking the submission as correct pythonwhat will automatically check whether
the student submission generated an error. This means it is not needed to use ``has_no_error()`` explicitly.
However, in some cases, using ``has_no_error()`` explicitly somewhere throughout your SCT execution can be helpful:
- If you want to make sure people didn't write typos when writing a long function name.
- If you want to first verify whether a function actually runs, before checking whether the arguments were specified correctly.
- More generally, if, because of the content, it's instrumental that the script runs without
errors before doing any other verifications.
Args:
incorrect_msg: if specified, this overrides the default message if the student code generated an error.
:Example:
Suppose you're verifying an exercise about model training and validation: ::
# pre exercise code
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import datasets
from sklearn import svm
iris = datasets.load_iris()
iris.data.shape, iris.target.shape
# solution
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.4, random_state=0)
If you want to make sure that ``train_test_split()`` ran without errors,
which would check if the student typed the function without typos and used
sensical arguments, you could use the following SCT: ::
Ex().has_no_error()
Ex().check_function('sklearn.model_selection.train_test_split').multi(
check_args(['arrays', 0]).has_equal_value(),
check_args(['arrays', 0]).has_equal_value(),
check_args(['options', 'test_size']).has_equal_value(),
check_args(['options', 'random_state']).has_equal_value()
)
If, on the other hand, you want to fall back onto pythonwhat's built in behavior,
that checks for an error before marking the exercise as correct, you can simply
leave of the ``has_no_error()`` step.
"""
state.assert_root("has_no_error")
if state.reporter.errors:
_msg = state.build_message(
incorrect_msg, {"error": str(state.reporter.errors[0])}
)
state.report(Feedback(_msg, state))
return state | [
"def",
"has_no_error",
"(",
"state",
",",
"incorrect_msg",
"=",
"\"Have a look at the console: your code contains an error. Fix it and try again!\"",
",",
")",
":",
"state",
".",
"assert_root",
"(",
"\"has_no_error\"",
")",
"if",
"state",
".",
"reporter",
".",
"errors",
":",
"_msg",
"=",
"state",
".",
"build_message",
"(",
"incorrect_msg",
",",
"{",
"\"error\"",
":",
"str",
"(",
"state",
".",
"reporter",
".",
"errors",
"[",
"0",
"]",
")",
"}",
")",
"state",
".",
"report",
"(",
"Feedback",
"(",
"_msg",
",",
"state",
")",
")",
"return",
"state"
] | 42.822581 | 31.983871 |
def add_filter(self, files_filter, filter_type=DefaultFilterType):
"""
Add a files filter to this iterator.
For a file to be processed, it must match ALL filters, eg they are added with ADD, not OR.
:param files_filter: filter to apply, must be an object inheriting from filters.FilterAPI.
:param filter_type: filter behavior, see FilterType for details.
"""
self.__filters.append((files_filter, filter_type))
return self | [
"def",
"add_filter",
"(",
"self",
",",
"files_filter",
",",
"filter_type",
"=",
"DefaultFilterType",
")",
":",
"self",
".",
"__filters",
".",
"append",
"(",
"(",
"files_filter",
",",
"filter_type",
")",
")",
"return",
"self"
] | 47.7 | 25.7 |
def parse_assignment(self, stream):
"""
AssignmentStmt ::= Name WSC AssignmentSymbol WSC Value StatementDelim
"""
lineno = stream.lineno
name = self.next_token(stream)
self.ensure_assignment(stream)
at_an_end = any((
self.has_end_group(stream),
self.has_end_object(stream),
self.has_end(stream),
self.has_next(self.statement_delimiter, stream, 0)))
if at_an_end:
value = self.broken_assignment(lineno)
self.skip_whitespace_or_comment(stream)
else:
value = self.parse_value(stream)
self.skip_statement_delimiter(stream)
return name.decode('utf-8'), value | [
"def",
"parse_assignment",
"(",
"self",
",",
"stream",
")",
":",
"lineno",
"=",
"stream",
".",
"lineno",
"name",
"=",
"self",
".",
"next_token",
"(",
"stream",
")",
"self",
".",
"ensure_assignment",
"(",
"stream",
")",
"at_an_end",
"=",
"any",
"(",
"(",
"self",
".",
"has_end_group",
"(",
"stream",
")",
",",
"self",
".",
"has_end_object",
"(",
"stream",
")",
",",
"self",
".",
"has_end",
"(",
"stream",
")",
",",
"self",
".",
"has_next",
"(",
"self",
".",
"statement_delimiter",
",",
"stream",
",",
"0",
")",
")",
")",
"if",
"at_an_end",
":",
"value",
"=",
"self",
".",
"broken_assignment",
"(",
"lineno",
")",
"self",
".",
"skip_whitespace_or_comment",
"(",
"stream",
")",
"else",
":",
"value",
"=",
"self",
".",
"parse_value",
"(",
"stream",
")",
"self",
".",
"skip_statement_delimiter",
"(",
"stream",
")",
"return",
"name",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"value"
] | 37.210526 | 9.526316 |
def _make_counter_path(self, machine_name, counter_name, instance_name, counters):
"""
When handling non english versions, the counters don't work quite as documented.
This is because strings like "Bytes Sent/sec" might appear multiple times in the
english master, and might not have mappings for each index.
Search each index, and make sure the requested counter name actually appears in
the list of available counters; that's the counter we'll use.
"""
path = ""
if WinPDHCounter._use_en_counter_names:
'''
In this case, we don't have any translations. Just attempt to make the
counter path
'''
try:
path = win32pdh.MakeCounterPath((machine_name, self._class_name, instance_name, None, 0, counter_name))
self.logger.debug("Successfully created English-only path")
except Exception as e: # noqa: E722
self.logger.warning("Unable to create English-only path %s" % str(e))
raise
return path
counter_name_index_list = WinPDHCounter.pdh_counter_dict[counter_name]
for index in counter_name_index_list:
c = win32pdh.LookupPerfNameByIndex(None, int(index))
if c is None or len(c) == 0:
self.logger.debug("Index %s not found, skipping" % index)
continue
# check to see if this counter is in the list of counters for this class
if c not in counters:
try:
self.logger.debug("Index %s counter %s not in counter list" % (index, text_type(c)))
except: # noqa: E722
# some unicode characters are not translatable here. Don't fail just
# because we couldn't log
self.logger.debug("Index %s not in counter list" % index)
continue
# see if we can create a counter
try:
path = win32pdh.MakeCounterPath((machine_name, self._class_name, instance_name, None, 0, c))
break
except: # noqa: E722
try:
self.logger.info("Unable to make path with counter %s, trying next available" % text_type(c))
except: # noqa: E722
self.logger.info("Unable to make path with counter index %s, trying next available" % index)
return path | [
"def",
"_make_counter_path",
"(",
"self",
",",
"machine_name",
",",
"counter_name",
",",
"instance_name",
",",
"counters",
")",
":",
"path",
"=",
"\"\"",
"if",
"WinPDHCounter",
".",
"_use_en_counter_names",
":",
"'''\n In this case, we don't have any translations. Just attempt to make the\n counter path\n '''",
"try",
":",
"path",
"=",
"win32pdh",
".",
"MakeCounterPath",
"(",
"(",
"machine_name",
",",
"self",
".",
"_class_name",
",",
"instance_name",
",",
"None",
",",
"0",
",",
"counter_name",
")",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Successfully created English-only path\"",
")",
"except",
"Exception",
"as",
"e",
":",
"# noqa: E722",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Unable to create English-only path %s\"",
"%",
"str",
"(",
"e",
")",
")",
"raise",
"return",
"path",
"counter_name_index_list",
"=",
"WinPDHCounter",
".",
"pdh_counter_dict",
"[",
"counter_name",
"]",
"for",
"index",
"in",
"counter_name_index_list",
":",
"c",
"=",
"win32pdh",
".",
"LookupPerfNameByIndex",
"(",
"None",
",",
"int",
"(",
"index",
")",
")",
"if",
"c",
"is",
"None",
"or",
"len",
"(",
"c",
")",
"==",
"0",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Index %s not found, skipping\"",
"%",
"index",
")",
"continue",
"# check to see if this counter is in the list of counters for this class",
"if",
"c",
"not",
"in",
"counters",
":",
"try",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Index %s counter %s not in counter list\"",
"%",
"(",
"index",
",",
"text_type",
"(",
"c",
")",
")",
")",
"except",
":",
"# noqa: E722",
"# some unicode characters are not translatable here. Don't fail just",
"# because we couldn't log",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Index %s not in counter list\"",
"%",
"index",
")",
"continue",
"# see if we can create a counter",
"try",
":",
"path",
"=",
"win32pdh",
".",
"MakeCounterPath",
"(",
"(",
"machine_name",
",",
"self",
".",
"_class_name",
",",
"instance_name",
",",
"None",
",",
"0",
",",
"c",
")",
")",
"break",
"except",
":",
"# noqa: E722",
"try",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Unable to make path with counter %s, trying next available\"",
"%",
"text_type",
"(",
"c",
")",
")",
"except",
":",
"# noqa: E722",
"self",
".",
"logger",
".",
"info",
"(",
"\"Unable to make path with counter index %s, trying next available\"",
"%",
"index",
")",
"return",
"path"
] | 47.134615 | 29.211538 |
def symmetry_measure(points_distorted, points_perfect):
"""
Computes the continuous symmetry measure of the (distorted) set of points "points_distorted" with respect to the
(perfect) set of points "points_perfect".
:param points_distorted: List of points describing a given (distorted) polyhedron for which the symmetry measure
has to be computed with respect to the model polyhedron described by the list of points
"points_perfect".
:param points_perfect: List of "perfect" points describing a given model polyhedron.
:return: The continuous symmetry measure of the distorted polyhedron with respect to the perfect polyhedron
"""
# When there is only one point, the symmetry measure is 0.0 by definition
if len(points_distorted) == 1:
return {'symmetry_measure': 0.0, 'scaling_factor': None, 'rotation_matrix': None}
# Find the rotation matrix that aligns the distorted points to the perfect points in a least-square sense.
rot = find_rotation(points_distorted=points_distorted,
points_perfect=points_perfect)
# Find the scaling factor between the distorted points and the perfect points in a least-square sense.
scaling_factor, rotated_coords, points_perfect = find_scaling_factor(points_distorted=points_distorted,
points_perfect=points_perfect,
rot=rot)
# Compute the continuous symmetry measure [see Eq. 1 in Pinsky et al., Inorganic Chemistry 37, 5575 (1998)]
rotated_coords = scaling_factor * rotated_coords
diff = points_perfect - rotated_coords
num = np.tensordot(diff, diff)
denom = np.tensordot(points_perfect, points_perfect)
return {'symmetry_measure': num / denom * 100.0, 'scaling_factor': scaling_factor, 'rotation_matrix': rot} | [
"def",
"symmetry_measure",
"(",
"points_distorted",
",",
"points_perfect",
")",
":",
"# When there is only one point, the symmetry measure is 0.0 by definition",
"if",
"len",
"(",
"points_distorted",
")",
"==",
"1",
":",
"return",
"{",
"'symmetry_measure'",
":",
"0.0",
",",
"'scaling_factor'",
":",
"None",
",",
"'rotation_matrix'",
":",
"None",
"}",
"# Find the rotation matrix that aligns the distorted points to the perfect points in a least-square sense.",
"rot",
"=",
"find_rotation",
"(",
"points_distorted",
"=",
"points_distorted",
",",
"points_perfect",
"=",
"points_perfect",
")",
"# Find the scaling factor between the distorted points and the perfect points in a least-square sense.",
"scaling_factor",
",",
"rotated_coords",
",",
"points_perfect",
"=",
"find_scaling_factor",
"(",
"points_distorted",
"=",
"points_distorted",
",",
"points_perfect",
"=",
"points_perfect",
",",
"rot",
"=",
"rot",
")",
"# Compute the continuous symmetry measure [see Eq. 1 in Pinsky et al., Inorganic Chemistry 37, 5575 (1998)]",
"rotated_coords",
"=",
"scaling_factor",
"*",
"rotated_coords",
"diff",
"=",
"points_perfect",
"-",
"rotated_coords",
"num",
"=",
"np",
".",
"tensordot",
"(",
"diff",
",",
"diff",
")",
"denom",
"=",
"np",
".",
"tensordot",
"(",
"points_perfect",
",",
"points_perfect",
")",
"return",
"{",
"'symmetry_measure'",
":",
"num",
"/",
"denom",
"*",
"100.0",
",",
"'scaling_factor'",
":",
"scaling_factor",
",",
"'rotation_matrix'",
":",
"rot",
"}"
] | 74.384615 | 37.846154 |
def generate_models(config, raml_resources):
""" Generate model for each resource in :raml_resources:
The DB model name is generated using singular titled version of current
resource's url. E.g. for resource under url '/stories', model with
name 'Story' will be generated.
:param config: Pyramid Configurator instance.
:param raml_resources: List of ramlfications.raml.ResourceNode.
"""
from .models import handle_model_generation
if not raml_resources:
return
for raml_resource in raml_resources:
# No need to generate models for dynamic resource
if is_dynamic_uri(raml_resource.path):
continue
# Since POST resource must define schema use only POST
# resources to generate models
if raml_resource.method.upper() != 'POST':
continue
# Generate DB model
# If this is an attribute resource we don't need to generate model
resource_uri = get_resource_uri(raml_resource)
route_name = get_route_name(resource_uri)
if not attr_subresource(raml_resource, route_name):
log.info('Configuring model for route `{}`'.format(route_name))
model_cls, is_auth_model = handle_model_generation(
config, raml_resource)
if is_auth_model:
config.registry.auth_model = model_cls | [
"def",
"generate_models",
"(",
"config",
",",
"raml_resources",
")",
":",
"from",
".",
"models",
"import",
"handle_model_generation",
"if",
"not",
"raml_resources",
":",
"return",
"for",
"raml_resource",
"in",
"raml_resources",
":",
"# No need to generate models for dynamic resource",
"if",
"is_dynamic_uri",
"(",
"raml_resource",
".",
"path",
")",
":",
"continue",
"# Since POST resource must define schema use only POST",
"# resources to generate models",
"if",
"raml_resource",
".",
"method",
".",
"upper",
"(",
")",
"!=",
"'POST'",
":",
"continue",
"# Generate DB model",
"# If this is an attribute resource we don't need to generate model",
"resource_uri",
"=",
"get_resource_uri",
"(",
"raml_resource",
")",
"route_name",
"=",
"get_route_name",
"(",
"resource_uri",
")",
"if",
"not",
"attr_subresource",
"(",
"raml_resource",
",",
"route_name",
")",
":",
"log",
".",
"info",
"(",
"'Configuring model for route `{}`'",
".",
"format",
"(",
"route_name",
")",
")",
"model_cls",
",",
"is_auth_model",
"=",
"handle_model_generation",
"(",
"config",
",",
"raml_resource",
")",
"if",
"is_auth_model",
":",
"config",
".",
"registry",
".",
"auth_model",
"=",
"model_cls"
] | 40.878788 | 17.818182 |
def reprsig(fun, name=None, method=False):
"""Format a methods signature for display."""
args, varargs, keywords, defs, kwargs = [], [], None, [], {}
argspec = fun
if callable(fun):
name = fun.__name__ if name is None else name
argspec = getargspec(fun)
try:
args = argspec[0]
varargs = argspec[1]
keywords = argspec[2]
defs = argspec[3]
except IndexError:
pass
if defs:
args, kwkeys = args[:-len(defs)], args[-len(defs):]
kwargs = dict(zip(kwkeys, defs))
if varargs:
args.append('*' + varargs)
if method:
args.insert(0, 'self')
return reprcall(name, map(str, args), kwargs, keywords,
argfilter=str) | [
"def",
"reprsig",
"(",
"fun",
",",
"name",
"=",
"None",
",",
"method",
"=",
"False",
")",
":",
"args",
",",
"varargs",
",",
"keywords",
",",
"defs",
",",
"kwargs",
"=",
"[",
"]",
",",
"[",
"]",
",",
"None",
",",
"[",
"]",
",",
"{",
"}",
"argspec",
"=",
"fun",
"if",
"callable",
"(",
"fun",
")",
":",
"name",
"=",
"fun",
".",
"__name__",
"if",
"name",
"is",
"None",
"else",
"name",
"argspec",
"=",
"getargspec",
"(",
"fun",
")",
"try",
":",
"args",
"=",
"argspec",
"[",
"0",
"]",
"varargs",
"=",
"argspec",
"[",
"1",
"]",
"keywords",
"=",
"argspec",
"[",
"2",
"]",
"defs",
"=",
"argspec",
"[",
"3",
"]",
"except",
"IndexError",
":",
"pass",
"if",
"defs",
":",
"args",
",",
"kwkeys",
"=",
"args",
"[",
":",
"-",
"len",
"(",
"defs",
")",
"]",
",",
"args",
"[",
"-",
"len",
"(",
"defs",
")",
":",
"]",
"kwargs",
"=",
"dict",
"(",
"zip",
"(",
"kwkeys",
",",
"defs",
")",
")",
"if",
"varargs",
":",
"args",
".",
"append",
"(",
"'*'",
"+",
"varargs",
")",
"if",
"method",
":",
"args",
".",
"insert",
"(",
"0",
",",
"'self'",
")",
"return",
"reprcall",
"(",
"name",
",",
"map",
"(",
"str",
",",
"args",
")",
",",
"kwargs",
",",
"keywords",
",",
"argfilter",
"=",
"str",
")"
] | 31.521739 | 15.565217 |
def WRatio(s1, s2, force_ascii=True, full_process=True):
"""
Return a measure of the sequences' similarity between 0 and 100, using different algorithms.
**Steps in the order they occur**
#. Run full_process from utils on both strings
#. Short circuit if this makes either string empty
#. Take the ratio of the two processed strings (fuzz.ratio)
#. Run checks to compare the length of the strings
* If one of the strings is more than 1.5 times as long as the other
use partial_ratio comparisons - scale partial results by 0.9
(this makes sure only full results can return 100)
* If one of the strings is over 8 times as long as the other
instead scale by 0.6
#. Run the other ratio functions
* if using partial ratio functions call partial_ratio,
partial_token_sort_ratio and partial_token_set_ratio
scale all of these by the ratio based on length
* otherwise call token_sort_ratio and token_set_ratio
* all token based comparisons are scaled by 0.95
(on top of any partial scalars)
#. Take the highest value from these results
round it and return it as an integer.
:param s1:
:param s2:
:param force_ascii: Allow only ascii characters
:type force_ascii: bool
:full_process: Process inputs, used here to avoid double processing in extract functions (Default: True)
:return:
"""
if full_process:
p1 = utils.full_process(s1, force_ascii=force_ascii)
p2 = utils.full_process(s2, force_ascii=force_ascii)
else:
p1 = s1
p2 = s2
if not utils.validate_string(p1):
return 0
if not utils.validate_string(p2):
return 0
# should we look at partials?
try_partial = True
unbase_scale = .95
partial_scale = .90
base = ratio(p1, p2)
len_ratio = float(max(len(p1), len(p2))) / min(len(p1), len(p2))
# if strings are similar length, don't use partials
if len_ratio < 1.5:
try_partial = False
# if one string is much much shorter than the other
if len_ratio > 8:
partial_scale = .6
if try_partial:
partial = partial_ratio(p1, p2) * partial_scale
ptsor = partial_token_sort_ratio(p1, p2, full_process=False) \
* unbase_scale * partial_scale
ptser = partial_token_set_ratio(p1, p2, full_process=False) \
* unbase_scale * partial_scale
return utils.intr(max(base, partial, ptsor, ptser))
else:
tsor = token_sort_ratio(p1, p2, full_process=False) * unbase_scale
tser = token_set_ratio(p1, p2, full_process=False) * unbase_scale
return utils.intr(max(base, tsor, tser)) | [
"def",
"WRatio",
"(",
"s1",
",",
"s2",
",",
"force_ascii",
"=",
"True",
",",
"full_process",
"=",
"True",
")",
":",
"if",
"full_process",
":",
"p1",
"=",
"utils",
".",
"full_process",
"(",
"s1",
",",
"force_ascii",
"=",
"force_ascii",
")",
"p2",
"=",
"utils",
".",
"full_process",
"(",
"s2",
",",
"force_ascii",
"=",
"force_ascii",
")",
"else",
":",
"p1",
"=",
"s1",
"p2",
"=",
"s2",
"if",
"not",
"utils",
".",
"validate_string",
"(",
"p1",
")",
":",
"return",
"0",
"if",
"not",
"utils",
".",
"validate_string",
"(",
"p2",
")",
":",
"return",
"0",
"# should we look at partials?",
"try_partial",
"=",
"True",
"unbase_scale",
"=",
".95",
"partial_scale",
"=",
".90",
"base",
"=",
"ratio",
"(",
"p1",
",",
"p2",
")",
"len_ratio",
"=",
"float",
"(",
"max",
"(",
"len",
"(",
"p1",
")",
",",
"len",
"(",
"p2",
")",
")",
")",
"/",
"min",
"(",
"len",
"(",
"p1",
")",
",",
"len",
"(",
"p2",
")",
")",
"# if strings are similar length, don't use partials",
"if",
"len_ratio",
"<",
"1.5",
":",
"try_partial",
"=",
"False",
"# if one string is much much shorter than the other",
"if",
"len_ratio",
">",
"8",
":",
"partial_scale",
"=",
".6",
"if",
"try_partial",
":",
"partial",
"=",
"partial_ratio",
"(",
"p1",
",",
"p2",
")",
"*",
"partial_scale",
"ptsor",
"=",
"partial_token_sort_ratio",
"(",
"p1",
",",
"p2",
",",
"full_process",
"=",
"False",
")",
"*",
"unbase_scale",
"*",
"partial_scale",
"ptser",
"=",
"partial_token_set_ratio",
"(",
"p1",
",",
"p2",
",",
"full_process",
"=",
"False",
")",
"*",
"unbase_scale",
"*",
"partial_scale",
"return",
"utils",
".",
"intr",
"(",
"max",
"(",
"base",
",",
"partial",
",",
"ptsor",
",",
"ptser",
")",
")",
"else",
":",
"tsor",
"=",
"token_sort_ratio",
"(",
"p1",
",",
"p2",
",",
"full_process",
"=",
"False",
")",
"*",
"unbase_scale",
"tser",
"=",
"token_set_ratio",
"(",
"p1",
",",
"p2",
",",
"full_process",
"=",
"False",
")",
"*",
"unbase_scale",
"return",
"utils",
".",
"intr",
"(",
"max",
"(",
"base",
",",
"tsor",
",",
"tser",
")",
")"
] | 35.052632 | 22.657895 |
def encode(self, value):
"""encode(value) -> bytearray
Encodes the given value to a bytearray according to this
Complex Type definition.
"""
e = self.evrs.get(value, None)
if not e:
log.error(str(value) + " not found as EVR. Cannot encode.")
return None
else:
return super(EVRType, self).encode(e.code) | [
"def",
"encode",
"(",
"self",
",",
"value",
")",
":",
"e",
"=",
"self",
".",
"evrs",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"not",
"e",
":",
"log",
".",
"error",
"(",
"str",
"(",
"value",
")",
"+",
"\" not found as EVR. Cannot encode.\"",
")",
"return",
"None",
"else",
":",
"return",
"super",
"(",
"EVRType",
",",
"self",
")",
".",
"encode",
"(",
"e",
".",
"code",
")"
] | 32 | 16.833333 |
def service_checks(self, name):
"""
Return the service checks received under the given name
"""
return [
ServiceCheckStub(
ensure_unicode(stub.check_id),
ensure_unicode(stub.name),
stub.status,
normalize_tags(stub.tags),
ensure_unicode(stub.hostname),
ensure_unicode(stub.message),
)
for stub in self._service_checks.get(to_string(name), [])
] | [
"def",
"service_checks",
"(",
"self",
",",
"name",
")",
":",
"return",
"[",
"ServiceCheckStub",
"(",
"ensure_unicode",
"(",
"stub",
".",
"check_id",
")",
",",
"ensure_unicode",
"(",
"stub",
".",
"name",
")",
",",
"stub",
".",
"status",
",",
"normalize_tags",
"(",
"stub",
".",
"tags",
")",
",",
"ensure_unicode",
"(",
"stub",
".",
"hostname",
")",
",",
"ensure_unicode",
"(",
"stub",
".",
"message",
")",
",",
")",
"for",
"stub",
"in",
"self",
".",
"_service_checks",
".",
"get",
"(",
"to_string",
"(",
"name",
")",
",",
"[",
"]",
")",
"]"
] | 33.4 | 12.466667 |
def find_isolated_tile_indices(hand_34):
"""
Tiles that don't have -1, 0 and +1 neighbors
:param hand_34: array of tiles in 34 tile format
:return: array of isolated tiles indices
"""
isolated_indices = []
for x in range(0, CHUN + 1):
# for honor tiles we don't need to check nearby tiles
if is_honor(x) and hand_34[x] == 0:
isolated_indices.append(x)
else:
simplified = simplify(x)
# 1 suit tile
if simplified == 0:
if hand_34[x] == 0 and hand_34[x + 1] == 0:
isolated_indices.append(x)
# 9 suit tile
elif simplified == 8:
if hand_34[x] == 0 and hand_34[x - 1] == 0:
isolated_indices.append(x)
# 2-8 tiles tiles
else:
if hand_34[x] == 0 and hand_34[x - 1] == 0 and hand_34[x + 1] == 0:
isolated_indices.append(x)
return isolated_indices | [
"def",
"find_isolated_tile_indices",
"(",
"hand_34",
")",
":",
"isolated_indices",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"CHUN",
"+",
"1",
")",
":",
"# for honor tiles we don't need to check nearby tiles",
"if",
"is_honor",
"(",
"x",
")",
"and",
"hand_34",
"[",
"x",
"]",
"==",
"0",
":",
"isolated_indices",
".",
"append",
"(",
"x",
")",
"else",
":",
"simplified",
"=",
"simplify",
"(",
"x",
")",
"# 1 suit tile",
"if",
"simplified",
"==",
"0",
":",
"if",
"hand_34",
"[",
"x",
"]",
"==",
"0",
"and",
"hand_34",
"[",
"x",
"+",
"1",
"]",
"==",
"0",
":",
"isolated_indices",
".",
"append",
"(",
"x",
")",
"# 9 suit tile",
"elif",
"simplified",
"==",
"8",
":",
"if",
"hand_34",
"[",
"x",
"]",
"==",
"0",
"and",
"hand_34",
"[",
"x",
"-",
"1",
"]",
"==",
"0",
":",
"isolated_indices",
".",
"append",
"(",
"x",
")",
"# 2-8 tiles tiles",
"else",
":",
"if",
"hand_34",
"[",
"x",
"]",
"==",
"0",
"and",
"hand_34",
"[",
"x",
"-",
"1",
"]",
"==",
"0",
"and",
"hand_34",
"[",
"x",
"+",
"1",
"]",
"==",
"0",
":",
"isolated_indices",
".",
"append",
"(",
"x",
")",
"return",
"isolated_indices"
] | 33.517241 | 14.344828 |
def zero(self):
"""Return a tensor of all zeros.
Examples
--------
>>> space = odl.rn(3)
>>> x = space.zero()
>>> x
rn(3).element([ 0., 0., 0.])
"""
return self.element(np.zeros(self.shape, dtype=self.dtype,
order=self.default_order)) | [
"def",
"zero",
"(",
"self",
")",
":",
"return",
"self",
".",
"element",
"(",
"np",
".",
"zeros",
"(",
"self",
".",
"shape",
",",
"dtype",
"=",
"self",
".",
"dtype",
",",
"order",
"=",
"self",
".",
"default_order",
")",
")"
] | 27.916667 | 17.833333 |
def create_logout_request(self, destination, issuer_entity_id,
subject_id=None, name_id=None,
reason=None, expire=None, message_id=0,
consent=None, extensions=None, sign=False,
session_indexes=None, sign_alg=None,
digest_alg=None):
""" Constructs a LogoutRequest
:param destination: Destination of the request
:param issuer_entity_id: The entity ID of the IdP the request is
target at.
:param subject_id: The identifier of the subject
:param name_id: A NameID instance identifying the subject
:param reason: An indication of the reason for the logout, in the
form of a URI reference.
:param expire: The time at which the request expires,
after which the recipient may discard the message.
:param message_id: Request identifier
:param consent: Whether the principal have given her consent
:param extensions: Possible extensions
:param sign: Whether the query should be signed or not.
:param session_indexes: SessionIndex instances or just values
:return: A LogoutRequest instance
"""
if subject_id:
if self.entity_type == "idp":
name_id = NameID(text=self.users.get_entityid(subject_id,
issuer_entity_id,
False))
else:
name_id = NameID(text=subject_id)
if not name_id:
raise SAMLError("Missing subject identification")
args = {}
if session_indexes:
sis = []
for si in session_indexes:
if isinstance(si, SessionIndex):
sis.append(si)
else:
sis.append(SessionIndex(text=si))
args["session_index"] = sis
return self._message(LogoutRequest, destination, message_id,
consent, extensions, sign, name_id=name_id,
reason=reason, not_on_or_after=expire,
issuer=self._issuer(), sign_alg=sign_alg,
digest_alg=digest_alg, **args) | [
"def",
"create_logout_request",
"(",
"self",
",",
"destination",
",",
"issuer_entity_id",
",",
"subject_id",
"=",
"None",
",",
"name_id",
"=",
"None",
",",
"reason",
"=",
"None",
",",
"expire",
"=",
"None",
",",
"message_id",
"=",
"0",
",",
"consent",
"=",
"None",
",",
"extensions",
"=",
"None",
",",
"sign",
"=",
"False",
",",
"session_indexes",
"=",
"None",
",",
"sign_alg",
"=",
"None",
",",
"digest_alg",
"=",
"None",
")",
":",
"if",
"subject_id",
":",
"if",
"self",
".",
"entity_type",
"==",
"\"idp\"",
":",
"name_id",
"=",
"NameID",
"(",
"text",
"=",
"self",
".",
"users",
".",
"get_entityid",
"(",
"subject_id",
",",
"issuer_entity_id",
",",
"False",
")",
")",
"else",
":",
"name_id",
"=",
"NameID",
"(",
"text",
"=",
"subject_id",
")",
"if",
"not",
"name_id",
":",
"raise",
"SAMLError",
"(",
"\"Missing subject identification\"",
")",
"args",
"=",
"{",
"}",
"if",
"session_indexes",
":",
"sis",
"=",
"[",
"]",
"for",
"si",
"in",
"session_indexes",
":",
"if",
"isinstance",
"(",
"si",
",",
"SessionIndex",
")",
":",
"sis",
".",
"append",
"(",
"si",
")",
"else",
":",
"sis",
".",
"append",
"(",
"SessionIndex",
"(",
"text",
"=",
"si",
")",
")",
"args",
"[",
"\"session_index\"",
"]",
"=",
"sis",
"return",
"self",
".",
"_message",
"(",
"LogoutRequest",
",",
"destination",
",",
"message_id",
",",
"consent",
",",
"extensions",
",",
"sign",
",",
"name_id",
"=",
"name_id",
",",
"reason",
"=",
"reason",
",",
"not_on_or_after",
"=",
"expire",
",",
"issuer",
"=",
"self",
".",
"_issuer",
"(",
")",
",",
"sign_alg",
"=",
"sign_alg",
",",
"digest_alg",
"=",
"digest_alg",
",",
"*",
"*",
"args",
")"
] | 45.588235 | 20.470588 |
def functions_factory(cls, coef, degree, knots, ext, **kwargs):
"""
Given some coefficients, return a B-spline.
"""
return cls._basis_spline_factory(coef, degree, knots, 0, ext) | [
"def",
"functions_factory",
"(",
"cls",
",",
"coef",
",",
"degree",
",",
"knots",
",",
"ext",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"_basis_spline_factory",
"(",
"coef",
",",
"degree",
",",
"knots",
",",
"0",
",",
"ext",
")"
] | 34.166667 | 17.166667 |
def scatter_plot(data, index_x, index_y, percent=100.0, seed=1, size=50, title=None, outfile=None, wait=True):
"""
Plots two attributes against each other.
TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html
:param data: the dataset
:type data: Instances
:param index_x: the 0-based index of the attribute on the x axis
:type index_x: int
:param index_y: the 0-based index of the attribute on the y axis
:type index_y: int
:param percent: the percentage of the dataset to use for plotting
:type percent: float
:param seed: the seed value to use for subsampling
:type seed: int
:param size: the size of the circles in point
:type size: int
:param title: an optional title
:type title: str
:param outfile: the (optional) file to save the generated plot to. The extension determines the file format.
:type outfile: str
:param wait: whether to wait for the user to close the plot
:type wait: bool
"""
if not plot.matplotlib_available:
logger.error("Matplotlib is not installed, plotting unavailable!")
return
# create subsample
data = plot.create_subsample(data, percent=percent, seed=seed)
# collect data
x = []
y = []
if data.class_index == -1:
c = None
else:
c = []
for i in range(data.num_instances):
inst = data.get_instance(i)
x.append(inst.get_value(index_x))
y.append(inst.get_value(index_y))
if c is not None:
c.append(inst.get_value(inst.class_index))
# plot data
fig, ax = plt.subplots()
if c is None:
ax.scatter(x, y, s=size, alpha=0.5)
else:
ax.scatter(x, y, c=c, s=size, alpha=0.5)
ax.set_xlabel(data.attribute(index_x).name)
ax.set_ylabel(data.attribute(index_y).name)
if title is None:
title = "Attribute scatter plot"
if percent != 100:
title += " (%0.1f%%)" % percent
ax.set_title(title)
ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c="0.3")
ax.grid(True)
fig.canvas.set_window_title(data.relationname)
plt.draw()
if outfile is not None:
plt.savefig(outfile)
if wait:
plt.show() | [
"def",
"scatter_plot",
"(",
"data",
",",
"index_x",
",",
"index_y",
",",
"percent",
"=",
"100.0",
",",
"seed",
"=",
"1",
",",
"size",
"=",
"50",
",",
"title",
"=",
"None",
",",
"outfile",
"=",
"None",
",",
"wait",
"=",
"True",
")",
":",
"if",
"not",
"plot",
".",
"matplotlib_available",
":",
"logger",
".",
"error",
"(",
"\"Matplotlib is not installed, plotting unavailable!\"",
")",
"return",
"# create subsample",
"data",
"=",
"plot",
".",
"create_subsample",
"(",
"data",
",",
"percent",
"=",
"percent",
",",
"seed",
"=",
"seed",
")",
"# collect data",
"x",
"=",
"[",
"]",
"y",
"=",
"[",
"]",
"if",
"data",
".",
"class_index",
"==",
"-",
"1",
":",
"c",
"=",
"None",
"else",
":",
"c",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"data",
".",
"num_instances",
")",
":",
"inst",
"=",
"data",
".",
"get_instance",
"(",
"i",
")",
"x",
".",
"append",
"(",
"inst",
".",
"get_value",
"(",
"index_x",
")",
")",
"y",
".",
"append",
"(",
"inst",
".",
"get_value",
"(",
"index_y",
")",
")",
"if",
"c",
"is",
"not",
"None",
":",
"c",
".",
"append",
"(",
"inst",
".",
"get_value",
"(",
"inst",
".",
"class_index",
")",
")",
"# plot data",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
")",
"if",
"c",
"is",
"None",
":",
"ax",
".",
"scatter",
"(",
"x",
",",
"y",
",",
"s",
"=",
"size",
",",
"alpha",
"=",
"0.5",
")",
"else",
":",
"ax",
".",
"scatter",
"(",
"x",
",",
"y",
",",
"c",
"=",
"c",
",",
"s",
"=",
"size",
",",
"alpha",
"=",
"0.5",
")",
"ax",
".",
"set_xlabel",
"(",
"data",
".",
"attribute",
"(",
"index_x",
")",
".",
"name",
")",
"ax",
".",
"set_ylabel",
"(",
"data",
".",
"attribute",
"(",
"index_y",
")",
".",
"name",
")",
"if",
"title",
"is",
"None",
":",
"title",
"=",
"\"Attribute scatter plot\"",
"if",
"percent",
"!=",
"100",
":",
"title",
"+=",
"\" (%0.1f%%)\"",
"%",
"percent",
"ax",
".",
"set_title",
"(",
"title",
")",
"ax",
".",
"plot",
"(",
"ax",
".",
"get_xlim",
"(",
")",
",",
"ax",
".",
"get_ylim",
"(",
")",
",",
"ls",
"=",
"\"--\"",
",",
"c",
"=",
"\"0.3\"",
")",
"ax",
".",
"grid",
"(",
"True",
")",
"fig",
".",
"canvas",
".",
"set_window_title",
"(",
"data",
".",
"relationname",
")",
"plt",
".",
"draw",
"(",
")",
"if",
"outfile",
"is",
"not",
"None",
":",
"plt",
".",
"savefig",
"(",
"outfile",
")",
"if",
"wait",
":",
"plt",
".",
"show",
"(",
")"
] | 32.537313 | 20.089552 |
def new(self, bootstrap_with=None, use_timer=False, with_proof=False):
"""
Actual constructor of the solver.
"""
if not self.maplesat:
self.maplesat = pysolvers.maplesat_new()
if bootstrap_with:
for clause in bootstrap_with:
self.add_clause(clause)
self.use_timer = use_timer
self.call_time = 0.0 # time spent for the last call to oracle
self.accu_time = 0.0 # time accumulated for all calls to oracle
if with_proof:
self.prfile = tempfile.TemporaryFile()
pysolvers.maplesat_tracepr(self.maplesat, self.prfile) | [
"def",
"new",
"(",
"self",
",",
"bootstrap_with",
"=",
"None",
",",
"use_timer",
"=",
"False",
",",
"with_proof",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"maplesat",
":",
"self",
".",
"maplesat",
"=",
"pysolvers",
".",
"maplesat_new",
"(",
")",
"if",
"bootstrap_with",
":",
"for",
"clause",
"in",
"bootstrap_with",
":",
"self",
".",
"add_clause",
"(",
"clause",
")",
"self",
".",
"use_timer",
"=",
"use_timer",
"self",
".",
"call_time",
"=",
"0.0",
"# time spent for the last call to oracle",
"self",
".",
"accu_time",
"=",
"0.0",
"# time accumulated for all calls to oracle",
"if",
"with_proof",
":",
"self",
".",
"prfile",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
")",
"pysolvers",
".",
"maplesat_tracepr",
"(",
"self",
".",
"maplesat",
",",
"self",
".",
"prfile",
")"
] | 35.473684 | 19.263158 |
def set_inlets(self, pores=None, clusters=None):
r"""
Parameters
----------
pores : array_like
The list of inlet pores from which the Phase can enter the Network
clusters : list of lists - can be just one list but each list defines
a cluster of pores that share a common invasion pressure.
Like Basic Invasion Percolation a queue of
"""
if pores is not None:
logger.info("Setting inlet pores at shared pressure")
clusters = []
clusters.append(pores)
elif clusters is not None:
logger.info("Setting inlet clusters at individual pressures")
else:
logger.error("Either 'inlets' or 'clusters' must be passed to" +
" setup method")
self.queue = []
for i, cluster in enumerate(clusters):
self.queue.append([])
# Perform initial analysis on input pores
self['pore.invasion_sequence'][cluster] = 0
self['pore.cluster'][cluster] = i
self['pore.invasion_pressure'][cluster] = -np.inf
if np.size(cluster) > 1:
for elem_id in cluster:
self._add_ts2q(elem_id, self.queue[i])
elif np.size(cluster) == 1:
self._add_ts2q(cluster, self.queue[i])
else:
logger.warning("Some inlet clusters have no pores")
if self.settings['snap_off']:
self._apply_snap_off() | [
"def",
"set_inlets",
"(",
"self",
",",
"pores",
"=",
"None",
",",
"clusters",
"=",
"None",
")",
":",
"if",
"pores",
"is",
"not",
"None",
":",
"logger",
".",
"info",
"(",
"\"Setting inlet pores at shared pressure\"",
")",
"clusters",
"=",
"[",
"]",
"clusters",
".",
"append",
"(",
"pores",
")",
"elif",
"clusters",
"is",
"not",
"None",
":",
"logger",
".",
"info",
"(",
"\"Setting inlet clusters at individual pressures\"",
")",
"else",
":",
"logger",
".",
"error",
"(",
"\"Either 'inlets' or 'clusters' must be passed to\"",
"+",
"\" setup method\"",
")",
"self",
".",
"queue",
"=",
"[",
"]",
"for",
"i",
",",
"cluster",
"in",
"enumerate",
"(",
"clusters",
")",
":",
"self",
".",
"queue",
".",
"append",
"(",
"[",
"]",
")",
"# Perform initial analysis on input pores",
"self",
"[",
"'pore.invasion_sequence'",
"]",
"[",
"cluster",
"]",
"=",
"0",
"self",
"[",
"'pore.cluster'",
"]",
"[",
"cluster",
"]",
"=",
"i",
"self",
"[",
"'pore.invasion_pressure'",
"]",
"[",
"cluster",
"]",
"=",
"-",
"np",
".",
"inf",
"if",
"np",
".",
"size",
"(",
"cluster",
")",
">",
"1",
":",
"for",
"elem_id",
"in",
"cluster",
":",
"self",
".",
"_add_ts2q",
"(",
"elem_id",
",",
"self",
".",
"queue",
"[",
"i",
"]",
")",
"elif",
"np",
".",
"size",
"(",
"cluster",
")",
"==",
"1",
":",
"self",
".",
"_add_ts2q",
"(",
"cluster",
",",
"self",
".",
"queue",
"[",
"i",
"]",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"\"Some inlet clusters have no pores\"",
")",
"if",
"self",
".",
"settings",
"[",
"'snap_off'",
"]",
":",
"self",
".",
"_apply_snap_off",
"(",
")"
] | 39.315789 | 16.868421 |
def nvmlUnitGetUnitInfo(unit):
r"""
/**
* Retrieves the static information associated with a unit.
*
* For S-class products.
*
* See \ref nvmlUnitInfo_t for details on available unit info.
*
* @param unit The identifier of the target unit
* @param info Reference in which to return the unit information
*
* @return
* - \ref NVML_SUCCESS if \a info has been populated
* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized
* - \ref NVML_ERROR_INVALID_ARGUMENT if \a unit is invalid or \a info is NULL
*/
nvmlReturn_t DECLDIR nvmlUnitGetUnitInfo
"""
"""
/**
* Retrieves the static information associated with a unit.
*
* For S-class products.
*
* See \ref nvmlUnitInfo_t for details on available unit info.
*
* @param unit The identifier of the target unit
* @param info Reference in which to return the unit information
*
* @return
* - \ref NVML_SUCCESS if \a info has been populated
* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized
* - \ref NVML_ERROR_INVALID_ARGUMENT if \a unit is invalid or \a info is NULL
*/
"""
c_info = c_nvmlUnitInfo_t()
fn = _nvmlGetFunctionPointer("nvmlUnitGetUnitInfo")
ret = fn(unit, byref(c_info))
_nvmlCheckReturn(ret)
return bytes_to_str(c_info) | [
"def",
"nvmlUnitGetUnitInfo",
"(",
"unit",
")",
":",
"\"\"\"\n/**\n * Retrieves the static information associated with a unit.\n *\n * For S-class products.\n *\n * See \\ref nvmlUnitInfo_t for details on available unit info.\n *\n * @param unit The identifier of the target unit\n * @param info Reference in which to return the unit information\n *\n * @return\n * - \\ref NVML_SUCCESS if \\a info has been populated\n * - \\ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized\n * - \\ref NVML_ERROR_INVALID_ARGUMENT if \\a unit is invalid or \\a info is NULL\n */\n \"\"\"",
"c_info",
"=",
"c_nvmlUnitInfo_t",
"(",
")",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlUnitGetUnitInfo\"",
")",
"ret",
"=",
"fn",
"(",
"unit",
",",
"byref",
"(",
"c_info",
")",
")",
"_nvmlCheckReturn",
"(",
"ret",
")",
"return",
"bytes_to_str",
"(",
"c_info",
")"
] | 37.853659 | 28.463415 |
def contains_any(self, other):
"""Check if any flags are set.
(OsuMod.Hidden | OsuMod.HardRock) in flags # Check if either hidden or hardrock are enabled.
OsuMod.keyMod in flags # Check if any keymod is enabled.
"""
return self.value == other.value or self.value & other.value | [
"def",
"contains_any",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"value",
"==",
"other",
".",
"value",
"or",
"self",
".",
"value",
"&",
"other",
".",
"value"
] | 44.428571 | 23.142857 |
def pop_fw_local(self, tenant_id, net_id, direc, node_ip):
"""Populate the local cache.
Read the Network DB and populate the local cache.
Read the subnet from the Subnet DB, given the net_id and populate the
cache.
"""
net = self.get_network(net_id)
serv_obj = self.get_service_obj(tenant_id)
serv_obj.update_fw_local_cache(net_id, direc, node_ip)
if net is not None:
net_dict = self.fill_dcnm_net_info(tenant_id, direc, net.vlan,
net.segmentation_id)
serv_obj.store_dcnm_net_dict(net_dict, direc)
if direc == "in":
subnet = self.service_in_ip.get_subnet_by_netid(net_id)
else:
subnet = self.service_out_ip.get_subnet_by_netid(net_id)
if subnet is not None:
subnet_dict = self.fill_dcnm_subnet_info(
tenant_id, subnet,
self.get_start_ip(subnet), self.get_end_ip(subnet),
self.get_gateway(subnet), self.get_secondary_gateway(subnet),
direc)
serv_obj.store_dcnm_subnet_dict(subnet_dict, direc) | [
"def",
"pop_fw_local",
"(",
"self",
",",
"tenant_id",
",",
"net_id",
",",
"direc",
",",
"node_ip",
")",
":",
"net",
"=",
"self",
".",
"get_network",
"(",
"net_id",
")",
"serv_obj",
"=",
"self",
".",
"get_service_obj",
"(",
"tenant_id",
")",
"serv_obj",
".",
"update_fw_local_cache",
"(",
"net_id",
",",
"direc",
",",
"node_ip",
")",
"if",
"net",
"is",
"not",
"None",
":",
"net_dict",
"=",
"self",
".",
"fill_dcnm_net_info",
"(",
"tenant_id",
",",
"direc",
",",
"net",
".",
"vlan",
",",
"net",
".",
"segmentation_id",
")",
"serv_obj",
".",
"store_dcnm_net_dict",
"(",
"net_dict",
",",
"direc",
")",
"if",
"direc",
"==",
"\"in\"",
":",
"subnet",
"=",
"self",
".",
"service_in_ip",
".",
"get_subnet_by_netid",
"(",
"net_id",
")",
"else",
":",
"subnet",
"=",
"self",
".",
"service_out_ip",
".",
"get_subnet_by_netid",
"(",
"net_id",
")",
"if",
"subnet",
"is",
"not",
"None",
":",
"subnet_dict",
"=",
"self",
".",
"fill_dcnm_subnet_info",
"(",
"tenant_id",
",",
"subnet",
",",
"self",
".",
"get_start_ip",
"(",
"subnet",
")",
",",
"self",
".",
"get_end_ip",
"(",
"subnet",
")",
",",
"self",
".",
"get_gateway",
"(",
"subnet",
")",
",",
"self",
".",
"get_secondary_gateway",
"(",
"subnet",
")",
",",
"direc",
")",
"serv_obj",
".",
"store_dcnm_subnet_dict",
"(",
"subnet_dict",
",",
"direc",
")"
] | 45.88 | 19.76 |
def _inspect_class(cls, subclass):
"""
Args:
cls(:py:class:`Plugin`): Parent class
subclass(:py:class:`Plugin`): Subclass to evaluate
Returns:
Result: Named tuple
Inspect subclass for inclusion
Values for errorcode:
* 0: No error
Error codes between 0 and 100 are not intended for import
* 50 Skipload flag is True
Error codes between 99 and 200 are excluded from import
* 156: Skipload call returned True
Error codes 200 and above are malformed classes
* 210: Missing abstract property
* 211: Missing abstract static method
* 212: Missing abstract class method
* 213: Missing abstract method
* 214: Missing abstract attribute
* 220: Argument spec does not match
"""
if callable(subclass._skipload_):
result = subclass._skipload_()
if isinstance(result, tuple):
skip, msg = result
else:
skip, msg = result, None
if skip:
return Result(False, msg, 156)
elif subclass._skipload_:
return Result(False, 'Skipload flag is True', 50)
return _check_methods(cls, subclass) | [
"def",
"_inspect_class",
"(",
"cls",
",",
"subclass",
")",
":",
"if",
"callable",
"(",
"subclass",
".",
"_skipload_",
")",
":",
"result",
"=",
"subclass",
".",
"_skipload_",
"(",
")",
"if",
"isinstance",
"(",
"result",
",",
"tuple",
")",
":",
"skip",
",",
"msg",
"=",
"result",
"else",
":",
"skip",
",",
"msg",
"=",
"result",
",",
"None",
"if",
"skip",
":",
"return",
"Result",
"(",
"False",
",",
"msg",
",",
"156",
")",
"elif",
"subclass",
".",
"_skipload_",
":",
"return",
"Result",
"(",
"False",
",",
"'Skipload flag is True'",
",",
"50",
")",
"return",
"_check_methods",
"(",
"cls",
",",
"subclass",
")"
] | 23.755102 | 19.795918 |
def _virtual_hv(osdata):
'''
Returns detailed hypervisor information from sysfs
Currently this seems to be used only by Xen
'''
grains = {}
# Bail early if we're not running on Xen
try:
if 'xen' not in osdata['virtual']:
return grains
except KeyError:
return grains
# Try to get the exact hypervisor version from sysfs
try:
version = {}
for fn in ('major', 'minor', 'extra'):
with salt.utils.files.fopen('/sys/hypervisor/version/{}'.format(fn), 'r') as fhr:
version[fn] = salt.utils.stringutils.to_unicode(fhr.read().strip())
grains['virtual_hv_version'] = '{}.{}{}'.format(version['major'], version['minor'], version['extra'])
grains['virtual_hv_version_info'] = [version['major'], version['minor'], version['extra']]
except (IOError, OSError, KeyError):
pass
# Try to read and decode the supported feature set of the hypervisor
# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py
# Table data from include/xen/interface/features.h
xen_feature_table = {0: 'writable_page_tables',
1: 'writable_descriptor_tables',
2: 'auto_translated_physmap',
3: 'supervisor_mode_kernel',
4: 'pae_pgdir_above_4gb',
5: 'mmu_pt_update_preserve_ad',
7: 'gnttab_map_avail_bits',
8: 'hvm_callback_vector',
9: 'hvm_safe_pvclock',
10: 'hvm_pirqs',
11: 'dom0',
12: 'grant_map_identity',
13: 'memory_op_vnode_supported',
14: 'ARM_SMCCC_supported'}
try:
with salt.utils.files.fopen('/sys/hypervisor/properties/features', 'r') as fhr:
features = salt.utils.stringutils.to_unicode(fhr.read().strip())
enabled_features = []
for bit, feat in six.iteritems(xen_feature_table):
if int(features, 16) & (1 << bit):
enabled_features.append(feat)
grains['virtual_hv_features'] = features
grains['virtual_hv_features_list'] = enabled_features
except (IOError, OSError, KeyError):
pass
return grains | [
"def",
"_virtual_hv",
"(",
"osdata",
")",
":",
"grains",
"=",
"{",
"}",
"# Bail early if we're not running on Xen",
"try",
":",
"if",
"'xen'",
"not",
"in",
"osdata",
"[",
"'virtual'",
"]",
":",
"return",
"grains",
"except",
"KeyError",
":",
"return",
"grains",
"# Try to get the exact hypervisor version from sysfs",
"try",
":",
"version",
"=",
"{",
"}",
"for",
"fn",
"in",
"(",
"'major'",
",",
"'minor'",
",",
"'extra'",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/sys/hypervisor/version/{}'",
".",
"format",
"(",
"fn",
")",
",",
"'r'",
")",
"as",
"fhr",
":",
"version",
"[",
"fn",
"]",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"fhr",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
")",
"grains",
"[",
"'virtual_hv_version'",
"]",
"=",
"'{}.{}{}'",
".",
"format",
"(",
"version",
"[",
"'major'",
"]",
",",
"version",
"[",
"'minor'",
"]",
",",
"version",
"[",
"'extra'",
"]",
")",
"grains",
"[",
"'virtual_hv_version_info'",
"]",
"=",
"[",
"version",
"[",
"'major'",
"]",
",",
"version",
"[",
"'minor'",
"]",
",",
"version",
"[",
"'extra'",
"]",
"]",
"except",
"(",
"IOError",
",",
"OSError",
",",
"KeyError",
")",
":",
"pass",
"# Try to read and decode the supported feature set of the hypervisor",
"# Based on https://github.com/brendangregg/Misc/blob/master/xen/xen-features.py",
"# Table data from include/xen/interface/features.h",
"xen_feature_table",
"=",
"{",
"0",
":",
"'writable_page_tables'",
",",
"1",
":",
"'writable_descriptor_tables'",
",",
"2",
":",
"'auto_translated_physmap'",
",",
"3",
":",
"'supervisor_mode_kernel'",
",",
"4",
":",
"'pae_pgdir_above_4gb'",
",",
"5",
":",
"'mmu_pt_update_preserve_ad'",
",",
"7",
":",
"'gnttab_map_avail_bits'",
",",
"8",
":",
"'hvm_callback_vector'",
",",
"9",
":",
"'hvm_safe_pvclock'",
",",
"10",
":",
"'hvm_pirqs'",
",",
"11",
":",
"'dom0'",
",",
"12",
":",
"'grant_map_identity'",
",",
"13",
":",
"'memory_op_vnode_supported'",
",",
"14",
":",
"'ARM_SMCCC_supported'",
"}",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/sys/hypervisor/properties/features'",
",",
"'r'",
")",
"as",
"fhr",
":",
"features",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"fhr",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
")",
"enabled_features",
"=",
"[",
"]",
"for",
"bit",
",",
"feat",
"in",
"six",
".",
"iteritems",
"(",
"xen_feature_table",
")",
":",
"if",
"int",
"(",
"features",
",",
"16",
")",
"&",
"(",
"1",
"<<",
"bit",
")",
":",
"enabled_features",
".",
"append",
"(",
"feat",
")",
"grains",
"[",
"'virtual_hv_features'",
"]",
"=",
"features",
"grains",
"[",
"'virtual_hv_features_list'",
"]",
"=",
"enabled_features",
"except",
"(",
"IOError",
",",
"OSError",
",",
"KeyError",
")",
":",
"pass",
"return",
"grains"
] | 42.090909 | 21.436364 |
def _create_header(self):
"""
Function to create the GroupHeader (GrpHdr) in the
CstmrCdtTrfInitn Node
"""
# Retrieve the node to which we will append the group header.
CstmrCdtTrfInitn_node = self._xml.find('CstmrCdtTrfInitn')
# Create the header nodes.
GrpHdr_node = ET.Element("GrpHdr")
MsgId_node = ET.Element("MsgId")
CreDtTm_node = ET.Element("CreDtTm")
NbOfTxs_node = ET.Element("NbOfTxs")
CtrlSum_node = ET.Element("CtrlSum")
InitgPty_node = ET.Element("InitgPty")
Nm_node = ET.Element("Nm")
# Add data to some header nodes.
MsgId_node.text = self.msg_id
CreDtTm_node.text = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
Nm_node.text = self._config['name']
# Append the nodes
InitgPty_node.append(Nm_node)
GrpHdr_node.append(MsgId_node)
GrpHdr_node.append(CreDtTm_node)
GrpHdr_node.append(NbOfTxs_node)
GrpHdr_node.append(CtrlSum_node)
GrpHdr_node.append(InitgPty_node)
# Append the header to its parent
CstmrCdtTrfInitn_node.append(GrpHdr_node) | [
"def",
"_create_header",
"(",
"self",
")",
":",
"# Retrieve the node to which we will append the group header.",
"CstmrCdtTrfInitn_node",
"=",
"self",
".",
"_xml",
".",
"find",
"(",
"'CstmrCdtTrfInitn'",
")",
"# Create the header nodes.",
"GrpHdr_node",
"=",
"ET",
".",
"Element",
"(",
"\"GrpHdr\"",
")",
"MsgId_node",
"=",
"ET",
".",
"Element",
"(",
"\"MsgId\"",
")",
"CreDtTm_node",
"=",
"ET",
".",
"Element",
"(",
"\"CreDtTm\"",
")",
"NbOfTxs_node",
"=",
"ET",
".",
"Element",
"(",
"\"NbOfTxs\"",
")",
"CtrlSum_node",
"=",
"ET",
".",
"Element",
"(",
"\"CtrlSum\"",
")",
"InitgPty_node",
"=",
"ET",
".",
"Element",
"(",
"\"InitgPty\"",
")",
"Nm_node",
"=",
"ET",
".",
"Element",
"(",
"\"Nm\"",
")",
"# Add data to some header nodes.",
"MsgId_node",
".",
"text",
"=",
"self",
".",
"msg_id",
"CreDtTm_node",
".",
"text",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%S'",
")",
"Nm_node",
".",
"text",
"=",
"self",
".",
"_config",
"[",
"'name'",
"]",
"# Append the nodes",
"InitgPty_node",
".",
"append",
"(",
"Nm_node",
")",
"GrpHdr_node",
".",
"append",
"(",
"MsgId_node",
")",
"GrpHdr_node",
".",
"append",
"(",
"CreDtTm_node",
")",
"GrpHdr_node",
".",
"append",
"(",
"NbOfTxs_node",
")",
"GrpHdr_node",
".",
"append",
"(",
"CtrlSum_node",
")",
"GrpHdr_node",
".",
"append",
"(",
"InitgPty_node",
")",
"# Append the header to its parent",
"CstmrCdtTrfInitn_node",
".",
"append",
"(",
"GrpHdr_node",
")"
] | 35.9375 | 11.5 |
def decode_filter(text, encoding='utf-8'):
"""
decode a binary object to str and filter out non-printable characters
Parameters
----------
text: bytes
the binary object to be decoded
encoding: str
the encoding to be used
Returns
-------
str
the decoded and filtered string
"""
if text is not None:
text = text.decode(encoding, errors='ignore')
printable = set(string.printable)
text = filter(lambda x: x in printable, text)
return ''.join(list(text))
else:
return None | [
"def",
"decode_filter",
"(",
"text",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"text",
"is",
"not",
"None",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"encoding",
",",
"errors",
"=",
"'ignore'",
")",
"printable",
"=",
"set",
"(",
"string",
".",
"printable",
")",
"text",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
"in",
"printable",
",",
"text",
")",
"return",
"''",
".",
"join",
"(",
"list",
"(",
"text",
")",
")",
"else",
":",
"return",
"None"
] | 24.521739 | 18 |
def reset(self):
"""Reset metric counter."""
self._positions = []
self._line = 1
self._curr = None # current scope we are analyzing
self._scope = 0
self.language = None | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_positions",
"=",
"[",
"]",
"self",
".",
"_line",
"=",
"1",
"self",
".",
"_curr",
"=",
"None",
"# current scope we are analyzing",
"self",
".",
"_scope",
"=",
"0",
"self",
".",
"language",
"=",
"None"
] | 30.142857 | 14.571429 |
def tokenize(self, docs):
"""
The first pass consists of converting documents
into "transactions" (sets of their tokens)
and the initial frequency/support filtering.
Then iterate until we close in on a final set.
`docs` can be any iterator or generator so long as it yields lists.
Each list represents a document (i.e. is a list of tokens).
For example, it can be a list of lists of nouns and noun phrases if trying
to identify aspects, where each list represents a sentence or document.
`min_sup` defines the minimum frequency (as a ratio over the total) necessary to
keep a candidate.
"""
if self.min_sup < 1/len(docs):
raise Exception('`min_sup` must be greater than or equal to `1/len(docs)`.')
# First pass
candidates = set()
transactions = []
# Use nouns and noun phrases.
for doc in POSTokenizer().tokenize(docs):
transaction = set(doc)
candidates = candidates.union({(t,) for t in transaction})
transactions.append(transaction)
freq_set = filter_support(candidates, transactions, self.min_sup)
# Iterate
k = 2
last_set = set()
while freq_set != set():
last_set = freq_set
cands = generate_candidates(freq_set, k)
freq_set = filter_support(cands, transactions, self.min_sup)
k += 1
# Map documents to their keywords.
keywords = flatten(last_set)
return prune([[kw for kw in keywords if kw in doc] for doc in docs]) | [
"def",
"tokenize",
"(",
"self",
",",
"docs",
")",
":",
"if",
"self",
".",
"min_sup",
"<",
"1",
"/",
"len",
"(",
"docs",
")",
":",
"raise",
"Exception",
"(",
"'`min_sup` must be greater than or equal to `1/len(docs)`.'",
")",
"# First pass",
"candidates",
"=",
"set",
"(",
")",
"transactions",
"=",
"[",
"]",
"# Use nouns and noun phrases.",
"for",
"doc",
"in",
"POSTokenizer",
"(",
")",
".",
"tokenize",
"(",
"docs",
")",
":",
"transaction",
"=",
"set",
"(",
"doc",
")",
"candidates",
"=",
"candidates",
".",
"union",
"(",
"{",
"(",
"t",
",",
")",
"for",
"t",
"in",
"transaction",
"}",
")",
"transactions",
".",
"append",
"(",
"transaction",
")",
"freq_set",
"=",
"filter_support",
"(",
"candidates",
",",
"transactions",
",",
"self",
".",
"min_sup",
")",
"# Iterate",
"k",
"=",
"2",
"last_set",
"=",
"set",
"(",
")",
"while",
"freq_set",
"!=",
"set",
"(",
")",
":",
"last_set",
"=",
"freq_set",
"cands",
"=",
"generate_candidates",
"(",
"freq_set",
",",
"k",
")",
"freq_set",
"=",
"filter_support",
"(",
"cands",
",",
"transactions",
",",
"self",
".",
"min_sup",
")",
"k",
"+=",
"1",
"# Map documents to their keywords.",
"keywords",
"=",
"flatten",
"(",
"last_set",
")",
"return",
"prune",
"(",
"[",
"[",
"kw",
"for",
"kw",
"in",
"keywords",
"if",
"kw",
"in",
"doc",
"]",
"for",
"doc",
"in",
"docs",
"]",
")"
] | 37.880952 | 22.071429 |
def create_archive(archive, filenames, verbosity=0, program=None, interactive=True):
"""Create given archive with given files."""
util.check_new_filename(archive)
util.check_archive_filelist(filenames)
if verbosity >= 0:
util.log_info("Creating %s ..." % archive)
res = _create_archive(archive, filenames, verbosity=verbosity,
interactive=interactive, program=program)
if verbosity >= 0:
util.log_info("... %s created." % archive)
return res | [
"def",
"create_archive",
"(",
"archive",
",",
"filenames",
",",
"verbosity",
"=",
"0",
",",
"program",
"=",
"None",
",",
"interactive",
"=",
"True",
")",
":",
"util",
".",
"check_new_filename",
"(",
"archive",
")",
"util",
".",
"check_archive_filelist",
"(",
"filenames",
")",
"if",
"verbosity",
">=",
"0",
":",
"util",
".",
"log_info",
"(",
"\"Creating %s ...\"",
"%",
"archive",
")",
"res",
"=",
"_create_archive",
"(",
"archive",
",",
"filenames",
",",
"verbosity",
"=",
"verbosity",
",",
"interactive",
"=",
"interactive",
",",
"program",
"=",
"program",
")",
"if",
"verbosity",
">=",
"0",
":",
"util",
".",
"log_info",
"(",
"\"... %s created.\"",
"%",
"archive",
")",
"return",
"res"
] | 45.545455 | 16.818182 |
def get_peer_resources(self, peer_jid):
"""
Return a dict mapping resources of the given bare `peer_jid` to the
presence state last received for that resource.
Unavailable presence states are not included. If the bare JID is in a
error state (i.e. an error presence stanza has been received), the
returned mapping is empty.
"""
try:
d = dict(self._presences[peer_jid])
d.pop(None, None)
return d
except KeyError:
return {} | [
"def",
"get_peer_resources",
"(",
"self",
",",
"peer_jid",
")",
":",
"try",
":",
"d",
"=",
"dict",
"(",
"self",
".",
"_presences",
"[",
"peer_jid",
"]",
")",
"d",
".",
"pop",
"(",
"None",
",",
"None",
")",
"return",
"d",
"except",
"KeyError",
":",
"return",
"{",
"}"
] | 35.266667 | 17.933333 |
def cache_context(self, context):
'''
Cache the given context to disk
'''
if not os.path.isdir(os.path.dirname(self.cache_path)):
os.mkdir(os.path.dirname(self.cache_path))
with salt.utils.files.fopen(self.cache_path, 'w+b') as cache:
self.serial.dump(context, cache) | [
"def",
"cache_context",
"(",
"self",
",",
"context",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"cache_path",
")",
")",
":",
"os",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"cache_path",
")",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"self",
".",
"cache_path",
",",
"'w+b'",
")",
"as",
"cache",
":",
"self",
".",
"serial",
".",
"dump",
"(",
"context",
",",
"cache",
")"
] | 40.5 | 17 |
def change_content_type(self, new_ctype, guess=False):
"""
Copies object to itself, but applies a new content-type. The guess
feature requires the container to be CDN-enabled. If not then the
content-type must be supplied. If using guess with a CDN-enabled
container, new_ctype can be set to None.
Failure during the put will result in a swift exception.
"""
self.container.change_object_content_type(self, new_ctype=new_ctype,
guess=guess) | [
"def",
"change_content_type",
"(",
"self",
",",
"new_ctype",
",",
"guess",
"=",
"False",
")",
":",
"self",
".",
"container",
".",
"change_object_content_type",
"(",
"self",
",",
"new_ctype",
"=",
"new_ctype",
",",
"guess",
"=",
"guess",
")"
] | 51.1 | 19.3 |
def block_user_signals(self, name, ignore_error=False):
"""
Temporarily disconnects the user-defined signals for the specified
parameter name.
Note this only affects those connections made with
connect_signal_changed(), and I do not recommend adding new connections
while they're blocked!
"""
x = self._find_parameter(name.split("/"), quiet=ignore_error)
# if it pooped.
if x==None: return None
# disconnect it from all its functions
if name in self._connection_lists:
for f in self._connection_lists[name]: x.sigValueChanged.disconnect(f)
return self | [
"def",
"block_user_signals",
"(",
"self",
",",
"name",
",",
"ignore_error",
"=",
"False",
")",
":",
"x",
"=",
"self",
".",
"_find_parameter",
"(",
"name",
".",
"split",
"(",
"\"/\"",
")",
",",
"quiet",
"=",
"ignore_error",
")",
"# if it pooped.",
"if",
"x",
"==",
"None",
":",
"return",
"None",
"# disconnect it from all its functions",
"if",
"name",
"in",
"self",
".",
"_connection_lists",
":",
"for",
"f",
"in",
"self",
".",
"_connection_lists",
"[",
"name",
"]",
":",
"x",
".",
"sigValueChanged",
".",
"disconnect",
"(",
"f",
")",
"return",
"self"
] | 36 | 20.631579 |
def device_unlocked(self, device):
"""Show unlock notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_unlocked',
_('Device unlocked'),
_('{0.device_presentation} unlocked', device),
device.icon_name) | [
"def",
"device_unlocked",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"self",
".",
"_show_notification",
"(",
"'device_unlocked'",
",",
"_",
"(",
"'Device unlocked'",
")",
",",
"_",
"(",
"'{0.device_presentation} unlocked'",
",",
"device",
")",
",",
"device",
".",
"icon_name",
")"
] | 39.111111 | 10.333333 |
def fill_area(self, x, y, width, height, color, opacity = 1):
"""fill rectangular area with specified color"""
self.save_context()
self.rectangle(x, y, width, height)
self._add_instruction("clip")
self.rectangle(x, y, width, height)
self.fill(color, opacity)
self.restore_context() | [
"def",
"fill_area",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"color",
",",
"opacity",
"=",
"1",
")",
":",
"self",
".",
"save_context",
"(",
")",
"self",
".",
"rectangle",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
"self",
".",
"_add_instruction",
"(",
"\"clip\"",
")",
"self",
".",
"rectangle",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
"self",
".",
"fill",
"(",
"color",
",",
"opacity",
")",
"self",
".",
"restore_context",
"(",
")"
] | 41.25 | 7.5 |
def read(self, size=None):
"""Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
remaining data.
Returns:
bytes: data read.
Raises:
IOError: if the read failed.
OSError: if the read failed.
"""
if not self._is_open:
raise IOError('Not opened.')
if self._fsntfs_data_stream:
return self._fsntfs_data_stream.read(size=size)
return self._fsntfs_file_entry.read(size=size) | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_is_open",
":",
"raise",
"IOError",
"(",
"'Not opened.'",
")",
"if",
"self",
".",
"_fsntfs_data_stream",
":",
"return",
"self",
".",
"_fsntfs_data_stream",
".",
"read",
"(",
"size",
"=",
"size",
")",
"return",
"self",
".",
"_fsntfs_file_entry",
".",
"read",
"(",
"size",
"=",
"size",
")"
] | 27.826087 | 20.347826 |
def get_lines_from_file(filename, lineno, context_lines):
"""
Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context).
"""
def get_lines(start, end):
return [linecache.getline(filename, l).rstrip() for l in range(start, end)]
lower_bound = max(1, lineno - context_lines)
upper_bound = lineno + context_lines
linecache.checkcache(filename)
pre_context = get_lines(lower_bound, lineno)
context_line = linecache.getline(filename, lineno).rstrip()
post_context = get_lines(lineno + 1, upper_bound)
return lower_bound, pre_context, context_line, post_context | [
"def",
"get_lines_from_file",
"(",
"filename",
",",
"lineno",
",",
"context_lines",
")",
":",
"def",
"get_lines",
"(",
"start",
",",
"end",
")",
":",
"return",
"[",
"linecache",
".",
"getline",
"(",
"filename",
",",
"l",
")",
".",
"rstrip",
"(",
")",
"for",
"l",
"in",
"range",
"(",
"start",
",",
"end",
")",
"]",
"lower_bound",
"=",
"max",
"(",
"1",
",",
"lineno",
"-",
"context_lines",
")",
"upper_bound",
"=",
"lineno",
"+",
"context_lines",
"linecache",
".",
"checkcache",
"(",
"filename",
")",
"pre_context",
"=",
"get_lines",
"(",
"lower_bound",
",",
"lineno",
")",
"context_line",
"=",
"linecache",
".",
"getline",
"(",
"filename",
",",
"lineno",
")",
".",
"rstrip",
"(",
")",
"post_context",
"=",
"get_lines",
"(",
"lineno",
"+",
"1",
",",
"upper_bound",
")",
"return",
"lower_bound",
",",
"pre_context",
",",
"context_line",
",",
"post_context"
] | 41.6875 | 17.8125 |
def get_period_last_30_days() -> str:
""" Returns the last week as a period string """
today = Datum()
today.today()
# start_date = today - timedelta(days=30)
start_date = today.clone()
start_date.subtract_days(30)
period = get_period(start_date.value, today.value)
return period | [
"def",
"get_period_last_30_days",
"(",
")",
"->",
"str",
":",
"today",
"=",
"Datum",
"(",
")",
"today",
".",
"today",
"(",
")",
"# start_date = today - timedelta(days=30)",
"start_date",
"=",
"today",
".",
"clone",
"(",
")",
"start_date",
".",
"subtract_days",
"(",
"30",
")",
"period",
"=",
"get_period",
"(",
"start_date",
".",
"value",
",",
"today",
".",
"value",
")",
"return",
"period"
] | 30.3 | 14.7 |
def _update_ned_query_history(
self):
"""*Update the database helper table to give details of the ned cone searches performed*
*Usage:*
.. code-block:: python
stream._update_ned_query_history()
"""
self.log.debug('starting the ``_update_ned_query_history`` method')
myPid = self.myPid
# ASTROCALC UNIT CONVERTER OBJECT
converter = unit_conversion(
log=self.log
)
# UPDATE THE DATABASE HELPER TABLE TO GIVE DETAILS OF THE NED CONE
# SEARCHES PERFORMED
dataList = []
for i, coord in enumerate(self.coordinateList):
if isinstance(coord, str):
ra = coord.split(" ")[0]
dec = coord.split(" ")[1]
elif isinstance(coord, tuple) or isinstance(coord, list):
ra = coord[0]
dec = coord[1]
dataList.append(
{"raDeg": ra,
"decDeg": dec,
"arcsecRadius": self.radiusArcsec}
)
if len(dataList) == 0:
return None
# CREATE TABLE IF NOT EXIST
createStatement = """CREATE TABLE IF NOT EXISTS `tcs_helper_ned_query_history` (
`primaryId` bigint(20) NOT NULL AUTO_INCREMENT,
`raDeg` double DEFAULT NULL,
`decDeg` double DEFAULT NULL,
`dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
`dateLastModified` datetime DEFAULT CURRENT_TIMESTAMP,
`updated` varchar(45) DEFAULT '0',
`arcsecRadius` int(11) DEFAULT NULL,
`dateQueried` datetime DEFAULT CURRENT_TIMESTAMP,
`htm16ID` bigint(20) DEFAULT NULL,
`htm13ID` int(11) DEFAULT NULL,
`htm10ID` int(11) DEFAULT NULL,
PRIMARY KEY (`primaryId`),
KEY `idx_htm16ID` (`htm16ID`),
KEY `dateQueried` (`dateQueried`),
KEY `dateHtm16` (`dateQueried`,`htm16ID`),
KEY `idx_htm10ID` (`htm10ID`),
KEY `idx_htm13ID` (`htm13ID`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
"""
writequery(
log=self.log,
sqlQuery=createStatement,
dbConn=self.cataloguesDbConn
)
# USE dbSettings TO ACTIVATE MULTIPROCESSING
insert_list_of_dictionaries_into_database_tables(
dbConn=self.cataloguesDbConn,
log=self.log,
dictList=dataList,
dbTableName="tcs_helper_ned_query_history",
uniqueKeyList=[],
dateModified=True,
batchSize=10000,
replace=True,
dbSettings=self.settings["database settings"][
"static catalogues"]
)
# INDEX THE TABLE FOR LATER SEARCHES
add_htm_ids_to_mysql_database_table(
raColName="raDeg",
declColName="decDeg",
tableName="tcs_helper_ned_query_history",
dbConn=self.cataloguesDbConn,
log=self.log,
primaryIdColumnName="primaryId"
)
self.log.debug('completed the ``_update_ned_query_history`` method')
return None | [
"def",
"_update_ned_query_history",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_update_ned_query_history`` method'",
")",
"myPid",
"=",
"self",
".",
"myPid",
"# ASTROCALC UNIT CONVERTER OBJECT",
"converter",
"=",
"unit_conversion",
"(",
"log",
"=",
"self",
".",
"log",
")",
"# UPDATE THE DATABASE HELPER TABLE TO GIVE DETAILS OF THE NED CONE",
"# SEARCHES PERFORMED",
"dataList",
"=",
"[",
"]",
"for",
"i",
",",
"coord",
"in",
"enumerate",
"(",
"self",
".",
"coordinateList",
")",
":",
"if",
"isinstance",
"(",
"coord",
",",
"str",
")",
":",
"ra",
"=",
"coord",
".",
"split",
"(",
"\" \"",
")",
"[",
"0",
"]",
"dec",
"=",
"coord",
".",
"split",
"(",
"\" \"",
")",
"[",
"1",
"]",
"elif",
"isinstance",
"(",
"coord",
",",
"tuple",
")",
"or",
"isinstance",
"(",
"coord",
",",
"list",
")",
":",
"ra",
"=",
"coord",
"[",
"0",
"]",
"dec",
"=",
"coord",
"[",
"1",
"]",
"dataList",
".",
"append",
"(",
"{",
"\"raDeg\"",
":",
"ra",
",",
"\"decDeg\"",
":",
"dec",
",",
"\"arcsecRadius\"",
":",
"self",
".",
"radiusArcsec",
"}",
")",
"if",
"len",
"(",
"dataList",
")",
"==",
"0",
":",
"return",
"None",
"# CREATE TABLE IF NOT EXIST",
"createStatement",
"=",
"\"\"\"CREATE TABLE IF NOT EXISTS `tcs_helper_ned_query_history` (\n `primaryId` bigint(20) NOT NULL AUTO_INCREMENT,\n `raDeg` double DEFAULT NULL,\n `decDeg` double DEFAULT NULL,\n `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,\n `dateLastModified` datetime DEFAULT CURRENT_TIMESTAMP,\n `updated` varchar(45) DEFAULT '0',\n `arcsecRadius` int(11) DEFAULT NULL,\n `dateQueried` datetime DEFAULT CURRENT_TIMESTAMP,\n `htm16ID` bigint(20) DEFAULT NULL,\n `htm13ID` int(11) DEFAULT NULL,\n `htm10ID` int(11) DEFAULT NULL,\n PRIMARY KEY (`primaryId`),\n KEY `idx_htm16ID` (`htm16ID`),\n KEY `dateQueried` (`dateQueried`),\n KEY `dateHtm16` (`dateQueried`,`htm16ID`),\n KEY `idx_htm10ID` (`htm10ID`),\n KEY `idx_htm13ID` (`htm13ID`)\n) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;\n \"\"\"",
"writequery",
"(",
"log",
"=",
"self",
".",
"log",
",",
"sqlQuery",
"=",
"createStatement",
",",
"dbConn",
"=",
"self",
".",
"cataloguesDbConn",
")",
"# USE dbSettings TO ACTIVATE MULTIPROCESSING",
"insert_list_of_dictionaries_into_database_tables",
"(",
"dbConn",
"=",
"self",
".",
"cataloguesDbConn",
",",
"log",
"=",
"self",
".",
"log",
",",
"dictList",
"=",
"dataList",
",",
"dbTableName",
"=",
"\"tcs_helper_ned_query_history\"",
",",
"uniqueKeyList",
"=",
"[",
"]",
",",
"dateModified",
"=",
"True",
",",
"batchSize",
"=",
"10000",
",",
"replace",
"=",
"True",
",",
"dbSettings",
"=",
"self",
".",
"settings",
"[",
"\"database settings\"",
"]",
"[",
"\"static catalogues\"",
"]",
")",
"# INDEX THE TABLE FOR LATER SEARCHES",
"add_htm_ids_to_mysql_database_table",
"(",
"raColName",
"=",
"\"raDeg\"",
",",
"declColName",
"=",
"\"decDeg\"",
",",
"tableName",
"=",
"\"tcs_helper_ned_query_history\"",
",",
"dbConn",
"=",
"self",
".",
"cataloguesDbConn",
",",
"log",
"=",
"self",
".",
"log",
",",
"primaryIdColumnName",
"=",
"\"primaryId\"",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'completed the ``_update_ned_query_history`` method'",
")",
"return",
"None"
] | 32.358696 | 15.728261 |
def filter(self, filter_arguments):
"""
Takes a dictionary of filter parameters.
Return a list of objects based on a list of parameters.
"""
results = self._get_content()
# Filter based on a dictionary of search parameters
if isinstance(filter_arguments, dict):
for item, content in iteritems(self._get_content()):
for key, value in iteritems(filter_arguments):
keys = key.split('.')
value = filter_arguments[key]
if not self._contains_value({item: content}, keys, value):
del results[item]
# Filter based on an input string that should match database key
if isinstance(filter_arguments, str):
if filter_arguments in results:
return [{filter_arguments: results[filter_arguments]}]
else:
return []
return results | [
"def",
"filter",
"(",
"self",
",",
"filter_arguments",
")",
":",
"results",
"=",
"self",
".",
"_get_content",
"(",
")",
"# Filter based on a dictionary of search parameters",
"if",
"isinstance",
"(",
"filter_arguments",
",",
"dict",
")",
":",
"for",
"item",
",",
"content",
"in",
"iteritems",
"(",
"self",
".",
"_get_content",
"(",
")",
")",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"filter_arguments",
")",
":",
"keys",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"value",
"=",
"filter_arguments",
"[",
"key",
"]",
"if",
"not",
"self",
".",
"_contains_value",
"(",
"{",
"item",
":",
"content",
"}",
",",
"keys",
",",
"value",
")",
":",
"del",
"results",
"[",
"item",
"]",
"# Filter based on an input string that should match database key",
"if",
"isinstance",
"(",
"filter_arguments",
",",
"str",
")",
":",
"if",
"filter_arguments",
"in",
"results",
":",
"return",
"[",
"{",
"filter_arguments",
":",
"results",
"[",
"filter_arguments",
"]",
"}",
"]",
"else",
":",
"return",
"[",
"]",
"return",
"results"
] | 37.56 | 17.8 |
def set_imap_cb(self, w, index):
"""This callback is invoked when the user selects a new intensity
map from the preferences pane."""
name = imap.get_names()[index]
self.t_.set(intensity_map=name) | [
"def",
"set_imap_cb",
"(",
"self",
",",
"w",
",",
"index",
")",
":",
"name",
"=",
"imap",
".",
"get_names",
"(",
")",
"[",
"index",
"]",
"self",
".",
"t_",
".",
"set",
"(",
"intensity_map",
"=",
"name",
")"
] | 44.6 | 2.2 |
def genfromtxt_args_error(self):
"""
Passed as keyword arguments to [`numpy.genfromtxt`][1]
when called by `scipy_data_fitting.Data.load_error`.
Even if defined here, the `usecols` value will always be reset based
on `scipy_data_fitting.Data.error_columns` before being passed to [`numpy.genfromtxt`][1].
If not set, this defaults to a copy of
`scipy_data_fitting.Data.genfromtxt_args` on first access.
[1]: http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html
"""
if not hasattr(self, '_genfromtxt_args_error'):
self._genfromtxt_args_error = self.genfromtxt_args.copy()
return self._genfromtxt_args_error | [
"def",
"genfromtxt_args_error",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_genfromtxt_args_error'",
")",
":",
"self",
".",
"_genfromtxt_args_error",
"=",
"self",
".",
"genfromtxt_args",
".",
"copy",
"(",
")",
"return",
"self",
".",
"_genfromtxt_args_error"
] | 44.625 | 24.25 |
def go_down(self):
"""
Go down one, wrap to beginning if necessary
"""
if self.current_option < len(self.items) - 1:
self.current_option += 1
else:
self.current_option = 0
self.draw() | [
"def",
"go_down",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_option",
"<",
"len",
"(",
"self",
".",
"items",
")",
"-",
"1",
":",
"self",
".",
"current_option",
"+=",
"1",
"else",
":",
"self",
".",
"current_option",
"=",
"0",
"self",
".",
"draw",
"(",
")"
] | 27.444444 | 11.444444 |
def _handle_display_data(self, msg):
""" Overridden to handle rich data types, like SVG.
"""
if not self._hidden and self._is_from_this_session(msg):
source = msg['content']['source']
data = msg['content']['data']
metadata = msg['content']['metadata']
# Try to use the svg or html representations.
# FIXME: Is this the right ordering of things to try?
if data.has_key('image/svg+xml'):
self.log.debug("display: %s", msg.get('content', ''))
svg = data['image/svg+xml']
self._append_svg(svg, True)
elif data.has_key('image/png'):
self.log.debug("display: %s", msg.get('content', ''))
# PNG data is base64 encoded as it passes over the network
# in a JSON structure so we decode it.
png = decodestring(data['image/png'].encode('ascii'))
self._append_png(png, True)
elif data.has_key('image/jpeg') and self._jpg_supported:
self.log.debug("display: %s", msg.get('content', ''))
jpg = decodestring(data['image/jpeg'].encode('ascii'))
self._append_jpg(jpg, True)
else:
# Default back to the plain text representation.
return super(RichIPythonWidget, self)._handle_display_data(msg) | [
"def",
"_handle_display_data",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"self",
".",
"_hidden",
"and",
"self",
".",
"_is_from_this_session",
"(",
"msg",
")",
":",
"source",
"=",
"msg",
"[",
"'content'",
"]",
"[",
"'source'",
"]",
"data",
"=",
"msg",
"[",
"'content'",
"]",
"[",
"'data'",
"]",
"metadata",
"=",
"msg",
"[",
"'content'",
"]",
"[",
"'metadata'",
"]",
"# Try to use the svg or html representations.",
"# FIXME: Is this the right ordering of things to try?",
"if",
"data",
".",
"has_key",
"(",
"'image/svg+xml'",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"display: %s\"",
",",
"msg",
".",
"get",
"(",
"'content'",
",",
"''",
")",
")",
"svg",
"=",
"data",
"[",
"'image/svg+xml'",
"]",
"self",
".",
"_append_svg",
"(",
"svg",
",",
"True",
")",
"elif",
"data",
".",
"has_key",
"(",
"'image/png'",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"display: %s\"",
",",
"msg",
".",
"get",
"(",
"'content'",
",",
"''",
")",
")",
"# PNG data is base64 encoded as it passes over the network",
"# in a JSON structure so we decode it.",
"png",
"=",
"decodestring",
"(",
"data",
"[",
"'image/png'",
"]",
".",
"encode",
"(",
"'ascii'",
")",
")",
"self",
".",
"_append_png",
"(",
"png",
",",
"True",
")",
"elif",
"data",
".",
"has_key",
"(",
"'image/jpeg'",
")",
"and",
"self",
".",
"_jpg_supported",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"display: %s\"",
",",
"msg",
".",
"get",
"(",
"'content'",
",",
"''",
")",
")",
"jpg",
"=",
"decodestring",
"(",
"data",
"[",
"'image/jpeg'",
"]",
".",
"encode",
"(",
"'ascii'",
")",
")",
"self",
".",
"_append_jpg",
"(",
"jpg",
",",
"True",
")",
"else",
":",
"# Default back to the plain text representation.",
"return",
"super",
"(",
"RichIPythonWidget",
",",
"self",
")",
".",
"_handle_display_data",
"(",
"msg",
")"
] | 53.423077 | 15.884615 |
def parse(cls, root):
"""
Create a new MDWrap by parsing root.
:param root: Element or ElementTree to be parsed into a MDWrap.
:raises exceptions.ParseError: If mdWrap does not contain MDTYPE
:raises exceptions.ParseError: If xmlData contains no children
"""
if root.tag != utils.lxmlns("mets") + "mdWrap":
raise exceptions.ParseError(
"MDWrap can only parse mdWrap elements with METS namespace."
)
mdtype = root.get("MDTYPE")
if not mdtype:
raise exceptions.ParseError("mdWrap must have a MDTYPE")
othermdtype = root.get("OTHERMDTYPE")
document = root.xpath("mets:xmlData/*", namespaces=utils.NAMESPACES)
if len(document) == 0:
raise exceptions.ParseError(
"All mdWrap/xmlData elements must have at least one child; this"
" one has none"
)
elif len(document) == 1:
document = document[0]
# Create a copy, so that the element is not moved by duplicate references.
document = copy.deepcopy(document)
return cls(document, mdtype, othermdtype) | [
"def",
"parse",
"(",
"cls",
",",
"root",
")",
":",
"if",
"root",
".",
"tag",
"!=",
"utils",
".",
"lxmlns",
"(",
"\"mets\"",
")",
"+",
"\"mdWrap\"",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"\"MDWrap can only parse mdWrap elements with METS namespace.\"",
")",
"mdtype",
"=",
"root",
".",
"get",
"(",
"\"MDTYPE\"",
")",
"if",
"not",
"mdtype",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"\"mdWrap must have a MDTYPE\"",
")",
"othermdtype",
"=",
"root",
".",
"get",
"(",
"\"OTHERMDTYPE\"",
")",
"document",
"=",
"root",
".",
"xpath",
"(",
"\"mets:xmlData/*\"",
",",
"namespaces",
"=",
"utils",
".",
"NAMESPACES",
")",
"if",
"len",
"(",
"document",
")",
"==",
"0",
":",
"raise",
"exceptions",
".",
"ParseError",
"(",
"\"All mdWrap/xmlData elements must have at least one child; this\"",
"\" one has none\"",
")",
"elif",
"len",
"(",
"document",
")",
"==",
"1",
":",
"document",
"=",
"document",
"[",
"0",
"]",
"# Create a copy, so that the element is not moved by duplicate references.",
"document",
"=",
"copy",
".",
"deepcopy",
"(",
"document",
")",
"return",
"cls",
"(",
"document",
",",
"mdtype",
",",
"othermdtype",
")"
] | 40.103448 | 19.275862 |
def filter(self,x):
"""
Filter the signal
"""
y = signal.lfilter(self.b,[1],x)
return y | [
"def",
"filter",
"(",
"self",
",",
"x",
")",
":",
"y",
"=",
"signal",
".",
"lfilter",
"(",
"self",
".",
"b",
",",
"[",
"1",
"]",
",",
"x",
")",
"return",
"y"
] | 20.333333 | 10 |
def as_string(self, name=None):
"""
Declares a stream converting each tuple on this stream
into a string using `str(tuple)`.
The stream is typed as a :py:const:`string stream <streamsx.topology.schema.CommonSchema.String>`.
If this stream is already typed as a string stream then it will
be returned (with no additional processing against it and `name`
is ignored).
Args:
name(str): Name of the resulting stream.
When `None` defaults to a generated name.
.. versionadded:: 1.6
.. versionadded:: 1.6.1 `name` parameter added.
Returns:
Stream: Stream containing the string representations of tuples on this stream.
"""
sas = self._change_schema(streamsx.topology.schema.CommonSchema.String, 'as_string', name)._layout('AsString')
sas.oport.operator.sl = _SourceLocation(_source_info(), 'as_string')
return sas | [
"def",
"as_string",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"sas",
"=",
"self",
".",
"_change_schema",
"(",
"streamsx",
".",
"topology",
".",
"schema",
".",
"CommonSchema",
".",
"String",
",",
"'as_string'",
",",
"name",
")",
".",
"_layout",
"(",
"'AsString'",
")",
"sas",
".",
"oport",
".",
"operator",
".",
"sl",
"=",
"_SourceLocation",
"(",
"_source_info",
"(",
")",
",",
"'as_string'",
")",
"return",
"sas"
] | 39.541667 | 28.041667 |
def run_migrations():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
with engine.connect() as connection:
context.configure(
connection=connection,
target_metadata=Model.metadata)
with context.begin_transaction():
context.run_migrations() | [
"def",
"run_migrations",
"(",
")",
":",
"with",
"engine",
".",
"connect",
"(",
")",
"as",
"connection",
":",
"context",
".",
"configure",
"(",
"connection",
"=",
"connection",
",",
"target_metadata",
"=",
"Model",
".",
"metadata",
")",
"with",
"context",
".",
"begin_transaction",
"(",
")",
":",
"context",
".",
"run_migrations",
"(",
")"
] | 27.357143 | 13.071429 |
def find_hal(self, atoms):
"""Look for halogen bond acceptors (Y-{O|P|N|S}, with Y=C,P,S)"""
data = namedtuple('hal_acceptor', 'o o_orig_idx y y_orig_idx')
a_set = []
# All oxygens, nitrogen, sulfurs with neighboring carbon, phosphor, nitrogen or sulfur
for a in [at for at in atoms if at.atomicnum in [8, 7, 16]]:
n_atoms = [na for na in pybel.ob.OBAtomAtomIter(a.OBAtom) if na.GetAtomicNum() in [6, 7, 15, 16]]
if len(n_atoms) == 1: # Proximal atom
o_orig_idx = self.Mapper.mapid(a.idx, mtype=self.mtype, bsid=self.bsid)
y_orig_idx = self.Mapper.mapid(n_atoms[0].GetIdx(), mtype=self.mtype, bsid=self.bsid)
a_set.append(data(o=a, o_orig_idx=o_orig_idx, y=pybel.Atom(n_atoms[0]), y_orig_idx=y_orig_idx))
return a_set | [
"def",
"find_hal",
"(",
"self",
",",
"atoms",
")",
":",
"data",
"=",
"namedtuple",
"(",
"'hal_acceptor'",
",",
"'o o_orig_idx y y_orig_idx'",
")",
"a_set",
"=",
"[",
"]",
"# All oxygens, nitrogen, sulfurs with neighboring carbon, phosphor, nitrogen or sulfur",
"for",
"a",
"in",
"[",
"at",
"for",
"at",
"in",
"atoms",
"if",
"at",
".",
"atomicnum",
"in",
"[",
"8",
",",
"7",
",",
"16",
"]",
"]",
":",
"n_atoms",
"=",
"[",
"na",
"for",
"na",
"in",
"pybel",
".",
"ob",
".",
"OBAtomAtomIter",
"(",
"a",
".",
"OBAtom",
")",
"if",
"na",
".",
"GetAtomicNum",
"(",
")",
"in",
"[",
"6",
",",
"7",
",",
"15",
",",
"16",
"]",
"]",
"if",
"len",
"(",
"n_atoms",
")",
"==",
"1",
":",
"# Proximal atom",
"o_orig_idx",
"=",
"self",
".",
"Mapper",
".",
"mapid",
"(",
"a",
".",
"idx",
",",
"mtype",
"=",
"self",
".",
"mtype",
",",
"bsid",
"=",
"self",
".",
"bsid",
")",
"y_orig_idx",
"=",
"self",
".",
"Mapper",
".",
"mapid",
"(",
"n_atoms",
"[",
"0",
"]",
".",
"GetIdx",
"(",
")",
",",
"mtype",
"=",
"self",
".",
"mtype",
",",
"bsid",
"=",
"self",
".",
"bsid",
")",
"a_set",
".",
"append",
"(",
"data",
"(",
"o",
"=",
"a",
",",
"o_orig_idx",
"=",
"o_orig_idx",
",",
"y",
"=",
"pybel",
".",
"Atom",
"(",
"n_atoms",
"[",
"0",
"]",
")",
",",
"y_orig_idx",
"=",
"y_orig_idx",
")",
")",
"return",
"a_set"
] | 68.916667 | 35.5 |
def generate_sizes(name, genome_dir):
"""Generate a sizes file with length of sequences in FASTA file."""
fa = os.path.join(genome_dir, name, "{}.fa".format(name))
sizes = fa + ".sizes"
g = Fasta(fa)
with open(sizes, "w") as f:
for seqname in g.keys():
f.write("{}\t{}\n".format(seqname, len(g[seqname]))) | [
"def",
"generate_sizes",
"(",
"name",
",",
"genome_dir",
")",
":",
"fa",
"=",
"os",
".",
"path",
".",
"join",
"(",
"genome_dir",
",",
"name",
",",
"\"{}.fa\"",
".",
"format",
"(",
"name",
")",
")",
"sizes",
"=",
"fa",
"+",
"\".sizes\"",
"g",
"=",
"Fasta",
"(",
"fa",
")",
"with",
"open",
"(",
"sizes",
",",
"\"w\"",
")",
"as",
"f",
":",
"for",
"seqname",
"in",
"g",
".",
"keys",
"(",
")",
":",
"f",
".",
"write",
"(",
"\"{}\\t{}\\n\"",
".",
"format",
"(",
"seqname",
",",
"len",
"(",
"g",
"[",
"seqname",
"]",
")",
")",
")"
] | 42.25 | 12.875 |
def path_glob(pattern, current_dir=None):
"""Use pathlib for ant-like patterns, like: "**/*.py"
:param pattern: File/directory pattern to use (as string).
:param current_dir: Current working directory (as Path, pathlib.Path, str)
:return Resolved Path (as path.Path).
"""
if not current_dir:
current_dir = pathlib.Path.cwd()
elif not isinstance(current_dir, pathlib.Path):
# -- CASE: string, path.Path (string-like)
current_dir = pathlib.Path(str(current_dir))
for p in current_dir.glob(pattern):
yield Path(str(p)) | [
"def",
"path_glob",
"(",
"pattern",
",",
"current_dir",
"=",
"None",
")",
":",
"if",
"not",
"current_dir",
":",
"current_dir",
"=",
"pathlib",
".",
"Path",
".",
"cwd",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"current_dir",
",",
"pathlib",
".",
"Path",
")",
":",
"# -- CASE: string, path.Path (string-like)",
"current_dir",
"=",
"pathlib",
".",
"Path",
"(",
"str",
"(",
"current_dir",
")",
")",
"for",
"p",
"in",
"current_dir",
".",
"glob",
"(",
"pattern",
")",
":",
"yield",
"Path",
"(",
"str",
"(",
"p",
")",
")"
] | 38.2 | 14.2 |
def run_command(self, cmd, history=True, new_prompt=True):
"""Run command in interpreter"""
if not cmd:
cmd = ''
else:
if history:
self.add_to_history(cmd)
if not self.multithreaded:
if 'input' not in cmd:
self.interpreter.stdin_write.write(
to_binary_string(cmd + '\n'))
self.interpreter.run_line()
self.refresh.emit()
else:
self.write(_('In order to use commands like "raw_input" '
'or "input" run Spyder with the multithread '
'option (--multithread) from a system terminal'),
error=True)
else:
self.interpreter.stdin_write.write(to_binary_string(cmd + '\n')) | [
"def",
"run_command",
"(",
"self",
",",
"cmd",
",",
"history",
"=",
"True",
",",
"new_prompt",
"=",
"True",
")",
":",
"if",
"not",
"cmd",
":",
"cmd",
"=",
"''",
"else",
":",
"if",
"history",
":",
"self",
".",
"add_to_history",
"(",
"cmd",
")",
"if",
"not",
"self",
".",
"multithreaded",
":",
"if",
"'input'",
"not",
"in",
"cmd",
":",
"self",
".",
"interpreter",
".",
"stdin_write",
".",
"write",
"(",
"to_binary_string",
"(",
"cmd",
"+",
"'\\n'",
")",
")",
"self",
".",
"interpreter",
".",
"run_line",
"(",
")",
"self",
".",
"refresh",
".",
"emit",
"(",
")",
"else",
":",
"self",
".",
"write",
"(",
"_",
"(",
"'In order to use commands like \"raw_input\" '",
"'or \"input\" run Spyder with the multithread '",
"'option (--multithread) from a system terminal'",
")",
",",
"error",
"=",
"True",
")",
"else",
":",
"self",
".",
"interpreter",
".",
"stdin_write",
".",
"write",
"(",
"to_binary_string",
"(",
"cmd",
"+",
"'\\n'",
")",
")"
] | 43.75 | 18.1 |
def script(self, s):
"""
Parse a script by compiling it.
Return a :class:`Contract` or None.
"""
try:
script = self._network.script.compile(s)
script_info = self._network.contract.info_for_script(script)
return Contract(script_info, self._network)
except Exception:
return None | [
"def",
"script",
"(",
"self",
",",
"s",
")",
":",
"try",
":",
"script",
"=",
"self",
".",
"_network",
".",
"script",
".",
"compile",
"(",
"s",
")",
"script_info",
"=",
"self",
".",
"_network",
".",
"contract",
".",
"info_for_script",
"(",
"script",
")",
"return",
"Contract",
"(",
"script_info",
",",
"self",
".",
"_network",
")",
"except",
"Exception",
":",
"return",
"None"
] | 33 | 13 |
def dcos_version():
"""Return the version of the running cluster.
:return: DC/OS cluster version as a string
"""
url = _gen_url('dcos-metadata/dcos-version.json')
response = dcos.http.request('get', url)
if response.status_code == 200:
return response.json()['version']
else:
return None | [
"def",
"dcos_version",
"(",
")",
":",
"url",
"=",
"_gen_url",
"(",
"'dcos-metadata/dcos-version.json'",
")",
"response",
"=",
"dcos",
".",
"http",
".",
"request",
"(",
"'get'",
",",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"response",
".",
"json",
"(",
")",
"[",
"'version'",
"]",
"else",
":",
"return",
"None"
] | 29.272727 | 12.909091 |
def _auth_session(self, username, password):
"""
Creates session to Hetzner account, authenticates with given credentials and
returns the session, if authentication was successful. Otherwise raises error.
"""
api = self.api[self.account]['auth']
endpoint = api.get('endpoint', self.api[self.account]['endpoint'])
session = requests.Session()
session_retries = Retry(total=10, backoff_factor=0.5)
session_adapter = requests.adapters.HTTPAdapter(max_retries=session_retries)
session.mount('https://', session_adapter)
response = session.request('GET', endpoint + api['GET'].get('url', '/'))
dom = Provider._filter_dom(response.text, api['filter'])
data = Provider._extract_hidden_data(dom)
data[api['user']], data[api['pass']] = username, password
response = session.request('POST', endpoint + api['POST']['url'], data=data)
if Provider._filter_dom(response.text, api['filter']):
LOGGER.error('Hetzner => Unable to authenticate session with %s account \'%s\': '
'Invalid credentials',
self.account, username)
raise AssertionError
LOGGER.info('Hetzner => Authenticate session with %s account \'%s\'',
self.account, username)
return session | [
"def",
"_auth_session",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"api",
"=",
"self",
".",
"api",
"[",
"self",
".",
"account",
"]",
"[",
"'auth'",
"]",
"endpoint",
"=",
"api",
".",
"get",
"(",
"'endpoint'",
",",
"self",
".",
"api",
"[",
"self",
".",
"account",
"]",
"[",
"'endpoint'",
"]",
")",
"session",
"=",
"requests",
".",
"Session",
"(",
")",
"session_retries",
"=",
"Retry",
"(",
"total",
"=",
"10",
",",
"backoff_factor",
"=",
"0.5",
")",
"session_adapter",
"=",
"requests",
".",
"adapters",
".",
"HTTPAdapter",
"(",
"max_retries",
"=",
"session_retries",
")",
"session",
".",
"mount",
"(",
"'https://'",
",",
"session_adapter",
")",
"response",
"=",
"session",
".",
"request",
"(",
"'GET'",
",",
"endpoint",
"+",
"api",
"[",
"'GET'",
"]",
".",
"get",
"(",
"'url'",
",",
"'/'",
")",
")",
"dom",
"=",
"Provider",
".",
"_filter_dom",
"(",
"response",
".",
"text",
",",
"api",
"[",
"'filter'",
"]",
")",
"data",
"=",
"Provider",
".",
"_extract_hidden_data",
"(",
"dom",
")",
"data",
"[",
"api",
"[",
"'user'",
"]",
"]",
",",
"data",
"[",
"api",
"[",
"'pass'",
"]",
"]",
"=",
"username",
",",
"password",
"response",
"=",
"session",
".",
"request",
"(",
"'POST'",
",",
"endpoint",
"+",
"api",
"[",
"'POST'",
"]",
"[",
"'url'",
"]",
",",
"data",
"=",
"data",
")",
"if",
"Provider",
".",
"_filter_dom",
"(",
"response",
".",
"text",
",",
"api",
"[",
"'filter'",
"]",
")",
":",
"LOGGER",
".",
"error",
"(",
"'Hetzner => Unable to authenticate session with %s account \\'%s\\': '",
"'Invalid credentials'",
",",
"self",
".",
"account",
",",
"username",
")",
"raise",
"AssertionError",
"LOGGER",
".",
"info",
"(",
"'Hetzner => Authenticate session with %s account \\'%s\\''",
",",
"self",
".",
"account",
",",
"username",
")",
"return",
"session"
] | 56.291667 | 21.208333 |
def __isValidTGZ(self, suffix):
"""To determine whether the suffix `.tar.gz` or `.tgz` format"""
if suffix and isinstance(suffix, string_types):
if suffix.endswith(".tar.gz") or suffix.endswith(".tgz"):
return True
return False | [
"def",
"__isValidTGZ",
"(",
"self",
",",
"suffix",
")",
":",
"if",
"suffix",
"and",
"isinstance",
"(",
"suffix",
",",
"string_types",
")",
":",
"if",
"suffix",
".",
"endswith",
"(",
"\".tar.gz\"",
")",
"or",
"suffix",
".",
"endswith",
"(",
"\".tgz\"",
")",
":",
"return",
"True",
"return",
"False"
] | 46.5 | 14.333333 |
def _clone(self, **kwargs):
"""
Create a clone of this collection. The only param in the
initial collection is the filter context. Each chainable
filter is added to the clone and returned to preserve
previous iterators and their returned elements.
:return: :class:`.ElementCollection`
"""
params = copy.deepcopy(self._params)
if self._iexact:
params.update(iexact=self._iexact)
params.update(**kwargs)
clone = self.__class__(**params)
return clone | [
"def",
"_clone",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_params",
")",
"if",
"self",
".",
"_iexact",
":",
"params",
".",
"update",
"(",
"iexact",
"=",
"self",
".",
"_iexact",
")",
"params",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"clone",
"=",
"self",
".",
"__class__",
"(",
"*",
"*",
"params",
")",
"return",
"clone"
] | 36.666667 | 12.533333 |
def is_ambiguous(self, dt, idx=None):
"""
Whether or not the "wall time" of a given datetime is ambiguous in this
zone.
:param dt:
A :py:class:`datetime.datetime`, naive or time zone aware.
:return:
Returns ``True`` if ambiguous, ``False`` otherwise.
.. versionadded:: 2.6.0
"""
if idx is None:
idx = self._find_last_transition(dt)
# Calculate the difference in offsets from current to previous
timestamp = _datetime_to_timestamp(dt)
tti = self._get_ttinfo(idx)
if idx is None or idx <= 0:
return False
od = self._get_ttinfo(idx - 1).offset - tti.offset
tt = self._trans_list[idx] # Transition time
return timestamp < tt + od | [
"def",
"is_ambiguous",
"(",
"self",
",",
"dt",
",",
"idx",
"=",
"None",
")",
":",
"if",
"idx",
"is",
"None",
":",
"idx",
"=",
"self",
".",
"_find_last_transition",
"(",
"dt",
")",
"# Calculate the difference in offsets from current to previous",
"timestamp",
"=",
"_datetime_to_timestamp",
"(",
"dt",
")",
"tti",
"=",
"self",
".",
"_get_ttinfo",
"(",
"idx",
")",
"if",
"idx",
"is",
"None",
"or",
"idx",
"<=",
"0",
":",
"return",
"False",
"od",
"=",
"self",
".",
"_get_ttinfo",
"(",
"idx",
"-",
"1",
")",
".",
"offset",
"-",
"tti",
".",
"offset",
"tt",
"=",
"self",
".",
"_trans_list",
"[",
"idx",
"]",
"# Transition time",
"return",
"timestamp",
"<",
"tt",
"+",
"od"
] | 27.964286 | 22.464286 |
def instance_attr_ancestors(self, name, context=None):
"""Iterate over the parents that define the given name as an attribute.
:param name: The name to find definitions for.
:type name: str
:returns: The parents that define the given name as
an instance attribute.
:rtype: iterable(NodeNG)
"""
for astroid in self.ancestors(context=context):
if name in astroid.instance_attrs:
yield astroid | [
"def",
"instance_attr_ancestors",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
")",
":",
"for",
"astroid",
"in",
"self",
".",
"ancestors",
"(",
"context",
"=",
"context",
")",
":",
"if",
"name",
"in",
"astroid",
".",
"instance_attrs",
":",
"yield",
"astroid"
] | 36.615385 | 14.615385 |
def update_version(self, version, step=1):
"Compute an new version and write it as a tag"
# update the version based on the flags passed.
if self.config.patch:
version.patch += step
if self.config.minor:
version.minor += step
if self.config.major:
version.major += step
if self.config.build:
version.build_number += step
if self.config.build_number:
version.build_number = self.config.build_number
# create a new tag in the repo with the new version.
if self.config.dry_run:
log.info('Not updating repo to version {0}, because of --dry-run'.format(version))
else:
version = self.call_plugin_function('set_version', version)
return version | [
"def",
"update_version",
"(",
"self",
",",
"version",
",",
"step",
"=",
"1",
")",
":",
"# update the version based on the flags passed.",
"if",
"self",
".",
"config",
".",
"patch",
":",
"version",
".",
"patch",
"+=",
"step",
"if",
"self",
".",
"config",
".",
"minor",
":",
"version",
".",
"minor",
"+=",
"step",
"if",
"self",
".",
"config",
".",
"major",
":",
"version",
".",
"major",
"+=",
"step",
"if",
"self",
".",
"config",
".",
"build",
":",
"version",
".",
"build_number",
"+=",
"step",
"if",
"self",
".",
"config",
".",
"build_number",
":",
"version",
".",
"build_number",
"=",
"self",
".",
"config",
".",
"build_number",
"# create a new tag in the repo with the new version.",
"if",
"self",
".",
"config",
".",
"dry_run",
":",
"log",
".",
"info",
"(",
"'Not updating repo to version {0}, because of --dry-run'",
".",
"format",
"(",
"version",
")",
")",
"else",
":",
"version",
"=",
"self",
".",
"call_plugin_function",
"(",
"'set_version'",
",",
"version",
")",
"return",
"version"
] | 36 | 18.090909 |
def close(self):
"""Closes the underlying database file."""
if hasattr(self.db, 'close'):
with self.write_mutex:
self.db.close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"db",
",",
"'close'",
")",
":",
"with",
"self",
".",
"write_mutex",
":",
"self",
".",
"db",
".",
"close",
"(",
")"
] | 33.6 | 8.4 |
def webfont_cookie(request):
'''Adds WEBFONT Flag to the context'''
if hasattr(request, 'COOKIES') and request.COOKIES.get(WEBFONT_COOKIE_NAME, None):
return {
WEBFONT_COOKIE_NAME.upper(): True
}
return {
WEBFONT_COOKIE_NAME.upper(): False
} | [
"def",
"webfont_cookie",
"(",
"request",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"'COOKIES'",
")",
"and",
"request",
".",
"COOKIES",
".",
"get",
"(",
"WEBFONT_COOKIE_NAME",
",",
"None",
")",
":",
"return",
"{",
"WEBFONT_COOKIE_NAME",
".",
"upper",
"(",
")",
":",
"True",
"}",
"return",
"{",
"WEBFONT_COOKIE_NAME",
".",
"upper",
"(",
")",
":",
"False",
"}"
] | 23.75 | 25.416667 |
def parse(self, text, context=0, skip_style_tags=False):
"""Parse *text*, returning a :class:`.Wikicode` object tree.
If given, *context* will be passed as a starting context to the parser.
This is helpful when this function is used inside node attribute
setters. For example, :class:`.ExternalLink`\\ 's
:attr:`~.ExternalLink.url` setter sets *context* to
:mod:`contexts.EXT_LINK_URI <.contexts>` to prevent the URL itself
from becoming an :class:`.ExternalLink`.
If *skip_style_tags* is ``True``, then ``''`` and ``'''`` will not be
parsed, but instead will be treated as plain text.
If there is an internal error while parsing, :exc:`.ParserError` will
be raised.
"""
tokens = self._tokenizer.tokenize(text, context, skip_style_tags)
code = self._builder.build(tokens)
return code | [
"def",
"parse",
"(",
"self",
",",
"text",
",",
"context",
"=",
"0",
",",
"skip_style_tags",
"=",
"False",
")",
":",
"tokens",
"=",
"self",
".",
"_tokenizer",
".",
"tokenize",
"(",
"text",
",",
"context",
",",
"skip_style_tags",
")",
"code",
"=",
"self",
".",
"_builder",
".",
"build",
"(",
"tokens",
")",
"return",
"code"
] | 46.736842 | 23.947368 |
def setup(self, builder: Builder):
"""Performs this component's simulation setup.
The ``setup`` method is automatically called by the simulation
framework. The framework passes in a ``builder`` object which
provides access to a variety of framework subsystems and metadata.
Parameters
----------
builder :
Access to simulation tools and subsystems.
"""
self.config = builder.configuration.mortality
self.population_view = builder.population.get_view(['alive'], query="alive == 'alive'")
self.randomness = builder.randomness.get_stream('mortality')
self.mortality_rate = builder.value.register_rate_producer('mortality_rate', source=self.base_mortality_rate)
builder.event.register_listener('time_step', self.determine_deaths) | [
"def",
"setup",
"(",
"self",
",",
"builder",
":",
"Builder",
")",
":",
"self",
".",
"config",
"=",
"builder",
".",
"configuration",
".",
"mortality",
"self",
".",
"population_view",
"=",
"builder",
".",
"population",
".",
"get_view",
"(",
"[",
"'alive'",
"]",
",",
"query",
"=",
"\"alive == 'alive'\"",
")",
"self",
".",
"randomness",
"=",
"builder",
".",
"randomness",
".",
"get_stream",
"(",
"'mortality'",
")",
"self",
".",
"mortality_rate",
"=",
"builder",
".",
"value",
".",
"register_rate_producer",
"(",
"'mortality_rate'",
",",
"source",
"=",
"self",
".",
"base_mortality_rate",
")",
"builder",
".",
"event",
".",
"register_listener",
"(",
"'time_step'",
",",
"self",
".",
"determine_deaths",
")"
] | 43.526316 | 28.842105 |
def _parse_leaves(self, leaves) -> List[Tuple[str, int]]:
"""Returns a list of pairs (leaf_name, distance)"""
return [(self._leaf_name(leaf), 0) for leaf in leaves] | [
"def",
"_parse_leaves",
"(",
"self",
",",
"leaves",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"int",
"]",
"]",
":",
"return",
"[",
"(",
"self",
".",
"_leaf_name",
"(",
"leaf",
")",
",",
"0",
")",
"for",
"leaf",
"in",
"leaves",
"]"
] | 59.333333 | 13 |
def compose_all(stream, Loader=Loader):
"""
Parse all YAML documents in a stream
and produce corresponding representation trees.
"""
loader = Loader(stream)
try:
while loader.check_node():
yield loader.get_node()
finally:
loader.dispose() | [
"def",
"compose_all",
"(",
"stream",
",",
"Loader",
"=",
"Loader",
")",
":",
"loader",
"=",
"Loader",
"(",
"stream",
")",
"try",
":",
"while",
"loader",
".",
"check_node",
"(",
")",
":",
"yield",
"loader",
".",
"get_node",
"(",
")",
"finally",
":",
"loader",
".",
"dispose",
"(",
")"
] | 25.818182 | 10.181818 |
def platform_from_version(major, minor):
"""
returns the minimum platform version that can load the given class
version indicated by major.minor or None if no known platforms
match the given version
"""
v = (major, minor)
for low, high, name in _platforms:
if low <= v <= high:
return name
return None | [
"def",
"platform_from_version",
"(",
"major",
",",
"minor",
")",
":",
"v",
"=",
"(",
"major",
",",
"minor",
")",
"for",
"low",
",",
"high",
",",
"name",
"in",
"_platforms",
":",
"if",
"low",
"<=",
"v",
"<=",
"high",
":",
"return",
"name",
"return",
"None"
] | 28.583333 | 15.25 |
def init(cls):
"""
Bind elements to callbacks.
"""
for el in cls.switcher_els:
el.checked = False
cls.bind_switcher()
cls._draw_conspects()
cls._create_searchable_typeahead() | [
"def",
"init",
"(",
"cls",
")",
":",
"for",
"el",
"in",
"cls",
".",
"switcher_els",
":",
"el",
".",
"checked",
"=",
"False",
"cls",
".",
"bind_switcher",
"(",
")",
"cls",
".",
"_draw_conspects",
"(",
")",
"cls",
".",
"_create_searchable_typeahead",
"(",
")"
] | 21.272727 | 13.818182 |
def fit(self, Z, **fit_params):
"""Fit all the transforms one after the other and transform the
data, then fit the transformed data using the final estimator.
Parameters
----------
Z : ArrayRDD, TupleRDD or DictRDD
Input data in blocked distributed format.
Returns
-------
self : SparkPipeline
"""
Zt, fit_params = self._pre_transform(Z, **fit_params)
self.steps[-1][-1].fit(Zt, **fit_params)
Zt.unpersist()
return self | [
"def",
"fit",
"(",
"self",
",",
"Z",
",",
"*",
"*",
"fit_params",
")",
":",
"Zt",
",",
"fit_params",
"=",
"self",
".",
"_pre_transform",
"(",
"Z",
",",
"*",
"*",
"fit_params",
")",
"self",
".",
"steps",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
".",
"fit",
"(",
"Zt",
",",
"*",
"*",
"fit_params",
")",
"Zt",
".",
"unpersist",
"(",
")",
"return",
"self"
] | 30.647059 | 18.058824 |
def notification_push(dev_type, to, message=None, **kwargs):
"""
Send data from your server to your users' devices.
"""
key = {
'ANDROID': settings.GCM_ANDROID_APIKEY,
'IOS': settings.GCM_IOS_APIKEY
}
if not key[dev_type]:
raise ImproperlyConfigured(
"You haven't set the 'GCM_{}_APIKEY' setting yet.".format(dev_type))
payload = {
'ANDROID': {'to': to,
'data': {'message': message}},
'IOS': {
'to': to,
'notification': {
'body': message,
},
}
}
payload[dev_type].update(**kwargs)
payload = json.dumps(payload[dev_type])
headers = {'Authorization': 'key={}'.format(key[dev_type]), 'Content-Type': 'application/json'}
response = requests.post(url='https://gcm-http.googleapis.com/gcm/send',
data=payload,
headers=headers
)
if response.status_code == 200:
response = response.json()
if response['success']:
return {'success': 'Message send successfully'}
elif response['canonical_ids']:
return {'canonical_id': response.get('results')[0].get('registration_id')}
elif response['failure']:
return {'error': response.get('results')[0].get('error')}
elif 400 <= response.status_code < 500:
return {'error': '%s Client Error: %s' % (response.status_code, response.reason)}
elif 500 <= response.status_code < 600:
return {'error': '%s Server Error: %s' % (response.status_code, response.reason)} | [
"def",
"notification_push",
"(",
"dev_type",
",",
"to",
",",
"message",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"{",
"'ANDROID'",
":",
"settings",
".",
"GCM_ANDROID_APIKEY",
",",
"'IOS'",
":",
"settings",
".",
"GCM_IOS_APIKEY",
"}",
"if",
"not",
"key",
"[",
"dev_type",
"]",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"You haven't set the 'GCM_{}_APIKEY' setting yet.\"",
".",
"format",
"(",
"dev_type",
")",
")",
"payload",
"=",
"{",
"'ANDROID'",
":",
"{",
"'to'",
":",
"to",
",",
"'data'",
":",
"{",
"'message'",
":",
"message",
"}",
"}",
",",
"'IOS'",
":",
"{",
"'to'",
":",
"to",
",",
"'notification'",
":",
"{",
"'body'",
":",
"message",
",",
"}",
",",
"}",
"}",
"payload",
"[",
"dev_type",
"]",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"payload",
"=",
"json",
".",
"dumps",
"(",
"payload",
"[",
"dev_type",
"]",
")",
"headers",
"=",
"{",
"'Authorization'",
":",
"'key={}'",
".",
"format",
"(",
"key",
"[",
"dev_type",
"]",
")",
",",
"'Content-Type'",
":",
"'application/json'",
"}",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
"=",
"'https://gcm-http.googleapis.com/gcm/send'",
",",
"data",
"=",
"payload",
",",
"headers",
"=",
"headers",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"response",
"=",
"response",
".",
"json",
"(",
")",
"if",
"response",
"[",
"'success'",
"]",
":",
"return",
"{",
"'success'",
":",
"'Message send successfully'",
"}",
"elif",
"response",
"[",
"'canonical_ids'",
"]",
":",
"return",
"{",
"'canonical_id'",
":",
"response",
".",
"get",
"(",
"'results'",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'registration_id'",
")",
"}",
"elif",
"response",
"[",
"'failure'",
"]",
":",
"return",
"{",
"'error'",
":",
"response",
".",
"get",
"(",
"'results'",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'error'",
")",
"}",
"elif",
"400",
"<=",
"response",
".",
"status_code",
"<",
"500",
":",
"return",
"{",
"'error'",
":",
"'%s Client Error: %s'",
"%",
"(",
"response",
".",
"status_code",
",",
"response",
".",
"reason",
")",
"}",
"elif",
"500",
"<=",
"response",
".",
"status_code",
"<",
"600",
":",
"return",
"{",
"'error'",
":",
"'%s Server Error: %s'",
"%",
"(",
"response",
".",
"status_code",
",",
"response",
".",
"reason",
")",
"}"
] | 31.588235 | 22.529412 |
def _follow_link(self, link_path_components, link):
"""Follow a link w.r.t. a path resolved so far.
The component is either a real file, which is a no-op, or a
symlink. In the case of a symlink, we have to modify the path
as built up so far
/a/b => ../c should yield /a/../c (which will normalize to /a/c)
/a/b => x should yield /a/x
/a/b => /x/y/z should yield /x/y/z
The modified path may land us in a new spot which is itself a
link, so we may repeat the process.
Args:
link_path_components: The resolved path built up to the link
so far.
link: The link object itself.
Returns:
(string) The updated path resolved after following the link.
Raises:
IOError: if there are too many levels of symbolic link
"""
link_path = link.contents
sep = self._path_separator(link_path)
# For links to absolute paths, we want to throw out everything
# in the path built so far and replace with the link. For relative
# links, we have to append the link to what we have so far,
if not self._starts_with_root_path(link_path):
# Relative path. Append remainder of path to what we have
# processed so far, excluding the name of the link itself.
# /a/b => ../c should yield /a/../c
# (which will normalize to /c)
# /a/b => d should yield a/d
components = link_path_components[:-1]
components.append(link_path)
link_path = sep.join(components)
# Don't call self.NormalizePath(), as we don't want to prepend
# self.cwd.
return self.normpath(link_path) | [
"def",
"_follow_link",
"(",
"self",
",",
"link_path_components",
",",
"link",
")",
":",
"link_path",
"=",
"link",
".",
"contents",
"sep",
"=",
"self",
".",
"_path_separator",
"(",
"link_path",
")",
"# For links to absolute paths, we want to throw out everything",
"# in the path built so far and replace with the link. For relative",
"# links, we have to append the link to what we have so far,",
"if",
"not",
"self",
".",
"_starts_with_root_path",
"(",
"link_path",
")",
":",
"# Relative path. Append remainder of path to what we have",
"# processed so far, excluding the name of the link itself.",
"# /a/b => ../c should yield /a/../c",
"# (which will normalize to /c)",
"# /a/b => d should yield a/d",
"components",
"=",
"link_path_components",
"[",
":",
"-",
"1",
"]",
"components",
".",
"append",
"(",
"link_path",
")",
"link_path",
"=",
"sep",
".",
"join",
"(",
"components",
")",
"# Don't call self.NormalizePath(), as we don't want to prepend",
"# self.cwd.",
"return",
"self",
".",
"normpath",
"(",
"link_path",
")"
] | 43.575 | 18.725 |
def sr(x, promisc=None, filter=None, iface=None, nofilter=0, *args, **kargs):
"""Send and receive packets at layer 3"""
s = conf.L3socket(promisc=promisc, filter=filter,
iface=iface, nofilter=nofilter)
result = sndrcv(s, x, *args, **kargs)
s.close()
return result | [
"def",
"sr",
"(",
"x",
",",
"promisc",
"=",
"None",
",",
"filter",
"=",
"None",
",",
"iface",
"=",
"None",
",",
"nofilter",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"s",
"=",
"conf",
".",
"L3socket",
"(",
"promisc",
"=",
"promisc",
",",
"filter",
"=",
"filter",
",",
"iface",
"=",
"iface",
",",
"nofilter",
"=",
"nofilter",
")",
"result",
"=",
"sndrcv",
"(",
"s",
",",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
"s",
".",
"close",
"(",
")",
"return",
"result"
] | 42.714286 | 16.285714 |
def _StopProcessStatusRPCServer(self):
"""Stops the process status RPC server."""
if not self._rpc_server:
return
# Make sure the engine gets one more status update so it knows
# the worker has completed.
self._WaitForStatusNotRunning()
self._rpc_server.Stop()
self._rpc_server = None
self.rpc_port.value = 0
logger.debug(
'Process: {0!s} process status RPC server stopped'.format(self._name)) | [
"def",
"_StopProcessStatusRPCServer",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_rpc_server",
":",
"return",
"# Make sure the engine gets one more status update so it knows",
"# the worker has completed.",
"self",
".",
"_WaitForStatusNotRunning",
"(",
")",
"self",
".",
"_rpc_server",
".",
"Stop",
"(",
")",
"self",
".",
"_rpc_server",
"=",
"None",
"self",
".",
"rpc_port",
".",
"value",
"=",
"0",
"logger",
".",
"debug",
"(",
"'Process: {0!s} process status RPC server stopped'",
".",
"format",
"(",
"self",
".",
"_name",
")",
")"
] | 28.8 | 20.133333 |
def _detect_loops(self, loop_callback=None):
"""
Loop detection.
:param func loop_callback: A callback function for each detected loop backedge.
:return: None
"""
loop_finder = self.project.analyses.LoopFinder(kb=self.kb, normalize=False, fail_fast=self._fail_fast)
if loop_callback is not None:
graph_copy = networkx.DiGraph(self._graph)
for loop in loop_finder.loops: # type: angr.analyses.loopfinder.Loop
loop_callback(graph_copy, loop)
self.model.graph = graph_copy
# Update loop backedges and graph
self._loop_back_edges = list(itertools.chain.from_iterable(loop.continue_edges for loop in loop_finder.loops)) | [
"def",
"_detect_loops",
"(",
"self",
",",
"loop_callback",
"=",
"None",
")",
":",
"loop_finder",
"=",
"self",
".",
"project",
".",
"analyses",
".",
"LoopFinder",
"(",
"kb",
"=",
"self",
".",
"kb",
",",
"normalize",
"=",
"False",
",",
"fail_fast",
"=",
"self",
".",
"_fail_fast",
")",
"if",
"loop_callback",
"is",
"not",
"None",
":",
"graph_copy",
"=",
"networkx",
".",
"DiGraph",
"(",
"self",
".",
"_graph",
")",
"for",
"loop",
"in",
"loop_finder",
".",
"loops",
":",
"# type: angr.analyses.loopfinder.Loop",
"loop_callback",
"(",
"graph_copy",
",",
"loop",
")",
"self",
".",
"model",
".",
"graph",
"=",
"graph_copy",
"# Update loop backedges and graph",
"self",
".",
"_loop_back_edges",
"=",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"loop",
".",
"continue_edges",
"for",
"loop",
"in",
"loop_finder",
".",
"loops",
")",
")"
] | 36.3 | 27.1 |
def load_from_file(path, fmt=None, is_training=True):
'''
load data from file
'''
if fmt is None:
fmt = 'squad'
assert fmt in ['squad', 'csv'], 'input format must be squad or csv'
qp_pairs = []
if fmt == 'squad':
with open(path) as data_file:
data = json.load(data_file)['data']
for doc in data:
for paragraph in doc['paragraphs']:
passage = paragraph['context']
for qa_pair in paragraph['qas']:
question = qa_pair['question']
qa_id = qa_pair['id']
if not is_training:
qp_pairs.append(
{'passage': passage, 'question': question, 'id': qa_id})
else:
for answer in qa_pair['answers']:
answer_begin = int(answer['answer_start'])
answer_end = answer_begin + len(answer['text'])
qp_pairs.append({'passage': passage,
'question': question,
'id': qa_id,
'answer_begin': answer_begin,
'answer_end': answer_end})
else:
with open(path, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
line_num = 0
for row in reader:
qp_pairs.append(
{'passage': row[1], 'question': row[0], 'id': line_num})
line_num += 1
return qp_pairs | [
"def",
"load_from_file",
"(",
"path",
",",
"fmt",
"=",
"None",
",",
"is_training",
"=",
"True",
")",
":",
"if",
"fmt",
"is",
"None",
":",
"fmt",
"=",
"'squad'",
"assert",
"fmt",
"in",
"[",
"'squad'",
",",
"'csv'",
"]",
",",
"'input format must be squad or csv'",
"qp_pairs",
"=",
"[",
"]",
"if",
"fmt",
"==",
"'squad'",
":",
"with",
"open",
"(",
"path",
")",
"as",
"data_file",
":",
"data",
"=",
"json",
".",
"load",
"(",
"data_file",
")",
"[",
"'data'",
"]",
"for",
"doc",
"in",
"data",
":",
"for",
"paragraph",
"in",
"doc",
"[",
"'paragraphs'",
"]",
":",
"passage",
"=",
"paragraph",
"[",
"'context'",
"]",
"for",
"qa_pair",
"in",
"paragraph",
"[",
"'qas'",
"]",
":",
"question",
"=",
"qa_pair",
"[",
"'question'",
"]",
"qa_id",
"=",
"qa_pair",
"[",
"'id'",
"]",
"if",
"not",
"is_training",
":",
"qp_pairs",
".",
"append",
"(",
"{",
"'passage'",
":",
"passage",
",",
"'question'",
":",
"question",
",",
"'id'",
":",
"qa_id",
"}",
")",
"else",
":",
"for",
"answer",
"in",
"qa_pair",
"[",
"'answers'",
"]",
":",
"answer_begin",
"=",
"int",
"(",
"answer",
"[",
"'answer_start'",
"]",
")",
"answer_end",
"=",
"answer_begin",
"+",
"len",
"(",
"answer",
"[",
"'text'",
"]",
")",
"qp_pairs",
".",
"append",
"(",
"{",
"'passage'",
":",
"passage",
",",
"'question'",
":",
"question",
",",
"'id'",
":",
"qa_id",
",",
"'answer_begin'",
":",
"answer_begin",
",",
"'answer_end'",
":",
"answer_end",
"}",
")",
"else",
":",
"with",
"open",
"(",
"path",
",",
"newline",
"=",
"''",
")",
"as",
"csvfile",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"csvfile",
",",
"delimiter",
"=",
"'\\t'",
")",
"line_num",
"=",
"0",
"for",
"row",
"in",
"reader",
":",
"qp_pairs",
".",
"append",
"(",
"{",
"'passage'",
":",
"row",
"[",
"1",
"]",
",",
"'question'",
":",
"row",
"[",
"0",
"]",
",",
"'id'",
":",
"line_num",
"}",
")",
"line_num",
"+=",
"1",
"return",
"qp_pairs"
] | 44.631579 | 19.736842 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.