hexsha
stringlengths 40
40
| size
int64 4
1.02M
| ext
stringclasses 8
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
209
| max_stars_repo_name
stringlengths 5
121
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 1
10
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
209
| max_issues_repo_name
stringlengths 5
121
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequencelengths 1
10
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
209
| max_forks_repo_name
stringlengths 5
121
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequencelengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 4
1.02M
| avg_line_length
float64 1.07
66.1k
| max_line_length
int64 4
266k
| alphanum_fraction
float64 0.01
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d864fea283fa92b4bd5e1f594830ca0f18e88c7d | 2,224 | py | Python | upstream/npc/hubconf.py | amberww/s3prl | d74784f80da2b5a84e64ff445e583163d215a3f9 | [
"MIT"
] | 3 | 2021-04-25T01:50:01.000Z | 2021-06-02T16:43:44.000Z | upstream/npc/hubconf.py | amberww/s3prl | d74784f80da2b5a84e64ff445e583163d215a3f9 | [
"MIT"
] | null | null | null | upstream/npc/hubconf.py | amberww/s3prl | d74784f80da2b5a84e64ff445e583163d215a3f9 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ upstream/npc/hubconf.py ]
# Synopsis [ the npc torch hubconf ]
# Author [ S3PRL ]
# Copyright [ Copyleft(c), Speech Lab, NTU, Taiwan ]
"""*********************************************************************************************"""
###############
# IMPORTATION #
###############
import os
import torch
#-------------#
from utility.download import _gdriveids_to_filepaths, _urls_to_filepaths
from .expert import UpstreamExpert as _UpstreamExpert
def npc_local(ckpt, *args, **kwargs):
"""
The model from local ckpt
ckpt (str): PATH
"""
assert os.path.isfile(ckpt)
return _UpstreamExpert(ckpt, *args, **kwargs)
def npc_gdriveid(ckpt, refresh=False, *args, **kwargs):
"""
The model from google drive id
ckpt (str): The unique id in the google drive share link
refresh (bool): whether to download ckpt/config again if existed
"""
return npc_local(_gdriveids_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
def npc_url(ckpt, refresh=False, *args, **kwargs):
"""
The model from URL
ckpt (str): URL
"""
return npc_local(_urls_to_filepaths(ckpt, refresh=refresh), *args, **kwargs)
def npc(refresh=False, *args, **kwargs):
"""
The default model
refresh (bool): whether to download ckpt/config again if existed
"""
return npc_360hr(refresh=refresh, *args, **kwargs)
def npc_360hr(refresh=False, *args, **kwargs):
"""
The npc standard model on 360hr
refresh (bool): whether to download ckpt/config again if existed
"""
kwargs['ckpt'] = 'https://www.dropbox.com/s/o4zpjz6xncbij8p/npc_default.ckpt?dl=0'
return npc_url(refresh=refresh, *args, **kwargs)
def npc_960hr(refresh=False, *args, **kwargs):
"""
The npc standard model on 960hr
refresh (bool): whether to download ckpt/config again if existed
"""
kwargs['ckpt'] = 'https://www.dropbox.com/s/7ep0v60ym136bpb/npc_960hr.ckpt?dl=0'
return npc_url(refresh=refresh, *args, **kwargs) | 32.231884 | 99 | 0.571942 |
f5f41957c7a2b1e32a19f3a825d607fcf690fb8c | 3,892 | py | Python | sdk/python/pulumi_azure_nextgen/datafactory/v20180601/get_integration_runtime.py | pulumi/pulumi-azure-nextgen | 452736b0a1cf584c2d4c04666e017af6e9b2c15c | [
"Apache-2.0"
] | 31 | 2020-09-21T09:41:01.000Z | 2021-02-26T13:21:59.000Z | sdk/python/pulumi_azure_nextgen/datafactory/v20180601/get_integration_runtime.py | pulumi/pulumi-azure-nextgen | 452736b0a1cf584c2d4c04666e017af6e9b2c15c | [
"Apache-2.0"
] | 231 | 2020-09-21T09:38:45.000Z | 2021-03-01T11:16:03.000Z | sdk/python/pulumi_azure_nextgen/datafactory/v20180601/get_integration_runtime.py | pulumi/pulumi-azure-nextgen | 452736b0a1cf584c2d4c04666e017af6e9b2c15c | [
"Apache-2.0"
] | 4 | 2020-09-29T14:14:59.000Z | 2021-02-10T20:38:16.000Z | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetIntegrationRuntimeResult',
'AwaitableGetIntegrationRuntimeResult',
'get_integration_runtime',
]
@pulumi.output_type
class GetIntegrationRuntimeResult:
"""
Integration runtime resource type.
"""
def __init__(__self__, etag=None, id=None, name=None, properties=None, type=None):
if etag and not isinstance(etag, str):
raise TypeError("Expected argument 'etag' to be a str")
pulumi.set(__self__, "etag", etag)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if properties and not isinstance(properties, dict):
raise TypeError("Expected argument 'properties' to be a dict")
pulumi.set(__self__, "properties", properties)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def etag(self) -> str:
"""
Etag identifies change in the resource.
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter
def id(self) -> str:
"""
The resource identifier.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def name(self) -> str:
"""
The resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def properties(self) -> Any:
"""
Integration runtime properties.
"""
return pulumi.get(self, "properties")
@property
@pulumi.getter
def type(self) -> str:
"""
The resource type.
"""
return pulumi.get(self, "type")
class AwaitableGetIntegrationRuntimeResult(GetIntegrationRuntimeResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetIntegrationRuntimeResult(
etag=self.etag,
id=self.id,
name=self.name,
properties=self.properties,
type=self.type)
def get_integration_runtime(factory_name: Optional[str] = None,
integration_runtime_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetIntegrationRuntimeResult:
"""
Integration runtime resource type.
:param str factory_name: The factory name.
:param str integration_runtime_name: The integration runtime name.
:param str resource_group_name: The resource group name.
"""
__args__ = dict()
__args__['factoryName'] = factory_name
__args__['integrationRuntimeName'] = integration_runtime_name
__args__['resourceGroupName'] = resource_group_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:datafactory/v20180601:getIntegrationRuntime', __args__, opts=opts, typ=GetIntegrationRuntimeResult).value
return AwaitableGetIntegrationRuntimeResult(
etag=__ret__.etag,
id=__ret__.id,
name=__ret__.name,
properties=__ret__.properties,
type=__ret__.type)
| 31.901639 | 156 | 0.634892 |
737de2eaa1d23ec2464b39dcd3edcc32f3444509 | 387 | py | Python | #9 Palindrome Number.py | medisean/leetcode | f218fb738fb2b57f5eea3795a0a02cf495561465 | [
"MIT"
] | null | null | null | #9 Palindrome Number.py | medisean/leetcode | f218fb738fb2b57f5eea3795a0a02cf495561465 | [
"MIT"
] | null | null | null | #9 Palindrome Number.py | medisean/leetcode | f218fb738fb2b57f5eea3795a0a02cf495561465 | [
"MIT"
] | null | null | null | #!/usr/bin/python3
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
s = str(x)
for i in range(int(len(s)/2)):
last = len(s) - i - 1
if s[i] != s[last]:
return False
return True
if __name__ == "__main__":
solution = Solution()
print(solution.isPalindrome(121)) | 24.1875 | 43 | 0.501292 |
b7cb87df69f374b5047e28a5d75f69c29597a51f | 5,151 | py | Python | x2paddle/core/fluid_code.py | aiyasin/X2Paddle | b37959f2ecdc09fdec7a38c01272126a7f3800e4 | [
"Apache-2.0"
] | null | null | null | x2paddle/core/fluid_code.py | aiyasin/X2Paddle | b37959f2ecdc09fdec7a38c01272126a7f3800e4 | [
"Apache-2.0"
] | null | null | null | x2paddle/core/fluid_code.py | aiyasin/X2Paddle | b37959f2ecdc09fdec7a38c01272126a7f3800e4 | [
"Apache-2.0"
] | 1 | 2021-02-22T09:05:44.000Z | 2021-02-22T09:05:44.000Z | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from x2paddle.core.graph import GraphNode
from x2paddle.core.util import *
import collections
import six
class Layer(object):
def __init__(self):
self.op = None
self.param_attr = dict()
self.inputs = dict()
self.output = None
self.is_custom_layer = False
self.use_fluid = False
def get_code(self):
layer_code = ""
if self.output is not None:
if isinstance(self.output, six.string_types):
layer_code = self.output + " = "
else:
layer_code = self.output.layer_name + " = "
if self.is_custom_layer:
layer_code = layer_code + self.op + "("
elif self.op == "=":
layer_code = layer_code
elif self.use_fluid:
layer_code = layer_code + "fluid." + self.op + "("
elif self.op == "full_like":
layer_code = layer_code + "paddle." + self.op + "("
else:
layer_code = layer_code + "fluid.layers." + self.op + "("
if isinstance(self.inputs, list):
in_list = "["
for input in self.inputs:
if isinstance(input, GraphNode):
if hasattr(input, "index"):
in_list += (
input.layer_name + "[{}]".format(input.index) + ", "
)
else:
in_list += (input.layer_name + ", ")
elif isinstance(input, six.string_types):
in_list += (input + ", ")
else:
raise Exception(
"Element of inputs should GraphNode or String")
in_list = in_list.strip(", ") + "], "
layer_code += in_list
elif isinstance(self.inputs, dict):
inputs = collections.OrderedDict(self.inputs)
for key, input in inputs.items():
if isinstance(input, GraphNode):
if hasattr(input, "index"):
layer_code = layer_code + key + "={}, ".format(
input.layer_name + "[{}]".format(input.index))
else:
layer_code = layer_code + key + "={}, ".format(
input.layer_name)
else:
layer_code = layer_code + key + "={}, ".format(input)
elif isinstance(self.inputs, GraphNode):
if hasattr(self.inputs, "index"):
layer_code += (
self.inputs.layer_name + "[{}]".format(self.inputs.index))
else:
layer_code += (self.inputs.layer_name)
if self.op != "=":
layer_code += ", "
elif isinstance(self.inputs, six.string_types):
layer_code += (self.inputs)
if self.op != "=":
layer_code += ", "
else:
raise Exception("Unknown type of inputs.")
param_attr = collections.OrderedDict(self.param_attr)
for key, value in param_attr.items():
if '\n' in str(value):
value = string(str(value).replace('\n', ','))
if str(key) == 'attr':
value = 'ParamAttr(' + str(value) + ')'
layer_code = layer_code + key + "={}, ".format(value)
layer_code = layer_code.strip(", ")
if self.op != "=":
layer_code += ")"
return layer_code
class FluidCode(object):
def __init__(self):
self.layers = list()
def add_layer(self,
op,
inputs,
output,
param_attr=None,
use_fluid=False,
is_custom_layer=False):
layer = Layer()
layer.op = op
layer.use_fluid = use_fluid
layer.is_custom_layer = is_custom_layer
if inputs is not None:
layer.inputs = inputs
layer.output = output
if param_attr is not None:
layer.param_attr = param_attr
self.layers.append(layer)
def add_note(self, note):
# note should be string
self.layers.append(note)
def clear(self):
self.layers = list()
def gen_codes(self):
codes = list()
for layer in self.layers:
if isinstance(layer, Layer):
codes.append(layer.get_code())
elif isinstance(layer, six.string_types):
codes.append(layer)
return codes
| 35.770833 | 80 | 0.522229 |
7c5d639b74b7f3c7dd8027a81da32eb5745667ef | 5,219 | py | Python | visual_search/server/server.py | tuan3w/visual_search | 62665d4ac58669bad8e7f5ffed18d2914ffa8b01 | [
"MIT"
] | 464 | 2017-03-10T18:29:56.000Z | 2022-03-26T08:52:38.000Z | visual_search/server/server.py | slothkong/visual_search | 4eb9eae6360eafde1b9249721dccd333057efdfe | [
"MIT"
] | 21 | 2017-03-14T02:43:32.000Z | 2020-06-11T14:49:11.000Z | visual_search/server/server.py | pranavramesh123/visual_search | d317dbfd309b26d1a50f24824ca93e405b36486f | [
"MIT"
] | 132 | 2017-03-10T19:24:26.000Z | 2022-02-04T12:35:49.000Z | #!/usr/bin/env python
from flask import Flask
from flask import request, jsonify, \
send_from_directory
import base64
import tensorflow as tf
from elasticsearch import Elasticsearch
from extractor import Extractor
from utils.im_util import read_img_blob
from es.ImFea_pb2 import ImFea, ImFeaArr,\
ImFeaBinArr, ImFeaBin
IMGS_PATH = './images/'
app = Flask(__name__, static_url_path='')
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
def load_model():
"""Load feature extractor model"""
# create feature extractor
weight_path = './models/vgg16.weights'
model_path = './models/vgg16_faster_rcnn_iter_490000.ckpt'
tfconfig = tf.ConfigProto(allow_soft_placement=True)
tfconfig.gpu_options.allow_growth = True
# init session
sess = tf.Session(config=tfconfig)
extractor = Extractor(model_path, weight_path, sess=sess)
return extractor
extractor = load_model()
es = Elasticsearch(hosts='http://elasticsearch:9200')
@app.route("/hello", methods=['GET'])
def hello():
return "Hello, world!"
@app.route("/extract_fea", methods=['GET', 'POST'])
def extract_fea():
imgStr = request.values.get('img')
if imgStr is None:
raise InvalidUsage('parameter "img" is missing', status_code=410)
try:
img = read_img_blob(imgStr)
except:
raise InvalidUsage('Invalid "img" param, must be a base64 string',
status_code=410)
fea = extractor.extract_imfea(img)
is_binary = request.values.get('is_binary')
if is_binary and is_binary == 'true':
fea = extractor.binarize_fea(fea)
fea_obj = ImFeaBin()
else:
fea_obj = ImFea()
fea_obj.f.extend(fea)
base64str = base64.b64encode(fea_obj.SerializeToString())
out = {}
out['fea'] = base64str
return jsonify(out)
@app.route("/get_tags", methods=['GET', 'POST'])
def get_tags():
"""get tags corresponding to a image"""
if not 'img' in request.files:
raise InvalidUsage('parameter "img" is missing', status_code=410)
try:
f = request.files.get('img')
img_str = f.read()
img = read_img_blob(img_str)
except:
raise InvalidUsage('Invalid "img" param, must be a blob string',
status_code=410)
tags = extractor.get_tags(img)
out = {}
out['tags'] = tags
return jsonify(out)
QUERY = """
{
"_source": ["im_src", "cl", "coords"],
"query": {
"function_score" : {
"query" : {
"match_all" : {
"boost" : 1.0
}
},
"functions" : [
{
"filter" : {
"match_all" : {
"boost" : 1.0
}
},
"script_score" : {
"script" : {
"inline" : "hamming_score",
"lang" : "native",
"params" : {
"f" : "bin_sigs",
"fea" : [##fea##],
"verbose" : true
}
}
}
}
],
"score_mode" : "sum",
"boost_mode" : "replace",
"max_boost" : 3.4028235E38,
"boost" : 1.0
}
}
}
"""
@app.route("/search", methods=['GET', 'POST'])
def search():
"""get tags corresponding to a image"""
if not 'img' in request.files:
raise InvalidUsage('parameter "img" is missing', status_code=410)
try:
f = request.files.get('img')
img_str = f.read()
img = read_img_blob(img_str)
except:
raise InvalidUsage('Invalid "img" param, must be a blob string',
status_code=410)
fea = extractor.extract_imfea(img)
fea = extractor.binarize_fea(fea)
fea_str = ','.join([str(int(t)) for t in fea])
query = QUERY.replace('##fea##', fea_str)
print(query)
result = es.search(index='im_data', doc_type='obj', body=query)
rs = []
if 'hits' in result and \
'hits' in result['hits']:
#distinct
all_imgs = set([])
hits = result['hits']['hits']
for hit in hits:
o = hit['_source']
o['score'] = hit['_score']
#update im_src
im_src = '/img/{}'.format(o['im_src'])
if not im_src in all_imgs:
o['im_src'] = im_src
all_imgs.add(im_src)
rs.append(o)
print all_imgs
out = {}
out['hits'] = rs
return jsonify(out)
@app.route('/static/<path:path>')
def send_static_files(path):
"static files"
return send_from_directory('static_data', path)
@app.route('/img/<path:path>')
def send_image(path):
"static files"
return send_from_directory(IMGS_PATH, path)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
| 26.095 | 74 | 0.587277 |
42ad869ec47f2d46073488aabc5de9df69df7c18 | 4,137 | py | Python | sekizai/templatetags/sekizai_tags.py | yakky/django-sekizai | 4869653f24e39070456c572624e5262824814d3b | [
"BSD-3-Clause"
] | 1 | 2016-02-13T01:00:30.000Z | 2016-02-13T01:00:30.000Z | sekizai/templatetags/sekizai_tags.py | sitkatech/django-sekizai | dab92a6bcaf6a0c1bc6ea43b3f685008ac5b51e1 | [
"BSD-3-Clause"
] | null | null | null | sekizai/templatetags/sekizai_tags.py | sitkatech/django-sekizai | dab92a6bcaf6a0c1bc6ea43b3f685008ac5b51e1 | [
"BSD-3-Clause"
] | null | null | null | from classytags.arguments import Argument, Flag
from classytags.core import Tag, Options
from classytags.parser import Parser
from django import template
from django.conf import settings
from django.utils.importlib import import_module
from sekizai.helpers import get_varname
register = template.Library()
def validate_context(context):
"""
Validates a given context.
Returns True if the context is valid.
Returns False if the context is invalid but the error should be silently
ignored.
Raises a TemplateSyntaxError if the context is invalid and we're in debug
mode.
"""
if get_varname() in context:
return True
if not settings.TEMPLATE_DEBUG:
return False
raise template.TemplateSyntaxError(
"You must enable the 'sekizai.context_processors.sekizai' template "
"context processor or use 'sekizai.context.SekizaiContext' to "
"render your templates."
)
def import_processor(import_path):
if '.' not in import_path:
raise TypeError("Import paths must contain at least one '.'")
module_name, object_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, object_name)
class SekizaiParser(Parser):
def parse_blocks(self):
super(SekizaiParser, self).parse_blocks()
self.blocks['nodelist'] = self.parser.parse()
class AddtoblockParser(Parser):
def parse_blocks(self):
name = self.kwargs['name'].var.token
self.blocks['nodelist'] = self.parser.parse(
('endaddtoblock', 'endaddtoblock %s' % name)
)
self.parser.delete_first_token()
class SekizaiTag(Tag):
def render(self, context):
if validate_context(context):
return super(SekizaiTag, self).render(context)
return ''
class RenderBlock(Tag):
name = 'render_block'
options = Options(
Argument('name'),
'postprocessor',
Argument('postprocessor', required=False, default=None, resolve=False),
parser_class=SekizaiParser,
)
def render_tag(self, context, name, postprocessor, nodelist):
if not validate_context(context):
return nodelist.render(context)
rendered_contents = nodelist.render(context)
varname = get_varname()
data = context[varname][name].render()
if postprocessor:
func = import_processor(postprocessor)
data = func(context, data, name)
return '%s\n%s' % (data, rendered_contents)
register.tag(RenderBlock)
class AddData(SekizaiTag):
name = 'add_data'
options = Options(
Argument('key'),
Argument('value'),
)
def render_tag(self, context, key, value):
varname = get_varname()
context[varname][key].append(value)
return ''
register.tag(AddData)
class WithData(SekizaiTag):
name = 'with_data'
options = Options(
Argument('name'),
'as',
Argument('variable', resolve=False),
blocks=[
('end_with_data', 'inner_nodelist'),
],
parser_class=SekizaiParser,
)
def render_tag(self, context, name, variable, inner_nodelist, nodelist):
rendered_contents = nodelist.render(context)
varname = get_varname()
data = context[varname][name]
context.push()
context[variable] = data
inner_contents = inner_nodelist.render(context)
context.pop()
return '%s\n%s' % (inner_contents, rendered_contents)
register.tag(WithData)
class Addtoblock(SekizaiTag):
name = 'addtoblock'
options = Options(
Argument('name'),
Flag('strip', default=False, true_values=['strip']),
parser_class=AddtoblockParser,
)
def render_tag(self, context, name, strip, nodelist):
rendered_contents = nodelist.render(context)
if strip:
rendered_contents = rendered_contents.strip()
varname = get_varname()
context[varname][name].append(rendered_contents)
return ""
register.tag(Addtoblock)
| 28.93007 | 79 | 0.648054 |
f0fa88f033b5ffc17d1d45e9c4725fb291e13a37 | 4,518 | py | Python | azure-iot-hub/azure/iot/hub/iothub_http_runtime_manager.py | anthonyvercolano/azure-iot-sdk-python | f54a3712c288406b0dfcaa2ffa02a13b1c9b6f32 | [
"MIT"
] | null | null | null | azure-iot-hub/azure/iot/hub/iothub_http_runtime_manager.py | anthonyvercolano/azure-iot-sdk-python | f54a3712c288406b0dfcaa2ffa02a13b1c9b6f32 | [
"MIT"
] | null | null | null | azure-iot-hub/azure/iot/hub/iothub_http_runtime_manager.py | anthonyvercolano/azure-iot-sdk-python | f54a3712c288406b0dfcaa2ffa02a13b1c9b6f32 | [
"MIT"
] | null | null | null | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .auth import ConnectionStringAuthentication, AzureIdentityCredentialAdapter
from .protocol.iot_hub_gateway_service_ap_is import IotHubGatewayServiceAPIs as protocol_client
class IoTHubHttpRuntimeManager(object):
"""A class to provide convenience APIs for IoTHub Http Runtime Manager operations,
based on top of the auto generated IotHub REST APIs
"""
def __init__(self, connection_string=None, host=None, auth=None):
"""Initializer for a Http Runtime Manager Service client.
After a successful creation the class has been authenticated with IoTHub and
it is ready to call the member APIs to communicate with IoTHub.
:param str connection_string: The IoTHub connection string used to authenticate connection
with IoTHub if we are using connection_str authentication. Default value: None
:param str host: The Azure service url if we are using token credential authentication.
Default value: None
:param str auth: The Azure authentication object if we are using token credential authentication.
Default value: None
:returns: Instance of the IoTHubHttpRuntimeManager object.
:rtype: :class:`azure.iot.hub.IoTHubHttpRuntimeManager`
"""
if connection_string is not None:
self.auth = ConnectionStringAuthentication(connection_string)
self.protocol = protocol_client(self.auth, "https://" + self.auth["HostName"])
else:
self.auth = auth
self.protocol = protocol_client(self.auth, "https://" + host)
@classmethod
def from_connection_string(cls, connection_string):
"""Classmethod initializer for a IoTHubHttpRuntimeManager Service client.
Creates IoTHubHttpRuntimeManager class from connection string.
After a successful creation the class has been authenticated with IoTHub and
it is ready to call the member APIs to communicate with IoTHub.
:param str connection_string: The IoTHub connection string used to authenticate connection
with IoTHub.
:rtype: :class:`azure.iot.hub.IoTHubHttpRuntimeManager`
"""
return cls(connection_string=connection_string)
@classmethod
def from_token_credential(cls, url, token_credential):
"""Classmethod initializer for a IoTHubHttpRuntimeManager Service client.
Creates IoTHubHttpRuntimeManager class from host name url and Azure token credential.
After a successful creation the class has been authenticated with IoTHub and
it is ready to call the member APIs to communicate with IoTHub.
:param str url: The Azure service url (host name).
:param str token_credential: The Azure token credential object.
:rtype: :class:`azure.iot.hub.IoTHubHttpRuntimeManager`
"""
host = url
auth = AzureIdentityCredentialAdapter(token_credential)
return cls(host=host, auth=auth)
def receive_feedback_notification(self):
"""This method is used to retrieve feedback of a cloud-to-device message.
:raises: `HttpOperationError<msrest.exceptions.HttpOperationError>`
if the HTTP response status is not in [200].
:returns: None.
"""
return self.protocol.cloud_to_device_messages.receive_feedback_notification()
def complete_feedback_notification(self, lock_token):
"""This method completes a feedback message.
:param str lock_token: Lock token.
:raises: `HttpOperationError<msrest.exceptions.HttpOperationError>`
if the HTTP response status is not in [200].
:returns: None.
"""
return self.protocol.cloud_to_device_messages.complete_feedback_notification(lock_token)
def abandon_feedback_notification(self, lock_token):
"""This method abandons a feedback message.
:param str lock_token: Lock token.
:raises: `HttpOperationError<msrest.exceptions.HttpOperationError>`
if the HTTP response status is not in [200].
:returns: None.
"""
return self.protocol.cloud_to_device_messages.abandon_feedback_notification(lock_token)
| 43.442308 | 105 | 0.687915 |
4e2fa657911e473e07f790232f59f9ec14665422 | 5,062 | py | Python | pyradar/Chapter08/pulse_train_ambiguity_example.py | mberkanbicer/software | 89f8004f567129216b92c156bbed658a9c03745a | [
"Apache-2.0"
] | 1 | 2020-12-18T04:07:54.000Z | 2020-12-18T04:07:54.000Z | pyradar/Chapter08/pulse_train_ambiguity_example.py | miltondsantos/software | d27375257b0260cad901837612fbca0174134229 | [
"Apache-2.0"
] | null | null | null | pyradar/Chapter08/pulse_train_ambiguity_example.py | miltondsantos/software | d27375257b0260cad901837612fbca0174134229 | [
"Apache-2.0"
] | null | null | null | """
Project: RadarBook
File: pulse_train_ambiguity_example.py
Created by: Lee A. Harrison
On: 1/24/2019
Created with: PyCharm
Copyright (C) 2019 Artech House ([email protected])
This file is part of Introduction to Radar Using Python and MATLAB
and can not be copied and/or distributed without the express permission of Artech House.
"""
import sys
from Chapter08.ui.AFTrain_ui import Ui_MainWindow
from numpy import linspace, meshgrid, finfo
from Libs.ambiguity.ambiguity_function import pulse_train
from PyQt5.QtWidgets import QApplication, QMainWindow
from matplotlib.backends.qt_compat import QtCore
from matplotlib.backends.backend_qt5agg import (FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
from matplotlib.figure import Figure
class PulseTrain(QMainWindow, Ui_MainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
# Connect to the input boxes, when the user presses enter the form updates
self.pulsewidth.returnPressed.connect(self._update_canvas)
self.pri.returnPressed.connect(self._update_canvas)
self.number_of_pulses.returnPressed.connect(self._update_canvas)
self.plot_type.currentIndexChanged.connect(self._update_canvas)
# Set up a figure for the plotting canvas
fig = Figure()
self.fig = fig
self.axes1 = fig.add_subplot(111)
self.my_canvas = FigureCanvas(fig)
# Add the canvas to the vertical layout
self.verticalLayout.addWidget(self.my_canvas)
self.addToolBar(QtCore.Qt.TopToolBarArea, NavigationToolbar(self.my_canvas, self))
# Update the canvas for the first display
self._update_canvas()
def _update_canvas(self):
"""
Update the figure when the user changes an input value
:return:
"""
# Get the parameters from the form
pulsewidth = float(self.pulsewidth.text())
pri = float(self.pri.text())
number_of_pulses = int(self.number_of_pulses.text())
plot_type = self.plot_type.currentText()
# Clear the axes for the updated plot
self.axes1.clear()
# Create the plots
if plot_type == 'Zero Doppler Cut':
# Set the time delay
time_delay = linspace(-number_of_pulses * pri, number_of_pulses * pri, 1000)
# Calculate the ambiguity function
ambiguity = pulse_train(time_delay, finfo(float).eps, pulsewidth, pri, number_of_pulses)
# Plot the ambiguity function
self.axes1.plot(time_delay, ambiguity, '')
# Set the x and y axis labels
self.axes1.set_xlabel("Time (s)", size=12)
self.axes1.set_ylabel("Relative Amplitude", size=12)
# Turn on the grid
self.axes1.grid(linestyle=':', linewidth=0.5)
elif plot_type == 'Zero Range Cut':
# Set the Doppler mismatch
doppler_frequency = linspace(-2.0 / pulsewidth, 2.0 / pulsewidth, 1000)
# Calculate the ambiguity function
ambiguity = pulse_train(finfo(float).eps, doppler_frequency, pulsewidth, pri, number_of_pulses)
# Plot the ambiguity function
self.axes1.plot(doppler_frequency, ambiguity, '')
# Set the x and y axis labels
self.axes1.set_xlabel("Doppler (Hz)", size=12)
self.axes1.set_ylabel("Relative Amplitude", size=12)
# Turn on the grid
self.axes1.grid(linestyle=':', linewidth=0.5)
elif plot_type == '2D Contour':
# Set the time delay
time_delay = linspace(-number_of_pulses * pri, number_of_pulses * pri, 500)
# Set the Doppler mismatch
doppler_frequency = linspace(-2.0 / pulsewidth, 2.0 / pulsewidth, 500)
# Create the grid
t, f = meshgrid(time_delay, doppler_frequency)
# Calculate the ambiguity function
ambiguity = pulse_train(t, f, pulsewidth, pri, number_of_pulses)
# Plot the ambiguity function
self.axes1.contour(t, f, ambiguity + finfo('float').eps, 30, cmap='jet', vmin=-0.2, vmax=1.0)
# Set the x and y axis labels
self.axes1.set_xlabel("Time (s)", size=12)
self.axes1.set_ylabel("Doppler (Hz)", size=12)
# Turn on the grid
self.axes1.grid(linestyle=':', linewidth=0.5)
# Set the plot title and labels
self.axes1.set_title('Pulse Train Ambiguity Function', size=14)
# Set the tick label size
self.axes1.tick_params(labelsize=12)
# Update the canvas
self.my_canvas.draw()
def start():
form = PulseTrain() # Set the form
form.show() # Show the form
def main():
app = QApplication(sys.argv) # A new instance of QApplication
form = PulseTrain() # Set the form
form.show() # Show the form
app.exec_() # Execute the app
if __name__ == '__main__':
main()
| 34.435374 | 107 | 0.642434 |
5724d8054b841fb1b79f098836e49676214a849f | 5,484 | py | Python | retdec/resource.py | s3rvac/retdec-python | 6360ecba75fae5420de2bf2ba63cf8a8c0e0c7cc | [
"MIT"
] | 102 | 2015-02-08T20:00:43.000Z | 2022-02-06T20:34:24.000Z | retdec/resource.py | s3rvac/retdec-python | 6360ecba75fae5420de2bf2ba63cf8a8c0e0c7cc | [
"MIT"
] | 5 | 2016-08-02T04:46:29.000Z | 2018-10-11T06:08:32.000Z | retdec/resource.py | s3rvac/retdec-python | 6360ecba75fae5420de2bf2ba63cf8a8c0e0c7cc | [
"MIT"
] | 24 | 2015-04-08T13:27:54.000Z | 2020-12-07T21:22:23.000Z | #
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <[email protected]> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Base class of all resources."""
import contextlib
import datetime
import os
import shutil
import time
class Resource:
"""Base class of all resources.
:param str id: Unique identifier of the resource.
:param retdec.conn.APIConnection conn: Connection to the API to be used for
sending API requests.
"""
#: Time interval after which we can update resource's state.
_STATE_UPDATE_INTERVAL = datetime.timedelta(seconds=0.5)
def __init__(self, id, conn):
self._id = id
self._conn = conn
# To prevent abuse of the API, we update the state of the resource only
# once in a while. To keep track whether we should perform an update,
# we store the date and time of the last update. By initializing it to
# the minimal representable date, we ensure that the resource gets
# updated upon the first call of a state-checking method, like
# has_finished().
# See the implementation of _state_should_be_updated() for more
# details.
self._last_updated = datetime.datetime.min
@property
def id(self):
"""Unique identifier of the resource."""
return self._id
def is_pending(self):
"""Is the resource in a pending state?
A resource is *pending* if it is scheduled to run but has not started
yet.
"""
self._update_state_if_needed()
return self._pending
def is_running(self):
"""Is the resource currently running?"""
self._update_state_if_needed()
return self._running
def has_finished(self):
"""Has the resource finished?"""
self._update_state_if_needed()
return self._finished
def has_succeeded(self):
"""Has the resource succeeded?"""
self._update_state_if_needed()
return self._finished
def has_failed(self):
"""Has the resource failed?
For finished resources, this is always the negation of
:func:`has_succeeded()`.
"""
self._update_state_if_needed()
return self._failed
def get_error(self):
"""Returns the reason why the resource failed.
If the resource has not failed, it returns ``None``.
"""
self._update_state_if_needed()
return self._error
def _update_state_if_needed(self):
"""Updates the state of the resource (if needed)."""
if self._state_should_be_updated():
self._update_state()
def _state_should_be_updated(self):
"""Should the state of the resource be updated?"""
# To prevent abuse of the API, update the status only once in a while.
now = datetime.datetime.now()
return (now - self._last_updated) > self._STATE_UPDATE_INTERVAL
def _wait_until_state_can_be_updated(self):
"""Waits until the state can be updated."""
time.sleep(self._STATE_UPDATE_INTERVAL.total_seconds())
def _update_state(self):
"""Updates the state of the resource."""
status = self._get_status()
self._pending = status['pending']
self._running = status['running']
self._finished = status['finished']
self._succeeded = status['succeeded']
self._failed = status['failed']
self._error = status['error']
self._last_updated = datetime.datetime.now()
return status
def _get_status(self):
"""Obtains and returns the current status of the resource."""
return self._conn.send_get_request('/{}/status'.format(self.id))
def _handle_failure(self, on_failure, *args):
"""Handles the situation where a resource failed to succeed.
:param callable on_failure: What should be done when the resource
failed?
If `on_failure` is ``None``, nothing is done when the resource failed.
Otherwise, it is called with `*args`. If the returned value is an
exception, it is raised.
"""
if on_failure is not None:
obj = on_failure(*args)
if isinstance(obj, Exception):
raise obj
def _get_file_contents(self, file_path, is_text_file):
"""Obtains the contents of a file from the given path.
:param str file_path: Path to the file to be downloaded.
:param bool is_text_file: Is it a text file or a binary file?
"""
with contextlib.closing(self._conn.get_file(file_path)) as file:
contents = file.read()
if is_text_file:
contents = contents.decode()
return contents
def _get_file_and_save_it(self, file_path, directory=None):
"""Obtains a file from `file_path` and saves it to `directory`.
:param str file_path: Path to the file to be downloaded.
:param str directory: Directory in which the file will be stored.
:returns: Path to the saved file (`str`).
If `directory` is ``None``, the current working directory is used.
"""
directory = directory or os.getcwd()
with contextlib.closing(self._conn.get_file(file_path)) as src:
dst_path = os.path.join(directory, src.name)
with open(dst_path, 'wb') as dst:
shutil.copyfileobj(src, dst)
return dst_path
| 34.062112 | 79 | 0.636214 |
5667327f44fd579d3b695d4e108a6127ad7f3326 | 3,141 | py | Python | openstack_dashboard/dashboards/admin/volumes/views.py | shhui/horizon | fd8cf6e31c07b147289bfb86c90133599eb2906e | [
"Apache-2.0"
] | null | null | null | openstack_dashboard/dashboards/admin/volumes/views.py | shhui/horizon | fd8cf6e31c07b147289bfb86c90133599eb2906e | [
"Apache-2.0"
] | null | null | null | openstack_dashboard/dashboards/admin/volumes/views.py | shhui/horizon | fd8cf6e31c07b147289bfb86c90133599eb2906e | [
"Apache-2.0"
] | null | null | null | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Admin views for managing volumes.
"""
from django.core.urlresolvers import reverse
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import tables
from openstack_dashboard.api import cinder
from openstack_dashboard.api import keystone
from openstack_dashboard.dashboards.admin.volumes \
import forms as project_forms
from openstack_dashboard.dashboards.admin.volumes \
import tables as project_tables
from openstack_dashboard.dashboards.project.volumes \
import tabs as project_tabs
from openstack_dashboard.dashboards.project.volumes \
.volumes import views as volume_views
class IndexView(tables.MultiTableView, project_tabs.VolumeTableMixIn):
table_classes = (project_tables.VolumesTable,
project_tables.VolumeTypesTable)
template_name = "admin/volumes/index.html"
def get_volumes_data(self):
volumes = self._get_volumes(search_opts={'all_tenants': True})
instances = self._get_instances(search_opts={'all_tenants': True})
self._set_attachments_string(volumes, instances)
# Gather our tenants to correlate against IDs
try:
tenants, has_more = keystone.tenant_list(self.request)
except Exception:
tenants = []
msg = _('Unable to retrieve volume project information.')
exceptions.handle(self.request, msg)
tenant_dict = SortedDict([(t.id, t) for t in tenants])
for volume in volumes:
tenant_id = getattr(volume, "os-vol-tenant-attr:tenant_id", None)
tenant = tenant_dict.get(tenant_id, None)
volume.tenant_name = getattr(tenant, "name", None)
return volumes
def get_volume_types_data(self):
try:
volume_types = cinder.volume_type_list(self.request)
except Exception:
volume_types = []
exceptions.handle(self.request,
_("Unable to retrieve volume types"))
return volume_types
class DetailView(volume_views.DetailView):
template_name = "admin/volumes/detail.html"
class CreateVolumeTypeView(forms.ModalFormView):
form_class = project_forms.CreateVolumeType
template_name = 'admin/volumes/create_volume_type.html'
success_url = 'horizon:admin:volumes:index'
def get_success_url(self):
return reverse(self.success_url)
| 34.9 | 78 | 0.713785 |
84608b947c43b89677a4b62c07b0ce79a5cc0cf7 | 13,697 | py | Python | multivitamin/data/response/response.py | gumgum/multivitamin | 11e2b8944fbe24d5f6f34d375d2cefa6be560be5 | [
"Apache-2.0"
] | 8 | 2019-05-08T20:27:41.000Z | 2021-04-19T15:17:22.000Z | multivitamin/data/response/response.py | gumgum/multivitamin | 11e2b8944fbe24d5f6f34d375d2cefa6be560be5 | [
"Apache-2.0"
] | 9 | 2019-05-17T19:16:50.000Z | 2022-03-11T23:46:55.000Z | multivitamin/data/response/response.py | gumgum/multivitamin | 11e2b8944fbe24d5f6f34d375d2cefa6be560be5 | [
"Apache-2.0"
] | 4 | 2019-05-07T18:00:51.000Z | 2019-06-22T02:35:51.000Z | import json
import traceback
import glog as log
from dataclasses import asdict
from multivitamin.data import Request
from multivitamin.data.response.io import AvroIO
from multivitamin.data.response.dtypes import (
ResponseInternal,
Region,
VideoAnn,
ImageAnn,
Footprint,
)
from multivitamin.data.response.utils import round_float
from multivitamin.media.file_retriever import FileRetriever
class Response():
def __init__(self, response_input=None, schema_registry_url=None):
""" Class for a Response object
2 cases for construction:
1) constructed from a request with a previous Response
2) constructing from a dictionary
Args:
input (Any): previous Response or dict
schema_registry_url (str): whether to use schema registry when serializing to bytes
"""
self._request = None
self._response_internal = None
self._schema_registry_url = schema_registry_url
self._tstamp2frameannsidx = {}
if isinstance(response_input, Request):
self._request = response_input
self._init_from_request()
elif isinstance(response_input, dict):
io = AvroIO(schema_registry_url)
if not io.is_valid_avro_doc(response_input):
raise ValueError("Input dict is incompatible with avro schema")
log.debug("Input dict is compatible with avro schema")
# unpack dictionary values into kwargs using ** operator
try:
self._response_internal = ResponseInternal(**response_input)
except Exception as e:
log.error("error unpacking prev_response_dict")
log.error(traceback.format_exc())
else:
log.debug("Initializing empty response")
self._response_internal = ResponseInternal()
self._init_tstamp2frameannsidx()
def to_dict(self):
"""Getter for response in the form of a dict
Returns:
dict: response as dict
"""
log.debug("Returning response as dictionary")
if self._request is not None:
if self._request.bin_encoding is True:
log.warning("self._request.bin_encoding is True but returning dictionary")
return asdict(self._response_internal)
def to_bytes(self, base64=False):
"""Getter for response in the form of bytes or base64 str
Args:
base64 (bool): flag for converting to base64 encoding
Returns:
bytes: response as bytes
"""
if self._request is not None:
base64 = self._request.base64_encoding
log.info("Using self._request to check base64_encoding flag")
log.debug(f"base64 encoding: {base64}")
log.debug("Returning response as binary")
try:
io = AvroIO(self._schema_registry_url)
return io.encode(asdict(self._response_internal), base64)
except Exception:
log.error("Error serializing response")
# what to do here?
raise Exception("Error serializing response")
@property
def data(self):
"""Convenience getter to return either dict or bytes depending on request
Returns:
Any: dict or bytes
"""
if self._request is None:
return self.to_dict()
if self._request.bin_encoding is False:
log.debug("Returning response as dictionary")
return self.to_dict()
return self.to_bytes(self._request.base64_encoding)
@property
def tracks(self):
"""Getter for returning tracks
Returns:
List[VideoAnn]: tracks
"""
return self._response_internal["media_annotation"]["tracks_summary"]
@tracks.setter
def tracks(self, tracks):
"""Setter for tracks
Args:
tracks (List[VideoAnn]): tracks
"""
self._response_internal["media_annotation"]["tracks_summary"] = tracks
@property
def frame_anns(self):
"""Getter for frames annotations
Returns:
List[ImageAnn]: frames ann
"""
return self._response_internal["media_annotation"]["frames_annotation"]
def has_frame_anns(self):
"""Bool check on whether there are frame anns
Returns:
bool: flag for existence of frame anns
"""
return len(self.frame_anns) > 0
def get_regions_from_tstamp(self, t):
"""Get regions for a timestamp
Args:
t (float): tstamp
Returns:
List[Region]: regions
"""
assert isinstance(t, float)
if t not in self._tstamp2frameannsidx:
return None
frame_anns_idx = self._tstamp2frameannsidx[t]
return self._response_internal["media_annotation"]["frames_annotation"][frame_anns_idx]["regions"]
@property
def request(self):
return self._request
@property
def url(self):
return self._response_internal["media_annotation"]["url"]
@url.setter
def url(self, url):
assert isinstance(url, str)
self._response_internal["media_annotation"]["url"] = url
@property
def url_original(self):
return self._response_internal["media_annotation"]["url_original"]
@url_original.setter
def url_original(self, url):
assert isinstance(url, str)
self._response_internal["media_annotation"]["url_original"] = url
@property
def media_summary(self):
return self._response_internal["media_annotation"]["media_summary"]
@property
def footprints(self):
return self._response_internal["media_annotation"]["codes"]
@property
def width(self):
return self._response_internal["media_annotation"]["w"]
@width.setter
def width(self, w):
assert isinstance(w, int)
self._response_internal["media_annotation"]["w"] = w
@property
def height(self):
return self._response_internal["media_annotation"]["h"]
@height.setter
def height(self, h):
assert isinstance(h, int)
self._response_internal["media_annotation"]["h"] = h
def get_timestamps_from_frames_ann(self):
return sorted(self._tstamp2frameannsidx.keys())
def get_timestamps(self, server=None):
"""Get timestamps from footprints. Option for querying on module name
Args:
server (str): module name
Returns:
List[float]: unique timestamps
"""
tstamps = []
for c in self._response_internal["media_annotation"]["codes"]:
if server:
if c["server"] != server:
continue
tstamps.extend([round_float(t) for t in c["tstamps"]])
return sorted(set(tstamps))
# Modifiers
def append_region(self, t, region):
"""Append a region given a timestamp.
If tstamp exists in frame_anns, appends region, otherwise, creates new ImageAnn
Args:
t (float): tstamp
region (Region): region
"""
assert isinstance(t, float)
assert isinstance(region, type(Region()))
log.debug(self._tstamp2frameannsidx)
if t in self._tstamp2frameannsidx:
log.debug(f"t: {t} in frame_anns, appending Region")
frame_anns_idx = self._tstamp2frameannsidx[t]
self._response_internal["media_annotation"]["frames_annotation"][frame_anns_idx]["regions"].append(region)
else:
log.debug(f"t: {t} NOT in frame_anns, appending ImageAnn")
ia = ImageAnn(t=t, regions=[region])
self._response_internal["media_annotation"]["frames_annotation"].append(ia)
self._tstamp2frameannsidx[t] = len(self.frame_anns) - 1
def append_regions(self, t, regions):
"""Append a list of regions given a timestamp
If tstamp exists in frame_anns, appends regions, otherwise, creates new ImageAnns
Args:
t (float): tstamp
region (Region): region
"""
assert isinstance(t, float)
assert isinstance(regions, list)
for region in regions:
assert isinstance(region, type(Region()))
if t in self._tstamp2frameannsidx:
log.debug(f"t: {t} in frame_anns, extending Regions")
frame_anns_idx = self._tstamp2frameannsidx[t]
self._response_internal["media_annotation"]["frames_annotation"][frame_anns_idx].extend(regions)
else:
log.debug(f"t: {t} NOT in frame_anns, appending ImageAnn")
ia = ImageAnn(t=t, regions=regions)
self._response_internal["media_annotation"]["frames_annotation"].append(ia)
self._tstamp2frameannsidx[t] = len(self.frame_anns) - 1
def append_footprint(self, footprint):
"""Append a footprint
Args:
footprint (Footprint): footprint
"""
assert isinstance(footprint, type(Footprint()))
self._response_internal["media_annotation"]["codes"].append(footprint)
def append_track(self, video_ann):
"""Append a track to tracks_summary
Args:
video_ann (VideoAnn): track
"""
assert isinstance(video_ann, type(VideoAnn()))
self._response_internal["media_annotation"]["tracks_summary"].append(video_ann)
def append_media_summary(self, video_ann):
"""Append a media_summary to media_summary section
Args:
video_ann (VideoAnn): media_summary
"""
assert isinstance(video_ann, type(VideoAnn()))
self._response_internal["media_annotation"]["media_summary"].append(video_ann)
def sort_image_anns_by_timestamp(self):
tmp = self._response_internal["media_annotation"]["frames_annotation"]
self._response_internal["media_annotation"]["frames_annotation"] = sorted(
tmp, key=lambda k: k["t"]
)
def sort_tracks_summary_by_timestamp(self):
tmp = self._response_internal["media_annotation"]["tracks_summary"]
self._response_internal["media_annotation"]["tracks_summary"] = sorted(
tmp, key=lambda k: k["t1"]
)
def _init_from_request(self):
"""Construct from a request.
Request object has a field for "prev_response", if not None,
convert prev_response into a Response
prev_responses can come in the following forms
1) prev_response_url
i) local file
ii) remote file
2) prev_response
a) binary
b) base64 binary string
c) dict
"""
log.debug("Constructing Response from Request")
if self._request.prev_response_url:
log.debug(f"Loading from prev_response_url: {self._request.prev_response_url}")
try:
file_retriever = FileRetriever(url=self._request.prev_response_url)
f = file_retriever.download(return_filelike=True)
self._request.prev_response = f.read().decode()
except:
log.error(traceback.format_exc())
if self._request.prev_response:
log.debug("Loading from prev_response")
prev_response_dict = None
if self._request.bin_encoding is True:
log.debug("bin_encoding is True")
io = AvroIO()
if isinstance(self._request.prev_response, str):
log.debug("prev_response is base64 encoded binary")
prev_response_dict = io.decode(
self._request.prev_response, use_base64=True, binary_flag=True
)
else:
log.debug("prev_response is in binary")
prev_response_dict = io.decode(
self._request.prev_response, use_base64=False, binary_flag=True
)
else:
if isinstance(self._request.prev_response, str):
log.debug("prev_response is a JSON str")
prev_response_dict = json.loads(self._request.prev_response)
elif isinstance(self._request.prev_response, dict):
log.debug("prev_response is a dict")
prev_response_dict = self._request.prev_response
else:
raise NotImplementedError("Intentionally not implemented--prev_response is not a JSON str or dict")
if prev_response_dict is None:
raise ValueError("error: prev_response_dict is None")
try:
self._response_internal = ResponseInternal(**prev_response_dict)
except Exception as e:
log.error("error unpacking prev_response_dict")
log.error(traceback.format_exc())
else:
log.debug("No prev_response, constructing empty response_internal")
self._response_internal = ResponseInternal()
if not self.url:
self.url = self._request.url
def _init_tstamp2frameannsidx(self):
"""If there is a previous response, we want to store the tstamp 2 frame_anns idx dict
"""
log.debug("Creating tstamp2frameannsidx")
log.debug(f"prev_response frame_anns: {self.frame_anns}")
for idx, image_ann in enumerate(self.frame_anns):
self._tstamp2frameannsidx[round_float(image_ann["t"])] = idx
log.debug(f"tstamp2frameannsidx: {self._tstamp2frameannsidx}")
| 35.392765 | 119 | 0.618895 |
33f6597017873e1747160dd2335c33ecd6b361e7 | 627 | py | Python | Python_Ex_vazio/ex077.py | matheusmiguelsa/Exerc-cios-de-Python | 53387266b747f79e67964356993b38c2267ac04a | [
"MIT"
] | null | null | null | Python_Ex_vazio/ex077.py | matheusmiguelsa/Exerc-cios-de-Python | 53387266b747f79e67964356993b38c2267ac04a | [
"MIT"
] | null | null | null | Python_Ex_vazio/ex077.py | matheusmiguelsa/Exerc-cios-de-Python | 53387266b747f79e67964356993b38c2267ac04a | [
"MIT"
] | null | null | null | tupla = (
'casa', 'quarto', 'apartamento', 'pescar', 'gosto', 'lol', 'corki',
'python', 'biologia', 'programacao',
'linux', 'casamento', 'noivado'
)
for tuplinhas in tupla:
print(f'\nNa palavra {tuplinhas} temos:', end=' ')
for letras in tuplinhas:
if letras.lower() in 'aeiou':
print(letras, end=' ')
'''if 'a' in tuplinhas:
print('a', end=' ')
if 'e' in tuplinhas:
print('e', end=' ')
if 'i' in tuplinhas:
print('i', end=' ')
if 'o' in tuplinhas:
print('o', end=' ')
if 'u' in tuplinhas:
print('u', end=' ')
print('\nFIM')''' | 29.857143 | 71 | 0.511962 |
b8c245198b326f17ac8aa053d68d36b660f36673 | 4,291 | py | Python | ddtrace/contrib/celery/utils.py | p7g/dd-trace-py | 141ac0ab6e9962e3b3bafc9de172076075289a19 | [
"Apache-2.0",
"BSD-3-Clause"
] | 308 | 2016-12-07T16:49:27.000Z | 2022-03-15T10:06:45.000Z | ddtrace/contrib/celery/utils.py | p7g/dd-trace-py | 141ac0ab6e9962e3b3bafc9de172076075289a19 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1,928 | 2016-11-28T17:13:18.000Z | 2022-03-31T21:43:19.000Z | ddtrace/contrib/celery/utils.py | p7g/dd-trace-py | 141ac0ab6e9962e3b3bafc9de172076075289a19 | [
"Apache-2.0",
"BSD-3-Clause"
] | 311 | 2016-11-27T03:01:49.000Z | 2022-03-18T21:34:03.000Z | from typing import Any
from typing import Dict
from weakref import WeakValueDictionary
from ddtrace.span import Span
from .constants import CTX_KEY
TAG_KEYS = frozenset(
[
("compression", "celery.compression"),
("correlation_id", "celery.correlation_id"),
("countdown", "celery.countdown"),
("delivery_info", "celery.delivery_info"),
("eta", "celery.eta"),
("exchange", "celery.exchange"),
("expires", "celery.expires"),
("hostname", "celery.hostname"),
("id", "celery.id"),
("priority", "celery.priority"),
("queue", "celery.queue"),
("reply_to", "celery.reply_to"),
("retries", "celery.retries"),
("routing_key", "celery.routing_key"),
("serializer", "celery.serializer"),
("timelimit", "celery.timelimit"),
# Celery 4.0 uses `origin` instead of `hostname`; this change preserves
# the same name for the tag despite Celery version
("origin", "celery.hostname"),
("state", "celery.state"),
]
)
def set_tags_from_context(span, context):
# type: (Span, Dict[str, Any]) -> None
"""Helper to extract meta values from a Celery Context"""
for key, tag_name in TAG_KEYS:
value = context.get(key)
# Skip this key if it is not set
if value is None or value == "":
continue
# Skip `timelimit` if it is not set (its default/unset value is a
# tuple or a list of `None` values
if key == "timelimit" and all(_ is None for _ in value):
continue
# Skip `retries` if its value is `0`
if key == "retries" and value == 0:
continue
span.set_tag(tag_name, value)
def attach_span(task, task_id, span, is_publish=False):
"""Helper to propagate a `Span` for the given `Task` instance. This
function uses a `WeakValueDictionary` that stores a Datadog Span using
the `(task_id, is_publish)` as a key. This is useful when information must be
propagated from one Celery signal to another.
DEV: We use (task_id, is_publish) for the key to ensure that publishing a
task from within another task does not cause any conflicts.
This mostly happens when either a task fails and a retry policy is in place,
or when a task is manually retried (e.g. `task.retry()`), we end up trying
to publish a task with the same id as the task currently running.
Previously publishing the new task would overwrite the existing `celery.run` span
in the `weak_dict` causing that span to be forgotten and never finished.
NOTE: We cannot test for this well yet, because we do not run a celery worker,
and cannot run `task.apply_async()`
"""
weak_dict = getattr(task, CTX_KEY, None)
if weak_dict is None:
weak_dict = WeakValueDictionary()
setattr(task, CTX_KEY, weak_dict)
weak_dict[(task_id, is_publish)] = span
def detach_span(task, task_id, is_publish=False):
"""Helper to remove a `Span` in a Celery task when it's propagated.
This function handles tasks where the `Span` is not attached.
"""
weak_dict = getattr(task, CTX_KEY, None)
if weak_dict is None:
return
# DEV: See note in `attach_span` for key info
try:
del weak_dict[(task_id, is_publish)]
except KeyError:
pass
def retrieve_span(task, task_id, is_publish=False):
"""Helper to retrieve an active `Span` stored in a `Task`
instance
"""
weak_dict = getattr(task, CTX_KEY, None)
if weak_dict is None:
return
else:
# DEV: See note in `attach_span` for key info
return weak_dict.get((task_id, is_publish))
def retrieve_task_id(context):
"""Helper to retrieve the `Task` identifier from the message `body`.
This helper supports Protocol Version 1 and 2. The Protocol is well
detailed in the official documentation:
http://docs.celeryproject.org/en/latest/internals/protocol.html
"""
headers = context.get("headers")
body = context.get("body")
if headers:
# Protocol Version 2 (default from Celery 4.0)
return headers.get("id")
else:
# Protocol Version 1
return body.get("id")
| 33.787402 | 90 | 0.638313 |
c3becdd11b9a8e8e8d317e6c0003a5f60f438bb9 | 2,470 | py | Python | discord/object.py | MinerChAI/discord.py | eeabb8ebb6eb5b6af2dea02c8d66c19c0e0e5dff | [
"MIT"
] | null | null | null | discord/object.py | MinerChAI/discord.py | eeabb8ebb6eb5b6af2dea02c8d66c19c0e0e5dff | [
"MIT"
] | null | null | null | discord/object.py | MinerChAI/discord.py | eeabb8ebb6eb5b6af2dea02c8d66c19c0e0e5dff | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2019 Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from . import utils
from .mixins import Hashable
class Object(Hashable):
"""Represents a generic Discord object.
The purpose of this class is to allow you to create 'miniature'
versions of data classes if you want to pass in just an ID. Most functions
that take in a specific data class with an ID can also take in this class
as a substitute instead. Note that even though this is the case, not all
objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received
in :issue:`strange order <21>` and when such events happened you would
receive this class rather than the actual data class. These cases are
extremely rare.
.. container:: operations
.. describe:: x == y
Checks if two objects are equal.
.. describe:: x != y
Checks if two objects are not equal.
.. describe:: hash(x)
Returns the object's hash.
Attributes
-----------
id: :class:`int`
The ID of the object.
"""
def __init__(self, id):
self.id = id
def __repr__(self):
return "<Object id=%r>" % self.id
@property
def created_at(self):
""":class:`datetime.datetime`: Returns the snowflake's creation time in UTC."""
return utils.snowflake_time(self.id)
| 32.933333 | 87 | 0.707692 |
ee143aefcbb6881123b8b113b62c44f377862faa | 1,391 | py | Python | setup.py | laundmo/multiton | 3609d1b6016ebb1845c5c5e4c3387ccb780b7176 | [
"MIT"
] | 1 | 2020-08-13T23:58:36.000Z | 2020-08-13T23:58:36.000Z | setup.py | laundmo/multiton | 3609d1b6016ebb1845c5c5e4c3387ccb780b7176 | [
"MIT"
] | null | null | null | setup.py | laundmo/multiton | 3609d1b6016ebb1845c5c5e4c3387ccb780b7176 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [ ]
setup_requirements = ['pytest-runner', ]
test_requirements = ['pytest>=3', ]
setup(
author="Laurin Schmidt",
author_email='[email protected]',
python_requires='>=3.6',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
description="A Multiton metaclass for preventing duplicate instances based on init values.",
install_requires=requirements,
license="MIT license",
long_description=readme + '\n\n' + history,
include_package_data=True,
keywords='multiton',
name='multiton',
packages=find_packages(include=['multiton', 'multiton.*']),
setup_requires=setup_requirements,
test_suite='tests',
tests_require=test_requirements,
url='https://github.com/laundmo/multiton',
version='0.2.3',
zip_safe=False,
)
| 28.979167 | 96 | 0.659957 |
4242fc8b8dc204332de4d2b727fbdaac7ab16aba | 2,664 | py | Python | webscrapbook/themes/default/locales/zh/messages.py | clach04/PyWebScrapBook | 310e8f20cc5337336875679246b9269265b4476a | [
"MIT"
] | 39 | 2019-04-10T18:07:40.000Z | 2022-02-07T07:11:30.000Z | webscrapbook/themes/default/locales/zh/messages.py | clach04/PyWebScrapBook | 310e8f20cc5337336875679246b9269265b4476a | [
"MIT"
] | 56 | 2019-05-07T23:29:14.000Z | 2022-02-24T10:33:43.000Z | webscrapbook/themes/default/locales/zh/messages.py | clach04/PyWebScrapBook | 310e8f20cc5337336875679246b9269265b4476a | [
"MIT"
] | 15 | 2019-06-12T05:16:43.000Z | 2022-01-16T13:24:11.000Z | bidi_dir = 'ltr'
#########################################################################
# scrapbook.cache
#########################################################################
# map.html
cache_index_toggle_all = '全部展開或收合'
cache_index_search_link_title = '搜尋'
cache_index_source_link_title = '來源連結'
# search.html
cache_search_title = '%book% :: 搜尋'
cache_search_view_in_map = '在索引頁中檢視'
cache_search_start = '查'
cache_search_help_label = '搜尋語法說明'
cache_search_help_desc = """\
• 輸入的關鍵詞會在標題、內文、評註中查找。
• 可用半形空白分隔要檢索的多個關鍵詞。例如「w3c organization」表示搜尋含有「w3c」及「organization」的項目 。
• 可用半形雙引號檢索完整關鍵詞,若關鍵詞包含半形雙引號,可用連續兩個半形雙引號表示。例如「"Tom ""loves"" Mary."」表示搜尋含有「Tom "loves" Mary.」的項目。
• 可用負號排除關鍵詞。例如「-virus」表示搜尋不含「virus」的項目。
• 可用「<命令>:<關鍵詞>」指定特殊的檢索條件,命令前可加負號表示排除或反向。可用命令如下:
• mc:之後的關鍵詞皆比對大小寫。加負號則反之。例如「mc: CIA FBI -mc: president」表示搜尋含有區分大小寫的「CIA」、「FBI」及不分大小寫的「president」的項目。
• re:之後的關鍵詞皆視為正規表示式。加負號則反之。例如「re: \\bcolou?r\\b -re: 1+1=2」表示搜尋匹配正規表示式「\\bcolou?r\\b」且含有關鍵詞「1+1=2」的項目。
• id:搜尋 ID 等同關鍵詞(或與正規表示式匹配)的項目。多次指定時以「或」連接。例如「id:2020 id:2021」表示搜尋 ID 為「2020」或「2021」的項目;「-id:2020」表示搜尋 ID 不為「2020」的項目。
• type:搜尋類型等同關鍵詞(或與正規表示式匹配)的項目。多次指定時以「或」連接。可用的類型有「」(網頁)、「bookmark」(書籤)、「file」(檔案)、「note」(筆記)等等。例如「type: type:bookmark」表示搜尋類型為網頁或書籤的項目。
• title:搜尋標題含有關鍵詞的項目。
• content:搜尋全文含有關鍵詞的項目。
• comment:搜尋評註含有關鍵詞的項目。
• tc:搜尋標題或評註含有關鍵詞的項目。
• tcc:搜尋標題、全文或評註含有關鍵詞的項目。
• index:搜尋索引檔含有關鍵詞的項目。
• source:搜尋原始網址含有關鍵詞的項目。
• icon:搜尋圖示網址含有關鍵詞的項目。
• charset:搜尋字集含有關鍵詞的項目。
• create:搜尋建立時間符合條件的項目。時間格式為 0-17 位數字,後面接負號(可略),再接 0-17 位數字,表示時間範圍的起始與結束。兩個 17 位數字表示本地時間的年(4 位數)、月(01-12)、日(01-31)、時(00-59)、分(00-59)、秒(00-59)、毫秒(000-999),省略的部分視為 0,唯結束時間全省略時視為「999...」。例如「create:2014-2015」表示 2014 年到 2015 年,「create:-201309」表示 2013 年九月以前,「create:20110825」表示 2011 年八月 25 日以後。
• modify:搜尋修改時間符合條件的項目。時間格式同 create。
• marked:搜尋強調標示的項目。
• locked:搜尋鎖定的項目。
• location:搜尋含有地理位置資訊的項目。
• file:搜尋檔名含有關鍵詞的項目。
• root:搜尋此 ID 項目下的子項目。多次指定時以「或」連接。
• book:搜尋指定剪貼簿(依名稱)中的項目。多次指定時以「或」連接。
• sort:將搜尋結果按指定方式排序,負號表示倒序。可填入 id、title、comment、file、content、source、type、create、modify。例如「sort:id -sort:modify」表示先按 ID 遞增排序再按修改時間遞減排序。
• limit:設定搜尋結果筆數限制。例如「limit:10」表示只呈現前 10 筆搜尋結果,「limit:-20」表示不呈現最後 20 筆搜尋結果,「limit:0」或「-limit:」表示移除之前設定的限制。"""
cache_search_result = '找到 %length% 筆結果:'
cache_search_result_named = '(%name%) 找到 %length% 筆結果:'
cache_search_sort_last_created = '最後建立'
cache_search_sort_last_modified = '最後修改'
cache_search_sort_title = '標題排序'
cache_search_sort_id = 'ID 排序'
#########################################################################
# WebScrapBook
#########################################################################
EditorDeleteAnnotationConfirm = '刪除這個批註嗎?'
| 44.4 | 290 | 0.661036 |
ba4207c06651f39cfdf21e70e8433cecac0b20f9 | 10,225 | py | Python | tests/test_dotfinder_chunking.py | kipolovnikov/cooltools | 986fe95f96978f669204226d99e3c0a6fd5be208 | [
"MIT"
] | 4 | 2018-12-24T10:37:25.000Z | 2021-12-16T08:02:22.000Z | tests/test_dotfinder_chunking.py | kipolovnikov/cooltools | 986fe95f96978f669204226d99e3c0a6fd5be208 | [
"MIT"
] | 1 | 2018-05-03T15:17:24.000Z | 2018-05-03T15:17:24.000Z | tests/test_dotfinder_chunking.py | kipolovnikov/cooltools | 986fe95f96978f669204226d99e3c0a6fd5be208 | [
"MIT"
] | 3 | 2018-12-12T04:53:05.000Z | 2020-05-15T10:13:50.000Z | # create a test for the chunking versions of 'get_adjusted_expected_tile_some_nans':
import numpy as np
import pandas as pd
import os.path as op
from cooltools import dotfinder
from cooltools.lib.numutils import LazyToeplitz
# adjust the path for data:
testdir = op.realpath(op.dirname(__file__))
# mock input data location:
mock_input = op.join(testdir, "data", "mock_inputs.npz")
mock_result = op.join(testdir, "data", "mock_res.csv.gz")
# load bunch of array from a numpy npz container:
arrays_loaded = np.load(mock_input)
# snippets of M_raw, M_ice, E_ice and v_ice are supposed
# to be there ...
mock_M_raw = arrays_loaded["mock_M_raw"]
mock_M_ice = arrays_loaded["mock_M_ice"]
mock_E_ice = arrays_loaded["mock_E_ice"]
mock_v_ice = arrays_loaded["mock_v_ice"]
# 1D expected extracted for tiling-tests:
mock_exp = LazyToeplitz(mock_E_ice[0, :])
# we need w-edge for tiling procedures:
w = 3
# p = 1
# kernel type: 'donut'
# # just a simple donut kernel for testing:
kernel = np.array(
[
[1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 1, 1, 1],
[1, 1, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 1, 1],
[1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 1, 1, 1],
]
)
# bin size:
# mock data were extracted
# from 20kb matrix:
b = 20000
# 2MB aroud diagonal to look at:
band = 2e6
# 1MB aroud diagonal to look at:
band_1 = 1e6
# start, stop for tiling procedures:
start, stop = 0, len(mock_M_raw)
# load mock results:
mock_res = (
pd.read_csv(mock_result)
.rename(columns={"row": "bin1_id", "col": "bin2_id"})
)
def test_adjusted_expected_tile_some_nans_and_diag_tiling():
print("Running tile some nans la_exp test + diag tiling")
# first, generate that locally-adjusted expected:
nnans = 1
band_1_idx = int(band_1 / b)
res_df = pd.DataFrame([])
for tile in dotfinder.diagonal_matrix_tiling(
start, stop, bandwidth=band_1_idx, edge=w
):
# let's keep i,j-part explicit here:
tilei, tilej = tile, tile
# define origin:
origin = (tilei[0], tilej[0])
# RAW observed matrix slice:
observed = mock_M_raw[slice(*tilei), slice(*tilej)]
# trying new expected function:
expected = mock_exp[slice(*tilei), slice(*tilej)]
# for diagonal chuynking/tiling tilei==tilej:
ice_weight = mock_v_ice[slice(*tilei)]
# that's the main working function from dotfinder:
res = dotfinder.get_adjusted_expected_tile_some_nans(
origin=origin,
observed=observed,
expected=expected,
bal_weights=ice_weight,
kernels={"donut": kernel, "footprint": np.ones_like(kernel)},
)
is_inside_band = res["bin1_id"] > (res["bin2_id"] - band_1_idx)
# new style, selecting good guys:
does_comply_nans = res["la_exp." + "footprint" + ".nnans"] < nnans
# so, selecting inside band and nNaNs compliant results and append:
res_df = res_df.append(
res[is_inside_band & does_comply_nans], ignore_index=True
)
# drop dups (from overlaping tiles), sort and reset index:
res_df = (
res_df
.drop_duplicates()
.sort_values(by=["bin1_id", "bin2_id"])
.reset_index(drop=True)
)
# prepare mock_data for comparison:
# get a subset of mock results (inside 1Mb band):
is_inside_band_1 = mock_res["bin1_id"] > (mock_res["bin2_id"] - band_1_idx)
mock_res_1 = mock_res[is_inside_band_1].reset_index(drop=True)
# apparently sorting is needed in this case:
mock_res_1 = (
mock_res_1
.drop_duplicates()
.sort_values(by=["bin1_id", "bin2_id"])
.reset_index(drop=True)
)
# ACTUAL TESTS:
# integer part of DataFrame must equals exactly:
assert res_df[["bin1_id", "bin2_id"]].equals(mock_res_1[["bin1_id", "bin2_id"]])
# compare floating point part separately:
assert np.isclose(
res_df["la_exp." + "donut" + ".value"],
mock_res_1["la_expected"],
equal_nan=True,
).all()
def test_adjusted_expected_tile_some_nans_and_square_tiling():
print("Running tile some nans la_exp test + square tiling")
# first, generate that locally-adjusted expected:
nnans = 1
band_idx = int(band / b)
res_df = pd.DataFrame([])
for tilei, tilej in dotfinder.square_matrix_tiling(
start, stop, step=40, edge=w, square=False
):
# define origin:
origin = (tilei[0], tilej[0])
# RAW observed matrix slice:
observed = mock_M_raw[slice(*tilei), slice(*tilej)]
# trying new expected function:
expected = mock_exp[slice(*tilei), slice(*tilej)]
# for diagonal chuynking/tiling tilei==tilej:
ice_weight_i = mock_v_ice[slice(*tilei)]
ice_weight_j = mock_v_ice[slice(*tilej)]
# that's the main working function from dotfinder:
res = dotfinder.get_adjusted_expected_tile_some_nans(
origin=origin,
observed=observed,
expected=expected,
bal_weights=(ice_weight_i, ice_weight_j),
kernels={"donut": kernel, "footprint": np.ones_like(kernel)},
# nan_threshold=1,
verbose=False,
)
is_inside_band = res["bin1_id"] > (res["bin2_id"] - band_idx)
# new style, selecting good guys:
does_comply_nans = res["la_exp." + "footprint" + ".nnans"] < nnans
# so, select inside band and nNaNs compliant results and append:
res_df = res_df.append(
res[is_inside_band & does_comply_nans], ignore_index=True
)
# drop dups (from overlaping tiles), sort and reset index:
res_df = (
res_df
.drop_duplicates()
.sort_values(by=["bin1_id", "bin2_id"])
.reset_index(drop=True)
)
# prepare mock_data for comparison:
# apparently sorting is needed in this case:
mock_res_sorted = (
mock_res
.drop_duplicates()
.sort_values(by=["bin1_id", "bin2_id"])
.reset_index(drop=True)
)
# ACTUAL TESTS:
# integer part of DataFrame must equals exactly:
assert res_df[["bin1_id", "bin2_id"]].equals(
mock_res_sorted[["bin1_id", "bin2_id"]]
)
# compare floating point part separately:
assert np.isclose(
res_df["la_exp." + "donut" + ".value"],
mock_res_sorted["la_expected"],
equal_nan=True,
).all()
def test_adjusted_expected_tile_some_nans_and_square_tiling_diag_band():
print("Running tile some nans la_exp test + square tiling + diag band")
# # Essentially, testing this function:
# def chrom_chunk_generator_s(chroms, w, band):
# for chrom in chroms:
# chr_start, chr_stop = the_c.extent(chrom)
# for tilei, tilej in square_matrix_tiling(chr_start, chr_stop, step, w):
# # check if a given tile intersects with
# # with the diagonal band of interest ...
# diag_from = tilej[0] - tilei[1]
# diag_to = tilej[1] - tilei[0]
# #
# band_from = 0
# band_to = band
# # we are using this >2w trick to exclude
# # tiles from the lower triangle from calculations ...
# if (min(band_to,diag_to) - max(band_from,diag_from)) > 2*w:
# yield chrom, tilei, tilej
# first, generate that locally-adjusted expected:
nnans = 1
band_idx = int(band / b)
res_df = pd.DataFrame([])
for tilei, tilej in dotfinder.square_matrix_tiling(
start, stop, step=40, edge=w, square=False
):
# check if a given tile intersects with
# with the diagonal band of interest ...
diag_from = tilej[0] - tilei[1]
diag_to = tilej[1] - tilei[0]
#
band_from = 0
band_to = band_idx
# we are using this >2w trick to exclude
# tiles from the lower triangle from calculations ...
if (min(band_to, diag_to) - max(band_from, diag_from)) > 2 * w:
# define origin:
origin = (tilei[0], tilej[0])
# RAW observed matrix slice:
observed = mock_M_raw[slice(*tilei), slice(*tilej)]
# trying new expected function:
expected = mock_exp[slice(*tilei), slice(*tilej)]
# for diagonal chuynking/tiling tilei==tilej:
ice_weight_i = mock_v_ice[slice(*tilei)]
ice_weight_j = mock_v_ice[slice(*tilej)]
# that's the main working function from dotfinder:
res = dotfinder.get_adjusted_expected_tile_some_nans(
origin=origin,
observed=observed,
expected=expected,
bal_weights=(ice_weight_i, ice_weight_j),
kernels={"donut": kernel, "footprint": np.ones_like(kernel)},
# nan_threshold=1,
verbose=False,
)
is_inside_band = res["bin1_id"] > (res["bin2_id"] - band_idx)
# new style, selecting good guys:
does_comply_nans = res["la_exp." + "footprint" + ".nnans"] < nnans
# so, select inside band and nNaNs compliant results and append:
res_df = res_df.append(
res[is_inside_band & does_comply_nans], ignore_index=True
)
# sort and reset index, there shouldn't be any duplicates now:
res_df = (
res_df
.drop_duplicates()
.sort_values(by=["bin1_id", "bin2_id"])
.reset_index(drop=True)
)
# prepare mock_data for comparison:
# apparently sorting is needed in this case:
mock_res_sorted = (
mock_res
.drop_duplicates()
.sort_values(by=["bin1_id", "bin2_id"])
.reset_index(drop=True)
)
# ACTUAL TESTS:
# integer part of DataFrame must equals exactly:
assert res_df[["bin1_id", "bin2_id"]].equals(
mock_res_sorted[["bin1_id", "bin2_id"]]
)
# compare floating point part separately:
assert np.isclose(
res_df["la_exp." + "donut" + ".value"],
mock_res_sorted["la_expected"],
equal_nan=True,
).all()
| 35.380623 | 85 | 0.609095 |
0df406444db76855a9e03dbfe44dcc70c57cc35e | 2,906 | py | Python | h2o-hadoop-common/tests_fault_tolerance/python/test_grid_reload.py | sergeiten/h2o-3 | 6ba1bb793dc702dbad7638f0864b85757a2ffd19 | [
"Apache-2.0"
] | 1 | 2021-01-30T22:19:48.000Z | 2021-01-30T22:19:48.000Z | h2o-hadoop-common/tests_fault_tolerance/python/test_grid_reload.py | sergeiten/h2o-3 | 6ba1bb793dc702dbad7638f0864b85757a2ffd19 | [
"Apache-2.0"
] | null | null | null | h2o-hadoop-common/tests_fault_tolerance/python/test_grid_reload.py | sergeiten/h2o-3 | 6ba1bb793dc702dbad7638f0864b85757a2ffd19 | [
"Apache-2.0"
] | null | null | null | from __future__ import print_function
import sys
import os
import time
sys.path.insert(1, os.path.join("..", "..", "..", "h2o-py"))
from tests import pyunit_utils
import fault_tolerance_utils as utils
import h2o
from h2o.grid.grid_search import H2OGridSearch
from h2o.estimators.gbm import H2OGradientBoostingEstimator
import unittest
class GridReloadTest(unittest.TestCase):
def test_frame_reload(self):
name_node = pyunit_utils.hadoop_namenode()
work_dir = "hdfs://%s%s" % (name_node, utils.get_workdir())
dataset = "/datasets/iris_wheader.csv"
ntrees_opts = [100, 120, 130, 140]
learn_rate_opts = [0.01, 0.02, 0.03, 0.04]
grid_size = len(ntrees_opts) * len(learn_rate_opts)
print("max models %s" % grid_size)
grid_id = "grid_ft_resume"
hyper_parameters = {
"learn_rate": learn_rate_opts,
"ntrees": ntrees_opts
}
cluster_1_name = "grid1-py"
try:
cluster_1 = utils.start_cluster(cluster_1_name)
h2o.connect(url=cluster_1)
train = h2o.import_file(path="hdfs://%s%s" % (name_node, dataset))
grid = H2OGridSearch(
H2OGradientBoostingEstimator,
grid_id=grid_id,
hyper_params=hyper_parameters,
recovery_dir=work_dir
)
print("starting initial grid and sleeping...")
grid.start(x=list(range(4)), y=4, training_frame=train)
grid_in_progress = None
times_waited = 0
while (times_waited < 20) and (grid_in_progress is None or len(grid_in_progress.model_ids) == 0):
time.sleep(5) # give it tome to train some models
times_waited += 1
try:
grid_in_progress = h2o.get_grid(grid_id)
except IndexError:
print("no models trained yet")
print("done sleeping")
h2o.connection().close()
finally:
utils.stop_cluster(cluster_1_name)
cluster_2_name = "grid2-py"
try:
cluster_2 = utils.start_cluster(cluster_2_name)
h2o.connect(url=cluster_2)
loaded = h2o.load_grid("%s/%s" % (work_dir, grid_id), load_params_references=True)
print("models after first run:")
for x in sorted(loaded.model_ids):
print(x)
loaded.resume()
print("models after second run:")
for x in sorted(loaded.model_ids):
print(x)
print("Newly grained grid has %d models" % len(loaded.model_ids))
self.assertEqual(len(loaded.model_ids), grid_size, "The full grid was not trained.")
h2o.connection().close()
finally:
utils.stop_cluster(cluster_2_name)
if __name__ == '__main__':
unittest.main()
| 36.78481 | 109 | 0.593599 |
7d2524e97e053fccb343b2bd2de3b71613be093f | 15,357 | py | Python | src/menubar.py | Mirko-r/Notepy | d6de39145b6597d1cae32df0fea1a2fbd92a7457 | [
"MIT"
] | 12 | 2021-06-20T14:51:44.000Z | 2021-11-15T09:51:48.000Z | src/menubar.py | Mirko-r/Notepy | d6de39145b6597d1cae32df0fea1a2fbd92a7457 | [
"MIT"
] | 2 | 2021-09-23T14:07:36.000Z | 2021-09-24T14:58:41.000Z | src/menubar.py | Mirko-r/Notepy | d6de39145b6597d1cae32df0fea1a2fbd92a7457 | [
"MIT"
] | 2 | 2021-07-17T07:00:41.000Z | 2021-07-17T11:17:30.000Z | import tkinter as tk
import os
import re
from tkinter.colorchooser import askcolor
from src.syntax_highlighting import SyntaxHighlighting
from time import sleep
class Menubar():
# initialising the menu bar of editor
def __init__(self, parent):
self._parent = parent
self.syntax = parent.syntax_highlighter
self.ptrn = r'[^\/]+$'
font_specs = ('Droid Sans Fallback', 12)
# setting up basic features in menubar
menubar = tk.Menu(
parent.master,
font=font_specs,
fg=parent.menu_fg,
bg=parent.menu_bg,
activeforeground= parent.menubar_fg_active,
activebackground= parent.menubar_bg_active,
activeborderwidth=0,
bd=0)
parent.master.config(menu=menubar)
self._menubar = menubar
# adding features file dropdown in menubar
file_dropdown = tk.Menu(menubar, font=font_specs, tearoff=0)
file_dropdown.add_command(
label='Load Previous File',
accelerator='Ctrl+P',
command=parent.load_previous_file)
# new file creation feature
file_dropdown.add_command(
label='New File',
accelerator='Ctrl+N',
command=parent.new_file)
# open file feature
file_dropdown.add_command(
label='Open File',
accelerator='Ctrl+O',
command=parent.open_file)
# save file feature
file_dropdown.add_command(
label='Save',
accelerator='Ctrl+S',
command=parent.save)
# Save as feature
file_dropdown.add_command(
label='Save As',
accelerator='Ctrl+Shift+S',
command=parent.save_as)
# exit feature
file_dropdown.add_separator()
file_dropdown.add_command(
label='Exit',
command=parent.on_closing)
# adding featues to settings dropdown in menubar
# Edit settings feature
settings_dropdown = tk.Menu(menubar, font=font_specs, tearoff=0)
settings_dropdown.add_command(
label='Edit Settings',
command=parent.open_settings_file)
# reset settings feature
settings_dropdown.add_command(
label='Reset Settings to Default',
command=parent.reset_settings_file)
#view dropdown menu
view_dropdown = tk.Menu(menubar, font=font_specs, tearoff=0)
view_dropdown.add_command(
label='Toggle Menu Bar',
accelerator='Alt',
command=self.hide_menu)
view_dropdown.add_command(
label='Hide Status Bar',
command=parent.hide_status_bar)
view_dropdown.add_command(
label='Toggle Line Numbers',
accelerator='Ctrl+Shift+L',
command=parent.toggle_linenumbers)
view_dropdown.add_command(
label='Toggle Text Border',
command=self.toggle_text_border)
view_dropdown.add_command(
label='Shrink/Enlarge Horizontal Scrollbar',
command=self.toggle_scroll_x)
view_dropdown.add_command(
label='Shrink/Enlarge Vertical Scrollbar',
command=self.toggle_scroll_y)
view_dropdown.add_command(
label='Destroy Horizontal Scrollbar',
command=self._parent.scrollx.forget)
view_dropdown.add_command(label='Destroy Vertical Scrollbar',
command=self._parent.scrolly.forget)
view_dropdown.add_command(
label='Enter Quiet Mode',
accelerator='Ctrl+Q',
command=self.enter_quiet_mode)
#tools dropdown menu
tools_dropdown = tk.Menu(menubar, font=font_specs, tearoff=0)
tools_dropdown.add_command(
label='Search and Replace',
accelerator='Ctrl+F',
command=parent.show_find_window)
tools_dropdown.add_command(
label='Open Color Selector',
accelerator='Ctrl+M',
command=self.open_color_picker)
#theme dropdown menu
theme_dropdown = tk.Menu(menubar, font=font_specs, tearoff=0)
theme_dropdown.add_command(
label='Dark Heart',
command=self.syntax.syntax_and_themes.load_darkheart)
theme_dropdown.add_command(
label='Dracula',
command=self.syntax.syntax_and_themes.load_dracula)
theme_dropdown.add_command(
label='Desert',
command=self.syntax.syntax_and_themes.load_desert)
theme_dropdown.add_command(
label='Githubly',
command=self.syntax.syntax_and_themes.load_githubly)
theme_dropdown.add_command(
label='Gruvbox',
command=self.syntax.syntax_and_themes.load_gruvbox)
theme_dropdown.add_command(
label='Material',
command=self.syntax.syntax_and_themes.load_material)
theme_dropdown.add_command(
label='Monokai',
command=self.syntax.syntax_and_themes.load_monokai)
theme_dropdown.add_command(
label='Monokai Pro',
command=self.syntax.syntax_and_themes.load_monokai_pro)
theme_dropdown.add_command(
label='Pumpkin',
command=self.syntax.syntax_and_themes.load_pumpkin)
theme_dropdown.add_command(
label='Rust',
command=self.syntax.syntax_and_themes.load_rust)
theme_dropdown.add_command(
label='Solarized',
command=self.syntax.syntax_and_themes.load_solarized)
theme_dropdown.add_command(
label='Tokyo night',
command=self.syntax.syntax_and_themes.load_tokyo)
syntax_dropdown = tk.Menu(menubar, font=font_specs, tearoff=0)
syntax_dropdown.add_command(
label='Batch',
command=self.syntax.syntax_and_themes.load_batch_syntax)
syntax_dropdown.add_command(
label='C',
command=self.syntax.syntax_and_themes.load_c_syntax)
syntax_dropdown.add_command(
label='C++',
command=self.syntax.syntax_and_themes.load_cpp_syntax)
syntax_dropdown.add_command(
label="C#",
command=self.syntax.syntax_and_themes.load_csharp_syntax)
syntax_dropdown.add_command(
label='CoffeeScript',
command=self.syntax.syntax_and_themes.load_coffeescript_syntax)
syntax_dropdown.add_command(
label='CSS',
command=self.syntax.syntax_and_themes.load_css_syntax)
syntax_dropdown.add_command(
label='Dart',
command=self.syntax.syntax_and_themes.load_dart_syntax)
syntax_dropdown.add_command(
label='Dockerfile',
command=self.syntax.syntax_and_themes.load_docker_syntax)
syntax_dropdown.add_command(
label='Haskell',
command=self.syntax.syntax_and_themes.load_haskell_syntax)
syntax_dropdown.add_command(
label='HTML/Django',
command=self.syntax.syntax_and_themes.load_html_syntax)
syntax_dropdown.add_command(
label='JavaScript',
command=self.syntax.syntax_and_themes.load_javascript_syntax)
syntax_dropdown.add_command(
label='Java',
command=self.syntax.syntax_and_themes.load_java_syntax)
syntax_dropdown.add_command(
label='Go',
command=self.syntax.syntax_and_themes.load_go_syntax)
syntax_dropdown.add_command(
label='Markdown',
command=self.syntax.syntax_and_themes.load_markdown_syntax)
syntax_dropdown.add_command(
label='Nim',
command=self.syntax.syntax_and_themes.load_nim_syntax)
syntax_dropdown.add_command(
label='Python3',
command=self.syntax.syntax_and_themes.load_python3_syntax)
syntax_dropdown.add_command(
label='Rust',
command=self.syntax.syntax_and_themes.load_rust_syntax)
syntax_dropdown.add_command(
label='SQL',
command=self.syntax.syntax_and_themes.load_sql_syntax)
syntax_dropdown.add_command(
label='Swift',
command=self.syntax.syntax_and_themes.load_swift_syntax)
syntax_dropdown.add_command(
label='Yaml',
command=self.syntax.syntax_and_themes.load_yaml_syntax)
build_dropdown = tk.Menu(menubar, font=font_specs, tearoff=0)
build_dropdown.add_command(
label='Build',
command=self.build)
build_dropdown.add_command(
label='Run',
accelerator='Ctrl+R',
command=self.run)
build_dropdown.add_command(
label='Build+Run',
command=self.build_run)
# menubar add buttons
menubar.add_cascade(label='File', menu=file_dropdown)
menubar.add_cascade(label='View', menu=view_dropdown)
menubar.add_cascade(label='Settings', menu=settings_dropdown)
menubar.add_cascade(label='Tools', menu=tools_dropdown)
menubar.add_cascade(label='Syntax', menu=syntax_dropdown)
menubar.add_cascade(label='Themes', menu=theme_dropdown)
menubar.add_cascade(label='Build Options', menu=build_dropdown)
self.menu_fields = [field for field in (
file_dropdown, view_dropdown, syntax_dropdown, build_dropdown,
settings_dropdown, tools_dropdown, theme_dropdown)]
# Settings reconfiguration function
def reconfigure_settings(self):
settings = self._parent.loader.load_settings_data()
for field in self.menu_fields:
field.configure(
bg=self._parent.menu_bg,
fg=self._parent.menu_fg,
activeforeground=self._parent.menubar_fg_active,
activebackground=self._parent.menubar_bg_active,
background = self._parent.bg_color,
)
self._menubar.configure(
bg=self._parent.menu_bg,
fg=self._parent.menu_fg,
background = self._parent.bg_color,
activeforeground= self._parent.menubar_fg_active,
activebackground = self._parent.menubar_bg_active,
)
# color to different text tye can be set here
def open_color_picker(self):
return askcolor(title='Color Menu', initialcolor='#d5c4a1')[1]
def toggle_text_border(self):
settings = self._parent.loader.load_settings_data()
border_status = settings['textarea_border']
if border_status == 0:
self._parent.textarea.configure(bd=0.5)
settings['textarea_border'] = 0.5
elif border_status > 0:
self._parent.textarea.configure(bd=0)
settings['textarea_border'] = 0
self._parent.loader.store_settings_data(settings)
def toggle_scroll_x(self):
settings = self._parent.loader.load_settings_data()
scrollx_width = settings['horizontal_scrollbar_width']
if scrollx_width > 0:
self._parent.scrollx.configure(width=0)
settings['horizontal_scrollbar_width'] = 0
elif scrollx_width == 0:
self._parent.scrollx.configure(width=8)
settings['horizontal_scrollbar_width'] = 8
self._parent.loader.store_settings_data(settings)
def toggle_scroll_y(self):
settings = self._parent.loader.load_settings_data()
scrolly_width = settings['vertical_scrollbar_width']
if scrolly_width > 0:
self._parent.scrolly.configure(width=0)
settings['vertical_scrollbar_width'] = 0
elif scrolly_width == 0:
self._parent.scrolly.configure(width=8)
settings['vertical_scrollbar_width'] = 8
self._parent.loader.store_settings_data(settings)
# quiet mode is defined here
def enter_quiet_mode(self):
self._parent.enter_quiet_mode()
# hiding the menubar
def hide_menu(self):
self._parent.master.config(menu='')
# display the menubar
def show_menu(self):
self._parent.master.config(menu=self._menubar)
def base_cmd(self, command):
cmd = None
if self._parent.operating_system == 'Windows':
cmd = f'start cmd.exe @cmd /k {command}'
elif self._parent.operating_system == 'Linux':
cmd = f"gnome-terminal -- bash -c '{command}; read'"
file_from_path = re.search(self.ptrn, self._parent.filename)
filename = file_from_path.group(0)
file_path = self._parent.filename[:-len(filename)]
os.chdir(file_path)
if cmd:
os.system(cmd)
else:
print('cmd went unassigned!')
def build(self):
try:
file_from_path = re.search(self.ptrn, self._parent.filename)
filename = file_from_path.group(0)
if filename[-3:] == '.go':
self.base_cmd(f'go build {self._parent.filename}')
elif filename[-2:] == '.c':
compiled_name = filename[:-2]
self.base_cmd(f'gcc {filename} -o {compiled_name}')
elif filename[-4:] == '.cpp':
compiled_name = filename[:-4]
self.base_cmd(f'g++ -o {compiled_name} {filename}')
elif filename[-5:] == '.java':
compiled_name = filename[:-5]
self.base_cmd(f'javac {filename}')
elif filename[-3:] == '.rs':
self.base_cmd(f'rustc {filename}')
elif filename[-3:] == '.hs':
compiled_name = filename[:-3]
self.base_cmd(f'ghc -o {compiled_name} {filename}')
else:
self._parent.statusbar.update_status('cant build')
except TypeError:
self._parent.statusbar.update_status('cant build')
def run(self, *args):
try:
file_from_path = re.search(self.ptrn, self._parent.filename)
filename = file_from_path.group(0)
if filename[-3:] == '.py':
self.base_cmd(f'python {self._parent.filename}')
elif filename[-5:] == '.html':
self.base_cmd(f'{self._parent.browser} {filename}')
elif filename[-3:] == '.js':
self.base_cmd(f'node {self._parent.filename}')
elif filename[-3:] == '.go':
self.base_cmd(f'go run {self._parent.filename}')
elif filename[-2:] == '.c':
compiled_name = filename[:-2]
self.base_cmd(f'{compiled_name}')
elif filename[-4:] == '.cpp':
compiled_name = filename[:-4]
self.base_cmd(f'{compiled_name}')
elif filename[-5:] == '.java':
compiled_name = filename[:-5]
self.base_cmd(f'java {compiled_name}')
elif filename[-3:] == '.rs':
compiled_name = filename[:-3]
self.base_cmd(f'{compiled_name}')
elif filename[-4:] == '.nim':
self.base_cmd(f'nim c -r {filename}')
elif filename[-3:] == '.hs':
compiled_name = filename[:-3]
self.base_cmd(f'{compiled_name}')
else:
self._parent.statusbar.update_status('no python')
except TypeError as e:
print(e)
self._parent.statusbar.update_status('no file run')
def build_run(self):
self.build()
sleep(.5)
self.run()
| 39.276215 | 74 | 0.620824 |
b036f78879dfbc60611c67248d3a0709dbdc0795 | 1,452 | py | Python | examples/benchmark.py | alvistack/ionrock-cachecontrol | 09992a140edca2602cf8230370fc8b28566a069b | [
"Apache-2.0"
] | 353 | 2015-01-03T11:07:43.000Z | 2022-03-01T10:24:29.000Z | examples/benchmark.py | alvistack/ionrock-cachecontrol | 09992a140edca2602cf8230370fc8b28566a069b | [
"Apache-2.0"
] | 190 | 2015-01-07T10:00:49.000Z | 2022-02-23T19:04:03.000Z | examples/benchmark.py | alvistack/ionrock-cachecontrol | 09992a140edca2602cf8230370fc8b28566a069b | [
"Apache-2.0"
] | 108 | 2015-01-05T19:17:33.000Z | 2022-02-27T20:02:18.000Z | # SPDX-FileCopyrightText: 2015 Eric Larson
#
# SPDX-License-Identifier: Apache-2.0
import sys
import requests
import argparse
from multiprocessing import Process
from datetime import datetime
from wsgiref.simple_server import make_server
from cachecontrol import CacheControl
HOST = "localhost"
PORT = 8050
URL = "http://{}:{}/".format(HOST, PORT)
class Server(object):
def __call__(self, env, sr):
body = "Hello World!"
status = "200 OK"
headers = [
("Cache-Control", "max-age=%i" % (60 * 10)), ("Content-Type", "text/plain")
]
sr(status, headers)
return body
def start_server():
httpd = make_server(HOST, PORT, Server())
httpd.serve_forever()
def run_benchmark(sess):
proc = Process(target=start_server)
proc.start()
start = datetime.now()
for i in range(0, 1000):
sess.get(URL)
sys.stdout.write(".")
end = datetime.now()
print()
total = end - start
print("Total time for 1000 requests: %s" % total)
proc.terminate()
def run():
parser = argparse.ArgumentParser()
parser.add_argument(
"-n",
"--no-cache",
default=False,
action="store_true",
help="Do not use cachecontrol",
)
args = parser.parse_args()
sess = requests.Session()
if not args.no_cache:
sess = CacheControl(sess)
run_benchmark(sess)
if __name__ == "__main__":
run()
| 20.166667 | 87 | 0.61708 |
1e69774c5e20b7a3fad394cdad7a38bc5651cef5 | 1,877 | py | Python | lib/compress/plot_delta_freq.py | phil-mansfield/guppy | 5394d20b83912cd072a358c38bae18a06853f419 | [
"MIT"
] | 1 | 2021-03-11T01:44:22.000Z | 2021-03-11T01:44:22.000Z | lib/compress/plot_delta_freq.py | phil-mansfield/guppy | 5394d20b83912cd072a358c38bae18a06853f419 | [
"MIT"
] | null | null | null | lib/compress/plot_delta_freq.py | phil-mansfield/guppy | 5394d20b83912cd072a358c38bae18a06853f419 | [
"MIT"
] | null | null | null | import numpy as np
import matplotlib.pyplot as plt
import palette
from palette import pc
def main():
palette.configure(False)
d_indiv, n_indiv = np.loadtxt("indiv_dx_min.txt").T
d_global, n_global = np.loadtxt("global_dx_min.txt").T
d_rot_global, n_rot_global = np.loadtxt("global_rotation.txt").T
d_window_indiv, n_window_indiv = np.loadtxt("rotate_window_indiv.txt").T
d_mean_indiv, n_mean_indiv = np.loadtxt("rotate_mean_indiv.txt").T
d_mode_indiv, n_mode_indiv = np.loadtxt("rotate_mode_indiv.txt").T
plt.plot(d_indiv, n_indiv, color=pc("k"),
label=r"${\rm individual\ (\Delta x)_{\rm min}}$")
plt.plot(d_global, n_global, color=pc("r"),
label=r"${\rm global\ (\Delta x)_{\rm min}}$")
plt.plot(d_rot_global, n_rot_global, color=pc("o"),
label=r"${\rm global\ rotation}$")
plt.plot(d_rot_global - 2**16, n_rot_global, color=pc("o"))
plt.plot(d_window_indiv, n_window_indiv, color=pc("g"),
label=r"${\rm individual\ rotation\ (window)}$")
plt.plot(d_window_indiv - 2**16, n_window_indiv, color=pc("g"))
plt.plot(d_mean_indiv, n_mean_indiv, color=pc("b"),
label=r"${\rm individual\ rotation\ (mean)}$")
plt.plot(d_mean_indiv - 2**16, n_mean_indiv, color=pc("b"))
plt.plot(d_mode_indiv, n_mode_indiv, color=pc("p"),
label=r"${\rm individual\ rotation\ (mode)}$")
plt.plot(d_mode_indiv - 2**16, n_mode_indiv, color=pc("p"))
plt.legend(loc="upper left", frameon=True, fontsize=16)
xlo, xhi = plt.xlim(-400, 2000)
ylo, yhi = plt.ylim()
plt.ylim(ylo, yhi)
plt.xlabel(r"$\Delta x$")
plt.ylabel(r"$N(\Delta x)$")
n = -512
while n < xhi:
plt.plot([n, n], [ylo, yhi], ":", lw=1, c="k")
n += 256
plt.show()
if __name__ == "__main__": main()
| 36.096154 | 76 | 0.613745 |
145282a06d92ee20032cabe041fa6a833f9a75a9 | 3,426 | py | Python | saas/migrations/0006_0_3_0.py | gikoluo/djaodjin-saas | badd7894ac327191008a1b3a0ebd0d07b55908c3 | [
"BSD-2-Clause"
] | null | null | null | saas/migrations/0006_0_3_0.py | gikoluo/djaodjin-saas | badd7894ac327191008a1b3a0ebd0d07b55908c3 | [
"BSD-2-Clause"
] | null | null | null | saas/migrations/0006_0_3_0.py | gikoluo/djaodjin-saas | badd7894ac327191008a1b3a0ebd0d07b55908c3 | [
"BSD-2-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2017-12-13 19:08
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import saas.utils
class Migration(migrations.Migration):
dependencies = [
('saas', '0005_role_extra'),
]
operations = [
migrations.CreateModel(
name='UseCharge',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.SlugField(unique=True)),
('title', models.CharField(max_length=50, null=True)),
('description', models.TextField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('use_amount', models.PositiveIntegerField(default=0)),
('extra', models.TextField(null=True)),
],
bases=(saas.utils.SlugTitleMixin, models.Model),
),
migrations.RenameField(
model_name='cartitem',
old_name='nb_periods',
new_name='quantity',
),
migrations.RemoveField(
model_name='cartitem',
name='email',
),
migrations.AddField(
model_name='cartitem',
name='sync_on',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AddField(
model_name='chargeitem',
name='invoice_key',
field=models.SlugField(blank=True, null=True),
),
migrations.AddField(
model_name='chargeitem',
name='sync_on',
field=models.CharField(max_length=255, null=True),
),
migrations.AddField(
model_name='roledescription',
name='skip_optin_on_grant',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='subscription',
name='grant_key',
field=models.CharField(blank=True, max_length=40, null=True),
),
migrations.AddField(
model_name='subscription',
name='request_key',
field=models.CharField(blank=True, max_length=40, null=True),
),
migrations.AlterField(
model_name='cartitem',
name='plan',
field=models.ForeignKey(help_text='item added to the cart (if plan).', null=True, on_delete=django.db.models.deletion.CASCADE, to='saas.Plan'),
),
migrations.AlterField(
model_name='charge',
name='state',
field=models.PositiveSmallIntegerField(choices=[(3, 'disputed'), (0, 'created'), (2, 'failed'), (1, 'done')], default=0),
),
migrations.AddField(
model_name='usecharge',
name='plan',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='plans', to='saas.Plan'),
),
migrations.AddField(
model_name='cartitem',
name='use',
field=models.ForeignKey(help_text='item added to the cart (if use charge).', null=True, on_delete=django.db.models.deletion.CASCADE, to='saas.UseCharge'),
),
migrations.AlterUniqueTogether(
name='usecharge',
unique_together=set([('slug', 'plan')]),
),
]
| 36.446809 | 166 | 0.568009 |
c65642780a4c316144612e6cff0977f31408d32f | 10,018 | py | Python | ParaMol/Utils/interface.py | mnagaku/ParaMol | 13529f584e2d50076e038388ecbdd57af23c73b9 | [
"MIT"
] | 15 | 2021-03-08T17:56:36.000Z | 2022-03-30T01:46:29.000Z | ParaMol/Utils/interface.py | mnagaku/ParaMol | 13529f584e2d50076e038388ecbdd57af23c73b9 | [
"MIT"
] | 7 | 2021-03-28T05:53:59.000Z | 2021-10-15T15:37:56.000Z | ParaMol/Utils/interface.py | mnagaku/ParaMol | 13529f584e2d50076e038388ecbdd57af23c73b9 | [
"MIT"
] | 2 | 2021-04-30T06:42:09.000Z | 2021-06-21T05:49:29.000Z | # -*- coding: utf-8 -*-
"""
Description
-----------
This module defines the :obj:`ParaMol.Utils.interface.ParaMolInterface` used for ParaMol to interact with system.
"""
import logging
import subprocess
import os
import shutil
class ParaMolInterface:
"""
This class defines method that has, for example, moving between and creating new directories, running subprocesses, etc...
Parameters
----------
base_dir : str, optional, default=os.getcwd()
Path to the base working directory.
Attributes
----------
base_dir : str
Path to the base working directory.
dirs : list
Keeps track of where we are at.
created_dirs : list
List of all created directories.
cwd : list
Current working directory
"""
def __init__(self, base_dir=None):
self.base_dir = os.getcwd() if base_dir is None else base_dir
self.dirs = [self.base_dir]
self.cwd = os.getcwd()
self.created_dirs = []
def remove_all_created_dirs(self):
"""
Method that removes all created directories.
Returns
-------
created_dirs: list
It should be an empty list.
"""
while len(self.created_dirs) > 0:
# Current directory
current_dir = self.created_dirs.pop()
# Check if directory exists
self.check_dir_exists(current_dir)
# Remove dir
shutil.rmtree(current_dir)
return self.created_dirs
def chdir(self, *args, absolute=False, relative_to_base=False):
"""
Method that changes directory.
Parameters
----------
args : strings
Strings to be joined.
absolute : bool
If True it assumes the first argument is absolute and the remaining are are defined relatively to the first.
relative_to_base : bool, default=False
If `False` path are defined relatively to the current working directory, if `True` paths are defined relatively to the base working directory.
Ignored if `absolute` is `True`.
Returns
-------
cwd : str
Current working directory.
"""
# Define prefix
if relative_to_base:
prefix = self.base_dir
else:
prefix = self.cwd
# Change directory
if absolute:
path = os.path.join(*args)
self.check_dir_exists(path)
os.chdir(path)
self.cwd = os.getcwd()
else:
path = os.path.join(prefix, *args)
self.check_dir_exists(path)
os.chdir(path)
self.cwd = os.getcwd()
self.dirs.append(self.cwd)
return self.cwd
def chdir_previous(self):
"""
Method that changes to previous directory.
Returns
-------
cwd : str
Current working directory.
"""
if len(self.dirs) == 1:
if self.dirs == [self.base_dir] and os.getcwd() == self.base_dir and self.base_dir == self.cwd:
logging.warn("ParaMol cannot change to previous directory as it is already in the base directory.")
else:
logging.warning("Something went wrong while trying to change to previous directory.")
raise NotADirectoryError("Something went wrong while trying to change to previous directory.")
else:
os.chdir("..")
self.dirs.pop()
self.cwd = os.getcwd()
assert self.cwd == self.dirs[-1], "Current directory is not what it is supposed to be."
logging.info("Changed to previous directory. Current directory is {}.".format(self.cwd))
return self.cwd
def chdir_base(self):
"""
Method that goes back to the base directory.
Returns
-------
cwd : str
Current working directory.
"""
# Sanity check
self.check_dir_exists(self.base_dir)
os.chdir(self.base_dir)
self.cwd = os.getcwd()
return self.cwd
def create_dir(self, dirs):
"""
Method that checks if the fed directories exists and if they don't exists it creates them.
Parameters
----------
dirs : str or list of str
Returns
-------
True
Returns `True` if all directories were created without errors.
"""
if type(dirs) is str:
dirs = [dirs]
for dir in dirs:
self.check_dir_exists(dir, not_exists=True)
os.mkdir(dir)
# Append to dictionary of created directories
self.created_dirs.append(os.path.abspath(dir))
return True
@staticmethod
def run_subprocess(*commands, process_name=None, output_file=None, pipe=False, shell=False):
"""
A wrapper for subprocess.check_call.
Parameters
----------
commands : str or list of str
Shell commands to be executed. If `pipe` is True they should be passes as shell commands.
process_name : str or None, optional
Name of the process. If it is none, it will be equal to the first argument's word.
Only relevant if `pipe` is `False`.
output_file : str or None, optional
Output name. `None` is equal to the process_name. If not `None` should include extension.
Only relevant if `pipe` is `False`.
pipe : bool
Whether to use subprocess.PIPE.
shell : bool
Shell command to be passed to subprocess
"""
if process_name is None:
try:
# Extract first word
process_name = str(commands[0]).split()[0]
except TypeError:
raise AttributeError("No commands were specified.")
if output_file is None:
output_file = process_name + ".out"
if pipe:
logging.info("Run_subprocess: Regardless of input shell bool, it will be set to true as pipe is true.")
shell=True
piped_sproc = [subprocess.Popen(commands[0], stdout=subprocess.PIPE, shell=shell)]
for i in range(1, len(commands)):
sproc = subprocess.Popen(commands[i], stdin=piped_sproc[-1].stdout, stdout=subprocess.PIPE, shell=shell)
piped_sproc.append(sproc)
return str(piped_sproc[-1].communicate()[0], 'utf-8')
else:
with open(output_file, "w") as std_out, open("{}.err".format(output_file), "w") as std_err:
try:
logging.info("Running process {} with commands {}.".format(process_name, commands))
subprocess.check_call(commands, shell=shell, stdout=std_out, stderr=std_err)
except subprocess.CalledProcessError:
logging.debug("Process {} failed with commands {}".format(process_name, commands))
raise OSError("Process {} failed with commands {}".format(process_name, commands))
@staticmethod
def check_dir_exists(dirs, not_exists=False):
"""
Method that checks if the fed directories exist.
Parameters
----------
dirs : str or list of str
List or str with directory path names.
not_exists : bool, optional, default=False
If True, the method checks if the fed directories do not exist.
Returns
-------
bool or list of bool or Exception:
If not_exists is False, returns `True` if dir exists and Raises an Exception if it does not exist.
If not_exists is True, returns `True` if dir does not exist and Raises an Exception if it exists.
"""
if type(dirs) is str:
dirs = [dirs]
dirs_exist = []
for dir in dirs:
if not ((not not_exists) ^ os.path.isdir(dir)):
dirs_exist.append(True)
else:
if not_exists:
logging.error("Directory {} already exists exist.".format(os.path.abspath(dir)))
raise IsADirectoryError("Directory {} already exists.".format(os.path.abspath(dir)))
else:
logging.error("Directory does {} not exist.".format(os.path.abspath(dir)))
raise NotADirectoryError("Directory {} does not exist.".format(os.path.abspath(dir)))
return dirs_exist[0] if len(dirs_exist) == 1 else dirs_exist
@staticmethod
def check_file_exists(files, not_exists=False):
"""
Method that checks if the fed files exist.
Parameters
----------
files : str or list of str
List or str with directory path names.
not_exists : bool, optional, default=False
If True, the method checks if the fed directories do not exists
Returns
-------
bool or list of bool or Exception:
If not_exists is False, returns `True` if file exists and Raises an Exception if it does not exist.
If not_exists is True, returns `True` if file does not exist and Raises an Exception if it exists.
"""
if type(files) is str:
files = [files]
files_exist = []
for file in files:
if (not not_exists) and os.path.isfile(file):
files_exist.append(True)
else:
if not_exists:
logging.error("File {} already exists.".format(os.path.abspath(file)))
raise FileExistsError("File {} already exists.".format(os.path.abspath(file)))
else:
logging.error("File {} does not exist.".format(os.path.abspath(file)))
raise FileNotFoundError("File {} does not exist.".format(os.path.abspath(file)))
return files_exist[0] if len(files_exist) == 1 else files_exist
| 35.027972 | 154 | 0.576662 |
ecbcfcc0ab3ecbf577f2f7730a342d2779198923 | 136 | py | Python | desafio-003/somando-dois-numeros-printados.py | roberto-cardoso/desafios-python | 524a5c723c3a85a441cd6bc226dff6009731d3f6 | [
"MIT"
] | null | null | null | desafio-003/somando-dois-numeros-printados.py | roberto-cardoso/desafios-python | 524a5c723c3a85a441cd6bc226dff6009731d3f6 | [
"MIT"
] | null | null | null | desafio-003/somando-dois-numeros-printados.py | roberto-cardoso/desafios-python | 524a5c723c3a85a441cd6bc226dff6009731d3f6 | [
"MIT"
] | null | null | null | n1 = int(input('Primero número:'))
n2 = int(input('Segundo número:'))
n3 = n1 + n2
print('A soma entre {} e {} é {}.'.format(n1,n2,n3))
| 27.2 | 52 | 0.595588 |
467cac3e1cac631ec139f8527d106e3825fef8a0 | 3,476 | py | Python | app.py | Rogergonzalez21/telegram_tts_bot | 51ceb66bdb2febfa09253e4aac531dcfac7dba12 | [
"MIT"
] | 3 | 2016-05-09T23:55:19.000Z | 2016-08-24T22:30:02.000Z | app.py | Rogergonzalez21/telegram_tts_bot | 51ceb66bdb2febfa09253e4aac531dcfac7dba12 | [
"MIT"
] | 1 | 2018-02-13T14:05:58.000Z | 2018-02-13T14:05:58.000Z | app.py | Rogergonzalez21/telegram_tts_bot | 51ceb66bdb2febfa09253e4aac531dcfac7dba12 | [
"MIT"
] | 3 | 2016-06-03T19:52:08.000Z | 2021-06-10T14:58:07.000Z | from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import telegram
import logging
import secrets
import os
from gtts import gTTS
from datetime import datetime
bot = telegram.Bot(token=secrets.bot_token)
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
def generate_tts(text, lang):
tts = gTTS(text=text, lang=lang)
filename = datetime.now()
if not os.path.exists('audios'):
os.makedirs('audios')
tts.save('audios/%s.ogg'%filename)
return filename
def start(bot, update):
bot.sendVoice(chat_id=update.message.chat_id, voice=open('hello.ogg', 'rb'))
bot.sendMessage(update.message.chat_id, text="Hi! I'm TTSpeechBot. To use: /tts [lang] [message], for example: /tts en I'm TTSBot!", parse_mode=telegram.ParseMode.HTML)
def help(bot, update):
bot.sendMessage(update.message.chat_id, text="To use: /tts [lang] [message], for example: /tts en I'm TTSBot!", parse_mode=telegram.ParseMode.HTML)
def tts(bot, update):
if len(update.message.text) <= 7:
echo(bot,update)
else:
try:
filename = generate_tts(update.message.text[8:], update.message.text[5:7])
except:
filename = False
bot.sendMessage(update.message.chat_id, text="There has been an issue with Google, please try again later.")
if filename != False:
try:
bot.sendVoice(chat_id=update.message.chat_id, voice=open('audios/%s.ogg'%filename, 'rb'))
except:
echo(bot,update)
def otts(bot,update):
try:
filename = generate_tts('Fucking' + update.message.text[9:], update.message.text[6:8])
bot.sendVoice(chat_id=update.message.chat_id, voice=open('audios/%s.ogg'%filename, 'rb'))
except:
bot.sendMessage(update.message.chat_id, text="Please, use the right format: /otts [lang] [message], for example: /tts en I'm TTSBot!")
def echo(bot, update):
bot.sendMessage(update.message.chat_id, text="Please, use the right format: /tts [lang] [message], for example: /tts en I'm TTSBot!")
def developer(bot, update):
bot.sendMessage(update.message.chat_id, text='Made by @Rogergonzalez21 with a lot of help from @sergsss. GitHub repo: https://github.com/Rogergonzalez21/telegram_tts_bot')
def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
def main():
# Create the EventHandler and pass it your bot's token.
updater = Updater(token=secrets.bot_token)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("tts", tts))
dp.add_handler(CommandHandler("otts", otts))
dp.add_handler(CommandHandler("developer", developer))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler([Filters.text], echo))
# log all errors
dp.add_error_handler(error)
updater.start_polling()
# Run the bot until the you presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
| 33.104762 | 175 | 0.682969 |
03f38a4eccb6410e0dbdb3584c7bd8afc2292e6a | 617 | py | Python | potd_ii/picture_of_the_day/migrations/0004_potd_image_thumbnail_url.py | qubitstream/picture_of_the_day_aggregation_site_2 | 675a354a84b8f3184cfa2c7568637be886939704 | [
"CNRI-Python"
] | null | null | null | potd_ii/picture_of_the_day/migrations/0004_potd_image_thumbnail_url.py | qubitstream/picture_of_the_day_aggregation_site_2 | 675a354a84b8f3184cfa2c7568637be886939704 | [
"CNRI-Python"
] | null | null | null | potd_ii/picture_of_the_day/migrations/0004_potd_image_thumbnail_url.py | qubitstream/picture_of_the_day_aggregation_site_2 | 675a354a84b8f3184cfa2c7568637be886939704 | [
"CNRI-Python"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11rc1 on 2017-03-25 18:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('picture_of_the_day', '0003_auto_20170325_1653'),
]
operations = [
migrations.AddField(
model_name='potd',
name='image_thumbnail_url',
field=models.URLField(blank=True, editable=False, help_text='URL for the direct link to a smaller image, preferable and sufficient for importing', verbose_name='thumbnail image url'),
),
]
| 29.380952 | 195 | 0.67423 |
b1f3dc88d7f1d49a972be8b07a26264c6f28c120 | 2,411 | py | Python | scripts/github_db_functions.py | navierula/DivHacks2017 | 2b272bb08f499de4309c961156a6f6a93124ec2f | [
"MIT"
] | null | null | null | scripts/github_db_functions.py | navierula/DivHacks2017 | 2b272bb08f499de4309c961156a6f6a93124ec2f | [
"MIT"
] | null | null | null | scripts/github_db_functions.py | navierula/DivHacks2017 | 2b272bb08f499de4309c961156a6f6a93124ec2f | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 15 18:13:31 2017
@author: navrajnarula
"""
import pandas as pd
import matplotlib.pyplot as plt
import itertools
import numpy as np
from collections import Counter
# read in dataset
df = pd.read_csv("data_sources/GitHub_Terms_Data.csv", sep=';', encoding='ISO-8859-1')
list(df.columns.values)
# returns number of male and female contributors
# in a tuple
def contribution_by_gender(df):
genderList = []
for val in df["genders"]:
genderList.append(val)
totalfCount = []
totalmCount = []
for gender in genderList:
fCount = gender.count("female")
totalfCount.append(fCount)
mCount = gender.count("male")
totalmCount.append(mCount)
return (sum(totalmCount), sum(totalfCount))
# returns dictionary of programming languages
# and number of times males vs. female used
# those languages
def languages_by_gender(df):
languages = {}
for valOne, valTwo in zip(df["language"], df["genders"]):
try:
languages[valOne].append(valTwo)
except KeyError:
languages[valOne] = [valTwo]
maleCount = 0
femaleCount = 0
for key, val in languages.items():
for item in val:
if "male" in item:
maleCount +=1
if "female" in item:
femaleCount += 1
languages[key] = (maleCount, femaleCount)
return languages
# returns a list of all languages used
def language_list(df):
languages = []
for val in df["language"]:
languages.append(val)
return sorted(list(set(languages)))
# returns dict_items of countributions by country in numbers
def contributions_by_country(df):
countries_list = []
for val in df["countries"]:
splits = val.split(",")
countries_list.append(splits)
entire_list = [item for sublist in countries_list for item in sublist if item != "None"]
c = Counter(entire_list)
return c.items()
# returns list of countries in alphabetical order
def countries_list(df):
countries_list = []
for val in df["countries"]:
splits = val.split(",")
countries_list.append(splits)
entire_list = [item for sublist in countries_list for item in sublist if item != "None"]
entire_list = list(set(entire_list))
return sorted(entire_list)
| 25.378947 | 92 | 0.645375 |
ef8f447a21ed4a59444433e999615b0e69317218 | 4,973 | py | Python | src/optim/ae_trainer.py | wenyushi451/Deep-SAD-PyTorch | 168d31f538a50fb029739206994ea5517d907853 | [
"MIT"
] | null | null | null | src/optim/ae_trainer.py | wenyushi451/Deep-SAD-PyTorch | 168d31f538a50fb029739206994ea5517d907853 | [
"MIT"
] | null | null | null | src/optim/ae_trainer.py | wenyushi451/Deep-SAD-PyTorch | 168d31f538a50fb029739206994ea5517d907853 | [
"MIT"
] | null | null | null | from base.base_trainer import BaseTrainer
from base.base_dataset import BaseADDataset
from base.base_net import BaseNet
from sklearn.metrics import roc_auc_score
import logging
import time
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
class AETrainer(BaseTrainer):
def __init__(self, optimizer_name: str = 'adam', lr: float = 0.001, n_epochs: int = 150, lr_milestones: tuple = (),
batch_size: int = 128, weight_decay: float = 1e-6, device: str = 'cuda', n_jobs_dataloader: int = 0):
super().__init__(optimizer_name, lr, n_epochs, lr_milestones, batch_size, weight_decay, device,
n_jobs_dataloader)
# Results
self.train_time = None
self.test_auc = None
self.test_time = None
def train(self, dataset: BaseADDataset, ae_net: BaseNet):
logger = logging.getLogger()
# Get train data loader
train_loader, _ = dataset.loaders(batch_size=self.batch_size, num_workers=self.n_jobs_dataloader)
# Set loss
criterion = nn.MSELoss(reduction='none')
# Set device
ae_net = ae_net.to(self.device)
criterion = criterion.to(self.device)
# Set optimizer (Adam optimizer for now)
optimizer = optim.Adam(ae_net.parameters(), lr=self.lr, weight_decay=self.weight_decay)
# Set learning rate scheduler
scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=self.lr_milestones, gamma=0.1)
# Training
logger.info('Starting pretraining...')
start_time = time.time()
ae_net.train()
for epoch in range(self.n_epochs):
if epoch in self.lr_milestones:
logger.info(' LR scheduler: new learning rate is %g' % float(scheduler.get_lr()[0]))
epoch_loss = 0.0
n_batches = 0
epoch_start_time = time.time()
for data in train_loader:
inputs, _, _, _ = data
inputs = inputs.to(self.device)
# Zero the network parameter gradients
optimizer.zero_grad()
# Update network parameters via backpropagation: forward + backward + optimize
rec = ae_net(inputs)
rec_loss = criterion(rec, inputs)
loss = torch.mean(rec_loss)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
n_batches += 1
scheduler.step()
# log epoch statistics
epoch_train_time = time.time() - epoch_start_time
logger.info(f'| Epoch: {epoch + 1:03}/{self.n_epochs:03} | Train Time: {epoch_train_time:.3f}s '
f'| Train Loss: {epoch_loss / n_batches:.6f} |')
self.train_time = time.time() - start_time
logger.info('Pretraining Time: {:.3f}s'.format(self.train_time))
logger.info('Finished pretraining.')
return ae_net
def test(self, dataset: BaseADDataset, ae_net: BaseNet):
logger = logging.getLogger()
# Get test data loader
_, test_loader = dataset.loaders(batch_size=self.batch_size, num_workers=self.n_jobs_dataloader)
# Set loss
criterion = nn.MSELoss(reduction='none')
# Set device for network
ae_net = ae_net.to(self.device)
criterion = criterion.to(self.device)
# Testing
logger.info('Testing autoencoder...')
epoch_loss = 0.0
n_batches = 0
start_time = time.time()
idx_label_score = []
ae_net.eval()
with torch.no_grad():
for data in test_loader:
inputs, labels, _, idx = data
inputs, labels, idx = inputs.to(self.device), labels.to(self.device), idx.to(self.device)
rec = ae_net(inputs)
rec_loss = criterion(rec, inputs)
scores = torch.mean(rec_loss, dim=tuple(range(1, rec.dim())))
# Save triple of (idx, label, score) in a list
idx_label_score += list(zip(idx.cpu().data.numpy().tolist(),
labels.cpu().data.numpy().tolist(),
scores.cpu().data.numpy().tolist()))
loss = torch.mean(rec_loss)
epoch_loss += loss.item()
n_batches += 1
self.test_time = time.time() - start_time
# Compute AUC
_, labels, scores = zip(*idx_label_score)
labels = np.array(labels)
scores = np.array(scores)
self.test_auc = roc_auc_score(labels, scores)
# Log results
logger.info('Test Loss: {:.6f}'.format(epoch_loss / n_batches))
logger.info('Test AUC: {:.2f}%'.format(100. * self.test_auc))
logger.info('Test Time: {:.3f}s'.format(self.test_time))
logger.info('Finished testing autoencoder.')
| 36.036232 | 119 | 0.584154 |
612a74fa44487e3939237a2df38aac214b52a653 | 14,408 | py | Python | pysnmp-with-texts/CISCO-TPC-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 8 | 2019-05-09T17:04:00.000Z | 2021-06-09T06:50:51.000Z | pysnmp-with-texts/CISCO-TPC-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 4 | 2019-05-31T16:42:59.000Z | 2020-01-31T21:57:17.000Z | pysnmp-with-texts/CISCO-TPC-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 10 | 2019-04-30T05:51:36.000Z | 2022-02-16T03:33:41.000Z | #
# PySNMP MIB module CISCO-TPC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TPC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:14:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
FcNameIdOrZero, = mibBuilder.importSymbols("CISCO-ST-TC", "FcNameIdOrZero")
vsanIndex, = mibBuilder.importSymbols("CISCO-VSAN-MIB", "vsanIndex")
PhysicalIndex, = mibBuilder.importSymbols("ENTITY-MIB", "PhysicalIndex")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
MibIdentifier, IpAddress, Counter32, TimeTicks, ModuleIdentity, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, iso, Gauge32, Counter64, NotificationType, Unsigned32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "IpAddress", "Counter32", "TimeTicks", "ModuleIdentity", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "iso", "Gauge32", "Counter64", "NotificationType", "Unsigned32", "Integer32")
TextualConvention, DisplayString, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "RowStatus")
ciscoTpcMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 460))
ciscoTpcMIB.setRevisions(('2005-01-24 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoTpcMIB.setRevisionsDescriptions(('Initial version of this MIB module. ',))
if mibBuilder.loadTexts: ciscoTpcMIB.setLastUpdated('200501240000Z')
if mibBuilder.loadTexts: ciscoTpcMIB.setOrganization('Cisco Systems, Inc.')
if mibBuilder.loadTexts: ciscoTpcMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553 -NETS E-mail: [email protected]')
if mibBuilder.loadTexts: ciscoTpcMIB.setDescription('The MIB module for Third Party Copy(TPC): Third Party Copy derives its name from the fact that there are three entities involved in the process of copying data either for backup operations or restore operations. The three entities: - entity originating the copy commands - data source for the copy - data destination for the copy. The entity originating the copy commands to perform the data transfer can use the SCSI Extended Copy (XCOPY). The TPC feature exposes a disk target with Logical Unit Number(LUN) 0 that is capable of processing the SCSI Extended Copy Command (XCOPY) to transfer data from a specified source to a specified destination. On receiving the XCOPY command, the TPC target performs the actual data transfer from the data source to the data destination on behalf of the entity issuing the XCOPY command. The MIB provides an interface to configure the TPC targets. The user specifies the module and the VSAN on which the TPC feature needs to be configured. Once the feature has been configured target ports are created on the specified module and VSAN that are XCOPY capable. Any application that can source a XCOPY command can use these targets to perform data movement. Acronyms The following acronyms are used in this document: XCOPY: SCSI Extended Copy Command. TPC: Third Party Copy. LUN: Logical Unit Number. VSAN: Virtual Storage Area Network. ')
ciscoTpcNotification = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 460, 0))
ciscoTpcObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 460, 1))
ciscoTpcMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 460, 2))
ciscoTpcConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1))
class TpcTargetState(TextualConvention, Integer32):
description = "Represents the state of the TPC target. 'active' - indicates that the TPC target is ready to process XCOPY requests. 'initializing' - indicates that the TPC target is not ready. 'error' - indicates that the TPC target was brought down due to error conditions. "
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("active", 1), ("initializing", 2), ("error", 3))
ctpcModuleTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 1), )
if mibBuilder.loadTexts: ctpcModuleTable.setStatus('current')
if mibBuilder.loadTexts: ctpcModuleTable.setDescription('A table listing the modules on which TPC functionality can be configured by the user. Each such module is identified by ctpcModuleId. The agent creates an entry in this table on detecting a module that can support TPC functionality. Similarly, it will remove the entry when the TPC functionality cannot be supported on this module any longer. The entry in the ctpcVsanTable can only be created on a module present in this table.')
ctpcModuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-TPC-MIB", "ctpcModuleId"))
if mibBuilder.loadTexts: ctpcModuleEntry.setStatus('current')
if mibBuilder.loadTexts: ctpcModuleEntry.setDescription('A conceptual row in the ctpcModuleTable. Each row represents a TPC capable module.')
ctpcModuleId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 1, 1, 1), PhysicalIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ctpcModuleId.setStatus('current')
if mibBuilder.loadTexts: ctpcModuleId.setDescription('This object specifies the physical index of the module on which TPC can be configured by the user. This is same as the entPhysicalIndex of the module.')
ctpcVsanTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 2), )
if mibBuilder.loadTexts: ctpcVsanTable.setStatus('current')
if mibBuilder.loadTexts: ctpcVsanTable.setDescription("A table listing all the VSANs for which TPC functionality has been configured by the user. The user configures TPC functionality on a per VSAN basis by specifying the module, identified by ctpcModuleId, on which to configure TPC and the VSAN number. An entry can be created in this table only if an entry exists in ctpcModuleTable for this module. If a management application attempts to create a row in this table corresponding to a module that does not exist in ctpcModuleTable table then the agent would respond with an error-status set to 'inconsistentValue'. Once an entry is created, even if this module no longer exists in the ctpcModuleTable, still this entry is not deleted. The entry can only be deleted by setting ctpcVsanRowStatus to 'delete'.")
ctpcVsanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-TPC-MIB", "ctpcModuleId"), (0, "CISCO-VSAN-MIB", "vsanIndex"))
if mibBuilder.loadTexts: ctpcVsanEntry.setStatus('current')
if mibBuilder.loadTexts: ctpcVsanEntry.setDescription('An entry in the TPC VSAN table for each configured VSAN on this module.')
ctpcVsanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 2, 1, 1), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ctpcVsanRowStatus.setStatus('current')
if mibBuilder.loadTexts: ctpcVsanRowStatus.setDescription("This object controls and reflects the status of rows in this table. When the agent successfully creates the entry, this object is set to 'active' by the agent. Deleting an entry from this table, unconfigures the TPC functionality on the module specified by the corresponding instance index 'ctpcModuleId' on the VSAN represented by the corresponding instance index 'vsanIndex' To delete an entry, set this object value to 'destroy'.")
ctpcTargetTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 3), )
if mibBuilder.loadTexts: ctpcTargetTable.setStatus('current')
if mibBuilder.loadTexts: ctpcTargetTable.setDescription('A list of all the TPC targets that are configured on this module and on this VSAN. There can be more than one TPC target in the same VSAN on a module. The number of TPC targets is implementation specific. Each TPC target has a unique node world-wide-name, identified by ctpcTargetNodeName and a unique port world-wide-name, identified by ctpcTargetPortName. Each TPC target exposes a single LUN (LUN 0) that is XCOPY capable and is only concerned with moving data in its own VSAN. Once an entry is created in ctpcVsanTable, one or more entries are created in this table by agent. Similarly the entries in this table are deleted when the entry with the same ctpcModuleId and vsanIndex is deleted from the ctpcVsanTable.')
ctpcTargetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 3, 1), ).setIndexNames((0, "CISCO-TPC-MIB", "ctpcModuleId"), (0, "CISCO-VSAN-MIB", "vsanIndex"), (0, "CISCO-TPC-MIB", "ctpcTargetIndex"))
if mibBuilder.loadTexts: ctpcTargetEntry.setStatus('current')
if mibBuilder.loadTexts: ctpcTargetEntry.setDescription('An entry in the TPC target table for each TPC target in this VSAN on this module.')
ctpcTargetIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 3, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ctpcTargetIndex.setStatus('current')
if mibBuilder.loadTexts: ctpcTargetIndex.setDescription('The unique id number associated with the TPC target. This id number is unique within the vsan in which the TPC target is configured.')
ctpcTargetNodeName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 3, 1, 2), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ctpcTargetNodeName.setStatus('current')
if mibBuilder.loadTexts: ctpcTargetNodeName.setDescription("The TPC target's node world-wide-name.")
ctpcTargetPortName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 3, 1, 3), FcNameIdOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ctpcTargetPortName.setStatus('current')
if mibBuilder.loadTexts: ctpcTargetPortName.setDescription("The TPC target's port world-wide-name.")
ctpcTargetState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 3, 1, 4), TpcTargetState()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ctpcTargetState.setStatus('current')
if mibBuilder.loadTexts: ctpcTargetState.setDescription('The current state of the TPC target')
ctpcTargetNumXcopies = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 3, 1, 5), Counter32()).setUnits('commands').setMaxAccess("readonly")
if mibBuilder.loadTexts: ctpcTargetNumXcopies.setStatus('current')
if mibBuilder.loadTexts: ctpcTargetNumXcopies.setDescription('The total number of XCOPY commands processed by the TPC target since the module on which this target has been configured has been online')
ctpcTargetMinXcopy = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 3, 1, 6), Gauge32()).setUnits('Kilobytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: ctpcTargetMinXcopy.setStatus('current')
if mibBuilder.loadTexts: ctpcTargetMinXcopy.setDescription('The smallest amount of data in Kilobytes transferred by the TPC target in a single xcopy command since the module on which this target has been configured has been online.')
ctpcTargetMaxXcopy = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 3, 1, 7), Gauge32()).setUnits('Kilobytes').setMaxAccess("readonly")
if mibBuilder.loadTexts: ctpcTargetMaxXcopy.setStatus('current')
if mibBuilder.loadTexts: ctpcTargetMaxXcopy.setDescription('The largest amount of data in Kilobytes transferred by the TPC target in a single xcopy command since the module on which this target has been configured has been online.')
ctpcTargetAvgKbPerSec = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 460, 1, 1, 3, 1, 8), Gauge32()).setUnits('Kilobytes/second').setMaxAccess("readonly")
if mibBuilder.loadTexts: ctpcTargetAvgKbPerSec.setStatus('current')
if mibBuilder.loadTexts: ctpcTargetAvgKbPerSec.setDescription('The average kilobytes per second throughput of the TPC target in processing the XCOPY commands.')
ctpcMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 460, 2, 1))
ctpcMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 460, 2, 2))
ctpcMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 460, 2, 1, 1)).setObjects(("CISCO-TPC-MIB", "ctpcVsanTargetGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ctpcMIBCompliance = ctpcMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: ctpcMIBCompliance.setDescription('The compliance statement for entities which implement the CISCO-TPC-MIB mib.')
ctpcVsanTargetGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 460, 2, 2, 1)).setObjects(("CISCO-TPC-MIB", "ctpcModuleId"), ("CISCO-TPC-MIB", "ctpcVsanRowStatus"), ("CISCO-TPC-MIB", "ctpcTargetNodeName"), ("CISCO-TPC-MIB", "ctpcTargetPortName"), ("CISCO-TPC-MIB", "ctpcTargetState"), ("CISCO-TPC-MIB", "ctpcTargetNumXcopies"), ("CISCO-TPC-MIB", "ctpcTargetMinXcopy"), ("CISCO-TPC-MIB", "ctpcTargetMaxXcopy"), ("CISCO-TPC-MIB", "ctpcTargetAvgKbPerSec"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ctpcVsanTargetGroup = ctpcVsanTargetGroup.setStatus('current')
if mibBuilder.loadTexts: ctpcVsanTargetGroup.setDescription('A collection of objects for displaying and configuring the TPC target.')
mibBuilder.exportSymbols("CISCO-TPC-MIB", ciscoTpcMIB=ciscoTpcMIB, ctpcTargetEntry=ctpcTargetEntry, ctpcMIBCompliance=ctpcMIBCompliance, ctpcVsanRowStatus=ctpcVsanRowStatus, ciscoTpcMIBConformance=ciscoTpcMIBConformance, ctpcVsanTargetGroup=ctpcVsanTargetGroup, ciscoTpcObjects=ciscoTpcObjects, ctpcTargetAvgKbPerSec=ctpcTargetAvgKbPerSec, ctpcVsanEntry=ctpcVsanEntry, ctpcTargetState=ctpcTargetState, ctpcTargetMinXcopy=ctpcTargetMinXcopy, ctpcMIBCompliances=ctpcMIBCompliances, TpcTargetState=TpcTargetState, PYSNMP_MODULE_ID=ciscoTpcMIB, ctpcTargetIndex=ctpcTargetIndex, ctpcTargetTable=ctpcTargetTable, ctpcModuleId=ctpcModuleId, ctpcModuleTable=ctpcModuleTable, ctpcTargetNodeName=ctpcTargetNodeName, ciscoTpcNotification=ciscoTpcNotification, ctpcMIBGroups=ctpcMIBGroups, ctpcTargetMaxXcopy=ctpcTargetMaxXcopy, ctpcTargetPortName=ctpcTargetPortName, ctpcTargetNumXcopies=ctpcTargetNumXcopies, ctpcModuleEntry=ctpcModuleEntry, ctpcVsanTable=ctpcVsanTable, ciscoTpcConfig=ciscoTpcConfig)
| 148.536082 | 1,427 | 0.77686 |
534660aad9f0a30841842b688232ba0388a38bba | 36,911 | py | Python | test/test_manager.py | kapilpokhrel/qtile | c9eac5aed41c22d87e22e7bc4b7b7fb64e863c47 | [
"MIT"
] | null | null | null | test/test_manager.py | kapilpokhrel/qtile | c9eac5aed41c22d87e22e7bc4b7b7fb64e863c47 | [
"MIT"
] | null | null | null | test/test_manager.py | kapilpokhrel/qtile | c9eac5aed41c22d87e22e7bc4b7b7fb64e863c47 | [
"MIT"
] | 1 | 2020-04-27T22:20:11.000Z | 2020-04-27T22:20:11.000Z | # Copyright (c) 2011 Florian Mounier
# Copyright (c) 2011 Anshuman Bhaduri
# Copyright (c) 2012-2014 Tycho Andersen
# Copyright (c) 2013 xarvh
# Copyright (c) 2013 Craig Barnes
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2014 Adi Sieker
# Copyright (c) 2014 Sebastien Blot
# Copyright (c) 2020 Mikel Ward
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import logging
import pytest
import libqtile.bar
import libqtile.config
import libqtile.confreader
import libqtile.hook
import libqtile.layout
import libqtile.widget
from libqtile.command.client import SelectError
from libqtile.command.interface import CommandError, CommandException
from libqtile.config import Match
from libqtile.confreader import Config
from libqtile.lazy import lazy
from test.conftest import dualmonitor, multimonitor
from test.helpers import BareConfig, Retry, assert_window_died
from test.layouts.layout_utils import assert_focused
class ManagerConfig(Config):
auto_fullscreen = True
groups = [
libqtile.config.Group("a"),
libqtile.config.Group("b"),
libqtile.config.Group("c"),
libqtile.config.Group("d")
]
layouts = [
libqtile.layout.stack.Stack(num_stacks=1),
libqtile.layout.stack.Stack(num_stacks=2),
libqtile.layout.tile.Tile(ratio=0.5),
libqtile.layout.max.Max()
]
floating_layout = libqtile.layout.floating.Floating(
float_rules=[
*libqtile.layout.floating.Floating.default_float_rules,
Match(wm_class='float'),
Match(title='float')
]
)
keys = [
libqtile.config.Key(
["control"],
"k",
lazy.layout.up(),
),
libqtile.config.Key(
["control"],
"j",
lazy.layout.down(),
),
]
mouse = []
screens = [libqtile.config.Screen(
bottom=libqtile.bar.Bar(
[
libqtile.widget.Prompt(),
libqtile.widget.GroupBox(),
],
20
),
)]
follow_mouse_focus = True
reconfigure_screens = False
manager_config = pytest.mark.parametrize("manager", [ManagerConfig], indirect=True)
@dualmonitor
@manager_config
def test_screen_dim(manager):
manager.test_window('one')
assert manager.c.screen.info()["index"] == 0
assert manager.c.screen.info()["x"] == 0
assert manager.c.screen.info()["width"] == 800
assert manager.c.group.info()["name"] == 'a'
assert manager.c.group.info()["focus"] == 'one'
manager.c.to_screen(1)
manager.test_window("one")
assert manager.c.screen.info()["index"] == 1
assert manager.c.screen.info()["x"] == 800
assert manager.c.screen.info()["width"] == 640
assert manager.c.group.info()["name"] == 'b'
assert manager.c.group.info()["focus"] == 'one'
manager.c.to_screen(0)
assert manager.c.screen.info()["index"] == 0
assert manager.c.screen.info()["x"] == 0
assert manager.c.screen.info()["width"] == 800
assert manager.c.group.info()["name"] == 'a'
assert manager.c.group.info()["focus"] == 'one'
@pytest.mark.parametrize("xephyr", [{"xoffset": 0}], indirect=True)
@manager_config
def test_clone_dim(manager):
manager.test_window('one')
assert manager.c.screen.info()["index"] == 0
assert manager.c.screen.info()["x"] == 0
assert manager.c.screen.info()["width"] == 800
assert manager.c.group.info()["name"] == 'a'
assert manager.c.group.info()["focus"] == 'one'
assert len(manager.c.screens()) == 1
@dualmonitor
@manager_config
def test_to_screen(manager):
assert manager.c.screen.info()["index"] == 0
manager.c.to_screen(1)
assert manager.c.screen.info()["index"] == 1
manager.test_window("one")
manager.c.to_screen(0)
manager.test_window("two")
ga = manager.c.groups()["a"]
assert ga["windows"] == ["two"]
gb = manager.c.groups()["b"]
assert gb["windows"] == ["one"]
assert manager.c.window.info()["name"] == "two"
manager.c.next_screen()
assert manager.c.window.info()["name"] == "one"
manager.c.next_screen()
assert manager.c.window.info()["name"] == "two"
manager.c.prev_screen()
assert manager.c.window.info()["name"] == "one"
@dualmonitor
@manager_config
def test_togroup(manager):
manager.test_window("one")
with pytest.raises(CommandError):
manager.c.window.togroup("nonexistent")
assert manager.c.groups()["a"]["focus"] == "one"
manager.c.window.togroup("a")
assert manager.c.groups()["a"]["focus"] == "one"
manager.c.window.togroup("b", switch_group=True)
assert manager.c.groups()["b"]["focus"] == "one"
assert manager.c.groups()["a"]["focus"] is None
assert manager.c.group.info()["name"] == "b"
manager.c.window.togroup("a")
assert manager.c.groups()["a"]["focus"] == "one"
assert manager.c.group.info()["name"] == "b"
manager.c.to_screen(1)
manager.c.window.togroup("c")
assert manager.c.groups()["c"]["focus"] == "one"
@manager_config
def test_resize(manager):
manager.c.screen[0].resize(x=10, y=10, w=100, h=100)
@Retry(ignore_exceptions=(AssertionError), fail_msg="Screen didn't resize")
def run():
d = manager.c.screen[0].info()
assert d['width'] == 100
assert d['height'] == 100
return d
d = run()
assert d['x'] == d['y'] == 10
def test_minimal(manager):
assert manager.c.status() == "OK"
@manager_config
def test_events(manager):
assert manager.c.status() == "OK"
# FIXME: failing test disabled. For some reason we don't seem
# to have a keymap in Xnest or Xephyr 99% of the time.
@manager_config
def test_keypress(manager):
manager.test_window("one")
manager.test_window("two")
with pytest.raises(CommandError):
manager.c.simulate_keypress(["unknown"], "j")
assert manager.c.groups()["a"]["focus"] == "two"
manager.c.simulate_keypress(["control"], "j")
assert manager.c.groups()["a"]["focus"] == "one"
class TooFewGroupsConfig(ManagerConfig):
groups = []
@pytest.mark.parametrize("manager", [TooFewGroupsConfig], indirect=True)
@multimonitor
def test_too_few_groups(manager):
assert manager.c.groups()
assert len(manager.c.groups()) == len(manager.c.screens())
class _ChordsConfig(Config):
groups = [
libqtile.config.Group("a")
]
layouts = [
libqtile.layout.max.Max()
]
floating_layout = libqtile.resources.default_config.floating_layout
keys = [
libqtile.config.Key(
[],
"k",
lazy.layout.up(),
),
libqtile.config.KeyChord(["control"], "a", [
libqtile.config.Key(
[],
"j",
lazy.layout.down(),
)
]),
libqtile.config.KeyChord(["control"], "b", [
libqtile.config.Key(
[],
"j",
lazy.layout.down(),
)
], "test"),
libqtile.config.KeyChord(["control"], "d", [
libqtile.config.KeyChord([], "a", [
libqtile.config.KeyChord([], "1", [
libqtile.config.Key([], "u", lazy.ungrab_chord()),
libqtile.config.Key([], "v", lazy.ungrab_all_chords()),
libqtile.config.Key([], "j", lazy.layout.down()),
], "inner_named"),
]),
libqtile.config.Key([], "z", lazy.layout.down()),
], "nesting_test"),
]
mouse = []
screens = [libqtile.config.Screen(
bottom=libqtile.bar.Bar(
[
libqtile.widget.GroupBox(),
],
20
),
)]
auto_fullscreen = True
chords_config = pytest.mark.parametrize("manager", [_ChordsConfig], indirect=True)
@chords_config
def test_immediate_chord(manager):
manager.test_window("three")
manager.test_window("two")
manager.test_window("one")
assert manager.c.groups()["a"]["focus"] == "one"
# use normal bind to shift focus up
manager.c.simulate_keypress([], "k")
assert manager.c.groups()["a"]["focus"] == "two"
# enter into key chord and "k" binding no longer working
manager.c.simulate_keypress(["control"], "a")
manager.c.simulate_keypress([], "k")
assert manager.c.groups()["a"]["focus"] == "two"
# leave chord using "Escape", "k" bind work again
manager.c.simulate_keypress([], "Escape")
manager.c.simulate_keypress([], "k")
assert manager.c.groups()["a"]["focus"] == "three"
# enter key chord and use it's "j" binding to shift focus down
manager.c.simulate_keypress(["control"], "a")
manager.c.simulate_keypress([], "j")
assert manager.c.groups()["a"]["focus"] == "two"
# in immediate chord we leave it after use any
# bind from it, "j" bind no longer working
manager.c.simulate_keypress([], "j")
assert manager.c.groups()["a"]["focus"] == "two"
@chords_config
def test_mode_chord(manager):
manager.test_window("three")
manager.test_window("two")
manager.test_window("one")
assert manager.c.groups()["a"]["focus"] == "one"
# use normal bind to shift focus up
manager.c.simulate_keypress([], "k")
assert manager.c.groups()["a"]["focus"] == "two"
# enter into key chord and "k" binding no longer working
manager.c.simulate_keypress(["control"], "b")
manager.c.simulate_keypress([], "k")
assert manager.c.groups()["a"]["focus"] == "two"
# leave chord using "Escape", "k" bind work again
manager.c.simulate_keypress([], "Escape")
manager.c.simulate_keypress([], "k")
assert manager.c.groups()["a"]["focus"] == "three"
# enter key chord and use it's "j" binding to shift focus down
manager.c.simulate_keypress(["control"], "b")
manager.c.simulate_keypress([], "j")
assert manager.c.groups()["a"]["focus"] == "two"
# in mode chord we __not__ leave it after use any
# bind from it, "j" bind still working
manager.c.simulate_keypress([], "j")
assert manager.c.groups()["a"]["focus"] == "one"
# only way to exit mode chord is by hit "Escape"
manager.c.simulate_keypress([], "Escape")
manager.c.simulate_keypress([], "j")
assert manager.c.groups()["a"]["focus"] == "one"
@chords_config
def test_chord_stack(manager):
manager.test_window("two")
manager.test_window("one")
assert manager.c.groups()["a"]["focus"] == "one"
manager.c.simulate_keypress(["control"], "d") # ["nesting_test"]
# "z" should work, "k" shouldn't:
manager.c.simulate_keypress([], "z")
assert manager.c.groups()["a"]["focus"] == "two"
manager.c.simulate_keypress([], "z")
assert manager.c.groups()["a"]["focus"] == "one"
manager.c.simulate_keypress([], "k")
assert manager.c.groups()["a"]["focus"] == "one"
# enter ["nesting_test", "", "inner_named"]:
manager.c.simulate_keypress([], "a")
manager.c.simulate_keypress([], "1")
# "j" should work:
manager.c.simulate_keypress([], "j")
assert manager.c.groups()["a"]["focus"] == "two"
manager.c.simulate_keypress([], "j")
assert manager.c.groups()["a"]["focus"] == "one"
# leave "inner_named" ~> ["nesting_test"]:
manager.c.simulate_keypress([], "u")
manager.c.simulate_keypress([], "z")
assert manager.c.groups()["a"]["focus"] == "two"
manager.c.simulate_keypress([], "z")
assert manager.c.groups()["a"]["focus"] == "one"
manager.c.simulate_keypress([], "k")
assert manager.c.groups()["a"]["focus"] == "one"
# enter ["nesting_test", "", "inner_named"]:
manager.c.simulate_keypress([], "a")
manager.c.simulate_keypress([], "1")
# leave all: ~> []
manager.c.simulate_keypress([], "v")
# "k" should work, "z" shouldn't:
manager.c.simulate_keypress([], "k")
assert manager.c.groups()["a"]["focus"] == "two"
manager.c.simulate_keypress([], "k")
assert manager.c.groups()["a"]["focus"] == "one"
manager.c.simulate_keypress([], "z")
assert manager.c.groups()["a"]["focus"] == "one"
@manager_config
def test_spawn(manager):
# Spawn something with a pid greater than init's
assert int(manager.c.spawn("true")) > 1
@manager_config
def test_spawn_list(manager):
# Spawn something with a pid greater than init's
assert int(manager.c.spawn(["echo", "true"])) > 1
@manager_config
def test_kill_window(manager):
manager.test_window("one")
window_info = manager.c.window.info()
manager.c.window[window_info["id"]].kill()
assert_window_died(manager.c, window_info)
@manager_config
def test_kill_other(manager):
manager.c.group.setlayout("tile")
one = manager.test_window("one")
assert manager.c.window.info()["width"] == 798
window_one_info = manager.c.window.info()
assert manager.c.window.info()["height"] == 578
two = manager.test_window("two")
assert manager.c.window.info()["name"] == "two"
assert manager.c.window.info()["width"] == 398
assert manager.c.window.info()["height"] == 578
assert len(manager.c.windows()) == 2
manager.kill_window(one)
assert_window_died(manager.c, window_one_info)
assert manager.c.window.info()["name"] == "two"
assert manager.c.window.info()["width"] == 798
assert manager.c.window.info()["height"] == 578
manager.kill_window(two)
@manager_config
def test_regression_groupswitch(manager):
manager.c.group["c"].toscreen()
manager.c.group["d"].toscreen()
assert manager.c.groups()["c"]["screen"] is None
@manager_config
def test_next_layout(manager):
manager.test_window("one")
manager.test_window("two")
assert len(manager.c.layout.info()["stacks"]) == 1
manager.c.next_layout()
assert len(manager.c.layout.info()["stacks"]) == 2
manager.c.next_layout()
manager.c.next_layout()
manager.c.next_layout()
assert len(manager.c.layout.info()["stacks"]) == 1
@manager_config
def test_setlayout(manager):
assert not manager.c.layout.info()["name"] == "max"
manager.c.group.setlayout("max")
assert manager.c.layout.info()["name"] == "max"
@manager_config
def test_to_layout_index(manager):
manager.c.to_layout_index(-1)
assert manager.c.layout.info()["name"] == "max"
manager.c.to_layout_index(-4)
assert manager.c.layout.info()["name"] == "stack"
with pytest.raises(SelectError):
manager.c.to_layout.index(-5)
manager.c.to_layout_index(-2)
assert manager.c.layout.info()["name"] == "tile"
@manager_config
def test_adddelgroup(manager):
manager.test_window("one")
manager.c.addgroup("dummygroup")
manager.c.addgroup("testgroup")
assert "testgroup" in manager.c.groups().keys()
manager.c.window.togroup("testgroup")
manager.c.delgroup("testgroup")
assert "testgroup" not in manager.c.groups().keys()
# Assert that the test window is still a member of some group.
assert sum(len(i["windows"]) for i in manager.c.groups().values())
for i in list(manager.c.groups().keys())[:-1]:
manager.c.delgroup(i)
with pytest.raises(CommandException):
manager.c.delgroup(list(manager.c.groups().keys())[0])
# Assert that setting layout via cmd_addgroup works
manager.c.addgroup("testgroup2", layout='max')
assert manager.c.groups()["testgroup2"]['layout'] == 'max'
@manager_config
def test_delgroup(manager):
manager.test_window("one")
for i in ['a', 'd', 'c']:
manager.c.delgroup(i)
with pytest.raises(CommandException):
manager.c.delgroup('b')
@manager_config
def test_nextprevgroup(manager):
start = manager.c.group.info()["name"]
ret = manager.c.screen.next_group()
assert manager.c.group.info()["name"] != start
assert manager.c.group.info()["name"] == ret
ret = manager.c.screen.prev_group()
assert manager.c.group.info()["name"] == start
@manager_config
def test_toggle_group(manager):
manager.c.group["a"].toscreen()
manager.c.group["b"].toscreen()
manager.c.screen.toggle_group("c")
assert manager.c.group.info()["name"] == "c"
manager.c.screen.toggle_group("c")
assert manager.c.group.info()["name"] == "b"
manager.c.screen.toggle_group()
assert manager.c.group.info()["name"] == "c"
@manager_config
def test_static(manager):
manager.test_window("one")
manager.test_window("two")
manager.c.window[manager.c.window.info()["id"]].static(
screen=0, x=10, y=10, width=10, height=10,
)
info = manager.c.window.info()
assert info["name"] == "one"
manager.c.window.kill()
assert_window_died(manager.c, info)
with pytest.raises(CommandError):
manager.c.window.info()
info = manager.c.windows()[0]
assert info["name"] == "two"
assert (info["x"], info["y"], info["width"], info["height"]) == (10, 10, 10, 10)
@manager_config
def test_match(manager):
manager.test_window("one")
assert manager.c.window.info()['name'] == 'one'
assert not manager.c.window.info()['name'] == 'nonexistent'
@manager_config
def test_default_float(manager):
# change to 2 col stack
manager.c.next_layout()
assert len(manager.c.layout.info()["stacks"]) == 2
manager.test_window('float')
assert manager.c.group.info()['focus'] == 'float'
assert manager.c.window.info()['width'] == 100
assert manager.c.window.info()['height'] == 100
assert manager.c.window.info()['x'] == 350
assert manager.c.window.info()['y'] == 240
assert manager.c.window.info()['floating'] is True
manager.c.window.move_floating(10, 20)
assert manager.c.window.info()['width'] == 100
assert manager.c.window.info()['height'] == 100
assert manager.c.window.info()['x'] == 360
assert manager.c.window.info()['y'] == 260
assert manager.c.window.info()['floating'] is True
manager.c.window.set_position_floating(10, 20)
assert manager.c.window.info()['width'] == 100
assert manager.c.window.info()['height'] == 100
assert manager.c.window.info()['x'] == 10
assert manager.c.window.info()['y'] == 20
assert manager.c.window.info()['floating'] is True
@manager_config
def test_last_float_size(manager):
"""
When you re-float something it would be preferable to have it use the previous float size
"""
manager.test_window("one")
assert manager.c.window.info()['name'] == 'one'
assert manager.c.window.info()['width'] == 798
assert manager.c.window.info()['height'] == 578
# float and it moves
manager.c.window.toggle_floating()
assert manager.c.window.info()['width'] == 100
assert manager.c.window.info()['height'] == 100
# resize
manager.c.window.set_size_floating(50, 90)
assert manager.c.window.info()['width'] == 50
assert manager.c.window.info()['height'] == 90
# back to not floating
manager.c.window.toggle_floating()
assert manager.c.window.info()['width'] == 798
assert manager.c.window.info()['height'] == 578
# float again, should use last float size
manager.c.window.toggle_floating()
assert manager.c.window.info()['width'] == 50
assert manager.c.window.info()['height'] == 90
# make sure it works through min and max
manager.c.window.toggle_maximize()
manager.c.window.toggle_minimize()
manager.c.window.toggle_minimize()
manager.c.window.toggle_floating()
assert manager.c.window.info()['width'] == 50
assert manager.c.window.info()['height'] == 90
@manager_config
def test_float_max_min_combo(manager):
# change to 2 col stack
manager.c.next_layout()
assert len(manager.c.layout.info()["stacks"]) == 2
manager.test_window('two')
manager.test_window("one")
assert manager.c.group.info()['focus'] == 'one'
assert manager.c.window.info()['width'] == 398
assert manager.c.window.info()['height'] == 578
assert manager.c.window.info()['x'] == 400
assert manager.c.window.info()['y'] == 0
assert manager.c.window.info()['floating'] is False
manager.c.window.toggle_maximize()
assert manager.c.window.info()['floating'] is True
assert manager.c.window.info()['maximized'] is True
assert manager.c.window.info()['width'] == 800
assert manager.c.window.info()['height'] == 580
assert manager.c.window.info()['x'] == 0
assert manager.c.window.info()['y'] == 0
manager.c.window.toggle_minimize()
assert manager.c.group.info()['focus'] == 'one'
assert manager.c.window.info()['floating'] is True
assert manager.c.window.info()['minimized'] is True
assert manager.c.window.info()['width'] == 800
assert manager.c.window.info()['height'] == 580
assert manager.c.window.info()['x'] == 0
assert manager.c.window.info()['y'] == 0
manager.c.window.toggle_floating()
assert manager.c.group.info()['focus'] == 'one'
assert manager.c.window.info()['floating'] is False
assert manager.c.window.info()['minimized'] is False
assert manager.c.window.info()['maximized'] is False
assert manager.c.window.info()['width'] == 398
assert manager.c.window.info()['height'] == 578
assert manager.c.window.info()['x'] == 400
assert manager.c.window.info()['y'] == 0
@manager_config
def test_toggle_fullscreen(manager):
# change to 2 col stack
manager.c.next_layout()
assert len(manager.c.layout.info()["stacks"]) == 2
manager.test_window('two')
manager.test_window("one")
assert manager.c.group.info()['focus'] == 'one'
assert manager.c.window.info()['width'] == 398
assert manager.c.window.info()['height'] == 578
assert manager.c.window.info()['float_info'] == {
'y': 0, 'x': 400, 'width': 100, 'height': 100}
assert manager.c.window.info()['x'] == 400
assert manager.c.window.info()['y'] == 0
manager.c.window.toggle_fullscreen()
assert manager.c.window.info()['floating'] is True
assert manager.c.window.info()['maximized'] is False
assert manager.c.window.info()['fullscreen'] is True
assert manager.c.window.info()['width'] == 800
assert manager.c.window.info()['height'] == 600
assert manager.c.window.info()['x'] == 0
assert manager.c.window.info()['y'] == 0
manager.c.window.toggle_fullscreen()
assert manager.c.window.info()['floating'] is False
assert manager.c.window.info()['maximized'] is False
assert manager.c.window.info()['fullscreen'] is False
assert manager.c.window.info()['width'] == 398
assert manager.c.window.info()['height'] == 578
assert manager.c.window.info()['x'] == 400
assert manager.c.window.info()['y'] == 0
@manager_config
def test_toggle_max(manager):
# change to 2 col stack
manager.c.next_layout()
assert len(manager.c.layout.info()["stacks"]) == 2
manager.test_window('two')
manager.test_window("one")
assert manager.c.group.info()['focus'] == 'one'
assert manager.c.window.info()['width'] == 398
assert manager.c.window.info()['height'] == 578
assert manager.c.window.info()['float_info'] == {
'y': 0, 'x': 400, 'width': 100, 'height': 100}
assert manager.c.window.info()['x'] == 400
assert manager.c.window.info()['y'] == 0
manager.c.window.toggle_maximize()
assert manager.c.window.info()['floating'] is True
assert manager.c.window.info()['maximized'] is True
assert manager.c.window.info()['width'] == 800
assert manager.c.window.info()['height'] == 580
assert manager.c.window.info()['x'] == 0
assert manager.c.window.info()['y'] == 0
manager.c.window.toggle_maximize()
assert manager.c.window.info()['floating'] is False
assert manager.c.window.info()['maximized'] is False
assert manager.c.window.info()['width'] == 398
assert manager.c.window.info()['height'] == 578
assert manager.c.window.info()['x'] == 400
assert manager.c.window.info()['y'] == 0
@manager_config
def test_toggle_min(manager):
# change to 2 col stack
manager.c.next_layout()
assert len(manager.c.layout.info()["stacks"]) == 2
manager.test_window('two')
manager.test_window("one")
assert manager.c.group.info()['focus'] == 'one'
assert manager.c.window.info()['width'] == 398
assert manager.c.window.info()['height'] == 578
assert manager.c.window.info()['float_info'] == {
'y': 0, 'x': 400, 'width': 100, 'height': 100}
assert manager.c.window.info()['x'] == 400
assert manager.c.window.info()['y'] == 0
manager.c.window.toggle_minimize()
assert manager.c.group.info()['focus'] == 'one'
assert manager.c.window.info()['floating'] is True
assert manager.c.window.info()['minimized'] is True
assert manager.c.window.info()['width'] == 398
assert manager.c.window.info()['height'] == 578
assert manager.c.window.info()['x'] == 400
assert manager.c.window.info()['y'] == 0
manager.c.window.toggle_minimize()
assert manager.c.group.info()['focus'] == 'one'
assert manager.c.window.info()['floating'] is False
assert manager.c.window.info()['minimized'] is False
assert manager.c.window.info()['width'] == 398
assert manager.c.window.info()['height'] == 578
assert manager.c.window.info()['x'] == 400
assert manager.c.window.info()['y'] == 0
@manager_config
def test_toggle_floating(manager):
manager.test_window("one")
assert manager.c.window.info()['floating'] is False
manager.c.window.toggle_floating()
assert manager.c.window.info()['floating'] is True
manager.c.window.toggle_floating()
assert manager.c.window.info()['floating'] is False
manager.c.window.toggle_floating()
assert manager.c.window.info()['floating'] is True
# change layout (should still be floating)
manager.c.next_layout()
assert manager.c.window.info()['floating'] is True
@manager_config
def test_floating_focus(manager):
# change to 2 col stack
manager.c.next_layout()
assert len(manager.c.layout.info()["stacks"]) == 2
manager.test_window("two")
manager.test_window("one")
assert manager.c.window.info()['width'] == 398
assert manager.c.window.info()['height'] == 578
manager.c.window.toggle_floating()
manager.c.window.move_floating(10, 20)
assert manager.c.window.info()['name'] == 'one'
assert manager.c.group.info()['focus'] == 'one'
# check what stack thinks is focus
assert [x['current'] for x in manager.c.layout.info()['stacks']] == [0, 0]
# change focus to "one"
manager.c.group.next_window()
assert manager.c.window.info()['width'] == 398
assert manager.c.window.info()['height'] == 578
assert manager.c.window.info()['name'] != 'one'
assert manager.c.group.info()['focus'] != 'one'
# check what stack thinks is focus
# check what stack thinks is focus
assert [x['current'] for x in manager.c.layout.info()['stacks']] == [0, 0]
# focus back to one
manager.c.group.next_window()
assert manager.c.window.info()['name'] == 'one'
# check what stack thinks is focus
assert [x['current'] for x in manager.c.layout.info()['stacks']] == [0, 0]
# now focusing via layout is borked (won't go to float)
manager.c.layout.up()
assert manager.c.window.info()['name'] != 'one'
manager.c.layout.up()
assert manager.c.window.info()['name'] != 'one'
# check what stack thinks is focus
assert [x['current'] for x in manager.c.layout.info()['stacks']] == [0, 0]
# focus back to one
manager.c.group.next_window()
assert manager.c.window.info()['name'] == 'one'
# check what stack thinks is focus
assert [x['current'] for x in manager.c.layout.info()['stacks']] == [0, 0]
@manager_config
def test_move_floating(manager):
manager.test_window("one")
# manager.test_window("one")
assert manager.c.window.info()['width'] == 798
assert manager.c.window.info()['height'] == 578
assert manager.c.window.info()['x'] == 0
assert manager.c.window.info()['y'] == 0
manager.c.window.toggle_floating()
assert manager.c.window.info()['floating'] is True
manager.c.window.move_floating(10, 20)
assert manager.c.window.info()['width'] == 100
assert manager.c.window.info()['height'] == 100
assert manager.c.window.info()['x'] == 10
assert manager.c.window.info()['y'] == 20
manager.c.window.set_size_floating(50, 90)
assert manager.c.window.info()['width'] == 50
assert manager.c.window.info()['height'] == 90
assert manager.c.window.info()['x'] == 10
assert manager.c.window.info()['y'] == 20
manager.c.window.resize_floating(10, 20)
assert manager.c.window.info()['width'] == 60
assert manager.c.window.info()['height'] == 110
assert manager.c.window.info()['x'] == 10
assert manager.c.window.info()['y'] == 20
manager.c.window.set_size_floating(10, 20)
assert manager.c.window.info()['width'] == 10
assert manager.c.window.info()['height'] == 20
assert manager.c.window.info()['x'] == 10
assert manager.c.window.info()['y'] == 20
# change layout (x, y should be same)
manager.c.next_layout()
assert manager.c.window.info()['width'] == 10
assert manager.c.window.info()['height'] == 20
assert manager.c.window.info()['x'] == 10
assert manager.c.window.info()['y'] == 20
@manager_config
def test_one_screen(manager):
assert len(manager.c.screens()) == 1
@dualmonitor
@manager_config
def test_two_screens(manager):
assert len(manager.c.screens()) == 2
@manager_config
def test_focus_stays_on_layout_switch(manager):
manager.test_window("one")
manager.test_window("two")
# switch to a double stack layout
manager.c.next_layout()
# focus on a different window than the default
manager.c.layout.next()
# toggle the layout
manager.c.next_layout()
manager.c.prev_layout()
assert manager.c.window.info()['name'] == 'one'
@pytest.mark.parametrize("manager", [BareConfig, ManagerConfig], indirect=True)
def test_map_request(manager):
manager.test_window("one")
info = manager.c.groups()["a"]
assert "one" in info["windows"]
assert info["focus"] == "one"
manager.test_window("two")
info = manager.c.groups()["a"]
assert "two" in info["windows"]
assert info["focus"] == "two"
@pytest.mark.parametrize("manager", [BareConfig, ManagerConfig], indirect=True)
def test_unmap(manager):
one = manager.test_window("one")
two = manager.test_window("two")
three = manager.test_window("three")
info = manager.c.groups()["a"]
assert info["focus"] == "three"
assert len(manager.c.windows()) == 3
manager.kill_window(three)
assert len(manager.c.windows()) == 2
info = manager.c.groups()["a"]
assert info["focus"] == "two"
manager.kill_window(two)
assert len(manager.c.windows()) == 1
info = manager.c.groups()["a"]
assert info["focus"] == "one"
manager.kill_window(one)
assert len(manager.c.windows()) == 0
info = manager.c.groups()["a"]
assert info["focus"] is None
@pytest.mark.parametrize("manager", [BareConfig, ManagerConfig], indirect=True)
@multimonitor
def test_setgroup(manager):
manager.test_window("one")
manager.c.group["b"].toscreen()
manager.groupconsistency()
if len(manager.c.screens()) == 1:
assert manager.c.groups()["a"]["screen"] is None
else:
assert manager.c.groups()["a"]["screen"] == 1
assert manager.c.groups()["b"]["screen"] == 0
manager.c.group["c"].toscreen()
manager.groupconsistency()
assert manager.c.groups()["c"]["screen"] == 0
# Setting the current group once again switches back to the previous group
manager.c.group["c"].toscreen()
manager.groupconsistency()
assert manager.c.group.info()["name"] == "b"
@pytest.mark.parametrize("manager", [BareConfig, ManagerConfig], indirect=True)
@multimonitor
def test_unmap_noscreen(manager):
manager.test_window("one")
pid = manager.test_window("two")
assert len(manager.c.windows()) == 2
manager.c.group["c"].toscreen()
manager.groupconsistency()
manager.c.status()
assert len(manager.c.windows()) == 2
manager.kill_window(pid)
assert len(manager.c.windows()) == 1
assert manager.c.groups()["a"]["focus"] == "one"
class TScreen(libqtile.config.Screen):
def set_group(self, x, save_prev=True):
pass
def test_dx():
s = TScreen(left=libqtile.bar.Gap(10))
s._configure(None, 0, 0, 0, 100, 100, None)
assert s.dx == 10
def test_dwidth():
s = TScreen(left=libqtile.bar.Gap(10))
s._configure(None, 0, 0, 0, 100, 100, None)
assert s.dwidth == 90
s.right = libqtile.bar.Gap(10)
assert s.dwidth == 80
def test_dy():
s = TScreen(top=libqtile.bar.Gap(10))
s._configure(None, 0, 0, 0, 100, 100, None)
assert s.dy == 10
def test_dheight():
s = TScreen(top=libqtile.bar.Gap(10))
s._configure(None, 0, 0, 0, 100, 100, None)
assert s.dheight == 90
s.bottom = libqtile.bar.Gap(10)
assert s.dheight == 80
@manager_config
def test_labelgroup(manager):
manager.c.group["a"].toscreen()
assert manager.c.group["a"].info()["label"] == "a"
manager.c.labelgroup()
manager.c.widget["prompt"].fake_keypress("b")
manager.c.widget["prompt"].fake_keypress("Return")
assert manager.c.group["a"].info()["label"] == "b"
manager.c.labelgroup()
manager.c.widget["prompt"].fake_keypress("Return")
assert manager.c.group["a"].info()["label"] == "a"
@manager_config
def test_change_loglevel(manager):
assert manager.c.loglevel() == logging.INFO
assert manager.c.loglevelname() == 'INFO'
manager.c.debug()
assert manager.c.loglevel() == logging.DEBUG
assert manager.c.loglevelname() == 'DEBUG'
manager.c.info()
assert manager.c.loglevel() == logging.INFO
assert manager.c.loglevelname() == 'INFO'
manager.c.warning()
assert manager.c.loglevel() == logging.WARNING
assert manager.c.loglevelname() == 'WARNING'
manager.c.error()
assert manager.c.loglevel() == logging.ERROR
assert manager.c.loglevelname() == 'ERROR'
manager.c.critical()
assert manager.c.loglevel() == logging.CRITICAL
assert manager.c.loglevelname() == 'CRITICAL'
def test_switch_groups_cursor_warp(manager_nospawn):
class SwitchGroupsCursorWarpConfig(ManagerConfig):
cursor_warp = True
layouts = [libqtile.layout.Stack(num_stacks=2), libqtile.layout.Max()]
groups = [libqtile.config.Group("a"), libqtile.config.Group("b", layout="max")]
manager_nospawn.start(SwitchGroupsCursorWarpConfig)
manager_nospawn.test_window("one")
manager_nospawn.test_window("two")
manager_nospawn.c.layout.previous()
assert_focused(manager_nospawn, "one")
assert manager_nospawn.c.group.info()["name"] == "a"
assert manager_nospawn.c.layout.info()["name"] == "stack"
manager_nospawn.c.group["b"].toscreen()
manager_nospawn.test_window("three")
assert_focused(manager_nospawn, "three")
assert manager_nospawn.c.group.info()["name"] == "b"
assert manager_nospawn.c.layout.info()["name"] == "max"
# do a fast switch to trigger races in focus behavior; unfortunately we
# need the window in layout 'b' to map quite slowly (e.g. like firefox or
# something), which it does not here most of the time.
manager_nospawn.c.group["a"].toscreen()
manager_nospawn.c.group["b"].toscreen()
manager_nospawn.c.group["a"].toscreen()
# make sure the right things are still focused
assert_focused(manager_nospawn, "one")
assert manager_nospawn.c.group.info()["name"] == "a"
assert manager_nospawn.c.layout.info()["name"] == "stack"
manager_nospawn.c.group["b"].toscreen()
assert_focused(manager_nospawn, "three")
assert manager_nospawn.c.group.info()["name"] == "b"
assert manager_nospawn.c.layout.info()["name"] == "max"
| 34.145236 | 93 | 0.643846 |
223d74ee2fd6eb1ccb704ce63361401949f27ec4 | 6,351 | py | Python | f5/bigip/tm/gtm/test/functional/test_datacenter.py | nghia-tran/f5-common-python | acb23a6e5830a119b460c19a578654113419f5c3 | [
"Apache-2.0"
] | 272 | 2016-02-23T06:05:44.000Z | 2022-02-20T02:09:32.000Z | f5/bigip/tm/gtm/test/functional/test_datacenter.py | nghia-tran/f5-common-python | acb23a6e5830a119b460c19a578654113419f5c3 | [
"Apache-2.0"
] | 1,103 | 2016-02-11T17:48:03.000Z | 2022-02-15T17:13:37.000Z | f5/bigip/tm/gtm/test/functional/test_datacenter.py | nghia-tran/f5-common-python | acb23a6e5830a119b460c19a578654113419f5c3 | [
"Apache-2.0"
] | 167 | 2016-02-11T17:48:21.000Z | 2022-01-17T20:13:05.000Z | # Copyright 2014-2017 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pytest
from f5.bigip.tm.gtm.datacenter import Datacenter
from f5.sdk_exception import MissingRequiredCreationParameter
from pytest import symbols
from requests.exceptions import HTTPError
pytestmark = pytest.mark.skipif(
symbols
and hasattr(symbols, 'modules')
and not symbols.modules['gtm'],
reason='The modules symbol for GTM is set to False.'
)
def delete_dc(mgmt_root, name, partition):
try:
foo = mgmt_root.tm.gtm.datacenters.datacenter.load(
name=name, partition=partition
)
except HTTPError as err:
if err.response.status_code != 404:
raise
return
foo.delete()
def setup_create_test(request, mgmt_root, name, partition):
def teardown():
delete_dc(mgmt_root, name, partition)
request.addfinalizer(teardown)
def setup_basic_test(request, mgmt_root, name, partition):
def teardown():
delete_dc(mgmt_root, name, partition)
dc1 = mgmt_root.tm.gtm.datacenters.datacenter.create(
name=name, partition=partition)
request.addfinalizer(teardown)
return dc1
class TestCreate(object):
def test_create_no_args(self, mgmt_root):
with pytest.raises(MissingRequiredCreationParameter):
mgmt_root.tm.gtm.datacenters.datacenter.create()
def test_create(self, request, mgmt_root):
setup_create_test(request, mgmt_root, 'dc1', 'Common')
dc1 = mgmt_root.tm.gtm.datacenters.datacenter.create(
name='dc1', partition='Common')
assert dc1.name == 'dc1'
assert dc1.partition == 'Common'
assert dc1.generation and isinstance(dc1.generation, int)
assert dc1.kind == 'tm:gtm:datacenter:datacenterstate'
assert dc1.selfLink.startswith(
'https://localhost/mgmt/tm/gtm/datacenter/~Common~dc1')
def test_create_optional_args(self, request, mgmt_root):
setup_create_test(request, mgmt_root, 'dc1', 'Common')
dc1 = mgmt_root.tm.gtm.datacenters.datacenter.create(
name='dc1',
partition='Common',
enabled=False,
contact="[email protected]",
description="A datacenter is fine too",
location="Between the earth and the moon")
assert dc1.enabled is False
assert "[email protected]" == dc1.contact
assert "A datacenter is fine too" == dc1.description
assert "Between the earth and the moon" == dc1.location
def test_create_duplicate(self, request, mgmt_root):
setup_basic_test(request, mgmt_root, 'dc1', 'Common')
with pytest.raises(HTTPError) as err:
mgmt_root.tm.gtm.datacenters.datacenter.create(
name='dc1', partition='Common')
assert err.value.response.status_code == 409
class TestRefresh(object):
def test_refresh(self, request, mgmt_root):
setup_basic_test(request, mgmt_root, 'dc1', 'Common')
d1 = mgmt_root.tm.gtm.datacenters.datacenter.load(
name='dc1', partition='Common')
d2 = mgmt_root.tm.gtm.datacenters.datacenter.load(
name='dc1', partition='Common')
assert d1.enabled is True
assert d2.enabled is True
d2.update(enabled=False)
assert d2.enabled is False
assert d1.enabled is True
d1.refresh()
assert d1.enabled is False
class TestLoad(object):
def test_load_no_object(self, mgmt_root):
with pytest.raises(HTTPError) as err:
mgmt_root.tm.gtm.datacenters.datacenter.load(
name='dc1', partition='Common')
assert err.value.response.status_code == 404
def test_load(self, request, mgmt_root):
setup_basic_test(request, mgmt_root, 'dc1', 'Common')
dc1 = mgmt_root.tm.gtm.datacenters.datacenter.load(
name='dc1', partition='Common')
assert dc1.enabled is True
dc1.update(enabled=False)
dc2 = mgmt_root.tm.gtm.datacenters.datacenter.load(
name='dc1', partition='Common')
assert dc1.enabled is False
assert dc2.enabled is False
class TestUpdate(object):
def test_update(self, request, mgmt_root):
dc1 = setup_basic_test(request, mgmt_root, 'dc1', 'Common')
assert dc1.enabled is True
assert dc1.disabled is False
dc1.update(enabled=False)
assert dc1.enabled is False
assert dc1.disabled is True
def test_update_samevalue(self, request, mgmt_root):
dc1 = setup_basic_test(request, mgmt_root, 'dc1', 'Common')
dc1.update(enabled=True)
assert dc1.enabled is True
class TestDelete(object):
def test_delete(self, request, mgmt_root):
dc1 = setup_basic_test(request, mgmt_root, 'dc1', 'Common')
dc1.delete()
with pytest.raises(HTTPError) as err:
mgmt_root.tm.gtm.datacenters.datacenter.load(
name='dc1', partition='Common')
assert err.value.response.status_code == 404
class TestDatacenterCollection(object):
def test_datacenter_collection(self, request, mgmt_root):
setup_create_test(request, mgmt_root, 'dc1', 'Common')
dc1 = mgmt_root.tm.gtm.datacenters.datacenter.create(
name='dc1', partition='Common')
assert dc1.name == 'dc1'
assert dc1.partition == 'Common'
assert dc1.generation and isinstance(dc1.generation, int)
assert dc1.fullPath == '/Common/dc1'
assert dc1.kind == 'tm:gtm:datacenter:datacenterstate'
assert dc1.selfLink.startswith(
'https://localhost/mgmt/tm/gtm/datacenter/~Common~dc1')
rc = mgmt_root.tm.gtm.datacenters.get_collection()
assert isinstance(rc, list)
assert len(rc)
assert isinstance(rc[0], Datacenter)
| 36.291429 | 74 | 0.667769 |
2717ea40a531eec3c4bbb30063e5145cbdaf304b | 2,926 | py | Python | spotdl/providers/audio/youtube.py | phcreery/spotdl-v4 | 3bd3768de10ae80b5e1ba3bbe6b792f7fc9f8dfc | [
"MIT"
] | null | null | null | spotdl/providers/audio/youtube.py | phcreery/spotdl-v4 | 3bd3768de10ae80b5e1ba3bbe6b792f7fc9f8dfc | [
"MIT"
] | null | null | null | spotdl/providers/audio/youtube.py | phcreery/spotdl-v4 | 3bd3768de10ae80b5e1ba3bbe6b792f7fc9f8dfc | [
"MIT"
] | null | null | null | """
Youtube module for downloading and searching songs.
"""
from typing import List, Optional
from pytube import Search
from spotdl.utils.formatter import create_song_title, create_search_query
from spotdl.providers.audio.base import AudioProvider
from spotdl.types import Song
from spotdl.types.search_result import SearchResult
class YouTube(AudioProvider):
"""
YouTube audio provider class
"""
def search(self, song: Song) -> Optional[str]:
"""
Search for a video on YouTube.
### Arguments
- song: The song to search for.
### Returns
- The url of the best match or None if no match was found.
"""
if self.search_query:
search_query = create_search_query(
song, self.search_query, False, None, True
)
else:
# if isrc is not None then we try to find song with it
if song.isrc:
isrc_results = self.get_results(song.isrc)
if isrc_results and len(isrc_results) == 1:
isrc_result = isrc_results[0]
if isrc_result and isrc_result.link is not None:
return isrc_result.link
search_query = create_song_title(song.name, song.artists).lower()
# Query YTM by songs only first, this way if we get correct result on the first try
# we don't have to make another request to ytmusic api that could result in us
# getting rate limited sooner
results = self.get_results(search_query)
if results is None:
return None
if self.filter_results:
ordered_results = {results[0].link: 100}
else:
# Order results
ordered_results = self.order_results(results, song)
# No matches found
if len(ordered_results) == 0:
return None
result_items = list(ordered_results.items())
# Sort results by highest score
sorted_results = sorted(result_items, key=lambda x: x[1], reverse=True)
# Return the first result
return sorted_results[0][0]
@staticmethod
def get_results(
search_term: str, *_args, **_kwargs
) -> List[SearchResult]: # pylint: disable=W0221
"""
Get results from YouTube
### Arguments
- search_term: The search term to search for.
- args: Unused.
- kwargs: Unused.
### Returns
- A list of YouTube results if found, None otherwise.
"""
return [
SearchResult(
name=result.title,
link=result.watch_url,
duration=result.length,
provider="youtube",
artists=None,
album=None,
owner=result.author,
)
for result in Search(search_term).results
]
| 28.686275 | 91 | 0.58339 |
9f102748d8a22153c3e22ccce9480925c8b24684 | 3,718 | py | Python | polls/forms.py | arch1tect1/MSForHR | 8bab6329cc56a2b509d472b42f91ddd1aa3ac28b | [
"Apache-2.0"
] | null | null | null | polls/forms.py | arch1tect1/MSForHR | 8bab6329cc56a2b509d472b42f91ddd1aa3ac28b | [
"Apache-2.0"
] | null | null | null | polls/forms.py | arch1tect1/MSForHR | 8bab6329cc56a2b509d472b42f91ddd1aa3ac28b | [
"Apache-2.0"
] | null | null | null | from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.models import User
from django import forms
from .models import File
class FileAddForm(forms.ModelForm):
name = forms.CharField(label="", widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Name'}), )
date = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'type': 'date',}))
comments = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'your comments'}))
class Meta:
model = File
fields = ('name', 'date', 'comments', 'pdf')
def __init__(self, *args, **kwargs):
super(FileAddForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['class'] = 'form-control'
self.fields['name'].widget.attrs['placeholder'] = 'name'
self.fields['name'].label = ''
self.fields['name'].help_text = '<ul class="form-text text-muted small"><li>max 35 characters</li></ul>'
self.fields['date'].widget.attrs['class'] = 'form-control'
self.fields['date'].widget.attrs['placeholder'] = ''
self.fields['date'].label = ''
self.fields['date'].help_text = '<ul class="form-text text-muted small"><li>date added</li></ul>'
self.fields['comments'].widget.attrs['class'] = 'form-control'
self.fields['comments'].widget.attrs['placeholder'] = 'comments'
self.fields['comments'].label = ''
self.fields['comments'].help_text = '<span class="form-text text-muted"><small>add comments</small></span>'
class EditProfileForm(UserChangeForm):
password = forms.CharField(label="", widget=forms.TextInput(attrs={'type':'hidden'}))
class Meta:
model = User
#excludes private information from User
fields = ('username', 'first_name', 'last_name', 'email','password',)
class SignUpForm(UserCreationForm):
email = forms.EmailField(label="", widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Email Address'}), )
first_name = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'First Name'}))
last_name = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Last Name'}))
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)
def __init__(self, *args, **kwargs):
super(SignUpForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['username'].widget.attrs['placeholder'] = 'User Name'
self.fields['username'].label = ''
self.fields['username'].help_text = '<span class="form-text text-muted"><small>Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</small></span>'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['placeholder'] = 'Password'
self.fields['password1'].label = ''
self.fields['password1'].help_text = '<ul class="form-text text-muted small"><li>Your password can\'t be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password can\'t be a commonly used password.</li><li>Your password can\'t be entirely numeric.</li></ul>'
self.fields['password2'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['placeholder'] = 'Confirm Password'
self.fields['password2'].label = ''
self.fields['password2'].help_text = '<span class="form-text text-muted"><small>Enter the same password as before, for verification.</small></span>'
| 51.638889 | 334 | 0.68908 |
cd719f6ae4bfbeec1a74dbe07273ae538d85feb4 | 18,226 | py | Python | automol/vmat.py | sjklipp/automol | ba87f4443ebe2ceb5929d4269c4be93fd28f68ca | [
"Apache-2.0"
] | null | null | null | automol/vmat.py | sjklipp/automol | ba87f4443ebe2ceb5929d4269c4be93fd28f68ca | [
"Apache-2.0"
] | null | null | null | automol/vmat.py | sjklipp/automol | ba87f4443ebe2ceb5929d4269c4be93fd28f68ca | [
"Apache-2.0"
] | 7 | 2019-12-18T20:11:06.000Z | 2020-10-14T08:54:16.000Z | """ V-Matrix: Variable V-Matrix (V-Matrix without coordinate values)
"""
import itertools
import more_itertools
import numpy
import autoread as ar
import autowrite as aw
from phydat import ptab
# # constructors
def from_data(symbs, key_mat, name_mat=None, one_indexed=False):
""" V-Matrix constructor (V-Matrix without numerical coordinate values).
:param symbs: atomic symbols
:type symbs: tuple[str]
:param key_mat: key/index columns of the v-matrix, zero-indexed
:type key_mat: tuple[tuple[float, float or None, float or None]]
:param name_mat: coordinate name columns of the v-matrix
:type name_mat; tuple[tuple[str, str or None, str or None]]
:param one_indexed: parameter to store keys in one-indexing
:type one_indexed: bool
:rtype: automol V-Matrix data structure
"""
symbs = list(map(ptab.to_symbol, symbs))
natms = len(symbs)
key_mat = _key_matrix(key_mat, natms, one_indexed)
name_mat = _name_matrix(name_mat, natms)
vma = tuple(zip(symbs, key_mat, name_mat))
return vma
# # V-Matrix/V-Matrix common functions (document these as z-matrix functions)
# # # getters
def symbols(vma):
""" Obtain the atomic symbols for all atoms defined in the V-Matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: tuple(str)
"""
return tuple(zip(*vma))[0] if vma else ()
def key_matrix(vma, shift=0):
""" Obtain the key matrix of the V-Matrix that contains the
coordinate atom keys by row and column.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param shift: value to shift the keys by when obtaining the key matrix
:type shift: int
:rtype: tuple(tuple(int))
"""
if vma:
key_mat = tuple(zip(*vma))[1]
# post-processing for adding the shift
key_mat = [list(row) + [None]*(3-len(row)) for row in key_mat]
key_mat = numpy.array(key_mat)
tril_idxs = numpy.tril_indices(key_mat.shape[0], -1, m=3)
key_mat[tril_idxs] += shift
key_mat[tril_idxs] = key_mat[tril_idxs].astype(int)
else:
key_mat = ()
return tuple(map(tuple, key_mat))
def name_matrix(vma):
""" Obtain the name matrix of the V-Matrix that contains the
coordinate names by row and column.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: tuple(tuple(str))
"""
if vma:
name_mat = tuple(zip(*vma))[2]
else:
name_mat = ()
name_mat = [list(row) + [None]*(3-len(row)) for row in name_mat]
return tuple(map(tuple, name_mat))
# # # properties
def count(vma):
""" Obtain the number of rows of the V-Matrix, which corresponds to
the number of atoms defined in the V-Matrix. This includes all
real and dummy atoms.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: int
"""
return len(symbols(vma))
def atom_indices(vma, symb, match=True):
""" Obtain the indices of a atoms of a particular type in the geometry.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param match: grab idxs that match given atom type
:param symb: atomic symbol
:type symb: str
:param match: obtain indices of symbols that match the type?
:type match: bool
:rtype: tuple(int)
"""
symbs = symbols(vma)
idxs = tuple()
for idx, symb_ in enumerate(symbs):
if symb_ == symb and match:
idxs += (idx,)
elif symb_ != symb and not match:
idxs += (idx,)
return idxs
def coordinate_key_matrix(vma, shift=0):
""" Obtain the coordinate key matrix of the V-Matrix that contains the
coordinate keys by row and column.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param shift: value to shift the keys by when obtaining the key matrix
:type shift: int
:rtype: tuple(tuple(int))
"""
key_mat = key_matrix(vma, shift=shift)
natms = len(key_mat)
atm_keys = range(shift, natms+shift)
coo_key_mat = [[(atm_key,) + key_row[:col+1]
if key_row[col] is not None else None for col in range(3)]
for atm_key, key_row in zip(atm_keys, key_mat)]
return tuple(map(tuple, coo_key_mat))
def coordinates(vma, shift=0, multi=True):
""" Obtain the coordinate keys associated with each coordinate name,
as a dictionary. Values are sequences of coordinate keys,
since there may be multiple.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param shift: value to shift the keys by when obtaining the keys
:type shift: int
:param multi: parameter to grab multiple coordinate keys
:type multi: bool
:rtype: dict[str: tuple(int)]
"""
_names = numpy.ravel(name_matrix(vma))
coo_keys = numpy.ravel(coordinate_key_matrix(vma, shift))
if not multi:
coo_dct = dict(zip(_names, coo_keys))
else:
coo_dct = {name: () for name in _names}
for name, coo_key in zip(_names, coo_keys):
coo_dct[name] += (coo_key,)
coo_dct.pop(None)
return coo_dct
# # # names and standard naming
def names(vma):
""" Obtain names of all coordinates defined in the V-Matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: tuple(str)
"""
name_mat = name_matrix(vma)
_names = filter(lambda x: x is not None,
numpy.ravel(numpy.transpose(name_mat)))
return tuple(more_itertools.unique_everseen(_names))
def distance_names(vma):
""" Obtain names of all distance coordinates defined in the V-Matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: tuple(str)
"""
name_mat = numpy.array(name_matrix(vma))
return tuple(more_itertools.unique_everseen(name_mat[1:, 0]))
def central_angle_names(vma):
""" Obtain names of all central-angle coordinates defined in the V-Matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: tuple(str)
"""
name_mat = numpy.array(name_matrix(vma))
return tuple(more_itertools.unique_everseen(name_mat[2:, 1]))
def dihedral_angle_names(vma):
""" Obtain names of all dihedral angle coordinates defined in the V-Matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: tuple(str)
"""
name_mat = numpy.array(name_matrix(vma))
return tuple(more_itertools.unique_everseen(name_mat[3:, 2]))
def angle_names(vma):
""" Obtain names of all angle coordinates defined in the V-Matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: tuple(str)
"""
return tuple(itertools.chain(central_angle_names(vma),
dihedral_angle_names(vma)))
def dummy_coordinate_names(vma):
""" Obtain names of all coordinates associated with dummy atoms
defined in the V-Matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: tuple(str)
"""
symbs = symbols(vma)
name_mat = numpy.array(name_matrix(vma))
dummy_keys = [idx for idx, sym in enumerate(symbs)
if not ptab.to_number(sym)]
dummy_names = []
for dummy_key in dummy_keys:
for col_idx in range(3):
dummy_name = next(filter(lambda x: x is not None,
name_mat[dummy_key:, col_idx]))
dummy_names.append(dummy_name)
dummy_names = tuple(dummy_names)
return dummy_names
def standard_names(vma, shift=0):
""" Build a dictionary that can mas the coordinate names
of the input V-Matrix to their name in a standard-form V-Matrix:
RN: (1<=N<=Ncoords)
AN: (2<=N<=Ncoords)
DN: (1<=N<=Ncoords)
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param shift: value to shift the keys by when obtaining the keys
:type shift: int
:rtype: dict[str: str]
"""
dist_names = distance_names(vma)
cent_ang_names = central_angle_names(vma)
dih_ang_names = dihedral_angle_names(vma)
name_dct = {}
name_dct.update({
dist_name: f'R{num+shift+1:d}'
for num, dist_name in enumerate(dist_names)})
name_dct.update({
cent_ang_name: f'A{num+shift+2:d}'
for num, cent_ang_name in enumerate(cent_ang_names)})
name_dct.update({
dih_ang_name: f'D{num+shift+3:d}'
for num, dih_ang_name in enumerate(dih_ang_names)})
return name_dct
def standard_name_matrix(vma, shift=0):
""" Builds a name matrix of the V-Matrix where all of the
coordinate names have been standardized:
RN: (1<=N<=Ncoords)
AN: (2<=N<=Ncoords)
DN: (1<=N<=Ncoords)
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param shift: value to shift the keys by when obtaining the keys
:type shift: int
:rtype: tuple(tuple(str))
"""
natms = count(vma)
name_mat = numpy.array(name_matrix(vma), dtype=numpy.object_)
name_mat[1:, 0] = [
f'R{num+shift:d}' for num in range(1, natms)]
name_mat[2:, 1] = [
f'A{num+shift:d}' for num in range(2, natms)]
name_mat[3:, 2] = [
f'D{num+shift:d}' for num in range(3, natms)]
name_mat = tuple(map(tuple, name_mat))
return name_mat
# # V-Matrix-specific functions
# # # setters
def set_key_matrix(vma, key_mat):
""" Re-set the key matrix of a V-Matrix using the input key matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param key_mat: key matrix of V-Matrix coordinate keys
:type key_mat: tuple(tuple(int))
:rtype: tuple(str)
"""
symbs = symbols(vma)
name_mat = name_matrix(vma)
vma = from_data(symbs, key_mat, name_mat)
return vma
def set_name_matrix(vma, name_mat):
""" Re-set the name matrix of a V-Matrix using the input name matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param name_mat: name matrix of V-Matrix coordinate names
:type name_mat: tuple(tuple(int))
:rtype: tuple(str)
"""
symbs = symbols(vma)
key_mat = key_matrix(vma)
vma = from_data(symbs, key_mat, name_mat)
return vma
# # # names and naming
def rename(vma, name_dct):
""" Rename a subset of the coordinates of a V-Matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param name_dct: mapping from old coordinate names to new ones
:type name_dct: dict[str: str]
:rtype: automol V-Matrix data strucutre
"""
orig_name_mat = numpy.array(name_matrix(vma))
tril_idxs = numpy.tril_indices(orig_name_mat.shape[0], -1, m=3)
orig_names = set(orig_name_mat[tril_idxs])
assert set(name_dct.keys()) <= orig_names
name_dct.update({orig_name: orig_name for orig_name in orig_names
if orig_name not in name_dct})
name_mat = numpy.empty(orig_name_mat.shape, dtype=numpy.object_)
name_mat[tril_idxs] = list(map(name_dct.__getitem__,
orig_name_mat[tril_idxs]))
return from_data(symbols(vma), key_matrix(vma), name_mat)
def standard_form(vma, shift=0):
""" Build a V-Matrix where all of the coordinate names of an input V-Matrix
have been put into standard form:
RN: (1<=N<=Ncoords)
AN: (2<=N<=Ncoords)
DN: (1<=N<=Ncoords)
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param shift: value to shift the keys by when obtaining the keys
:type shift: int
:rtype: automol V-Matrix data strucutre
"""
name_mat = standard_name_matrix(vma, shift=shift)
return set_name_matrix(vma, name_mat)
# # # add/remove atoms
def add_atom(vma, symb, key_row, name_row=None, one_indexed=False):
""" Add an atom to a V-Matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param symb: symbol of atom to add
:type symb: str
:param key_row: row of keys to define new atom added to key matrix
:type key_row: tuple(int)
:param name_row: row of names to define new atom added to name matrix
:type name_row: tuple(str)
:param one_indexed: parameter to store keys in one-indexing
:type one_indexed: bool
:rtype: automol V-Matrix data structure
"""
symbs = symbols(vma)
symbs += (symb,)
key_mat = key_matrix(vma, shift=(1 if one_indexed else 0))
key_mat += (key_row,)
name_mat = None if name_row is None else name_matrix(vma) + (name_row,)
vma = from_data(
symbs, key_mat, name_mat, one_indexed=one_indexed)
return vma
def remove_atom(vma, key):
""" Remove an atom from a V-Matrix. Error raised if attempting
to remove atom other atoms depend on.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param key: key of atom to remove
:type key: str
:rtype: automol V-Matrix data structure
"""
symbs = list(symbols(vma))
symbs.pop(key)
key_mat = list(key_matrix(vma))
key_mat.pop(key)
key_mat = numpy.array(key_mat, dtype=numpy.object_)
if (key_mat == key).any():
raise ValueError(f"Other atoms in z-matrix depend on atom {key}")
key_map = numpy.vectorize(lambda x: x if (x is None or x < key) else x-1)
key_mat = key_map(key_mat)
name_mat = list(name_matrix(vma))
name_mat.pop(key)
vma = from_data(symbs, key_mat, name_mat)
return vma
# # # validation
def is_valid(vma):
""" Assess if a V-Matrix has proper structure.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: bool
"""
ret = True
try:
assert _is_sequence_of_triples(vma)
symbs, key_mat, name_mat = zip(*vma)
from_data(symbs, key_mat, name_mat)
except AssertionError:
ret = False
return ret
def is_standard_form(vma):
""" Assesses if the names of the V-Matrix are in standard form:
RN: (1<=N<=Ncoords)
AN: (2<=N<=Ncoords)
DN: (1<=N<=Ncoords)
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: bool
"""
return names(vma) == names(standard_form(vma))
# # # I/O
def string(vma, one_indexed=True):
""" Write a V-Matrix object to a string.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:param one_indexed: parameter to write keys in one-indexing
:type one_indexed: bool
:rtype: str
"""
shift = 1 if one_indexed else 0
vma_str = aw.vmat.write(
symbs=symbols(vma),
key_mat=key_matrix(vma, shift=shift),
name_mat=name_matrix(vma),
)
return vma_str
def from_string(vma_str):
""" Parse a V-Matrix object from a string.
:param vma_str: string containing a V-Matrix
:type vma_str: str
:rtype: automol V-Matrix data structure
"""
symbs, key_mat, name_mat = ar.vmat.read(vma_str)
vma = from_data(symbs, key_mat, name_mat, one_indexed=True)
return vma
# # helpers
def _key_matrix(key_mat, natms, one_indexed):
""" Build name matrix of the V-Matrix that contains the
coordinate keys by row and column.
:param key_mat: key matrix of V-Matrix coordinate keys
:type key_mat: tuple(tuple(int))
:param natms: number of atoms
:type natms: int
:param one_indexed: parameter to write keys in one-indexing
:type one_indexed: bool
:rtype: tuple(tuple(str))
"""
# Check dimensions and ensure proper formatting
key_mat = [list(row) + [None]*(3-len(row)) for row in key_mat]
key_mat = numpy.array(key_mat, dtype=numpy.object_)
assert key_mat.ndim == 2 and key_mat.shape == (natms, 3)
triu_idxs = numpy.triu_indices(natms, m=3)
key_mat[1:, 0] -= 1 if one_indexed else 0
key_mat[2:, 1] -= 1 if one_indexed else 0
key_mat[3:, 2] -= 1 if one_indexed else 0
key_mat[triu_idxs] = None
return tuple(map(tuple, key_mat))
def _name_matrix(name_mat, natms):
""" Build name matrix of the V-Matrix that contains the
coordinate names by row and column.
:param name_mat: key matrix of V-Matrix coordinate keys
:type name_mat: tuple(tuple(int))
:param natms: number of atoms
:type natms: int
:rtype: tuple(tuple(str))
"""
if name_mat is None:
name_mat = numpy.empty((natms, 3), dtype=numpy.object_)
for row in range(0, natms):
if row > 0:
name_mat[row, 0] = f'R{row:d}'
if row > 1:
name_mat[row, 1] = f'A{row:d}'
if row > 2:
name_mat[row, 2] = f'D{row:d}'
# Check dimensions and make sure there are Nones in the right places
name_mat = [list(row) + [None]*(3-len(row)) for row in name_mat]
name_mat = numpy.array(name_mat, dtype=numpy.object_)
assert name_mat.ndim == 2 and name_mat.shape == (natms, 3)
natms = name_mat.shape[0]
triu_idxs = numpy.triu_indices(natms, m=3)
tril_idxs = numpy.tril_indices(natms, -1, m=3)
assert all(isinstance(name, str) for name in name_mat[tril_idxs])
name_mat[triu_idxs] = None
return tuple(map(tuple, name_mat))
def _is_sequence_of_triples(obj):
""" Assess if input object sequence has length of three.
:param obj: object with __len__ attribute
:type obj: list, tuple, dict
:rtype: bool
"""
ret = hasattr(obj, '__len__')
if ret:
ret = all(hasattr(item, '__len__') and len(item) == 3 for item in obj)
return ret
| 29.302251 | 79 | 0.626029 |
32a7740e83e40107c5183a4c5032016cf108b47d | 2,310 | py | Python | code/ch_02_foundations/_03_multipe_compares.py | TimothyHelton/write-pythonic-code-demos | 5d8aff7ee261f6b2ea0085d9a428d34b1bb875d0 | [
"MIT"
] | null | null | null | code/ch_02_foundations/_03_multipe_compares.py | TimothyHelton/write-pythonic-code-demos | 5d8aff7ee261f6b2ea0085d9a428d34b1bb875d0 | [
"MIT"
] | null | null | null | code/ch_02_foundations/_03_multipe_compares.py | TimothyHelton/write-pythonic-code-demos | 5d8aff7ee261f6b2ea0085d9a428d34b1bb875d0 | [
"MIT"
] | null | null | null | from enum import Enum
from timeit import repeat
def main():
d_text = input("Which direction [n,s,w,e,nw,ne,sw,se]? ")
m = Moves.parse(d_text)
if m is None:
print("That's not a move!")
return
print(m)
# ******** less pythonic ********
if m == Moves.North or m == Moves.South or m == Moves.West or \
m == Moves.East:
print("That's a direct move.")
else:
print("That's a diagonal move.")
# ******** more pythonic ********
if m in {Moves.North, Moves.South, Moves.West, Moves.East}:
print("That's a direct move.")
else:
print("That's a diagonal move.")
time_for_loop(m)
class Moves(Enum):
West = 1
North = 2
East = 3
South = 4
NorthEast = 5
SouthEast = 6
NorthWest = 7
SouthWest = 8
@staticmethod
def parse(text: str):
if not text:
return None
text = text.strip().lower()
if text == 'w':
return Moves.West
if text == 'e':
return Moves.East
if text == 's':
return Moves.South
if text == 'n':
return Moves.North
if text == 'nw':
return Moves.NorthWest
if text == 'sw':
return Moves.SouthWest
if text == 'ne':
return Moves.NorthEast
if text == 'se':
return Moves.SouthEast
return None
def time_for_loop(move: Moves):
"""
Display the cpu time required to execute various types of for loops.
:param move: integer describing move
"""
g = {'m': move}
statements = {
# 'test_name': (timer_statement, timer_globals),
'or': ('m == 0 or m == 1 or m == 2 or m == 3', g),
'set': ('m in range(3)', g),
'global': ('m in direction', {**{'direction': range(3)}, **g}),
}
times = {}
for name, args in statements.items():
kwargs = {k: v for k, v in zip(('stmt', 'globals'), args)}
times[name] = min(repeat(repeat=3, **kwargs))
sorted_times = sorted(times.items(), key=lambda x: x[1])
sorted_times = [x for row in sorted_times for x in row]
fmt = '{:<%d} : ' % max(map(len, times))
print(((fmt + '{:.3f}\n') * 3).format(*sorted_times))
if __name__ == '__main__':
main()
| 24.574468 | 72 | 0.517749 |
0dbccd2eeeae1b022adef06c9a5c7fcb7dada719 | 790 | py | Python | XML/ex3_xmltodict_single.py | ramyacr97/RamyaPython | 27ae8c88ec1459372d422fa5f97baa415898f875 | [
"Apache-2.0"
] | null | null | null | XML/ex3_xmltodict_single.py | ramyacr97/RamyaPython | 27ae8c88ec1459372d422fa5f97baa415898f875 | [
"Apache-2.0"
] | 4 | 2021-03-31T19:20:41.000Z | 2021-12-13T20:25:28.000Z | XML/ex3_xmltodict_single.py | ramyacr97/RamyaPython | 27ae8c88ec1459372d422fa5f97baa415898f875 | [
"Apache-2.0"
] | null | null | null | #!usr/bin/env python
import xmltodict
def fileopenread(filename):
f = open(filename)
xmldata = f.read().strip()
my_xml = xmltodict.parse(xmldata)
return my_xml
file1 = fileopenread("show_security_zones.xml")
file2 = fileopenread("show_security_zones_single_trust.xml")
#####Question 3B ####
print(type(file1['zones-information']['zones-security']))
print(type(file2['zones-information']['zones-security']))
#n#### Question 3C ###
def fileopenread_forcelist(filename):
f = open(filename)
xmldata1 = f.read().strip()
my_xml1 = xmltodict.parse(xmldata1, force_list = {'zones-security': True})
return my_xml1
security_zone1 = fileopenread_forcelist("show_security_zones_single_trust.xml")
print(type(security_zone1['zones-information']['zones-security']))
| 29.259259 | 79 | 0.729114 |
4bae7ab2047a69911a92b0f68c9f0b4d1d6ace11 | 848 | py | Python | test/test_control_flow.py | vlasenkov/matchbox | e29f8ae177218cf03b0b613a7c20fff7ca1919cf | [
"Apache-2.0",
"BSD-3-Clause"
] | 499 | 2018-03-28T21:01:10.000Z | 2022-02-17T06:27:51.000Z | test/test_control_flow.py | vlasenkov/matchbox | e29f8ae177218cf03b0b613a7c20fff7ca1919cf | [
"Apache-2.0",
"BSD-3-Clause"
] | 14 | 2018-03-29T13:20:26.000Z | 2019-03-14T01:15:33.000Z | test/test_control_flow.py | vlasenkov/matchbox | e29f8ae177218cf03b0b613a7c20fff7ca1919cf | [
"Apache-2.0",
"BSD-3-Clause"
] | 26 | 2018-03-28T21:11:09.000Z | 2021-10-19T19:38:14.000Z | # Copyright (c) 2018, salesforce.com, inc.
# All rights reserved.
# Licensed under the BSD 3-Clause license.
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
import torch
from torch.autograd import Variable
from torch import nn
import matchbox
from matchbox import functional as F
from matchbox import MaskedBatch, batch
from matchbox.test_utils import mb_test, mb_assert
import random
@batch
def while_loop(x):
while x > 0:
x = x - 1
return x
def test_while():
mb_test(while_loop, (4, ()))
@batch
def if_else(x):
if x > 0:
x = x - 1
else:
pass
return x
def test_if_else():
mb_test(if_else, (4, ()))
@batch
def if_noelse(x):
if x > 0:
x = x - 1
return x
def test_if_noelse():
mb_test(if_noelse, (4, ()))
| 18.844444 | 62 | 0.661557 |
4713d89d578166f230969f0e1afe20509566ac03 | 12,806 | py | Python | pyinfra/api/state.py | ryan109/pyinfra | 6814920c634a2a047299875077633f72ecc46fce | [
"MIT"
] | 1 | 2020-04-12T16:15:15.000Z | 2020-04-12T16:15:15.000Z | pyinfra/api/state.py | gchazot/pyinfra | 40dd01f11086dba2be20fa2f509556abb40d84f8 | [
"MIT"
] | null | null | null | pyinfra/api/state.py | gchazot/pyinfra | 40dd01f11086dba2be20fa2f509556abb40d84f8 | [
"MIT"
] | null | null | null | # pyinfra
# File: pyinfra/api/state.py
# Desc: class that represents the current pyinfra.state
from __future__ import division, unicode_literals
from contextlib import contextmanager
from multiprocessing import cpu_count
from uuid import uuid4
import six
from gevent.pool import Pool
from pkg_resources import parse_version
from pyinfra import __version__, logger
from .config import Config
from .exceptions import PyinfraError
from .util import ensure_host_list, sha1_hash
# Work out the max parallel we can achieve with the open files limit of the user/process,
# take 10 for opening Python files and /3 for ~3 files per host during op runs.
# See: https://github.com/Fizzadar/pyinfra/issues/44
try:
from resource import getrlimit, RLIMIT_NOFILE
nofile_limit, _ = getrlimit(RLIMIT_NOFILE)
MAX_PARALLEL = round((nofile_limit - 10) / 3)
# Resource isn't available on Windows
except ImportError:
nofile_limit = 0
MAX_PARALLEL = None
def _make_name(current, new):
'''
Stops duplication between similarly named nested deploys, eg:
Turn:
Deploy Kubernetes master/Configure Kubernetes
Into:
Deploy Kubernetes master/Configure
'''
current_tokens = current.split()
new_tokens = new.split()
new = ' '.join(
new_token for new_token in new_tokens
if new_token not in current_tokens
)
return '/'.join((current, new))
class State(object):
'''
Manages state for a pyinfra deploy.
'''
initialised = False
# A pyinfra.api.Inventory which stores all our pyinfra.api.Host's
inventory = None
# A pyinfra.api.Config
config = None
# Main gevent pool
pool = None
# Whether we are in an @operation (so inner ops aren't wrapped)
in_op = False
# Whether we are deploying (ie hosts are all ready)
deploying = False
# Current op hash for use w/facts
current_op_hash = None
# Name of the current deploy
in_deploy = False
deploy_name = None
deploy_kwargs = None
deploy_data = None
deploy_line_numbers = None
# Flags for printing
print_output = False # print output from the actual deploy (-v)
print_fact_info = False # log fact gathering as INFO > DEBUG (-v)
print_fact_output = False # print output from facts (-vv)
# Used in CLI
deploy_dir = None # base directory for locating files/templates/etc
current_op_file = 0 # increments for each file excuted to maintain order
def __init__(self, inventory=None, config=None, **kwargs):
if inventory:
self.init(inventory, config, **kwargs)
def init(self, inventory, config, initial_limit=None):
# Config validation
#
# If no config, create one using the defaults
if config is None:
config = Config()
# Error if our min version is not met
if config.MIN_PYINFRA_VERSION is not None:
running_version = parse_version(__version__)
needed_version = parse_version(
# Version must be a string
six.text_type(config.MIN_PYINFRA_VERSION),
)
if needed_version > running_version:
raise PyinfraError((
'Minimum pyinfra version not met '
'(minimum={0}, running={1})'
).format(
config.MIN_PYINFRA_VERSION,
__version__,
))
if not config.PARALLEL:
# TODO: benchmark this
# In my own tests the optimum number of parallel SSH processes is
# ~20 per CPU core - no science here yet, needs benchmarking!
cpus = cpu_count()
ideal_parallel = cpus * 20
config.PARALLEL = (
min(ideal_parallel, len(inventory), MAX_PARALLEL)
if MAX_PARALLEL is not None
else min(ideal_parallel, len(inventory))
)
# If explicitly set, just issue a warning
elif MAX_PARALLEL is not None and config.PARALLEL > MAX_PARALLEL:
logger.warning((
'Parallel set to {0}, but this may hit the open files limit of {1}.\n'
' Max recommended value: {2}'
).format(config.PARALLEL, nofile_limit, MAX_PARALLEL))
# Actually initialise the state object
#
# Setup greenlet pools
self.pool = Pool(config.PARALLEL)
self.fact_pool = Pool(config.PARALLEL)
# Connection storage
self.ssh_connections = {}
self.sftp_connections = {}
# Private keys
self.private_keys = {}
# Facts storage
self.facts = {}
self.fact_locks = {}
# Assign inventory/config
self.inventory = inventory
self.config = config
# Hosts we've activated at any time
self.activated_hosts = set()
# Active hosts that *haven't* failed yet
self.active_hosts = set()
# Hosts that are ready to be deployed to
self.ready_hosts = set()
# Limit hosts changes dynamically to limit operations to a subset of hosts
self.limit_hosts = initial_limit
# Op basics
self.op_line_numbers_to_hash = {}
self.op_meta = {} # maps operation hash -> names/etc
self.ops_run = set() # list of ops which have been started/run
# Op dict for each host
self.ops = {
host: {}
for host in inventory
}
# Facts dict for each host
self.facts = {
host: {}
for host in inventory
}
# Meta dict for each host
self.meta = {
host: {
'ops': 0, # one function call in a deploy file
'commands': 0, # actual # of commands to run
'op_hashes': set(),
}
for host in inventory
}
# Results dict for each host
self.results = {
host: {
'ops': 0, # success_ops + failed ops w/ignore_errors
'success_ops': 0,
'error_ops': 0,
'commands': 0,
}
for host in inventory
}
# Assign state back references to inventory & config
inventory.state = config.state = self
self.initialised = True
def limit(self, hosts):
logger.warning((
'Use of `State.limit` is deprecated, '
'please use normal `if` statements instead.'
))
return self.hosts(hosts)
@contextmanager
def hosts(self, hosts):
logger.warning((
'Use of `State.hosts` is deprecated, '
'please use normal `if` statements instead.'
))
hosts = ensure_host_list(hosts, inventory=self.inventory)
# Store the previous value
old_limit_hosts = self.limit_hosts
# Limit the new hosts to a subset of the old hosts if they existed
if old_limit_hosts is not None:
hosts = [
host for host in hosts
if host in old_limit_hosts
]
# Set the new value
self.limit_hosts = hosts
logger.debug('Setting limit to hosts: {0}'.format(hosts))
yield
# Restore the old value
self.limit_hosts = old_limit_hosts
logger.debug('Reset limit to hosts: {0}'.format(old_limit_hosts))
@contextmanager
def when(self, predicate):
logger.warning((
'Use of `State.when` is deprecated, '
'please use normal `if` statements instead.'
))
# Truth-y? Just yield/end, nothing happens here!
if predicate:
yield
return
# Otherwise limit any operations within to match no hosts
with self.hosts([]):
yield
@contextmanager
def deploy(self, name, kwargs, data, line_number, in_deploy=True):
'''
Wraps a group of operations as a deploy, this should not be used
directly, instead use ``pyinfra.api.deploy.deploy``.
'''
# Handle nested deploy names
if self.deploy_name:
name = _make_name(self.deploy_name, name)
# Store the previous values
old_in_deploy = self.in_deploy
old_deploy_name = self.deploy_name
old_deploy_kwargs = self.deploy_kwargs
old_deploy_data = self.deploy_data
old_deploy_line_numbers = self.deploy_line_numbers
self.in_deploy = in_deploy
# Limit the new hosts to a subset of the old hosts if they existed
if (
old_deploy_kwargs
and old_deploy_kwargs.get('hosts') is not None
):
# If we have hosts - subset them based on the old hosts
if 'hosts' in kwargs:
kwargs['hosts'] = [
host for host in kwargs['hosts']
if host in old_deploy_kwargs['hosts']
]
# Otherwise simply carry the previous hosts
else:
kwargs['hosts'] = old_deploy_kwargs['hosts']
# Make new line numbers - note convert from and back to tuple to avoid
# keeping deploy_line_numbers mutable.
new_line_numbers = list(self.deploy_line_numbers or [])
new_line_numbers.append(line_number)
new_line_numbers = tuple(new_line_numbers)
# Set the new values
self.deploy_name = name
self.deploy_kwargs = kwargs
self.deploy_data = data
self.deploy_line_numbers = new_line_numbers
logger.debug('Starting deploy {0} (args={1}, data={2})'.format(
name, kwargs, data,
))
yield
# Restore the previous values
self.in_deploy = old_in_deploy
self.deploy_name = old_deploy_name
self.deploy_kwargs = old_deploy_kwargs
self.deploy_data = old_deploy_data
self.deploy_line_numbers = old_deploy_line_numbers
logger.debug('Reset deploy to {0} (args={1}, data={2})'.format(
old_deploy_name, old_deploy_kwargs, old_deploy_data,
))
def get_op_order(self):
line_numbers_to_hash = self.op_line_numbers_to_hash
sorted_line_numbers = sorted(list(line_numbers_to_hash.keys()))
return [
line_numbers_to_hash[numbers]
for numbers in sorted_line_numbers
]
def activate_host(self, host):
'''
Flag a host as active.
'''
logger.debug('Activating host: {0}'.format(host))
# Add to *both* activated and active - active will reduce as hosts fail
# but connected will not, enabling us to track failed %.
self.activated_hosts.add(host)
self.active_hosts.add(host)
# def ready_host(self, host):
# '''
# Flag a host as ready, after which facts will not be gathered for it.
# '''
# logger.debug('Readying host: {0}'.format(host))
# self.ready_hosts.add(host)
def fail_hosts(self, hosts_to_fail, activated_count=None):
'''
Flag a ``set`` of hosts as failed, error for ``config.FAIL_PERCENT``.
'''
if not hosts_to_fail:
return
activated_count = activated_count or len(self.activated_hosts)
logger.debug('Failing hosts: {0}'.format(', '.join(
(host.name for host in hosts_to_fail),
)))
# Remove the failed hosts from the inventory
self.active_hosts -= hosts_to_fail
# Check we're not above the fail percent
active_hosts = self.active_hosts
# No hosts left!
if not active_hosts:
raise PyinfraError('No hosts remaining!')
if self.config.FAIL_PERCENT is not None:
percent_failed = (
1 - len(active_hosts) / activated_count
) * 100
if percent_failed > self.config.FAIL_PERCENT:
raise PyinfraError('Over {0}% of hosts failed ({1}%)'.format(
self.config.FAIL_PERCENT,
int(round(percent_failed)),
))
def is_host_in_limit(self, host):
'''
Returns a boolean indicating if the host is within the current state limit.
'''
limit_hosts = self.limit_hosts
if not isinstance(limit_hosts, list):
return True
return host in limit_hosts
def get_temp_filename(self, hash_key=None):
'''
Generate a temporary filename for this deploy.
'''
if not hash_key:
hash_key = six.text_type(uuid4())
temp_filename = '{0}/{1}'.format(
self.config.TEMP_DIR, sha1_hash(hash_key),
)
return temp_filename
| 30.20283 | 89 | 0.594643 |
77c57052abd41c1bb9190a1d3ce603cd4008e431 | 6,194 | py | Python | codebase/database.py | JamesWRC/Cloudflare_DDNS | 283422628f66b305c7d230e35adb5a3a6a5963f3 | [
"MIT"
] | 1 | 2020-09-10T12:18:41.000Z | 2020-09-10T12:18:41.000Z | codebase/database.py | JamesWRC/Cloudflare_DDNS | 283422628f66b305c7d230e35adb5a3a6a5963f3 | [
"MIT"
] | null | null | null | codebase/database.py | JamesWRC/Cloudflare_DDNS | 283422628f66b305c7d230e35adb5a3a6a5963f3 | [
"MIT"
] | 1 | 2021-11-29T16:26:13.000Z | 2021-11-29T16:26:13.000Z | from sqlalchemy import Table, Column, Integer, String, MetaData, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from util import Util
import os
from undoAction import UndoAction
import time
# Define the util object
util = Util()
Base = declarative_base()
db_engine = create_engine('sqlite:///' + util.databaseFileName)
# Try changing this to True and see what happens
db_engine.echo = False
metadata = MetaData(db_engine)
Session = sessionmaker(bind=db_engine)
Session.configure(bind=db_engine)
session = Session()
class Database:
def createUpdates(self):
# Visitors table holds
updates = Table('requests', metadata,
Column('dns_id', String(256)),
Column('name', String(256)),
Column('record_type', String(10)),
Column('ip_address', String(40)),
Column('proxied', String(40)))
updates.create()
def run(self):
self.createUpdates()
def buildDatabaseTables(self):
print("\n\t[+]\t\t Building Database...")
Base.metadata.create_all(db_engine)
def testDatabaseExists(self):
print(
"\n\n\t[-]\t\t Testing the database...\n\n")
# Test to see if database exists
if os.path.isfile(util.databaseFileName):
retVal = True
print(
"\t[+]\t\t Database exists, OK.")
else:
retVal = False
print(
"\t[+]\t\t WARNING: Database not found! This is ok if you are running the tool in a Docker container\
\n\t\t\t\tand the container is starting up...")
print("\t[+]\t\t INFO: Building a clean database...\n\n")
# Build database
Database().buildDatabaseTables()
# Sleep a few seconds to ensure database is created
time.sleep(5)
# Populate Access Rules from Cloudflare
print(
"\t[+]\t\t INFO: Populating database with existing DNS records...\n\n")
UndoAction().updateDatabase() # FIX UP LATER
return retVal
############## Below are the classes of the database. ##############
class Visitors(Base):
# The visitors of the site / resource
__tablename__ = 'visitors'
id = Column(Integer, primary_key=True, autoincrement=True)
ip_address = Column(String)
action = Column(String)
user_agent = Column(String)
path = Column(String)
query_string = Column(String)
asn = Column(String)
country = Column(String)
rule_id = Column(String)
requested_at = Column(String)
ray_name = Column(String)
def addVisitor(self, action, ip_address, user_agent, path, query_string,
asn, country, rule_id, requested_at, ray_name):
# Create a new visitor to the database.
visitor = Visitors()
visitor.ip_address = ip_address
visitor.action = action
visitor.user_agent = user_agent
visitor.path = path
visitor.query_string = query_string
visitor.asn = asn
visitor.country = country
visitor.rule_id = rule_id
visitor.requested_at = requested_at
visitor.ray_name = ray_name
session.add(visitor)
session.commit()
def getUniqueIPs(self):
# Returns a list of unique IP addresses in the Database.
query = session.query(
Visitors.ip_address.distinct().label("ip_address"))
titles = [row.ip_address for row in query.all()]
return titles
def getNumberOfRequestsFromIP(self, ip):
count = session.query(Visitors).filter(
Visitors.ip_address == ip).count()
return count
def getLastHost(self):
lastHost = session.query(Visitors).order_by(Visitors.id.desc()).first()
return lastHost
def deleteAllRows(self):
session.query(Visitors).delete()
session.commit()
print("delete all")
def __repr__(self):
# Return the record in a string format
return "< Visitor(IP Address='%s', user_agent='%s', method='%s', path='%s', \
query_string='%s', asn='%s', country='%s', rule_id='%s') >" % (self.ip_address, self.user_agent, self.method,
self.path, self.query_string, self.asn, self.country, self.rule_id)
class ActionHistory(Base):
# This will store the request log cursors.
# Will keep a record of where we are up to in the Cloudflare logs.
__tablename__ = 'actionHistory'
id = Column(Integer, primary_key=True, autoincrement=True)
ip_Address = Column(String)
uiid = Column(String)
note = Column(String)
actioned_date = Column(String)
revoke_date = Column(String)
def addActionHistory(self, ip, uiid, note, actioned_date, revoke_date):
# uiid = unique IP ID
log = ActionHistory(ip_Address=ip, uiid=uiid, note=note,
actioned_date=actioned_date, revoke_date=revoke_date)
session.add(log)
session.commit()
def getActionByIP(self, hostip):
ret = session.query(ActionHistory).filter_by(ip_Address=hostip).first()
return ret
def getActionByUUID(self, uiid):
ret = session.query(ActionHistory).filter_by(uiid=uiid).first()
return ret
def updateRecordUIID(self, ip, id):
record = session.query(ActionHistory).filter_by(
ip_Address=ip).first()
record.uiid = id
session.commit()
def getRules(self):
return session.query(ActionHistory).all()
def deleteRule(self, uiid):
session.query(ActionHistory).filter_by(
uiid=uiid).delete()
session.commit()
def __repr__(self):
return "< LogHostory(IPAddress='%s', UUID='%s', Note='%s', ActionDate='%s', RevokeDate='%s')> " % (str(self.ip_Address), str(self.uiid), str(self.note), str(self.actioned_date), str(self.revoke_date))
if __name__ == '__main__':
# build tables
Database().testDatabaseExists()
| 35.193182 | 208 | 0.611882 |
479eb08a8fac2788d9b6ca9c50e073bb52cc22fc | 1,568 | py | Python | Python/accountant/Amount.py | Fornost461/drafts | 39f56fb16ebf206077e5f8617741aa93623195af | [
"CC0-1.0"
] | null | null | null | Python/accountant/Amount.py | Fornost461/drafts | 39f56fb16ebf206077e5f8617741aa93623195af | [
"CC0-1.0"
] | null | null | null | Python/accountant/Amount.py | Fornost461/drafts | 39f56fb16ebf206077e5f8617741aa93623195af | [
"CC0-1.0"
] | null | null | null | #!/usr/bin/env python3
# symbol
# precision
# number of digits after period
# int >= 0 or 'unlimited'
# todo
# decimal separator
# generalize auto_attributes to use it with the other modules
# mix-in? class decorator?
class Amount:
constant_defaults = dict(symbol = '€', precision = 2, symbol_side = 'right')
dynamic_defaults = dict(l = lambda : []) # useless here, shown only for showcasing purposes
auto_attributes = 'value symbol precision symbol_side'.split()
def __init__(self, **kwargs):
for attribute in auto_attributes:
if attribute in kwargs:
setattr(self, attribute, kwargs[attribute])
elif attribute in Amount.constant_defaults:
setattr(self, attribute, Amount.constant_defaults[attribute])
elif attribute in Amount.dynamic_defaults:
setattr(self, attribute, Amount.dynamic_defaults[attribute]())
else:
setattr(self, attribute, None)
# fixme
def truncate_value(self, precision = None):
if precision == 'unlimited':
result = self.value
else:
result = round self.value to `precision` digits
return result
# todo
def __str__(self, precision = None, side = None):
# if side == 'right':
return f'{truncate_amount(amount)} {self.symbol}'
# elif side == 'left':
# todo
def __repr__(self):
# (goal: unambiguous output)
return self.__str__()
# if __name__ == '__main__':
| 29.584906 | 98 | 0.609694 |
ff0fa95c46992c38d17df95ecb2405b099f54fc8 | 6,974 | py | Python | dasha/web/templates/pager.py | toltec-astro/dasha | d6e7a8489d6c58c77858df18d4798e10196bb3eb | [
"BSD-3-Clause"
] | null | null | null | dasha/web/templates/pager.py | toltec-astro/dasha | d6e7a8489d6c58c77858df18d4798e10196bb3eb | [
"BSD-3-Clause"
] | null | null | null | dasha/web/templates/pager.py | toltec-astro/dasha | d6e7a8489d6c58c77858df18d4798e10196bb3eb | [
"BSD-3-Clause"
] | null | null | null | #! /usr/bin/env python
import dash
from dash import html, dcc, Output, Input, State, ALL
import dash_bootstrap_components as dbc
from dash_component_template import ComponentTemplate
from .utils import parse_triggered_prop_ids
from .collapsecontent import CollapseContent
from .shareddatastore import SharedDataStore
from tollan.utils.fmt import pformat_yaml
from tollan.utils import to_typed
from tollan.utils.log import get_logger
__all__ = ['ButtonListPager', ]
def _get_items_range(
page_id, n_items_per_page, n_items):
start = page_id * n_items_per_page
stop = start + n_items_per_page
if stop > n_items:
stop = n_items
return start, stop
def _get_n_pages(n_items_per_page, n_items):
n_pages = n_items // n_items_per_page + (
n_items % n_items_per_page > 0)
return n_pages
class ButtonListPager(ComponentTemplate):
class Meta:
component_cls = html.Div
logger = get_logger()
def __init__(self, title_text, n_items_per_page_options, *args, **kwargs):
super().__init__(*args, **kwargs)
self.title_text = title_text
self.n_items_per_page_options = n_items_per_page_options
settings_container, btns_container = self.grid(2, 1)
settings_container.child(dbc.Label(
self.title_text))
settings_container_form = settings_container.child(
dbc.Form)
settings_container_fgrp = settings_container_form.child(
dbc.Row, className='g-2')
# settings_container_fgrp.child(dbc.Label(
# self.title_text, className='me-2'))
n_items_per_page_select_igrp = settings_container_fgrp.child(
dbc.InputGroup, size='sm', className='w-auto me-2')
n_items_per_page_drp = n_items_per_page_select_igrp.child(
dbc.Select,
options=[
{
'label': v,
'value': v
}
for i, v in enumerate(
self.n_items_per_page_options)
],
value=self.n_items_per_page_options[0],
)
n_items_per_page_select_igrp.child(
dbc.InputGroupText("items per page"))
self._ctx = {
'n_items_per_page_drp': n_items_per_page_drp,
'settings_container': settings_container,
'settings_container_form': settings_container_form,
'btns_container': btns_container
}
self._settings = self.child(SharedDataStore())
self._current_page_store = self.child(dcc.Store, data=None)
def register_n_items_callback(self, inputs, callback):
self._settings.register_callback(
outputs='n_items',
inputs=inputs,
callback=callback
)
@property
def page_data_inputs(self):
return [Input(self._current_page_store.id, 'data'), ]
def setup_layout(self, app):
def _get_n_items_per_page(value):
if isinstance(value, str):
return to_typed(value)
return value
# this had to be done here because id is only accessible
# after __init__
self._settings.register_callback(
outputs='n_items_per_page',
inputs=Input(
self._ctx['n_items_per_page_drp'].id, 'value'),
callback=_get_n_items_per_page
)
btns_container = self._ctx['btns_container']
settings_container_form = self._ctx['settings_container_form']
details_container = settings_container_form.child(
CollapseContent(button_text='Details ...')).content
details_container.parent = settings_container_form.parent
super().setup_layout(app)
def get_page_btn_id(i):
return {
'parent_id': btns_container.id,
'page_id': i
}
def resolve_page_info(d):
n_items = d['n_items']
n_items_per_page = d['n_items_per_page']
if (
isinstance(n_items_per_page, str)
and n_items_per_page.lower() == 'all'):
n_items_per_page = n_items
n_pages = _get_n_pages(n_items_per_page, n_items)
return {
'n_items': n_items,
'n_items_per_page': n_items_per_page,
'n_pages': n_pages,
}
@app.callback(
[
Output(btns_container.id, 'children'),
Output(details_container.id, 'children')
],
[
Input(self._settings.id, 'data')
]
)
def update_btns_container(d):
if d is None:
return dash.no_update, html.Pre('(empty)')
d = resolve_page_info(d)
n_items = d['n_items']
n_items_per_page = d['n_items_per_page']
n_pages = d['n_pages']
def get_page_btn_text(i):
if n_pages == 1:
return 'All items'
start, _ = _get_items_range(
i, n_items_per_page, n_items)
return f'{start}'
btns = [
dbc.Button(
get_page_btn_text(i),
id=get_page_btn_id(i),
color='link',
className='me-1', size='sm')
for i in range(n_pages)
]
return btns, html.Pre(pformat_yaml(d))
@app.callback(
Output(self._current_page_store.id, 'data'),
[
Input(get_page_btn_id(ALL), 'n_clicks')
],
[
State(self._settings.id, 'data')
]
)
def update_current_page(n_clicks_values, settings):
self.logger.debug(f"settings: {settings}")
if settings is None:
raise dash.exceptions.PreventUpdate
d = parse_triggered_prop_ids()[0]
if d is None:
page_id = 0
else:
page_id = d['id']['page_id']
settings = resolve_page_info(settings)
n_items = settings['n_items']
n_items_per_page = settings['n_items_per_page']
n_pages = settings['n_pages']
start, stop = _get_items_range(page_id, n_items_per_page, n_items)
result = dict(**settings)
result.update({
'page_id': page_id,
'start': start,
'stop': stop,
'n_pages': n_pages
})
return result
| 34.35468 | 78 | 0.539576 |
4e3ee5226a352745afd75a2808d1f691fc9cc9b1 | 2,512 | py | Python | MoleculeMOTScripts/optimas/motmaster_wrapper.py | ColdMatter/EDMSuite | 80a8bc0f3fd9d33a081f606707140de51512b28a | [
"MIT"
] | 6 | 2017-02-02T17:54:23.000Z | 2021-07-03T12:41:36.000Z | MoleculeMOTScripts/optimas/motmaster_wrapper.py | ColdMatter/EDMSuite | 80a8bc0f3fd9d33a081f606707140de51512b28a | [
"MIT"
] | null | null | null | MoleculeMOTScripts/optimas/motmaster_wrapper.py | ColdMatter/EDMSuite | 80a8bc0f3fd9d33a081f606707140de51512b28a | [
"MIT"
] | 11 | 2015-03-19T18:23:38.000Z | 2021-02-18T11:05:51.000Z | from __future__ import print_function
import clr
import sys
from System.IO import Path
import time
sys.path.append(Path.GetFullPath("C:\\ControlPrograms\\EDMSuite\\MOTMaster\\bin\\CaF\\"))
clr.AddReference("C:\\ControlPrograms\\EDMSuite\\MOTMaster\\bin\\CaF\\MOTMaster.exe")
sys.path.append(Path.GetFullPath("C:\\ControlPrograms\\EDMSuite\\MoleculeMOTHardwareControl\\bin\\CaF\\"))
clr.AddReference("C:\\ControlPrograms\\EDMSuite\\MoleculeMOTHardwareControl\\bin\\CaF\\MoleculeMOTHardwareControl.exe")
clr.AddReference("C:\\ControlPrograms\\EDMSuite\\MoleculeMOTHardwareControl\\bin\\CaF\\DAQ.dll")
clr.AddReference("C:\\ControlPrograms\\EDMSuite\\MoleculeMOTHardwareControl\\bin\\CaF\\SharedCode.dll")
# Load some system assemblies that we'll need
clr.AddReference("System.Drawing")
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Xml")
# create connections to the control programs
import System
#import ScanMaster
import MOTMaster
import MoleculeMOTHardwareControl
#sm = typedproxy(System.Activator.GetObject(ScanMaster.Controller, 'tcp://localhost:1170/controller.rem'), #ScanMaster.Controller)
hc = System.Activator.GetObject(MoleculeMOTHardwareControl.Controller, 'tcp://localhost:1172/controller.rem')
mm = System.Activator.GetObject(MOTMaster.Controller, 'tcp://localhost:1187/controller.rem')
# some generic stuff
from System.IO import *
from System.Drawing import *
from System.Runtime.Remoting import *
from System.Threading import *
from System.Windows.Forms import *
from System.Xml.Serialization import *
from System import *
from System.Collections.Generic import Dictionary
import time
import itertools
from random import shuffle
# specific EDMSuite stuff
from DAQ.Environment import *
from DAQ import *
from MOTMaster import *
def single_param_single_shot(script_name, parameter_name, value):
dict_instance = Dictionary[String, Object]()
script_path = 'C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts\\{}.cs'.format(script_name)
mm.SetScriptPath(script_path)
dict_instance[parameter_name] = value
mm.Go(dict_instance)
return True
def multi_param_single_shot(script_name, parameter_names, values):
dict_instance = Dictionary[String, Object]()
script_path = 'C:\\ControlPrograms\\EDMSuite\\MoleculeMOTMasterScripts\\{}.cs'.format(script_name)
mm.SetScriptPath(script_path)
for parameter_name, value in zip(parameter_names, values):
dict_instance[parameter_name] = value
mm.Go(dict_instance)
return True
| 36.941176 | 130 | 0.789013 |
99386fe907ff2646189ebaffdc767beb3ce4f8f7 | 8,218 | py | Python | sdk/python/pulumi_azure_native/servicebus/v20180101preview/get_namespace.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/servicebus/v20180101preview/get_namespace.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/servicebus/v20180101preview/get_namespace.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
__all__ = [
'GetNamespaceResult',
'AwaitableGetNamespaceResult',
'get_namespace',
]
@pulumi.output_type
class GetNamespaceResult:
"""
Description of a namespace resource.
"""
def __init__(__self__, created_at=None, encryption=None, id=None, identity=None, location=None, metric_id=None, name=None, provisioning_state=None, service_bus_endpoint=None, sku=None, tags=None, type=None, updated_at=None, zone_redundant=None):
if created_at and not isinstance(created_at, str):
raise TypeError("Expected argument 'created_at' to be a str")
pulumi.set(__self__, "created_at", created_at)
if encryption and not isinstance(encryption, dict):
raise TypeError("Expected argument 'encryption' to be a dict")
pulumi.set(__self__, "encryption", encryption)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if identity and not isinstance(identity, dict):
raise TypeError("Expected argument 'identity' to be a dict")
pulumi.set(__self__, "identity", identity)
if location and not isinstance(location, str):
raise TypeError("Expected argument 'location' to be a str")
pulumi.set(__self__, "location", location)
if metric_id and not isinstance(metric_id, str):
raise TypeError("Expected argument 'metric_id' to be a str")
pulumi.set(__self__, "metric_id", metric_id)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if provisioning_state and not isinstance(provisioning_state, str):
raise TypeError("Expected argument 'provisioning_state' to be a str")
pulumi.set(__self__, "provisioning_state", provisioning_state)
if service_bus_endpoint and not isinstance(service_bus_endpoint, str):
raise TypeError("Expected argument 'service_bus_endpoint' to be a str")
pulumi.set(__self__, "service_bus_endpoint", service_bus_endpoint)
if sku and not isinstance(sku, dict):
raise TypeError("Expected argument 'sku' to be a dict")
pulumi.set(__self__, "sku", sku)
if tags and not isinstance(tags, dict):
raise TypeError("Expected argument 'tags' to be a dict")
pulumi.set(__self__, "tags", tags)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
if updated_at and not isinstance(updated_at, str):
raise TypeError("Expected argument 'updated_at' to be a str")
pulumi.set(__self__, "updated_at", updated_at)
if zone_redundant and not isinstance(zone_redundant, bool):
raise TypeError("Expected argument 'zone_redundant' to be a bool")
pulumi.set(__self__, "zone_redundant", zone_redundant)
@property
@pulumi.getter(name="createdAt")
def created_at(self) -> str:
"""
The time the namespace was created
"""
return pulumi.get(self, "created_at")
@property
@pulumi.getter
def encryption(self) -> Optional['outputs.EncryptionResponse']:
"""
Properties of BYOK Encryption description
"""
return pulumi.get(self, "encryption")
@property
@pulumi.getter
def id(self) -> str:
"""
Resource Id
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def identity(self) -> Optional['outputs.IdentityResponse']:
"""
Properties of BYOK Identity description
"""
return pulumi.get(self, "identity")
@property
@pulumi.getter
def location(self) -> str:
"""
The Geo-location where the resource lives
"""
return pulumi.get(self, "location")
@property
@pulumi.getter(name="metricId")
def metric_id(self) -> str:
"""
Identifier for Azure Insights metrics
"""
return pulumi.get(self, "metric_id")
@property
@pulumi.getter
def name(self) -> str:
"""
Resource name
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> str:
"""
Provisioning state of the namespace.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="serviceBusEndpoint")
def service_bus_endpoint(self) -> str:
"""
Endpoint you can use to perform Service Bus operations.
"""
return pulumi.get(self, "service_bus_endpoint")
@property
@pulumi.getter
def sku(self) -> Optional['outputs.SBSkuResponse']:
"""
Properties of SKU
"""
return pulumi.get(self, "sku")
@property
@pulumi.getter
def tags(self) -> Optional[Mapping[str, str]]:
"""
Resource tags
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> str:
"""
Resource type
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="updatedAt")
def updated_at(self) -> str:
"""
The time the namespace was updated.
"""
return pulumi.get(self, "updated_at")
@property
@pulumi.getter(name="zoneRedundant")
def zone_redundant(self) -> Optional[bool]:
"""
Enabling this property creates a Premium Service Bus Namespace in regions supported availability zones.
"""
return pulumi.get(self, "zone_redundant")
class AwaitableGetNamespaceResult(GetNamespaceResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetNamespaceResult(
created_at=self.created_at,
encryption=self.encryption,
id=self.id,
identity=self.identity,
location=self.location,
metric_id=self.metric_id,
name=self.name,
provisioning_state=self.provisioning_state,
service_bus_endpoint=self.service_bus_endpoint,
sku=self.sku,
tags=self.tags,
type=self.type,
updated_at=self.updated_at,
zone_redundant=self.zone_redundant)
def get_namespace(namespace_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetNamespaceResult:
"""
Description of a namespace resource.
:param str namespace_name: The namespace name
:param str resource_group_name: Name of the Resource group within the Azure subscription.
"""
__args__ = dict()
__args__['namespaceName'] = namespace_name
__args__['resourceGroupName'] = resource_group_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:servicebus/v20180101preview:getNamespace', __args__, opts=opts, typ=GetNamespaceResult).value
return AwaitableGetNamespaceResult(
created_at=__ret__.created_at,
encryption=__ret__.encryption,
id=__ret__.id,
identity=__ret__.identity,
location=__ret__.location,
metric_id=__ret__.metric_id,
name=__ret__.name,
provisioning_state=__ret__.provisioning_state,
service_bus_endpoint=__ret__.service_bus_endpoint,
sku=__ret__.sku,
tags=__ret__.tags,
type=__ret__.type,
updated_at=__ret__.updated_at,
zone_redundant=__ret__.zone_redundant)
| 34.822034 | 249 | 0.638355 |
52eb9eaec7302f1d0e0799ed749d630bdd78859d | 869 | py | Python | DataStructures/Queue/implementation.py | samiunblack/algorithm-study | f003d5eaa5b38b69ffd7ea889d69b3580abd2d0d | [
"MIT"
] | null | null | null | DataStructures/Queue/implementation.py | samiunblack/algorithm-study | f003d5eaa5b38b69ffd7ea889d69b3580abd2d0d | [
"MIT"
] | null | null | null | DataStructures/Queue/implementation.py | samiunblack/algorithm-study | f003d5eaa5b38b69ffd7ea889d69b3580abd2d0d | [
"MIT"
] | null | null | null | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class Queue:
def __init__(self):
self.first = None
self.last = None
self.length = 0
def peek(self):
return self.first.value
def enqueue(self, value):
new_node = Node(value)
if (self.length == 0):
self.first = new_node
self.last = new_node
else:
self.last.next = new_node
self.last = self.last.next
self.length += 1
def dequeue(self):
if (self.length != 0):
self.first = self.first.next
self.length -= 1
queue = Queue()
queue.enqueue("Sam")
queue.enqueue("Pika")
queue.enqueue("Pichu")
queue.dequeue()
print(queue.peek()) | 19.311111 | 41 | 0.501726 |
a9b41edb91279a2052faac04e4d4a3972809e838 | 20 | py | Python | static/__init__.py | ShaiEdy/anyway | ea669ad089d37fe0933a4596397bcb2d0b4f5de9 | [
"BSD-3-Clause"
] | 8 | 2016-09-14T11:31:04.000Z | 2021-02-23T22:29:55.000Z | static/__init__.py | ShaiEdy/anyway | ea669ad089d37fe0933a4596397bcb2d0b4f5de9 | [
"BSD-3-Clause"
] | 5 | 2020-07-30T08:30:04.000Z | 2021-06-25T15:39:48.000Z | static/__init__.py | ShaiEdy/anyway | ea669ad089d37fe0933a4596397bcb2d0b4f5de9 | [
"BSD-3-Clause"
] | 4 | 2015-03-01T09:50:57.000Z | 2020-08-28T12:03:37.000Z | __author__ = 'omri'
| 10 | 19 | 0.7 |
40d708a1cbf8875bdd109e6e04da7057c7e2f9fe | 4,645 | py | Python | test/test.py | abdcelik/Book-Store | f7a8c6227cae47f0f7b7205a36d4658617c1b5ad | [
"MIT"
] | null | null | null | test/test.py | abdcelik/Book-Store | f7a8c6227cae47f0f7b7205a36d4658617c1b5ad | [
"MIT"
] | null | null | null | test/test.py | abdcelik/Book-Store | f7a8c6227cae47f0f7b7205a36d4658617c1b5ad | [
"MIT"
] | 2 | 2020-10-27T11:10:28.000Z | 2021-03-11T12:24:02.000Z | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import unittest
import time
PATH = "C:\Program Files (x86)\chromedriver.exe"
def search_test_func(data,driver):
search = driver.find_element_by_id("searchData")
search.send_keys(data)
search.send_keys(Keys.RETURN)
try:
main = WebDriverWait(driver,10).until(
EC.presence_of_all_elements_located((By.CLASS_NAME,"products"))
)
except:
driver.quit()
def sign_in(user,passw,driver):
search = driver.find_element_by_id("username")
search.send_keys(user)
search = driver.find_element_by_id("password")
search.send_keys(passw)
search.send_keys(Keys.RETURN)
def user_edit(driver):
text = driver.find_element_by_name("username")
text.send_keys(Keys.LEFT_CONTROL + "a")
text.send_keys(Keys.BACKSPACE)
text.send_keys("data")
text = driver.find_element_by_name("name")
text.send_keys(Keys.LEFT_CONTROL + "a")
text.send_keys(Keys.BACKSPACE)
text.send_keys("can")
text = driver.find_element_by_name("surname")
text.send_keys(Keys.LEFT_CONTROL + "a")
text.send_keys(Keys.BACKSPACE)
text.send_keys("akkaya")
text = driver.find_element_by_name("email")
text.send_keys(Keys.LEFT_CONTROL + "a")
text.send_keys(Keys.BACKSPACE)
text.send_keys("[email protected]")
text = driver.find_element_by_name("phoneNumber")
text.send_keys(Keys.LEFT_CONTROL + "a")
text.send_keys(Keys.BACKSPACE)
text.send_keys("12315468")
text = driver.find_element_by_name("address")
text.send_keys(Keys.LEFT_CONTROL + "a")
text.send_keys(Keys.BACKSPACE)
text.send_keys("sancaktepe")
text = driver.find_element_by_id("newPassword")
text.send_keys(Keys.LEFT_CONTROL + "a")
text.send_keys(Keys.BACKSPACE)
text.send_keys("123")
text = driver.find_element_by_id("newPassword2")
text.send_keys(Keys.LEFT_CONTROL + "a")
text.send_keys(Keys.BACKSPACE)
text.send_keys("123")
text = driver.find_element_by_id("oldPassword")
text.send_keys(Keys.LEFT_CONTROL + "a")
text.send_keys(Keys.BACKSPACE)
text.send_keys("123")
driver.find_element_by_id("submit").click()
class Bookie(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(PATH)
self.driver.get("https://localhost:44361")
def test_title(self):
return "Bookie" and self.driver.title
def test_search_1(self):
search_test_func("",self.driver)
def test_search_2(self):
search_test_func("Olasılıksız",self.driver)
def test_search_3(self):
search_test_func("Metro",self.driver)
def test_search_4(self):
search_test_func("Düşerken",self.driver)
def test_search_5(self):
search_test_func("Sherlock Holmes",self.driver)
def test_user_1(self):
self.driver.find_element_by_link_text("Sign In").click()
sign_in("Muratyldz","123",self.driver)
def test_user_2(self):
self.driver.find_element_by_link_text("Sign In").click()
sign_in("BerkPgz","456",self.driver)
def test_user_3(self):
self.driver.find_element_by_link_text("Sign In").click()
sign_in("abdcelik","789",self.driver)
def test_user_nav(self):
self.driver.find_element_by_link_text("Sign In").click()
time.sleep(3)
sign_in("Muratyldz","123",self.driver)
time.sleep(1)
self.driver.find_element_by_link_text("Profile").click()
time.sleep(1)
self.driver.find_element_by_link_text("My sales").click()
time.sleep(1)
self.driver.find_element_by_link_text("My orders").click()
time.sleep(1)
self.driver.find_element_by_link_text("My solds").click()
time.sleep(1)
self.driver.find_element_by_link_text("Sign out").click()
def test_user_edit(self):
self.driver.find_element_by_link_text("Sign In").click()
time.sleep(1)
sign_in("Muratyldz","123",self.driver)
time.sleep(2)
self.driver.find_element_by_link_text("Profile").click()
user_edit(self.driver)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main() | 27.981928 | 76 | 0.657051 |
626e321a1406e28e03a1c42ad4b76813c1cce6fb | 239 | py | Python | FirstStepsInPython/Fundamentals/Exercice/Functions/More Exercises/04. Tribonacci Sequence.py | Pittor052/SoftUni-Studies | 1ee6341082f6ccfa45b3e82824c37722bcf2fb31 | [
"MIT"
] | null | null | null | FirstStepsInPython/Fundamentals/Exercice/Functions/More Exercises/04. Tribonacci Sequence.py | Pittor052/SoftUni-Studies | 1ee6341082f6ccfa45b3e82824c37722bcf2fb31 | [
"MIT"
] | null | null | null | FirstStepsInPython/Fundamentals/Exercice/Functions/More Exercises/04. Tribonacci Sequence.py | Pittor052/SoftUni-Studies | 1ee6341082f6ccfa45b3e82824c37722bcf2fb31 | [
"MIT"
] | 1 | 2021-10-07T18:30:42.000Z | 2021-10-07T18:30:42.000Z | numbers = int(input())
number_list = [1]
for i in range(numbers - 1):
sum_of_number_list = sum(number_list[-3:])
number_list.append(sum_of_number_list)
nums_to_str = [str(num) for num in number_list]
print(" ".join(nums_to_str))
| 23.9 | 47 | 0.711297 |
3482ed9f7d533ec5e99c7c8efe5b1438e534bdd9 | 458 | py | Python | previewers/event/EventWaiter.py | C3RV1/LaytonEditor | 51e1a9a372a8acdaa4183ae008235a721dc56cdc | [
"Unlicense"
] | 6 | 2019-12-24T00:18:54.000Z | 2022-02-28T17:09:22.000Z | previewers/event/EventWaiter.py | C3RV1/LaytonEditor | 51e1a9a372a8acdaa4183ae008235a721dc56cdc | [
"Unlicense"
] | 1 | 2021-08-18T11:10:35.000Z | 2021-08-18T17:32:21.000Z | previewers/event/EventWaiter.py | C3RV1/LaytonEditor | 51e1a9a372a8acdaa4183ae008235a721dc56cdc | [
"Unlicense"
] | 2 | 2021-01-17T10:42:48.000Z | 2021-08-18T11:10:54.000Z | from pg_utils.rom.rom_extract import ORIGINAL_FPS
class EventWaiter:
def __init__(self):
self.current_wait_time = 0
def wait(self, wait_frames):
self.current_wait_time = wait_frames / ORIGINAL_FPS
def busy(self):
return self.current_wait_time > 0
def stop(self):
self.current_wait_time = 0
def update_(self, dt: float):
if self.current_wait_time > 0:
self.current_wait_time -= dt
| 22.9 | 59 | 0.661572 |
987337214b256ee594bcb571070afad8098cebcf | 2,145 | py | Python | api/recommender/satisfaction_calculator.py | sorinburghiu2323/Supervisio | df0b682d031914904547efafb3ec4d060bf96526 | [
"MIT"
] | null | null | null | api/recommender/satisfaction_calculator.py | sorinburghiu2323/Supervisio | df0b682d031914904547efafb3ec4d060bf96526 | [
"MIT"
] | null | null | null | api/recommender/satisfaction_calculator.py | sorinburghiu2323/Supervisio | df0b682d031914904547efafb3ec4d060bf96526 | [
"MIT"
] | null | null | null | from typing import List
from api.grades.models import Grade
from api.projects.models import Project
from api.recommender.utils import (
calculate_grade_relevance,
calculate_interest_match_factor,
)
from api.users.models import User
RECOMMENDED_BEFORE_BIAS = 4
def calculate_recommendation_satisfaction(
user: User, projects: List[Project], supervisors: List[User]
) -> float:
"""
Satisfaction calculator based on:
- interest relation
- how much it was already recommended
Output value:
0 - recommendations are pointless
1 - recommendations are perfect
:param user: User instance.
:param projects: List of recommended projects.
:param supervisors: List of recommended supervisors.
:return: Satisfaction score as float.
"""
user_interests = user.interests.all()
interests_count = user_interests.count()
grades = Grade.objects.filter(student=user)
grade_count = grades.count()
# Get matches and recommended before count.
matches = []
recommended_before = 0
for project in projects:
matches.append(
(
calculate_interest_match_factor(user_interests, project)
+ calculate_grade_relevance(grades, project)
)
/ (interests_count + grade_count)
)
recommended_before += project.recommended_count
project.recommended_count += 1
project.save()
for supervisor in supervisors:
matches.append(
(
calculate_interest_match_factor(user_interests, supervisor)
+ calculate_grade_relevance(grades, supervisor)
)
/ (interests_count + grade_count)
)
recommended_before += supervisor.recommended_count
supervisor.recommended_count += 1
supervisor.save()
# Add 0's until max.
for _ in range(6 - len(matches)):
matches.append(0)
average_match = sum(matches) / len(matches)
return (
average_match
if recommended_before == 0
else average_match / (recommended_before ** (1 / RECOMMENDED_BEFORE_BIAS))
)
| 30.211268 | 82 | 0.663403 |
09fcd1de5fdce2eca2b652fa9cb00e2217ca6628 | 297 | py | Python | oscar/lib/python2.7/site-packages/IPython/core/tests/daft_extension/daft_extension.py | sainjusajan/django-oscar | 466e8edc807be689b0a28c9e525c8323cc48b8e1 | [
"BSD-3-Clause"
] | null | null | null | oscar/lib/python2.7/site-packages/IPython/core/tests/daft_extension/daft_extension.py | sainjusajan/django-oscar | 466e8edc807be689b0a28c9e525c8323cc48b8e1 | [
"BSD-3-Clause"
] | null | null | null | oscar/lib/python2.7/site-packages/IPython/core/tests/daft_extension/daft_extension.py | sainjusajan/django-oscar | 466e8edc807be689b0a28c9e525c8323cc48b8e1 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Useless IPython extension to test installing and loading extensions.
"""
some_vars = {'arq': 185}
def load_ipython_extension(ip):
# set up simplified quantity input
ip.push(some_vars)
def unload_ipython_extension(ip):
ip.drop_by_id(some_vars)
| 22.846154 | 69 | 0.686869 |
ebe0b2a16ca0b708c098610bc7b619ac37f411b2 | 4,569 | py | Python | src/models/train/model_main.py | duynhat-nguyen/detect-classify-trafficlights | bb986fc255237a6b25e52fdcb5fff28d35139dd2 | [
"Apache-2.0"
] | null | null | null | src/models/train/model_main.py | duynhat-nguyen/detect-classify-trafficlights | bb986fc255237a6b25e52fdcb5fff28d35139dd2 | [
"Apache-2.0"
] | null | null | null | src/models/train/model_main.py | duynhat-nguyen/detect-classify-trafficlights | bb986fc255237a6b25e52fdcb5fff28d35139dd2 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Binary to run train and evaluation on object detection model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import flags
import tensorflow.compat.v1 as tf
from object_detection import model_lib
flags.DEFINE_string(
'model_dir', None, 'Path to output model directory '
'where event and checkpoint files will be written.')
flags.DEFINE_string('pipeline_config_path', None, 'Path to pipeline config '
'file.')
flags.DEFINE_integer('num_train_steps', None, 'Number of train steps.')
flags.DEFINE_boolean('eval_training_data', False,
'If training data should be evaluated for this job. Note '
'that one call only use this in eval-only mode, and '
'`checkpoint_dir` must be supplied.')
flags.DEFINE_integer('sample_1_of_n_eval_examples', 1, 'Will sample one of '
'every n eval input examples, where n is provided.')
flags.DEFINE_integer('sample_1_of_n_eval_on_train_examples', 5, 'Will sample '
'one of every n train input examples for evaluation, '
'where n is provided. This is only used if '
'`eval_training_data` is True.')
flags.DEFINE_string(
'checkpoint_dir', None, 'Path to directory holding a checkpoint. If '
'`checkpoint_dir` is provided, this binary operates in eval-only mode, '
'writing resulting metrics to `model_dir`.')
flags.DEFINE_boolean(
'run_once', False, 'If running in eval-only mode, whether to run just '
'one round of eval vs running continuously (default).'
)
flags.DEFINE_integer(
'max_eval_retries', 0, 'If running continuous eval, the maximum number of '
'retries upon encountering tf.errors.InvalidArgumentError. If negative, '
'will always retry the evaluation.'
)
FLAGS = flags.FLAGS
def main(unused_argv):
flags.mark_flag_as_required('model_dir')
flags.mark_flag_as_required('pipeline_config_path')
config = tf.estimator.RunConfig(model_dir=FLAGS.model_dir, keep_checkpoint_max=None, save_checkpoints_steps=1000)
train_and_eval_dict = model_lib.create_estimator_and_inputs(
run_config=config,
pipeline_config_path=FLAGS.pipeline_config_path,
train_steps=FLAGS.num_train_steps,
sample_1_of_n_eval_examples=FLAGS.sample_1_of_n_eval_examples,
sample_1_of_n_eval_on_train_examples=(
FLAGS.sample_1_of_n_eval_on_train_examples))
estimator = train_and_eval_dict['estimator']
train_input_fn = train_and_eval_dict['train_input_fn']
eval_input_fns = train_and_eval_dict['eval_input_fns']
eval_on_train_input_fn = train_and_eval_dict['eval_on_train_input_fn']
predict_input_fn = train_and_eval_dict['predict_input_fn']
train_steps = train_and_eval_dict['train_steps']
if FLAGS.checkpoint_dir:
if FLAGS.eval_training_data:
name = 'training_data'
input_fn = eval_on_train_input_fn
else:
name = 'validation_data'
# The first eval input will be evaluated.
input_fn = eval_input_fns[0]
if FLAGS.run_once:
estimator.evaluate(input_fn,
steps=None,
checkpoint_path=tf.train.latest_checkpoint(
FLAGS.checkpoint_dir))
else:
model_lib.continuous_eval(estimator, FLAGS.checkpoint_dir, input_fn,
train_steps, name, FLAGS.max_eval_retries)
else:
train_spec, eval_specs = model_lib.create_train_and_eval_specs(
train_input_fn,
eval_input_fns,
eval_on_train_input_fn,
predict_input_fn,
train_steps,
eval_on_train_data=False)
# Currently only a single Eval Spec is allowed.
tf.estimator.train_and_evaluate(estimator, train_spec, eval_specs[0])
if __name__ == '__main__':
tf.app.run()
| 41.917431 | 115 | 0.703874 |
2b8e891f0eb42de14a4844bf88c0e8ed2aeab933 | 909 | py | Python | read_statistics/migrations/0002_readdetail.py | knightwk/mysite | 9935b05e97fd5fb0cd57a0e97b8241ee4a8a67a5 | [
"Apache-2.0"
] | 1 | 2019-02-20T02:33:25.000Z | 2019-02-20T02:33:25.000Z | 20.Servers/read_statistics/migrations/0002_readdetail.py | ReverseScale/DjangoProject | b82fffdef5084f616f9de86516254d6398ba08e8 | [
"MIT"
] | 14 | 2020-06-05T07:13:18.000Z | 2022-03-11T23:45:57.000Z | 20.Servers/read_statistics/migrations/0002_readdetail.py | ReverseScale/DjangoProject | b82fffdef5084f616f9de86516254d6398ba08e8 | [
"MIT"
] | null | null | null | # Generated by Django 2.0 on 2018-02-28 16:47
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('read_statistics', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ReadDetail',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateField(default=django.utils.timezone.now)),
('read_num', models.IntegerField(default=0)),
('object_id', models.PositiveIntegerField()),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='contenttypes.ContentType')),
],
),
]
| 33.666667 | 131 | 0.628163 |
ae277b1e44064a7c1bdf70f09887428fb50f1ecf | 439 | py | Python | hospital/migrations/0010_auto_20200523_1122.py | favourch/hospitalmanagement | 7dcf4d9f548b7808d54b758a1769a3de07280227 | [
"MIT"
] | 3 | 2021-03-08T17:41:12.000Z | 2022-01-10T13:01:20.000Z | hospital/migrations/0010_auto_20200523_1122.py | sharon-06/hospitalmanagement | 853135de381be15797a219b33b7d383ae2a5c62b | [
"MIT"
] | null | null | null | hospital/migrations/0010_auto_20200523_1122.py | sharon-06/hospitalmanagement | 853135de381be15797a219b33b7d383ae2a5c62b | [
"MIT"
] | 2 | 2021-12-25T20:01:05.000Z | 2022-01-09T14:12:20.000Z | # Generated by Django 3.0.5 on 2020-05-23 05:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hospital', '0009_auto_20200523_1118'),
]
operations = [
migrations.AlterField(
model_name='doctor',
name='profile_pic',
field=models.ImageField(blank=True, null=True, upload_to='static/DoctorProfilePic/'),
),
]
| 23.105263 | 97 | 0.624146 |
59124771232afcb620667fd64b446c71ec18d83d | 11,229 | py | Python | isi_sdk_8_1_1/isi_sdk_8_1_1/models/job_job_summary_summary.py | mohitjain97/isilon_sdk_python | a371f438f542568edb8cda35e929e6b300b1177c | [
"Unlicense"
] | 24 | 2018-06-22T14:13:23.000Z | 2022-03-23T01:21:26.000Z | isi_sdk_8_1_1/isi_sdk_8_1_1/models/job_job_summary_summary.py | mohitjain97/isilon_sdk_python | a371f438f542568edb8cda35e929e6b300b1177c | [
"Unlicense"
] | 46 | 2018-04-30T13:28:22.000Z | 2022-03-21T21:11:07.000Z | isi_sdk_8_1_1/isi_sdk_8_1_1/models/job_job_summary_summary.py | mohitjain97/isilon_sdk_python | a371f438f542568edb8cda35e929e6b300b1177c | [
"Unlicense"
] | 29 | 2018-06-19T00:14:04.000Z | 2022-02-08T17:51:19.000Z | # coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 6
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class JobJobSummarySummary(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'cluster_is_degraded': 'bool',
'connected': 'bool',
'coordinator': 'int',
'disconnected_nodes': 'list[int]',
'down_or_read_only_nodes': 'bool',
'next_jid': 'int',
'run_degraded': 'bool',
'stats_ready': 'bool'
}
attribute_map = {
'cluster_is_degraded': 'cluster_is_degraded',
'connected': 'connected',
'coordinator': 'coordinator',
'disconnected_nodes': 'disconnected_nodes',
'down_or_read_only_nodes': 'down_or_read_only_nodes',
'next_jid': 'next_jid',
'run_degraded': 'run_degraded',
'stats_ready': 'stats_ready'
}
def __init__(self, cluster_is_degraded=None, connected=None, coordinator=None, disconnected_nodes=None, down_or_read_only_nodes=None, next_jid=None, run_degraded=None, stats_ready=None): # noqa: E501
"""JobJobSummarySummary - a model defined in Swagger""" # noqa: E501
self._cluster_is_degraded = None
self._connected = None
self._coordinator = None
self._disconnected_nodes = None
self._down_or_read_only_nodes = None
self._next_jid = None
self._run_degraded = None
self._stats_ready = None
self.discriminator = None
self.cluster_is_degraded = cluster_is_degraded
self.connected = connected
self.coordinator = coordinator
if disconnected_nodes is not None:
self.disconnected_nodes = disconnected_nodes
self.down_or_read_only_nodes = down_or_read_only_nodes
self.next_jid = next_jid
self.run_degraded = run_degraded
self.stats_ready = stats_ready
@property
def cluster_is_degraded(self):
"""Gets the cluster_is_degraded of this JobJobSummarySummary. # noqa: E501
Whether the cluster is in a degraded state. Note this is from the perspective of the node handling the query, which might be different from another node. # noqa: E501
:return: The cluster_is_degraded of this JobJobSummarySummary. # noqa: E501
:rtype: bool
"""
return self._cluster_is_degraded
@cluster_is_degraded.setter
def cluster_is_degraded(self, cluster_is_degraded):
"""Sets the cluster_is_degraded of this JobJobSummarySummary.
Whether the cluster is in a degraded state. Note this is from the perspective of the node handling the query, which might be different from another node. # noqa: E501
:param cluster_is_degraded: The cluster_is_degraded of this JobJobSummarySummary. # noqa: E501
:type: bool
"""
if cluster_is_degraded is None:
raise ValueError("Invalid value for `cluster_is_degraded`, must not be `None`") # noqa: E501
self._cluster_is_degraded = cluster_is_degraded
@property
def connected(self):
"""Gets the connected of this JobJobSummarySummary. # noqa: E501
Whether isi_job_d instances on all up nodes in the cluster are connected to the coordinator. # noqa: E501
:return: The connected of this JobJobSummarySummary. # noqa: E501
:rtype: bool
"""
return self._connected
@connected.setter
def connected(self, connected):
"""Sets the connected of this JobJobSummarySummary.
Whether isi_job_d instances on all up nodes in the cluster are connected to the coordinator. # noqa: E501
:param connected: The connected of this JobJobSummarySummary. # noqa: E501
:type: bool
"""
if connected is None:
raise ValueError("Invalid value for `connected`, must not be `None`") # noqa: E501
self._connected = connected
@property
def coordinator(self):
"""Gets the coordinator of this JobJobSummarySummary. # noqa: E501
The devid of the job engine coordinator. # noqa: E501
:return: The coordinator of this JobJobSummarySummary. # noqa: E501
:rtype: int
"""
return self._coordinator
@coordinator.setter
def coordinator(self, coordinator):
"""Sets the coordinator of this JobJobSummarySummary.
The devid of the job engine coordinator. # noqa: E501
:param coordinator: The coordinator of this JobJobSummarySummary. # noqa: E501
:type: int
"""
if coordinator is None:
raise ValueError("Invalid value for `coordinator`, must not be `None`") # noqa: E501
self._coordinator = coordinator
@property
def disconnected_nodes(self):
"""Gets the disconnected_nodes of this JobJobSummarySummary. # noqa: E501
If connected=false, this is the set of devids that are not connected to the coordinator. # noqa: E501
:return: The disconnected_nodes of this JobJobSummarySummary. # noqa: E501
:rtype: list[int]
"""
return self._disconnected_nodes
@disconnected_nodes.setter
def disconnected_nodes(self, disconnected_nodes):
"""Sets the disconnected_nodes of this JobJobSummarySummary.
If connected=false, this is the set of devids that are not connected to the coordinator. # noqa: E501
:param disconnected_nodes: The disconnected_nodes of this JobJobSummarySummary. # noqa: E501
:type: list[int]
"""
self._disconnected_nodes = disconnected_nodes
@property
def down_or_read_only_nodes(self):
"""Gets the down_or_read_only_nodes of this JobJobSummarySummary. # noqa: E501
Whether the cluster has any down or read-only nodes. These nodes are not considered in the connected property. # noqa: E501
:return: The down_or_read_only_nodes of this JobJobSummarySummary. # noqa: E501
:rtype: bool
"""
return self._down_or_read_only_nodes
@down_or_read_only_nodes.setter
def down_or_read_only_nodes(self, down_or_read_only_nodes):
"""Sets the down_or_read_only_nodes of this JobJobSummarySummary.
Whether the cluster has any down or read-only nodes. These nodes are not considered in the connected property. # noqa: E501
:param down_or_read_only_nodes: The down_or_read_only_nodes of this JobJobSummarySummary. # noqa: E501
:type: bool
"""
if down_or_read_only_nodes is None:
raise ValueError("Invalid value for `down_or_read_only_nodes`, must not be `None`") # noqa: E501
self._down_or_read_only_nodes = down_or_read_only_nodes
@property
def next_jid(self):
"""Gets the next_jid of this JobJobSummarySummary. # noqa: E501
The job ID to be assigned to the next job. # noqa: E501
:return: The next_jid of this JobJobSummarySummary. # noqa: E501
:rtype: int
"""
return self._next_jid
@next_jid.setter
def next_jid(self, next_jid):
"""Sets the next_jid of this JobJobSummarySummary.
The job ID to be assigned to the next job. # noqa: E501
:param next_jid: The next_jid of this JobJobSummarySummary. # noqa: E501
:type: int
"""
if next_jid is None:
raise ValueError("Invalid value for `next_jid`, must not be `None`") # noqa: E501
self._next_jid = next_jid
@property
def run_degraded(self):
"""Gets the run_degraded of this JobJobSummarySummary. # noqa: E501
Whether the job engine would allow most jobs to run even when the cluster is in a degraded state. # noqa: E501
:return: The run_degraded of this JobJobSummarySummary. # noqa: E501
:rtype: bool
"""
return self._run_degraded
@run_degraded.setter
def run_degraded(self, run_degraded):
"""Sets the run_degraded of this JobJobSummarySummary.
Whether the job engine would allow most jobs to run even when the cluster is in a degraded state. # noqa: E501
:param run_degraded: The run_degraded of this JobJobSummarySummary. # noqa: E501
:type: bool
"""
if run_degraded is None:
raise ValueError("Invalid value for `run_degraded`, must not be `None`") # noqa: E501
self._run_degraded = run_degraded
@property
def stats_ready(self):
"""Gets the stats_ready of this JobJobSummarySummary. # noqa: E501
Whether the coordinator has recently gathered statistics for all nodes in the cluster. # noqa: E501
:return: The stats_ready of this JobJobSummarySummary. # noqa: E501
:rtype: bool
"""
return self._stats_ready
@stats_ready.setter
def stats_ready(self, stats_ready):
"""Sets the stats_ready of this JobJobSummarySummary.
Whether the coordinator has recently gathered statistics for all nodes in the cluster. # noqa: E501
:param stats_ready: The stats_ready of this JobJobSummarySummary. # noqa: E501
:type: bool
"""
if stats_ready is None:
raise ValueError("Invalid value for `stats_ready`, must not be `None`") # noqa: E501
self._stats_ready = stats_ready
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, JobJobSummarySummary):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 35.311321 | 204 | 0.644047 |
3b17a9870da1026f84cce525976960e6083656cc | 4,138 | py | Python | domainics/domobj/dattr.py | lcgong/dpillars | e138b8b52383191e8ea758ef3319e79da8a32dcb | [
"Apache-2.0"
] | 3 | 2015-09-20T23:43:13.000Z | 2017-11-07T15:00:36.000Z | domainics/domobj/dattr.py | lcgong/dpillars | e138b8b52383191e8ea758ef3319e79da8a32dcb | [
"Apache-2.0"
] | null | null | null | domainics/domobj/dattr.py | lcgong/dpillars | e138b8b52383191e8ea758ef3319e79da8a32dcb | [
"Apache-2.0"
] | 4 | 2015-07-12T08:40:33.000Z | 2016-04-11T08:01:51.000Z | # -*- coding: utf-8 -*-
from collections import OrderedDict
from collections import namedtuple
from collections.abc import Iterable
from typing import Mapping, Generic
from datetime import datetime, date, timedelta, time
from decimal import Decimal
# from dateutil.parser import parse as datetime_parse
from .typing import DSet, cast_attr_value, DAttribute, DAggregate
from .typing import DObject, AnyDObject, DSetBase
from .dset import dset
class datt(DAttribute):
"""Attribute of dobject"""
__slots__ = ('name', 'type', 'default_expr', 'default', 'len', 'doc')
def __init__(self, type=object, default=None, len=None, doc=None, **kwargs):
self.name = None
self.type = type
self.len = len
self.default = default
self.doc = doc
self.owner_class = None
self._kwargs = kwargs
def __get__(self, instance, owner):
if instance is None: # get domain field
return self
attr_value = instance.__value_dict__.get(self.name, None)
if attr_value is None:
if hasattr(self.type, '__default_value__'):
attr_value = self.type.__default_value__()
instance.__value_dict__[self.name] = attr_value
elif self.default is not None:
attr_value = self.initialize(instance)
instance.__value_dict__[self.name] = attr_value
return attr_value
def __set__(self, instance, value):
if self.name in instance.__class__.__dobject_key__:
errmsg = "The primary key attribute '%s' is read-only"
errmsg %= self.name
raise ValueError(errmsg)
self.set_value_unguardedly(instance, value)
def setup(self, owner_class, attr_name):
"""
When building the dobject class, it' required to setup this attribute
to it (owner dobject class).
"""
self.name = attr_name
self.owner_class = owner_class
if issubclass(self.type, DSetBase):
dset_cls = self.type
key_names = list(dset_cls.__dobject_key__.keys())
self.type = dset(dset_cls.__dset_item_class__,
_dominion = owner_class,
_key = key_names
)
self.type.__dset_links__ = dset_cls.__dset_links__
self.default = self.type # the inializer of dset
def initialize(self, instance):
""" """
if issubclass(self.type, DSetBase):
return self.type(_dominion=instance)
if isinstance(self.default, type):
return self.default()
if isinstance(self.default, (str, int, float, Decimal,
date, time, datetime,
timedelta)):
return self.default
errmsg = "Unknown the default value: %r" % self.default
raise ValueError(errmsg)
def set_value_unguardedly(self, instance, value):
attr_values = instance.__value_dict__
if issubclass(self.type, DSetBase) and isinstance(value, Iterable):
if self.name not in attr_values:
attr_value = self.initialize(instance)
attr_value += value
attr_values[self.name] = attr_value
else:
attr_value = attr_values[self.name]
if value is not attr_value : # important!
attr_value._clear()
attr_value += value
return
elif hasattr(self.type, '__setter_filter__'):
value = self.type.__setter_filter__(value)
elif hasattr(value.__class__, '__dobject_cast__'):
value = value.__dobject_cast__(self.type)
else:
value = cast_attr_value(self.name, value, self.type)
attr_values[self.name] = value
def copy(self):
obj = datt(type=self.type, default=self.default, doc=self.doc,
**self._kwargs)
obj.name = self.name
obj.owner_class = self.owner_class
return obj
| 31.587786 | 80 | 0.59449 |
fea29f241f90f0a08b02b93fec66a98567192d7c | 699 | py | Python | date.py | Zeebra38/bot_tlgr_shedule | 54566efc0583743e21256304dc4320f5ea1e3255 | [
"MIT"
] | null | null | null | date.py | Zeebra38/bot_tlgr_shedule | 54566efc0583743e21256304dc4320f5ea1e3255 | [
"MIT"
] | null | null | null | date.py | Zeebra38/bot_tlgr_shedule | 54566efc0583743e21256304dc4320f5ea1e3255 | [
"MIT"
] | null | null | null | from datetime import date, timedelta, datetime
def weeknum():
zero = datetime(2021, 2, 8)
now = datetime.today()
#now = datetime(2020, 9, 22)
delta = now - zero
deltaweeks = 1
#print(delta.days)
if delta.days >= 7:
buf = delta.days
while buf >= 7:
deltaweeks += 1
buf = buf - 7
return deltaweeks
def getweekday(today = datetime.today().weekday()):
if today == 0:
return 'Понедельник'
elif today == 1:
return 'Вторник'
elif today == 2:
return 'Среда'
elif today == 3:
return 'Четверг'
elif today == 4:
return 'Пятница'
elif today == 5:
return 'Суббота'
| 22.548387 | 51 | 0.545064 |
9a6e7a95b1d92d81d0bfa6f5a8470a74156038f5 | 1,131 | py | Python | 092_reverse_linked_list_II.py | Sanster/LeetCode | 5a0c448928b216b49c127c4542ae3cd74c797782 | [
"MIT"
] | 2 | 2018-10-13T15:12:55.000Z | 2020-06-07T09:35:40.000Z | 092_reverse_linked_list_II.py | Sanster/PyLeeCode | 5a0c448928b216b49c127c4542ae3cd74c797782 | [
"MIT"
] | null | null | null | 092_reverse_linked_list_II.py | Sanster/PyLeeCode | 5a0c448928b216b49c127c4542ae3cd74c797782 | [
"MIT"
] | null | null | null | # https://leetcode.com/problems/reverse-linked-list-ii/
from typing import Optional
from utils import ListNode, createList, compareList
class Solution:
successor = None
def reverseN(self, head: ListNode, n) -> ListNode:
if n == 1:
self.successor = head.next
return head
last = self.reverseN(head.next, n - 1)
head.next.next = head
head.next = self.successor
return last
def reverseBetween(
self, head: Optional[ListNode], left: int, right: int
) -> Optional[ListNode]:
"""
OMG! https://leetcode.com/problems/reverse-linked-list-ii/solution/242639
Time: O(n)
Space: O(1)
"""
if left == 1:
reversed_N = self.reverseN(head, right)
return reversed_N
head.next = self.reverseBetween(head.next, left - 1, right - 1)
return head
if __name__ == "__main__":
s = Solution()
data = [
([1, 2, 3, 4, 5], 2, 4, [1, 4, 3, 2, 5]),
]
for it, l, r, gt in data:
assert compareList(s.reverseBetween(createList(it), l, r), gt) is True
| 26.928571 | 82 | 0.57206 |
431ee027270d670086251d6acaba42fc304b0fa4 | 243,031 | py | Python | src/black/__init__.py | dpalmasan/black | 9cbf1f162261b64ebb150639b608be0c38f23e2b | [
"MIT"
] | null | null | null | src/black/__init__.py | dpalmasan/black | 9cbf1f162261b64ebb150639b608be0c38f23e2b | [
"MIT"
] | null | null | null | src/black/__init__.py | dpalmasan/black | 9cbf1f162261b64ebb150639b608be0c38f23e2b | [
"MIT"
] | null | null | null | import ast
import asyncio
from abc import ABC, abstractmethod
from collections import defaultdict
from concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutor
from contextlib import contextmanager
from datetime import datetime
from enum import Enum
from functools import lru_cache, partial, wraps
import io
import itertools
import logging
from multiprocessing import Manager, freeze_support
import os
from pathlib import Path
import pickle
import regex as re
import signal
import sys
import tempfile
import tokenize
import traceback
from typing import (
Any,
Callable,
Collection,
Dict,
Generator,
Generic,
Iterable,
Iterator,
List,
Optional,
Pattern,
Sequence,
Set,
Sized,
Tuple,
Type,
TypeVar,
Union,
cast,
TYPE_CHECKING,
)
from mypy_extensions import mypyc_attr
from appdirs import user_cache_dir
from dataclasses import dataclass, field, replace
import click
import toml
try:
from typed_ast import ast3, ast27
except ImportError:
if sys.version_info < (3, 8):
print(
"The typed_ast package is not installed.\n"
"You can install it with `python3 -m pip install typed-ast`.",
file=sys.stderr,
)
sys.exit(1)
else:
ast3 = ast27 = ast
from pathspec import PathSpec
# lib2to3 fork
from blib2to3.pytree import Node, Leaf, type_repr
from blib2to3 import pygram, pytree
from blib2to3.pgen2 import driver, token
from blib2to3.pgen2.grammar import Grammar
from blib2to3.pgen2.parse import ParseError
from _black_version import version as __version__
if sys.version_info < (3, 8):
from typing_extensions import Final
else:
from typing import Final
if TYPE_CHECKING:
import colorama # noqa: F401
DEFAULT_LINE_LENGTH = 88
DEFAULT_EXCLUDES = r"/(\.direnv|\.eggs|\.git|\.hg|\.mypy_cache|\.nox|\.tox|\.venv|\.svn|_build|buck-out|build|dist)/" # noqa: B950
DEFAULT_INCLUDES = r"\.pyi?$"
CACHE_DIR = Path(user_cache_dir("black", version=__version__))
STDIN_PLACEHOLDER = "__BLACK_STDIN_FILENAME__"
STRING_PREFIX_CHARS: Final = "furbFURB" # All possible string prefix characters.
# types
FileContent = str
Encoding = str
NewLine = str
Depth = int
NodeType = int
ParserState = int
LeafID = int
StringID = int
Priority = int
Index = int
LN = Union[Leaf, Node]
Transformer = Callable[["Line", Collection["Feature"]], Iterator["Line"]]
Timestamp = float
FileSize = int
CacheInfo = Tuple[Timestamp, FileSize]
Cache = Dict[str, CacheInfo]
out = partial(click.secho, bold=True, err=True)
err = partial(click.secho, fg="red", err=True)
pygram.initialize(CACHE_DIR)
syms = pygram.python_symbols
class NothingChanged(UserWarning):
"""Raised when reformatted code is the same as source."""
class CannotTransform(Exception):
"""Base class for errors raised by Transformers."""
class CannotSplit(CannotTransform):
"""A readable split that fits the allotted line length is impossible."""
class InvalidInput(ValueError):
"""Raised when input source code fails all parse attempts."""
class BracketMatchError(KeyError):
"""Raised when an opening bracket is unable to be matched to a closing bracket."""
T = TypeVar("T")
E = TypeVar("E", bound=Exception)
class Ok(Generic[T]):
def __init__(self, value: T) -> None:
self._value = value
def ok(self) -> T:
return self._value
class Err(Generic[E]):
def __init__(self, e: E) -> None:
self._e = e
def err(self) -> E:
return self._e
# The 'Result' return type is used to implement an error-handling model heavily
# influenced by that used by the Rust programming language
# (see https://doc.rust-lang.org/book/ch09-00-error-handling.html).
Result = Union[Ok[T], Err[E]]
TResult = Result[T, CannotTransform] # (T)ransform Result
TMatchResult = TResult[Index]
class WriteBack(Enum):
NO = 0
YES = 1
DIFF = 2
CHECK = 3
COLOR_DIFF = 4
@classmethod
def from_configuration(
cls, *, check: bool, diff: bool, color: bool = False
) -> "WriteBack":
if check and not diff:
return cls.CHECK
if diff and color:
return cls.COLOR_DIFF
return cls.DIFF if diff else cls.YES
class Changed(Enum):
NO = 0
CACHED = 1
YES = 2
class TargetVersion(Enum):
PY27 = 2
PY33 = 3
PY34 = 4
PY35 = 5
PY36 = 6
PY37 = 7
PY38 = 8
PY39 = 9
def is_python2(self) -> bool:
return self is TargetVersion.PY27
class Feature(Enum):
# All string literals are unicode
UNICODE_LITERALS = 1
F_STRINGS = 2
NUMERIC_UNDERSCORES = 3
TRAILING_COMMA_IN_CALL = 4
TRAILING_COMMA_IN_DEF = 5
# The following two feature-flags are mutually exclusive, and exactly one should be
# set for every version of python.
ASYNC_IDENTIFIERS = 6
ASYNC_KEYWORDS = 7
ASSIGNMENT_EXPRESSIONS = 8
POS_ONLY_ARGUMENTS = 9
RELAXED_DECORATORS = 10
FORCE_OPTIONAL_PARENTHESES = 50
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
TargetVersion.PY27: {Feature.ASYNC_IDENTIFIERS},
TargetVersion.PY33: {Feature.UNICODE_LITERALS, Feature.ASYNC_IDENTIFIERS},
TargetVersion.PY34: {Feature.UNICODE_LITERALS, Feature.ASYNC_IDENTIFIERS},
TargetVersion.PY35: {
Feature.UNICODE_LITERALS,
Feature.TRAILING_COMMA_IN_CALL,
Feature.ASYNC_IDENTIFIERS,
},
TargetVersion.PY36: {
Feature.UNICODE_LITERALS,
Feature.F_STRINGS,
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
Feature.ASYNC_IDENTIFIERS,
},
TargetVersion.PY37: {
Feature.UNICODE_LITERALS,
Feature.F_STRINGS,
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
Feature.ASYNC_KEYWORDS,
},
TargetVersion.PY38: {
Feature.UNICODE_LITERALS,
Feature.F_STRINGS,
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
Feature.ASYNC_KEYWORDS,
Feature.ASSIGNMENT_EXPRESSIONS,
Feature.POS_ONLY_ARGUMENTS,
},
TargetVersion.PY39: {
Feature.UNICODE_LITERALS,
Feature.F_STRINGS,
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
Feature.ASYNC_KEYWORDS,
Feature.ASSIGNMENT_EXPRESSIONS,
Feature.RELAXED_DECORATORS,
Feature.POS_ONLY_ARGUMENTS,
},
}
@dataclass
class Mode:
target_versions: Set[TargetVersion] = field(default_factory=set)
line_length: int = DEFAULT_LINE_LENGTH
string_normalization: bool = True
magic_trailing_comma: bool = True
experimental_string_processing: bool = False
is_pyi: bool = False
def get_cache_key(self) -> str:
if self.target_versions:
version_str = ",".join(
str(version.value)
for version in sorted(self.target_versions, key=lambda v: v.value)
)
else:
version_str = "-"
parts = [
version_str,
str(self.line_length),
str(int(self.string_normalization)),
str(int(self.is_pyi)),
]
return ".".join(parts)
# Legacy name, left for integrations.
FileMode = Mode
def supports_feature(target_versions: Set[TargetVersion], feature: Feature) -> bool:
return all(feature in VERSION_TO_FEATURES[version] for version in target_versions)
def find_pyproject_toml(path_search_start: Iterable[str]) -> Optional[str]:
"""Find the absolute filepath to a pyproject.toml if it exists"""
path_project_root = find_project_root(path_search_start)
path_pyproject_toml = path_project_root / "pyproject.toml"
if path_pyproject_toml.is_file():
return str(path_pyproject_toml)
path_user_pyproject_toml = find_user_pyproject_toml()
return str(path_user_pyproject_toml) if path_user_pyproject_toml.is_file() else None
def parse_pyproject_toml(path_config: str) -> Dict[str, Any]:
"""Parse a pyproject toml file, pulling out relevant parts for Black
If parsing fails, will raise a toml.TomlDecodeError
"""
pyproject_toml = toml.load(path_config)
config = pyproject_toml.get("tool", {}).get("black", {})
return {k.replace("--", "").replace("-", "_"): v for k, v in config.items()}
def read_pyproject_toml(
ctx: click.Context, param: click.Parameter, value: Optional[str]
) -> Optional[str]:
"""Inject Black configuration from "pyproject.toml" into defaults in `ctx`.
Returns the path to a successfully found and read configuration file, None
otherwise.
"""
if not value:
value = find_pyproject_toml(ctx.params.get("src", ()))
if value is None:
return None
try:
config = parse_pyproject_toml(value)
except (toml.TomlDecodeError, OSError) as e:
raise click.FileError(
filename=value, hint=f"Error reading configuration file: {e}"
)
if not config:
return None
else:
# Sanitize the values to be Click friendly. For more information please see:
# https://github.com/psf/black/issues/1458
# https://github.com/pallets/click/issues/1567
config = {
k: str(v) if not isinstance(v, (list, dict)) else v
for k, v in config.items()
}
target_version = config.get("target_version")
if target_version is not None and not isinstance(target_version, list):
raise click.BadOptionUsage(
"target-version", "Config key target-version must be a list"
)
default_map: Dict[str, Any] = {}
if ctx.default_map:
default_map.update(ctx.default_map)
default_map.update(config)
ctx.default_map = default_map
return value
def target_version_option_callback(
c: click.Context, p: Union[click.Option, click.Parameter], v: Tuple[str, ...]
) -> List[TargetVersion]:
"""Compute the target versions from a --target-version flag.
This is its own function because mypy couldn't infer the type correctly
when it was a lambda, causing mypyc trouble.
"""
return [TargetVersion[val.upper()] for val in v]
def validate_regex(
ctx: click.Context,
param: click.Parameter,
value: Optional[str],
) -> Optional[Pattern]:
try:
return re_compile_maybe_verbose(value) if value is not None else None
except re.error:
raise click.BadParameter("Not a valid regular expression")
@click.command(context_settings=dict(help_option_names=["-h", "--help"]))
@click.option("-c", "--code", type=str, help="Format the code passed in as a string.")
@click.option(
"-l",
"--line-length",
type=int,
default=DEFAULT_LINE_LENGTH,
help="How many characters per line to allow.",
show_default=True,
)
@click.option(
"-t",
"--target-version",
type=click.Choice([v.name.lower() for v in TargetVersion]),
callback=target_version_option_callback,
multiple=True,
help=(
"Python versions that should be supported by Black's output. [default: per-file"
" auto-detection]"
),
)
@click.option(
"--pyi",
is_flag=True,
help=(
"Format all input files like typing stubs regardless of file extension (useful"
" when piping source on standard input)."
),
)
@click.option(
"-S",
"--skip-string-normalization",
is_flag=True,
help="Don't normalize string quotes or prefixes.",
)
@click.option(
"-C",
"--skip-magic-trailing-comma",
is_flag=True,
help="Don't use trailing commas as a reason to split lines.",
)
@click.option(
"--experimental-string-processing",
is_flag=True,
hidden=True,
help=(
"Experimental option that performs more normalization on string literals."
" Currently disabled because it leads to some crashes."
),
)
@click.option(
"--check",
is_flag=True,
help=(
"Don't write the files back, just return the status. Return code 0 means"
" nothing would change. Return code 1 means some files would be reformatted."
" Return code 123 means there was an internal error."
),
)
@click.option(
"--diff",
is_flag=True,
help="Don't write the files back, just output a diff for each file on stdout.",
)
@click.option(
"--color/--no-color",
is_flag=True,
help="Show colored diff. Only applies when `--diff` is given.",
)
@click.option(
"--fast/--safe",
is_flag=True,
help="If --fast given, skip temporary sanity checks. [default: --safe]",
)
@click.option(
"--include",
type=str,
default=DEFAULT_INCLUDES,
callback=validate_regex,
help=(
"A regular expression that matches files and directories that should be"
" included on recursive searches. An empty value means all files are included"
" regardless of the name. Use forward slashes for directories on all platforms"
" (Windows, too). Exclusions are calculated first, inclusions later."
),
show_default=True,
)
@click.option(
"--exclude",
type=str,
default=DEFAULT_EXCLUDES,
callback=validate_regex,
help=(
"A regular expression that matches files and directories that should be"
" excluded on recursive searches. An empty value means no paths are excluded."
" Use forward slashes for directories on all platforms (Windows, too)."
" Exclusions are calculated first, inclusions later."
),
show_default=True,
)
@click.option(
"--extend-exclude",
type=str,
callback=validate_regex,
help=(
"Like --exclude, but adds additional files and directories on top of the"
" excluded ones. (Useful if you simply want to add to the default)"
),
)
@click.option(
"--force-exclude",
type=str,
callback=validate_regex,
help=(
"Like --exclude, but files and directories matching this regex will be "
"excluded even when they are passed explicitly as arguments."
),
)
@click.option(
"--stdin-filename",
type=str,
help=(
"The name of the file when passing it through stdin. Useful to make "
"sure Black will respect --force-exclude option on some "
"editors that rely on using stdin."
),
)
@click.option(
"-q",
"--quiet",
is_flag=True,
help=(
"Don't emit non-error messages to stderr. Errors are still emitted; silence"
" those with 2>/dev/null."
),
)
@click.option(
"-v",
"--verbose",
is_flag=True,
help=(
"Also emit messages to stderr about files that were not changed or were ignored"
" due to exclusion patterns."
),
)
@click.version_option(version=__version__)
@click.argument(
"src",
nargs=-1,
type=click.Path(
exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
),
is_eager=True,
)
@click.option(
"--config",
type=click.Path(
exists=True,
file_okay=True,
dir_okay=False,
readable=True,
allow_dash=False,
path_type=str,
),
is_eager=True,
callback=read_pyproject_toml,
help="Read configuration from FILE path.",
)
@click.pass_context
def main(
ctx: click.Context,
code: Optional[str],
line_length: int,
target_version: List[TargetVersion],
check: bool,
diff: bool,
color: bool,
fast: bool,
pyi: bool,
skip_string_normalization: bool,
skip_magic_trailing_comma: bool,
experimental_string_processing: bool,
quiet: bool,
verbose: bool,
include: Pattern,
exclude: Pattern,
extend_exclude: Optional[Pattern],
force_exclude: Optional[Pattern],
stdin_filename: Optional[str],
src: Tuple[str, ...],
config: Optional[str],
) -> None:
"""The uncompromising code formatter."""
write_back = WriteBack.from_configuration(check=check, diff=diff, color=color)
if target_version:
versions = set(target_version)
else:
# We'll autodetect later.
versions = set()
mode = Mode(
target_versions=versions,
line_length=line_length,
is_pyi=pyi,
string_normalization=not skip_string_normalization,
magic_trailing_comma=not skip_magic_trailing_comma,
experimental_string_processing=experimental_string_processing,
)
if config and verbose:
out(f"Using configuration from {config}.", bold=False, fg="blue")
if code is not None:
print(format_str(code, mode=mode))
ctx.exit(0)
report = Report(check=check, diff=diff, quiet=quiet, verbose=verbose)
sources = get_sources(
ctx=ctx,
src=src,
quiet=quiet,
verbose=verbose,
include=include,
exclude=exclude,
extend_exclude=extend_exclude,
force_exclude=force_exclude,
report=report,
stdin_filename=stdin_filename,
)
path_empty(
sources,
"No Python files are present to be formatted. Nothing to do 😴",
quiet,
verbose,
ctx,
)
if len(sources) == 1:
reformat_one(
src=sources.pop(),
fast=fast,
write_back=write_back,
mode=mode,
report=report,
)
else:
reformat_many(
sources=sources, fast=fast, write_back=write_back, mode=mode, report=report
)
if verbose or not quiet:
out("Oh no! 💥 💔 💥" if report.return_code else "All done! ✨ 🍰 ✨")
click.secho(str(report), err=True)
ctx.exit(report.return_code)
def get_sources(
*,
ctx: click.Context,
src: Tuple[str, ...],
quiet: bool,
verbose: bool,
include: Pattern[str],
exclude: Pattern[str],
extend_exclude: Optional[Pattern[str]],
force_exclude: Optional[Pattern[str]],
report: "Report",
stdin_filename: Optional[str],
) -> Set[Path]:
"""Compute the set of files to be formatted."""
root = find_project_root(src)
sources: Set[Path] = set()
path_empty(src, "No Path provided. Nothing to do 😴", quiet, verbose, ctx)
gitignore = get_gitignore(root)
for s in src:
if s == "-" and stdin_filename:
p = Path(stdin_filename)
is_stdin = True
else:
p = Path(s)
is_stdin = False
if is_stdin or p.is_file():
normalized_path = normalize_path_maybe_ignore(p, root, report)
if normalized_path is None:
continue
normalized_path = "/" + normalized_path
# Hard-exclude any files that matches the `--force-exclude` regex.
if force_exclude:
force_exclude_match = force_exclude.search(normalized_path)
else:
force_exclude_match = None
if force_exclude_match and force_exclude_match.group(0):
report.path_ignored(p, "matches the --force-exclude regular expression")
continue
if is_stdin:
p = Path(f"{STDIN_PLACEHOLDER}{str(p)}")
sources.add(p)
elif p.is_dir():
sources.update(
gen_python_files(
p.iterdir(),
root,
include,
exclude,
extend_exclude,
force_exclude,
report,
gitignore,
)
)
elif s == "-":
sources.add(p)
else:
err(f"invalid path: {s}")
return sources
def path_empty(
src: Sized, msg: str, quiet: bool, verbose: bool, ctx: click.Context
) -> None:
"""
Exit if there is no `src` provided for formatting
"""
if not src and (verbose or not quiet):
out(msg)
ctx.exit(0)
def reformat_one(
src: Path, fast: bool, write_back: WriteBack, mode: Mode, report: "Report"
) -> None:
"""Reformat a single file under `src` without spawning child processes.
`fast`, `write_back`, and `mode` options are passed to
:func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
"""
try:
changed = Changed.NO
if str(src) == "-":
is_stdin = True
elif str(src).startswith(STDIN_PLACEHOLDER):
is_stdin = True
# Use the original name again in case we want to print something
# to the user
src = Path(str(src)[len(STDIN_PLACEHOLDER) :])
else:
is_stdin = False
if is_stdin:
if format_stdin_to_stdout(fast=fast, write_back=write_back, mode=mode):
changed = Changed.YES
else:
cache: Cache = {}
if write_back not in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
cache = read_cache(mode)
res_src = src.resolve()
res_src_s = str(res_src)
if res_src_s in cache and cache[res_src_s] == get_cache_info(res_src):
changed = Changed.CACHED
if changed is not Changed.CACHED and format_file_in_place(
src, fast=fast, write_back=write_back, mode=mode
):
changed = Changed.YES
if (write_back is WriteBack.YES and changed is not Changed.CACHED) or (
write_back is WriteBack.CHECK and changed is Changed.NO
):
write_cache(cache, [src], mode)
report.done(src, changed)
except Exception as exc:
if report.verbose:
traceback.print_exc()
report.failed(src, str(exc))
def reformat_many(
sources: Set[Path], fast: bool, write_back: WriteBack, mode: Mode, report: "Report"
) -> None:
"""Reformat multiple files using a ProcessPoolExecutor."""
executor: Executor
loop = asyncio.get_event_loop()
worker_count = os.cpu_count()
if sys.platform == "win32":
# Work around https://bugs.python.org/issue26903
worker_count = min(worker_count, 60)
try:
executor = ProcessPoolExecutor(max_workers=worker_count)
except (ImportError, OSError):
# we arrive here if the underlying system does not support multi-processing
# like in AWS Lambda or Termux, in which case we gracefully fallback to
# a ThreadPollExecutor with just a single worker (more workers would not do us
# any good due to the Global Interpreter Lock)
executor = ThreadPoolExecutor(max_workers=1)
try:
loop.run_until_complete(
schedule_formatting(
sources=sources,
fast=fast,
write_back=write_back,
mode=mode,
report=report,
loop=loop,
executor=executor,
)
)
finally:
shutdown(loop)
if executor is not None:
executor.shutdown()
async def schedule_formatting(
sources: Set[Path],
fast: bool,
write_back: WriteBack,
mode: Mode,
report: "Report",
loop: asyncio.AbstractEventLoop,
executor: Executor,
) -> None:
"""Run formatting of `sources` in parallel using the provided `executor`.
(Use ProcessPoolExecutors for actual parallelism.)
`write_back`, `fast`, and `mode` options are passed to
:func:`format_file_in_place`.
"""
cache: Cache = {}
if write_back not in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
cache = read_cache(mode)
sources, cached = filter_cached(cache, sources)
for src in sorted(cached):
report.done(src, Changed.CACHED)
if not sources:
return
cancelled = []
sources_to_cache = []
lock = None
if write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
# For diff output, we need locks to ensure we don't interleave output
# from different processes.
manager = Manager()
lock = manager.Lock()
tasks = {
asyncio.ensure_future(
loop.run_in_executor(
executor, format_file_in_place, src, fast, mode, write_back, lock
)
): src
for src in sorted(sources)
}
pending: Iterable["asyncio.Future[bool]"] = tasks.keys()
try:
loop.add_signal_handler(signal.SIGINT, cancel, pending)
loop.add_signal_handler(signal.SIGTERM, cancel, pending)
except NotImplementedError:
# There are no good alternatives for these on Windows.
pass
while pending:
done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
for task in done:
src = tasks.pop(task)
if task.cancelled():
cancelled.append(task)
elif task.exception():
report.failed(src, str(task.exception()))
else:
changed = Changed.YES if task.result() else Changed.NO
# If the file was written back or was successfully checked as
# well-formatted, store this information in the cache.
if write_back is WriteBack.YES or (
write_back is WriteBack.CHECK and changed is Changed.NO
):
sources_to_cache.append(src)
report.done(src, changed)
if cancelled:
await asyncio.gather(*cancelled, loop=loop, return_exceptions=True)
if sources_to_cache:
write_cache(cache, sources_to_cache, mode)
def format_file_in_place(
src: Path,
fast: bool,
mode: Mode,
write_back: WriteBack = WriteBack.NO,
lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy
) -> bool:
"""Format file under `src` path. Return True if changed.
If `write_back` is DIFF, write a diff to stdout. If it is YES, write reformatted
code to the file.
`mode` and `fast` options are passed to :func:`format_file_contents`.
"""
if src.suffix == ".pyi":
mode = replace(mode, is_pyi=True)
then = datetime.utcfromtimestamp(src.stat().st_mtime)
with open(src, "rb") as buf:
src_contents, encoding, newline = decode_bytes(buf.read())
try:
dst_contents = format_file_contents(src_contents, fast=fast, mode=mode)
except NothingChanged:
return False
if write_back == WriteBack.YES:
with open(src, "w", encoding=encoding, newline=newline) as f:
f.write(dst_contents)
elif write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
now = datetime.utcnow()
src_name = f"{src}\t{then} +0000"
dst_name = f"{src}\t{now} +0000"
diff_contents = diff(src_contents, dst_contents, src_name, dst_name)
if write_back == WriteBack.COLOR_DIFF:
diff_contents = color_diff(diff_contents)
with lock or nullcontext():
f = io.TextIOWrapper(
sys.stdout.buffer,
encoding=encoding,
newline=newline,
write_through=True,
)
f = wrap_stream_for_windows(f)
f.write(diff_contents)
f.detach()
return True
def color_diff(contents: str) -> str:
"""Inject the ANSI color codes to the diff."""
lines = contents.split("\n")
for i, line in enumerate(lines):
if line.startswith("+++") or line.startswith("---"):
line = "\033[1;37m" + line + "\033[0m" # bold white, reset
elif line.startswith("@@"):
line = "\033[36m" + line + "\033[0m" # cyan, reset
elif line.startswith("+"):
line = "\033[32m" + line + "\033[0m" # green, reset
elif line.startswith("-"):
line = "\033[31m" + line + "\033[0m" # red, reset
lines[i] = line
return "\n".join(lines)
def wrap_stream_for_windows(
f: io.TextIOWrapper,
) -> Union[io.TextIOWrapper, "colorama.AnsiToWin32"]:
"""
Wrap stream with colorama's wrap_stream so colors are shown on Windows.
If `colorama` is unavailable, the original stream is returned unmodified.
Otherwise, the `wrap_stream()` function determines whether the stream needs
to be wrapped for a Windows environment and will accordingly either return
an `AnsiToWin32` wrapper or the original stream.
"""
try:
from colorama.initialise import wrap_stream
except ImportError:
return f
else:
# Set `strip=False` to avoid needing to modify test_express_diff_with_color.
return wrap_stream(f, convert=None, strip=False, autoreset=False, wrap=True)
def format_stdin_to_stdout(
fast: bool, *, write_back: WriteBack = WriteBack.NO, mode: Mode
) -> bool:
"""Format file on stdin. Return True if changed.
If `write_back` is YES, write reformatted code back to stdout. If it is DIFF,
write a diff to stdout. The `mode` argument is passed to
:func:`format_file_contents`.
"""
then = datetime.utcnow()
src, encoding, newline = decode_bytes(sys.stdin.buffer.read())
dst = src
try:
dst = format_file_contents(src, fast=fast, mode=mode)
return True
except NothingChanged:
return False
finally:
f = io.TextIOWrapper(
sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True
)
if write_back == WriteBack.YES:
f.write(dst)
elif write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
now = datetime.utcnow()
src_name = f"STDIN\t{then} +0000"
dst_name = f"STDOUT\t{now} +0000"
d = diff(src, dst, src_name, dst_name)
if write_back == WriteBack.COLOR_DIFF:
d = color_diff(d)
f = wrap_stream_for_windows(f)
f.write(d)
f.detach()
def format_file_contents(src_contents: str, *, fast: bool, mode: Mode) -> FileContent:
"""Reformat contents of a file and return new contents.
If `fast` is False, additionally confirm that the reformatted code is
valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
`mode` is passed to :func:`format_str`.
"""
if not src_contents.strip():
raise NothingChanged
dst_contents = format_str(src_contents, mode=mode)
if src_contents == dst_contents:
raise NothingChanged
if not fast:
assert_equivalent(src_contents, dst_contents)
assert_stable(src_contents, dst_contents, mode=mode)
return dst_contents
def format_str(src_contents: str, *, mode: Mode) -> FileContent:
"""Reformat a string and return new contents.
`mode` determines formatting options, such as how many characters per line are
allowed. Example:
>>> import black
>>> print(black.format_str("def f(arg:str='')->None:...", mode=black.Mode()))
def f(arg: str = "") -> None:
...
A more complex example:
>>> print(
... black.format_str(
... "def f(arg:str='')->None: hey",
... mode=black.Mode(
... target_versions={black.TargetVersion.PY36},
... line_length=10,
... string_normalization=False,
... is_pyi=False,
... ),
... ),
... )
def f(
arg: str = '',
) -> None:
hey
"""
src_node = lib2to3_parse(src_contents.lstrip(), mode.target_versions)
dst_contents = []
future_imports = get_future_imports(src_node)
if mode.target_versions:
versions = mode.target_versions
else:
versions = detect_target_versions(src_node)
normalize_fmt_off(src_node)
lines = LineGenerator(
mode=mode,
remove_u_prefix="unicode_literals" in future_imports
or supports_feature(versions, Feature.UNICODE_LITERALS),
)
elt = EmptyLineTracker(is_pyi=mode.is_pyi)
empty_line = Line(mode=mode)
after = 0
split_line_features = {
feature
for feature in {Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF}
if supports_feature(versions, feature)
}
for current_line in lines.visit(src_node):
dst_contents.append(str(empty_line) * after)
before, after = elt.maybe_empty_lines(current_line)
dst_contents.append(str(empty_line) * before)
for line in transform_line(
current_line, mode=mode, features=split_line_features
):
dst_contents.append(str(line))
return "".join(dst_contents)
def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
"""Return a tuple of (decoded_contents, encoding, newline).
`newline` is either CRLF or LF but `decoded_contents` is decoded with
universal newlines (i.e. only contains LF).
"""
srcbuf = io.BytesIO(src)
encoding, lines = tokenize.detect_encoding(srcbuf.readline)
if not lines:
return "", encoding, "\n"
newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
srcbuf.seek(0)
with io.TextIOWrapper(srcbuf, encoding) as tiow:
return tiow.read(), encoding, newline
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]:
if not target_versions:
# No target_version specified, so try all grammars.
return [
# Python 3.7+
pygram.python_grammar_no_print_statement_no_exec_statement_async_keywords,
# Python 3.0-3.6
pygram.python_grammar_no_print_statement_no_exec_statement,
# Python 2.7 with future print_function import
pygram.python_grammar_no_print_statement,
# Python 2.7
pygram.python_grammar,
]
if all(version.is_python2() for version in target_versions):
# Python 2-only code, so try Python 2 grammars.
return [
# Python 2.7 with future print_function import
pygram.python_grammar_no_print_statement,
# Python 2.7
pygram.python_grammar,
]
# Python 3-compatible code, so only try Python 3 grammar.
grammars = []
# If we have to parse both, try to parse async as a keyword first
if not supports_feature(target_versions, Feature.ASYNC_IDENTIFIERS):
# Python 3.7+
grammars.append(
pygram.python_grammar_no_print_statement_no_exec_statement_async_keywords
)
if not supports_feature(target_versions, Feature.ASYNC_KEYWORDS):
# Python 3.0-3.6
grammars.append(pygram.python_grammar_no_print_statement_no_exec_statement)
# At least one of the above branches must have been taken, because every Python
# version has exactly one of the two 'ASYNC_*' flags
return grammars
def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -> Node:
"""Given a string with source, return the lib2to3 Node."""
if not src_txt.endswith("\n"):
src_txt += "\n"
for grammar in get_grammars(set(target_versions)):
drv = driver.Driver(grammar, pytree.convert)
try:
result = drv.parse_string(src_txt, True)
break
except ParseError as pe:
lineno, column = pe.context[1]
lines = src_txt.splitlines()
try:
faulty_line = lines[lineno - 1]
except IndexError:
faulty_line = "<line number missing in source>"
exc = InvalidInput(f"Cannot parse: {lineno}:{column}: {faulty_line}")
else:
raise exc from None
if isinstance(result, Leaf):
result = Node(syms.file_input, [result])
return result
def lib2to3_unparse(node: Node) -> str:
"""Given a lib2to3 node, return its string representation."""
code = str(node)
return code
class Visitor(Generic[T]):
"""Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
def visit(self, node: LN) -> Iterator[T]:
"""Main method to visit `node` and its children.
It tries to find a `visit_*()` method for the given `node.type`, like
`visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
If no dedicated `visit_*()` method is found, chooses `visit_default()`
instead.
Then yields objects of type `T` from the selected visitor.
"""
if node.type < 256:
name = token.tok_name[node.type]
else:
name = str(type_repr(node.type))
# We explicitly branch on whether a visitor exists (instead of
# using self.visit_default as the default arg to getattr) in order
# to save needing to create a bound method object and so mypyc can
# generate a native call to visit_default.
visitf = getattr(self, f"visit_{name}", None)
if visitf:
yield from visitf(node)
else:
yield from self.visit_default(node)
def visit_default(self, node: LN) -> Iterator[T]:
"""Default `visit_*()` implementation. Recurses to children of `node`."""
if isinstance(node, Node):
for child in node.children:
yield from self.visit(child)
@dataclass
class DebugVisitor(Visitor[T]):
tree_depth: int = 0
def visit_default(self, node: LN) -> Iterator[T]:
indent = " " * (2 * self.tree_depth)
if isinstance(node, Node):
_type = type_repr(node.type)
out(f"{indent}{_type}", fg="yellow")
self.tree_depth += 1
for child in node.children:
yield from self.visit(child)
self.tree_depth -= 1
out(f"{indent}/{_type}", fg="yellow", bold=False)
else:
_type = token.tok_name.get(node.type, str(node.type))
out(f"{indent}{_type}", fg="blue", nl=False)
if node.prefix:
# We don't have to handle prefixes for `Node` objects since
# that delegates to the first child anyway.
out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
out(f" {node.value!r}", fg="blue", bold=False)
@classmethod
def show(cls, code: Union[str, Leaf, Node]) -> None:
"""Pretty-print the lib2to3 AST of a given string of `code`.
Convenience method for debugging.
"""
v: DebugVisitor[None] = DebugVisitor()
if isinstance(code, str):
code = lib2to3_parse(code)
list(v.visit(code))
WHITESPACE: Final = {token.DEDENT, token.INDENT, token.NEWLINE}
STATEMENT: Final = {
syms.if_stmt,
syms.while_stmt,
syms.for_stmt,
syms.try_stmt,
syms.except_clause,
syms.with_stmt,
syms.funcdef,
syms.classdef,
}
STANDALONE_COMMENT: Final = 153
token.tok_name[STANDALONE_COMMENT] = "STANDALONE_COMMENT"
LOGIC_OPERATORS: Final = {"and", "or"}
COMPARATORS: Final = {
token.LESS,
token.GREATER,
token.EQEQUAL,
token.NOTEQUAL,
token.LESSEQUAL,
token.GREATEREQUAL,
}
MATH_OPERATORS: Final = {
token.VBAR,
token.CIRCUMFLEX,
token.AMPER,
token.LEFTSHIFT,
token.RIGHTSHIFT,
token.PLUS,
token.MINUS,
token.STAR,
token.SLASH,
token.DOUBLESLASH,
token.PERCENT,
token.AT,
token.TILDE,
token.DOUBLESTAR,
}
STARS: Final = {token.STAR, token.DOUBLESTAR}
VARARGS_SPECIALS: Final = STARS | {token.SLASH}
VARARGS_PARENTS: Final = {
syms.arglist,
syms.argument, # double star in arglist
syms.trailer, # single argument to call
syms.typedargslist,
syms.varargslist, # lambdas
}
UNPACKING_PARENTS: Final = {
syms.atom, # single element of a list or set literal
syms.dictsetmaker,
syms.listmaker,
syms.testlist_gexp,
syms.testlist_star_expr,
}
TEST_DESCENDANTS: Final = {
syms.test,
syms.lambdef,
syms.or_test,
syms.and_test,
syms.not_test,
syms.comparison,
syms.star_expr,
syms.expr,
syms.xor_expr,
syms.and_expr,
syms.shift_expr,
syms.arith_expr,
syms.trailer,
syms.term,
syms.power,
}
ASSIGNMENTS: Final = {
"=",
"+=",
"-=",
"*=",
"@=",
"/=",
"%=",
"&=",
"|=",
"^=",
"<<=",
">>=",
"**=",
"//=",
}
COMPREHENSION_PRIORITY: Final = 20
COMMA_PRIORITY: Final = 18
TERNARY_PRIORITY: Final = 16
LOGIC_PRIORITY: Final = 14
STRING_PRIORITY: Final = 12
COMPARATOR_PRIORITY: Final = 10
MATH_PRIORITIES: Final = {
token.VBAR: 9,
token.CIRCUMFLEX: 8,
token.AMPER: 7,
token.LEFTSHIFT: 6,
token.RIGHTSHIFT: 6,
token.PLUS: 5,
token.MINUS: 5,
token.STAR: 4,
token.SLASH: 4,
token.DOUBLESLASH: 4,
token.PERCENT: 4,
token.AT: 4,
token.TILDE: 3,
token.DOUBLESTAR: 2,
}
DOT_PRIORITY: Final = 1
@dataclass
class BracketTracker:
"""Keeps track of brackets on a line."""
depth: int = 0
bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = field(default_factory=dict)
delimiters: Dict[LeafID, Priority] = field(default_factory=dict)
previous: Optional[Leaf] = None
_for_loop_depths: List[int] = field(default_factory=list)
_lambda_argument_depths: List[int] = field(default_factory=list)
invisible: List[Leaf] = field(default_factory=list)
def mark(self, leaf: Leaf) -> None:
"""Mark `leaf` with bracket-related metadata. Keep track of delimiters.
All leaves receive an int `bracket_depth` field that stores how deep
within brackets a given leaf is. 0 means there are no enclosing brackets
that started on this line.
If a leaf is itself a closing bracket, it receives an `opening_bracket`
field that it forms a pair with. This is a one-directional link to
avoid reference cycles.
If a leaf is a delimiter (a token on which Black can split the line if
needed) and it's on depth 0, its `id()` is stored in the tracker's
`delimiters` field.
"""
if leaf.type == token.COMMENT:
return
self.maybe_decrement_after_for_loop_variable(leaf)
self.maybe_decrement_after_lambda_arguments(leaf)
if leaf.type in CLOSING_BRACKETS:
self.depth -= 1
try:
opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
except KeyError as e:
raise BracketMatchError(
"Unable to match a closing bracket to the following opening"
f" bracket: {leaf}"
) from e
leaf.opening_bracket = opening_bracket
if not leaf.value:
self.invisible.append(leaf)
leaf.bracket_depth = self.depth
if self.depth == 0:
delim = is_split_before_delimiter(leaf, self.previous)
if delim and self.previous is not None:
self.delimiters[id(self.previous)] = delim
else:
delim = is_split_after_delimiter(leaf, self.previous)
if delim:
self.delimiters[id(leaf)] = delim
if leaf.type in OPENING_BRACKETS:
self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf
self.depth += 1
if not leaf.value:
self.invisible.append(leaf)
self.previous = leaf
self.maybe_increment_lambda_arguments(leaf)
self.maybe_increment_for_loop_variable(leaf)
def any_open_brackets(self) -> bool:
"""Return True if there is an yet unmatched open bracket on the line."""
return bool(self.bracket_match)
def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> Priority:
"""Return the highest priority of a delimiter found on the line.
Values are consistent with what `is_split_*_delimiter()` return.
Raises ValueError on no delimiters.
"""
return max(v for k, v in self.delimiters.items() if k not in exclude)
def delimiter_count_with_priority(self, priority: Priority = 0) -> int:
"""Return the number of delimiters with the given `priority`.
If no `priority` is passed, defaults to max priority on the line.
"""
if not self.delimiters:
return 0
priority = priority or self.max_delimiter_priority()
return sum(1 for p in self.delimiters.values() if p == priority)
def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
"""In a for loop, or comprehension, the variables are often unpacks.
To avoid splitting on the comma in this situation, increase the depth of
tokens between `for` and `in`.
"""
if leaf.type == token.NAME and leaf.value == "for":
self.depth += 1
self._for_loop_depths.append(self.depth)
return True
return False
def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
"""See `maybe_increment_for_loop_variable` above for explanation."""
if (
self._for_loop_depths
and self._for_loop_depths[-1] == self.depth
and leaf.type == token.NAME
and leaf.value == "in"
):
self.depth -= 1
self._for_loop_depths.pop()
return True
return False
def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool:
"""In a lambda expression, there might be more than one argument.
To avoid splitting on the comma in this situation, increase the depth of
tokens between `lambda` and `:`.
"""
if leaf.type == token.NAME and leaf.value == "lambda":
self.depth += 1
self._lambda_argument_depths.append(self.depth)
return True
return False
def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
"""See `maybe_increment_lambda_arguments` above for explanation."""
if (
self._lambda_argument_depths
and self._lambda_argument_depths[-1] == self.depth
and leaf.type == token.COLON
):
self.depth -= 1
self._lambda_argument_depths.pop()
return True
return False
def get_open_lsqb(self) -> Optional[Leaf]:
"""Return the most recent opening square bracket (if any)."""
return self.bracket_match.get((self.depth - 1, token.RSQB))
@dataclass
class Line:
"""Holds leaves and comments. Can be printed with `str(line)`."""
mode: Mode
depth: int = 0
leaves: List[Leaf] = field(default_factory=list)
# keys ordered like `leaves`
comments: Dict[LeafID, List[Leaf]] = field(default_factory=dict)
bracket_tracker: BracketTracker = field(default_factory=BracketTracker)
inside_brackets: bool = False
should_split_rhs: bool = False
magic_trailing_comma: Optional[Leaf] = None
def append(self, leaf: Leaf, preformatted: bool = False) -> None:
"""Add a new `leaf` to the end of the line.
Unless `preformatted` is True, the `leaf` will receive a new consistent
whitespace prefix and metadata applied by :class:`BracketTracker`.
Trailing commas are maybe removed, unpacked for loop variables are
demoted from being delimiters.
Inline comments are put aside.
"""
has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
if not has_value:
return
if token.COLON == leaf.type and self.is_class_paren_empty:
del self.leaves[-2:]
if self.leaves and not preformatted:
# Note: at this point leaf.prefix should be empty except for
# imports, for which we only preserve newlines.
leaf.prefix += whitespace(
leaf, complex_subscript=self.is_complex_subscript(leaf)
)
if self.inside_brackets or not preformatted:
self.bracket_tracker.mark(leaf)
if self.mode.magic_trailing_comma:
if self.has_magic_trailing_comma(leaf):
self.magic_trailing_comma = leaf
elif self.has_magic_trailing_comma(leaf, ensure_removable=True):
self.remove_trailing_comma()
if not self.append_comment(leaf):
self.leaves.append(leaf)
def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
"""Like :func:`append()` but disallow invalid standalone comment structure.
Raises ValueError when any `leaf` is appended after a standalone comment
or when a standalone comment is not the first leaf on the line.
"""
if self.bracket_tracker.depth == 0:
if self.is_comment:
raise ValueError("cannot append to standalone comments")
if self.leaves and leaf.type == STANDALONE_COMMENT:
raise ValueError(
"cannot append standalone comments to a populated line"
)
self.append(leaf, preformatted=preformatted)
@property
def is_comment(self) -> bool:
"""Is this line a standalone comment?"""
return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
@property
def is_decorator(self) -> bool:
"""Is this line a decorator?"""
return bool(self) and self.leaves[0].type == token.AT
@property
def is_import(self) -> bool:
"""Is this an import line?"""
return bool(self) and is_import(self.leaves[0])
@property
def is_class(self) -> bool:
"""Is this line a class definition?"""
return (
bool(self)
and self.leaves[0].type == token.NAME
and self.leaves[0].value == "class"
)
@property
def is_stub_class(self) -> bool:
"""Is this line a class definition with a body consisting only of "..."?"""
return self.is_class and self.leaves[-3:] == [
Leaf(token.DOT, ".") for _ in range(3)
]
@property
def is_def(self) -> bool:
"""Is this a function definition? (Also returns True for async defs.)"""
try:
first_leaf = self.leaves[0]
except IndexError:
return False
try:
second_leaf: Optional[Leaf] = self.leaves[1]
except IndexError:
second_leaf = None
return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
first_leaf.type == token.ASYNC
and second_leaf is not None
and second_leaf.type == token.NAME
and second_leaf.value == "def"
)
@property
def is_class_paren_empty(self) -> bool:
"""Is this a class with no base classes but using parentheses?
Those are unnecessary and should be removed.
"""
return (
bool(self)
and len(self.leaves) == 4
and self.is_class
and self.leaves[2].type == token.LPAR
and self.leaves[2].value == "("
and self.leaves[3].type == token.RPAR
and self.leaves[3].value == ")"
)
@property
def is_triple_quoted_string(self) -> bool:
"""Is the line a triple quoted string?"""
return (
bool(self)
and self.leaves[0].type == token.STRING
and self.leaves[0].value.startswith(('"""', "'''"))
)
def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
"""If so, needs to be split before emitting."""
for leaf in self.leaves:
if leaf.type == STANDALONE_COMMENT and leaf.bracket_depth <= depth_limit:
return True
return False
def contains_uncollapsable_type_comments(self) -> bool:
ignored_ids = set()
try:
last_leaf = self.leaves[-1]
ignored_ids.add(id(last_leaf))
if last_leaf.type == token.COMMA or (
last_leaf.type == token.RPAR and not last_leaf.value
):
# When trailing commas or optional parens are inserted by Black for
# consistency, comments after the previous last element are not moved
# (they don't have to, rendering will still be correct). So we ignore
# trailing commas and invisible.
last_leaf = self.leaves[-2]
ignored_ids.add(id(last_leaf))
except IndexError:
return False
# A type comment is uncollapsable if it is attached to a leaf
# that isn't at the end of the line (since that could cause it
# to get associated to a different argument) or if there are
# comments before it (since that could cause it to get hidden
# behind a comment.
comment_seen = False
for leaf_id, comments in self.comments.items():
for comment in comments:
if is_type_comment(comment):
if comment_seen or (
not is_type_comment(comment, " ignore")
and leaf_id not in ignored_ids
):
return True
comment_seen = True
return False
def contains_unsplittable_type_ignore(self) -> bool:
if not self.leaves:
return False
# If a 'type: ignore' is attached to the end of a line, we
# can't split the line, because we can't know which of the
# subexpressions the ignore was meant to apply to.
#
# We only want this to apply to actual physical lines from the
# original source, though: we don't want the presence of a
# 'type: ignore' at the end of a multiline expression to
# justify pushing it all onto one line. Thus we
# (unfortunately) need to check the actual source lines and
# only report an unsplittable 'type: ignore' if this line was
# one line in the original code.
# Grab the first and last line numbers, skipping generated leaves
first_line = next((leaf.lineno for leaf in self.leaves if leaf.lineno != 0), 0)
last_line = next(
(leaf.lineno for leaf in reversed(self.leaves) if leaf.lineno != 0), 0
)
if first_line == last_line:
# We look at the last two leaves since a comma or an
# invisible paren could have been added at the end of the
# line.
for node in self.leaves[-2:]:
for comment in self.comments.get(id(node), []):
if is_type_comment(comment, " ignore"):
return True
return False
def contains_multiline_strings(self) -> bool:
return any(is_multiline_string(leaf) for leaf in self.leaves)
def has_magic_trailing_comma(
self, closing: Leaf, ensure_removable: bool = False
) -> bool:
"""Return True if we have a magic trailing comma, that is when:
- there's a trailing comma here
- it's not a one-tuple
Additionally, if ensure_removable:
- it's not from square bracket indexing
"""
if not (
closing.type in CLOSING_BRACKETS
and self.leaves
and self.leaves[-1].type == token.COMMA
):
return False
if closing.type == token.RBRACE:
return True
if closing.type == token.RSQB:
if not ensure_removable:
return True
comma = self.leaves[-1]
return bool(comma.parent and comma.parent.type == syms.listmaker)
if self.is_import:
return True
if not is_one_tuple_between(closing.opening_bracket, closing, self.leaves):
return True
return False
def append_comment(self, comment: Leaf) -> bool:
"""Add an inline or standalone comment to the line."""
if (
comment.type == STANDALONE_COMMENT
and self.bracket_tracker.any_open_brackets()
):
comment.prefix = ""
return False
if comment.type != token.COMMENT:
return False
if not self.leaves:
comment.type = STANDALONE_COMMENT
comment.prefix = ""
return False
last_leaf = self.leaves[-1]
if (
last_leaf.type == token.RPAR
and not last_leaf.value
and last_leaf.parent
and len(list(last_leaf.parent.leaves())) <= 3
and not is_type_comment(comment)
):
# Comments on an optional parens wrapping a single leaf should belong to
# the wrapped node except if it's a type comment. Pinning the comment like
# this avoids unstable formatting caused by comment migration.
if len(self.leaves) < 2:
comment.type = STANDALONE_COMMENT
comment.prefix = ""
return False
last_leaf = self.leaves[-2]
self.comments.setdefault(id(last_leaf), []).append(comment)
return True
def comments_after(self, leaf: Leaf) -> List[Leaf]:
"""Generate comments that should appear directly after `leaf`."""
return self.comments.get(id(leaf), [])
def remove_trailing_comma(self) -> None:
"""Remove the trailing comma and moves the comments attached to it."""
trailing_comma = self.leaves.pop()
trailing_comma_comments = self.comments.pop(id(trailing_comma), [])
self.comments.setdefault(id(self.leaves[-1]), []).extend(
trailing_comma_comments
)
def is_complex_subscript(self, leaf: Leaf) -> bool:
"""Return True iff `leaf` is part of a slice with non-trivial exprs."""
open_lsqb = self.bracket_tracker.get_open_lsqb()
if open_lsqb is None:
return False
subscript_start = open_lsqb.next_sibling
if isinstance(subscript_start, Node):
if subscript_start.type == syms.listmaker:
return False
if subscript_start.type == syms.subscriptlist:
subscript_start = child_towards(subscript_start, leaf)
return subscript_start is not None and any(
n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
)
def clone(self) -> "Line":
return Line(
mode=self.mode,
depth=self.depth,
inside_brackets=self.inside_brackets,
should_split_rhs=self.should_split_rhs,
magic_trailing_comma=self.magic_trailing_comma,
)
def __str__(self) -> str:
"""Render the line."""
if not self:
return "\n"
indent = " " * self.depth
leaves = iter(self.leaves)
first = next(leaves)
res = f"{first.prefix}{indent}{first.value}"
for leaf in leaves:
res += str(leaf)
for comment in itertools.chain.from_iterable(self.comments.values()):
res += str(comment)
return res + "\n"
def __bool__(self) -> bool:
"""Return True if the line has leaves or comments."""
return bool(self.leaves or self.comments)
@dataclass
class EmptyLineTracker:
"""Provides a stateful method that returns the number of potential extra
empty lines needed before and after the currently processed line.
Note: this tracker works on lines that haven't been split yet. It assumes
the prefix of the first leaf consists of optional newlines. Those newlines
are consumed by `maybe_empty_lines()` and included in the computation.
"""
is_pyi: bool = False
previous_line: Optional[Line] = None
previous_after: int = 0
previous_defs: List[int] = field(default_factory=list)
def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
"""Return the number of extra empty lines before and after the `current_line`.
This is for separating `def`, `async def` and `class` with extra empty
lines (two on module-level).
"""
before, after = self._maybe_empty_lines(current_line)
before = (
# Black should not insert empty lines at the beginning
# of the file
0
if self.previous_line is None
else before - self.previous_after
)
self.previous_after = after
self.previous_line = current_line
return before, after
def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
max_allowed = 1
if current_line.depth == 0:
max_allowed = 1 if self.is_pyi else 2
if current_line.leaves:
# Consume the first leaf's extra newlines.
first_leaf = current_line.leaves[0]
before = first_leaf.prefix.count("\n")
before = min(before, max_allowed)
first_leaf.prefix = ""
else:
before = 0
depth = current_line.depth
while self.previous_defs and self.previous_defs[-1] >= depth:
self.previous_defs.pop()
if self.is_pyi:
before = 0 if depth else 1
else:
before = 1 if depth else 2
if current_line.is_decorator or current_line.is_def or current_line.is_class:
return self._maybe_empty_lines_for_class_or_def(current_line, before)
if (
self.previous_line
and self.previous_line.is_import
and not current_line.is_import
and depth == self.previous_line.depth
):
return (before or 1), 0
if (
self.previous_line
and self.previous_line.is_class
and current_line.is_triple_quoted_string
):
return before, 1
return before, 0
def _maybe_empty_lines_for_class_or_def(
self, current_line: Line, before: int
) -> Tuple[int, int]:
if not current_line.is_decorator:
self.previous_defs.append(current_line.depth)
if self.previous_line is None:
# Don't insert empty lines before the first line in the file.
return 0, 0
if self.previous_line.is_decorator:
if self.is_pyi and current_line.is_stub_class:
# Insert an empty line after a decorated stub class
return 0, 1
return 0, 0
if self.previous_line.depth < current_line.depth and (
self.previous_line.is_class or self.previous_line.is_def
):
return 0, 0
if (
self.previous_line.is_comment
and self.previous_line.depth == current_line.depth
and before == 0
):
return 0, 0
if self.is_pyi:
if self.previous_line.depth > current_line.depth:
newlines = 1
elif current_line.is_class or self.previous_line.is_class:
if current_line.is_stub_class and self.previous_line.is_stub_class:
# No blank line between classes with an empty body
newlines = 0
else:
newlines = 1
elif (
current_line.is_def or current_line.is_decorator
) and not self.previous_line.is_def:
# Blank line between a block of functions (maybe with preceding
# decorators) and a block of non-functions
newlines = 1
else:
newlines = 0
else:
newlines = 2
if current_line.depth and newlines:
newlines -= 1
return newlines, 0
@dataclass
class LineGenerator(Visitor[Line]):
"""Generates reformatted Line objects. Empty lines are not emitted.
Note: destroys the tree it's visiting by mutating prefixes of its leaves
in ways that will no longer stringify to valid Python code on the tree.
"""
mode: Mode
remove_u_prefix: bool = False
current_line: Line = field(init=False)
def line(self, indent: int = 0) -> Iterator[Line]:
"""Generate a line.
If the line is empty, only emit if it makes sense.
If the line is too long, split it first and then generate.
If any lines were generated, set up a new current_line.
"""
if not self.current_line:
self.current_line.depth += indent
return # Line is empty, don't emit. Creating a new one unnecessary.
complete_line = self.current_line
self.current_line = Line(mode=self.mode, depth=complete_line.depth + indent)
yield complete_line
def visit_default(self, node: LN) -> Iterator[Line]:
"""Default `visit_*()` implementation. Recurses to children of `node`."""
if isinstance(node, Leaf):
any_open_brackets = self.current_line.bracket_tracker.any_open_brackets()
for comment in generate_comments(node):
if any_open_brackets:
# any comment within brackets is subject to splitting
self.current_line.append(comment)
elif comment.type == token.COMMENT:
# regular trailing comment
self.current_line.append(comment)
yield from self.line()
else:
# regular standalone comment
yield from self.line()
self.current_line.append(comment)
yield from self.line()
normalize_prefix(node, inside_brackets=any_open_brackets)
if self.mode.string_normalization and node.type == token.STRING:
normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix)
normalize_string_quotes(node)
if node.type == token.NUMBER:
normalize_numeric_literal(node)
if node.type not in WHITESPACE:
self.current_line.append(node)
yield from super().visit_default(node)
def visit_INDENT(self, node: Leaf) -> Iterator[Line]:
"""Increase indentation level, maybe yield a line."""
# In blib2to3 INDENT never holds comments.
yield from self.line(+1)
yield from self.visit_default(node)
def visit_DEDENT(self, node: Leaf) -> Iterator[Line]:
"""Decrease indentation level, maybe yield a line."""
# The current line might still wait for trailing comments. At DEDENT time
# there won't be any (they would be prefixes on the preceding NEWLINE).
# Emit the line then.
yield from self.line()
# While DEDENT has no value, its prefix may contain standalone comments
# that belong to the current indentation level. Get 'em.
yield from self.visit_default(node)
# Finally, emit the dedent.
yield from self.line(-1)
def visit_stmt(
self, node: Node, keywords: Set[str], parens: Set[str]
) -> Iterator[Line]:
"""Visit a statement.
This implementation is shared for `if`, `while`, `for`, `try`, `except`,
`def`, `with`, `class`, `assert` and assignments.
The relevant Python language `keywords` for a given statement will be
NAME leaves within it. This methods puts those on a separate line.
`parens` holds a set of string leaf values immediately after which
invisible parens should be put.
"""
normalize_invisible_parens(node, parens_after=parens)
for child in node.children:
if child.type == token.NAME and child.value in keywords: # type: ignore
yield from self.line()
yield from self.visit(child)
def visit_suite(self, node: Node) -> Iterator[Line]:
"""Visit a suite."""
if self.mode.is_pyi and is_stub_suite(node):
yield from self.visit(node.children[2])
else:
yield from self.visit_default(node)
def visit_simple_stmt(self, node: Node) -> Iterator[Line]:
"""Visit a statement without nested statements."""
if first_child_is_arith(node):
wrap_in_parentheses(node, node.children[0], visible=False)
is_suite_like = node.parent and node.parent.type in STATEMENT
if is_suite_like:
if self.mode.is_pyi and is_stub_body(node):
yield from self.visit_default(node)
else:
yield from self.line(+1)
yield from self.visit_default(node)
yield from self.line(-1)
else:
if (
not self.mode.is_pyi
or not node.parent
or not is_stub_suite(node.parent)
):
yield from self.line()
yield from self.visit_default(node)
def visit_async_stmt(self, node: Node) -> Iterator[Line]:
"""Visit `async def`, `async for`, `async with`."""
yield from self.line()
children = iter(node.children)
for child in children:
yield from self.visit(child)
if child.type == token.ASYNC:
break
internal_stmt = next(children)
for child in internal_stmt.children:
yield from self.visit(child)
def visit_decorators(self, node: Node) -> Iterator[Line]:
"""Visit decorators."""
for child in node.children:
yield from self.line()
yield from self.visit(child)
def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]:
"""Remove a semicolon and put the other statement on a separate line."""
yield from self.line()
def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]:
"""End of file. Process outstanding comments and end with a newline."""
yield from self.visit_default(leaf)
yield from self.line()
def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]:
if not self.current_line.bracket_tracker.any_open_brackets():
yield from self.line()
yield from self.visit_default(leaf)
def visit_factor(self, node: Node) -> Iterator[Line]:
"""Force parentheses between a unary op and a binary power:
-2 ** 8 -> -(2 ** 8)
"""
_operator, operand = node.children
if (
operand.type == syms.power
and len(operand.children) == 3
and operand.children[1].type == token.DOUBLESTAR
):
lpar = Leaf(token.LPAR, "(")
rpar = Leaf(token.RPAR, ")")
index = operand.remove() or 0
node.insert_child(index, Node(syms.atom, [lpar, operand, rpar]))
yield from self.visit_default(node)
def visit_STRING(self, leaf: Leaf) -> Iterator[Line]:
if is_docstring(leaf) and "\\\n" not in leaf.value:
# We're ignoring docstrings with backslash newline escapes because changing
# indentation of those changes the AST representation of the code.
prefix = get_string_prefix(leaf.value)
lead_len = len(prefix) + 3
tail_len = -3
indent = " " * 4 * self.current_line.depth
docstring = fix_docstring(leaf.value[lead_len:tail_len], indent)
if docstring:
if leaf.value[lead_len - 1] == docstring[0]:
docstring = " " + docstring
if leaf.value[tail_len + 1] == docstring[-1]:
docstring = docstring + " "
leaf.value = leaf.value[0:lead_len] + docstring + leaf.value[tail_len:]
yield from self.visit_default(leaf)
def __post_init__(self) -> None:
"""You are in a twisty little maze of passages."""
self.current_line = Line(mode=self.mode)
v = self.visit_stmt
Ø: Set[str] = set()
self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","})
self.visit_if_stmt = partial(
v, keywords={"if", "else", "elif"}, parens={"if", "elif"}
)
self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"})
self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"})
self.visit_try_stmt = partial(
v, keywords={"try", "except", "else", "finally"}, parens=Ø
)
self.visit_except_clause = partial(v, keywords={"except"}, parens=Ø)
self.visit_with_stmt = partial(v, keywords={"with"}, parens=Ø)
self.visit_funcdef = partial(v, keywords={"def"}, parens=Ø)
self.visit_classdef = partial(v, keywords={"class"}, parens=Ø)
self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS)
self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
self.visit_del_stmt = partial(v, keywords=Ø, parens={"del"})
self.visit_async_funcdef = self.visit_async_stmt
self.visit_decorated = self.visit_decorators
IMPLICIT_TUPLE = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
BRACKET = {token.LPAR: token.RPAR, token.LSQB: token.RSQB, token.LBRACE: token.RBRACE}
OPENING_BRACKETS = set(BRACKET.keys())
CLOSING_BRACKETS = set(BRACKET.values())
BRACKETS = OPENING_BRACKETS | CLOSING_BRACKETS
ALWAYS_NO_SPACE = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str: # noqa: C901
"""Return whitespace prefix if needed for the given `leaf`.
`complex_subscript` signals whether the given leaf is part of a subscription
which has non-trivial arguments, like arithmetic expressions or function calls.
"""
NO = ""
SPACE = " "
DOUBLESPACE = " "
t = leaf.type
p = leaf.parent
v = leaf.value
if t in ALWAYS_NO_SPACE:
return NO
if t == token.COMMENT:
return DOUBLESPACE
assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
if t == token.COLON and p.type not in {
syms.subscript,
syms.subscriptlist,
syms.sliceop,
}:
return NO
prev = leaf.prev_sibling
if not prev:
prevp = preceding_leaf(p)
if not prevp or prevp.type in OPENING_BRACKETS:
return NO
if t == token.COLON:
if prevp.type == token.COLON:
return NO
elif prevp.type != token.COMMA and not complex_subscript:
return NO
return SPACE
if prevp.type == token.EQUAL:
if prevp.parent:
if prevp.parent.type in {
syms.arglist,
syms.argument,
syms.parameters,
syms.varargslist,
}:
return NO
elif prevp.parent.type == syms.typedargslist:
# A bit hacky: if the equal sign has whitespace, it means we
# previously found it's a typed argument. So, we're using
# that, too.
return prevp.prefix
elif prevp.type in VARARGS_SPECIALS:
if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
return NO
elif prevp.type == token.COLON:
if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
return SPACE if complex_subscript else NO
elif (
prevp.parent
and prevp.parent.type == syms.factor
and prevp.type in MATH_OPERATORS
):
return NO
elif (
prevp.type == token.RIGHTSHIFT
and prevp.parent
and prevp.parent.type == syms.shift_expr
and prevp.prev_sibling
and prevp.prev_sibling.type == token.NAME
and prevp.prev_sibling.value == "print" # type: ignore
):
# Python 2 print chevron
return NO
elif prevp.type == token.AT and p.parent and p.parent.type == syms.decorator:
# no space in decorators
return NO
elif prev.type in OPENING_BRACKETS:
return NO
if p.type in {syms.parameters, syms.arglist}:
# untyped function signatures or calls
if not prev or prev.type != token.COMMA:
return NO
elif p.type == syms.varargslist:
# lambdas
if prev and prev.type != token.COMMA:
return NO
elif p.type == syms.typedargslist:
# typed function signatures
if not prev:
return NO
if t == token.EQUAL:
if prev.type != syms.tname:
return NO
elif prev.type == token.EQUAL:
# A bit hacky: if the equal sign has whitespace, it means we
# previously found it's a typed argument. So, we're using that, too.
return prev.prefix
elif prev.type != token.COMMA:
return NO
elif p.type == syms.tname:
# type names
if not prev:
prevp = preceding_leaf(p)
if not prevp or prevp.type != token.COMMA:
return NO
elif p.type == syms.trailer:
# attributes and calls
if t == token.LPAR or t == token.RPAR:
return NO
if not prev:
if t == token.DOT:
prevp = preceding_leaf(p)
if not prevp or prevp.type != token.NUMBER:
return NO
elif t == token.LSQB:
return NO
elif prev.type != token.COMMA:
return NO
elif p.type == syms.argument:
# single argument
if t == token.EQUAL:
return NO
if not prev:
prevp = preceding_leaf(p)
if not prevp or prevp.type == token.LPAR:
return NO
elif prev.type in {token.EQUAL} | VARARGS_SPECIALS:
return NO
elif p.type == syms.decorator:
# decorators
return NO
elif p.type == syms.dotted_name:
if prev:
return NO
prevp = preceding_leaf(p)
if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
return NO
elif p.type == syms.classdef:
if t == token.LPAR:
return NO
if prev and prev.type == token.LPAR:
return NO
elif p.type in {syms.subscript, syms.sliceop}:
# indexing
if not prev:
assert p.parent is not None, "subscripts are always parented"
if p.parent.type == syms.subscriptlist:
return SPACE
return NO
elif not complex_subscript:
return NO
elif p.type == syms.atom:
if prev and t == token.DOT:
# dots, but not the first one.
return NO
elif p.type == syms.dictsetmaker:
# dict unpacking
if prev and prev.type == token.DOUBLESTAR:
return NO
elif p.type in {syms.factor, syms.star_expr}:
# unary ops
if not prev:
prevp = preceding_leaf(p)
if not prevp or prevp.type in OPENING_BRACKETS:
return NO
prevp_parent = prevp.parent
assert prevp_parent is not None
if prevp.type == token.COLON and prevp_parent.type in {
syms.subscript,
syms.sliceop,
}:
return NO
elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
return NO
elif t in {token.NAME, token.NUMBER, token.STRING}:
return NO
elif p.type == syms.import_from:
if t == token.DOT:
if prev and prev.type == token.DOT:
return NO
elif t == token.NAME:
if v == "import":
return SPACE
if prev and prev.type == token.DOT:
return NO
elif p.type == syms.sliceop:
return NO
return SPACE
def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
"""Return the first leaf that precedes `node`, if any."""
while node:
res = node.prev_sibling
if res:
if isinstance(res, Leaf):
return res
try:
return list(res.leaves())[-1]
except IndexError:
return None
node = node.parent
return None
def prev_siblings_are(node: Optional[LN], tokens: List[Optional[NodeType]]) -> bool:
"""Return if the `node` and its previous siblings match types against the provided
list of tokens; the provided `node`has its type matched against the last element in
the list. `None` can be used as the first element to declare that the start of the
list is anchored at the start of its parent's children."""
if not tokens:
return True
if tokens[-1] is None:
return node is None
if not node:
return False
if node.type != tokens[-1]:
return False
return prev_siblings_are(node.prev_sibling, tokens[:-1])
def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
"""Return the child of `ancestor` that contains `descendant`."""
node: Optional[LN] = descendant
while node and node.parent != ancestor:
node = node.parent
return node
def container_of(leaf: Leaf) -> LN:
"""Return `leaf` or one of its ancestors that is the topmost container of it.
By "container" we mean a node where `leaf` is the very first child.
"""
same_prefix = leaf.prefix
container: LN = leaf
while container:
parent = container.parent
if parent is None:
break
if parent.children[0].prefix != same_prefix:
break
if parent.type == syms.file_input:
break
if parent.prev_sibling is not None and parent.prev_sibling.type in BRACKETS:
break
container = parent
return container
def is_split_after_delimiter(leaf: Leaf, previous: Optional[Leaf] = None) -> Priority:
"""Return the priority of the `leaf` delimiter, given a line break after it.
The delimiter priorities returned here are from those delimiters that would
cause a line break after themselves.
Higher numbers are higher priority.
"""
if leaf.type == token.COMMA:
return COMMA_PRIORITY
return 0
def is_split_before_delimiter(leaf: Leaf, previous: Optional[Leaf] = None) -> Priority:
"""Return the priority of the `leaf` delimiter, given a line break before it.
The delimiter priorities returned here are from those delimiters that would
cause a line break before themselves.
Higher numbers are higher priority.
"""
if is_vararg(leaf, within=VARARGS_PARENTS | UNPACKING_PARENTS):
# * and ** might also be MATH_OPERATORS but in this case they are not.
# Don't treat them as a delimiter.
return 0
if (
leaf.type == token.DOT
and leaf.parent
and leaf.parent.type not in {syms.import_from, syms.dotted_name}
and (previous is None or previous.type in CLOSING_BRACKETS)
):
return DOT_PRIORITY
if (
leaf.type in MATH_OPERATORS
and leaf.parent
and leaf.parent.type not in {syms.factor, syms.star_expr}
):
return MATH_PRIORITIES[leaf.type]
if leaf.type in COMPARATORS:
return COMPARATOR_PRIORITY
if (
leaf.type == token.STRING
and previous is not None
and previous.type == token.STRING
):
return STRING_PRIORITY
if leaf.type not in {token.NAME, token.ASYNC}:
return 0
if (
leaf.value == "for"
and leaf.parent
and leaf.parent.type in {syms.comp_for, syms.old_comp_for}
or leaf.type == token.ASYNC
):
if (
not isinstance(leaf.prev_sibling, Leaf)
or leaf.prev_sibling.value != "async"
):
return COMPREHENSION_PRIORITY
if (
leaf.value == "if"
and leaf.parent
and leaf.parent.type in {syms.comp_if, syms.old_comp_if}
):
return COMPREHENSION_PRIORITY
if leaf.value in {"if", "else"} and leaf.parent and leaf.parent.type == syms.test:
return TERNARY_PRIORITY
if leaf.value == "is":
return COMPARATOR_PRIORITY
if (
leaf.value == "in"
and leaf.parent
and leaf.parent.type in {syms.comp_op, syms.comparison}
and not (
previous is not None
and previous.type == token.NAME
and previous.value == "not"
)
):
return COMPARATOR_PRIORITY
if (
leaf.value == "not"
and leaf.parent
and leaf.parent.type == syms.comp_op
and not (
previous is not None
and previous.type == token.NAME
and previous.value == "is"
)
):
return COMPARATOR_PRIORITY
if leaf.value in LOGIC_OPERATORS and leaf.parent:
return LOGIC_PRIORITY
return 0
FMT_OFF = {"# fmt: off", "# fmt:off", "# yapf: disable"}
FMT_SKIP = {"# fmt: skip", "# fmt:skip"}
FMT_PASS = {*FMT_OFF, *FMT_SKIP}
FMT_ON = {"# fmt: on", "# fmt:on", "# yapf: enable"}
def generate_comments(leaf: LN) -> Iterator[Leaf]:
"""Clean the prefix of the `leaf` and generate comments from it, if any.
Comments in lib2to3 are shoved into the whitespace prefix. This happens
in `pgen2/driver.py:Driver.parse_tokens()`. This was a brilliant implementation
move because it does away with modifying the grammar to include all the
possible places in which comments can be placed.
The sad consequence for us though is that comments don't "belong" anywhere.
This is why this function generates simple parentless Leaf objects for
comments. We simply don't know what the correct parent should be.
No matter though, we can live without this. We really only need to
differentiate between inline and standalone comments. The latter don't
share the line with any code.
Inline comments are emitted as regular token.COMMENT leaves. Standalone
are emitted with a fake STANDALONE_COMMENT token identifier.
"""
for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
@dataclass
class ProtoComment:
"""Describes a piece of syntax that is a comment.
It's not a :class:`blib2to3.pytree.Leaf` so that:
* it can be cached (`Leaf` objects should not be reused more than once as
they store their lineno, column, prefix, and parent information);
* `newlines` and `consumed` fields are kept separate from the `value`. This
simplifies handling of special marker comments like ``# fmt: off/on``.
"""
type: int # token.COMMENT or STANDALONE_COMMENT
value: str # content of the comment
newlines: int # how many newlines before the comment
consumed: int # how many characters of the original leaf's prefix did we consume
@lru_cache(maxsize=4096)
def list_comments(prefix: str, *, is_endmarker: bool) -> List[ProtoComment]:
"""Return a list of :class:`ProtoComment` objects parsed from the given `prefix`."""
result: List[ProtoComment] = []
if not prefix or "#" not in prefix:
return result
consumed = 0
nlines = 0
ignored_lines = 0
for index, line in enumerate(re.split("\r?\n", prefix)):
consumed += len(line) + 1 # adding the length of the split '\n'
line = line.lstrip()
if not line:
nlines += 1
if not line.startswith("#"):
# Escaped newlines outside of a comment are not really newlines at
# all. We treat a single-line comment following an escaped newline
# as a simple trailing comment.
if line.endswith("\\"):
ignored_lines += 1
continue
if index == ignored_lines and not is_endmarker:
comment_type = token.COMMENT # simple trailing comment
else:
comment_type = STANDALONE_COMMENT
comment = make_comment(line)
result.append(
ProtoComment(
type=comment_type, value=comment, newlines=nlines, consumed=consumed
)
)
nlines = 0
return result
def make_comment(content: str) -> str:
"""Return a consistently formatted comment from the given `content` string.
All comments (except for "##", "#!", "#:", '#'", "#%%") should have a single
space between the hash sign and the content.
If `content` didn't start with a hash sign, one is provided.
"""
content = content.rstrip()
if not content:
return "#"
if content[0] == "#":
content = content[1:]
if content and content[0] not in " !:#'%":
content = " " + content
return "#" + content
def transform_line(
line: Line, mode: Mode, features: Collection[Feature] = ()
) -> Iterator[Line]:
"""Transform a `line`, potentially splitting it into many lines.
They should fit in the allotted `line_length` but might not be able to.
`features` are syntactical features that may be used in the output.
"""
if line.is_comment:
yield line
return
line_str = line_to_string(line)
def init_st(ST: Type[StringTransformer]) -> StringTransformer:
"""Initialize StringTransformer"""
return ST(mode.line_length, mode.string_normalization)
string_merge = init_st(StringMerger)
string_paren_strip = init_st(StringParenStripper)
string_split = init_st(StringSplitter)
string_paren_wrap = init_st(StringParenWrapper)
transformers: List[Transformer]
if (
not line.contains_uncollapsable_type_comments()
and not line.should_split_rhs
and not line.magic_trailing_comma
and (
is_line_short_enough(line, line_length=mode.line_length, line_str=line_str)
or line.contains_unsplittable_type_ignore()
)
and not (line.inside_brackets and line.contains_standalone_comments())
):
# Only apply basic string preprocessing, since lines shouldn't be split here.
if mode.experimental_string_processing:
transformers = [string_merge, string_paren_strip]
else:
transformers = []
elif line.is_def:
transformers = [left_hand_split]
else:
def rhs(line: Line, features: Collection[Feature]) -> Iterator[Line]:
"""Wraps calls to `right_hand_split`.
The calls increasingly `omit` right-hand trailers (bracket pairs with
content), meaning the trailers get glued together to split on another
bracket pair instead.
"""
for omit in generate_trailers_to_omit(line, mode.line_length):
lines = list(
right_hand_split(line, mode.line_length, features, omit=omit)
)
# Note: this check is only able to figure out if the first line of the
# *current* transformation fits in the line length. This is true only
# for simple cases. All others require running more transforms via
# `transform_line()`. This check doesn't know if those would succeed.
if is_line_short_enough(lines[0], line_length=mode.line_length):
yield from lines
return
# All splits failed, best effort split with no omits.
# This mostly happens to multiline strings that are by definition
# reported as not fitting a single line, as well as lines that contain
# trailing commas (those have to be exploded).
yield from right_hand_split(
line, line_length=mode.line_length, features=features
)
if mode.experimental_string_processing:
if line.inside_brackets:
transformers = [
string_merge,
string_paren_strip,
string_split,
delimiter_split,
standalone_comment_split,
string_paren_wrap,
rhs,
]
else:
transformers = [
string_merge,
string_paren_strip,
string_split,
string_paren_wrap,
rhs,
]
else:
if line.inside_brackets:
transformers = [delimiter_split, standalone_comment_split, rhs]
else:
transformers = [rhs]
for transform in transformers:
# We are accumulating lines in `result` because we might want to abort
# mission and return the original line in the end, or attempt a different
# split altogether.
try:
result = run_transformer(line, transform, mode, features, line_str=line_str)
except CannotTransform:
continue
else:
yield from result
break
else:
yield line
@dataclass # type: ignore
class StringTransformer(ABC):
"""
An implementation of the Transformer protocol that relies on its
subclasses overriding the template methods `do_match(...)` and
`do_transform(...)`.
This Transformer works exclusively on strings (for example, by merging
or splitting them).
The following sections can be found among the docstrings of each concrete
StringTransformer subclass.
Requirements:
Which requirements must be met of the given Line for this
StringTransformer to be applied?
Transformations:
If the given Line meets all of the above requirements, which string
transformations can you expect to be applied to it by this
StringTransformer?
Collaborations:
What contractual agreements does this StringTransformer have with other
StringTransfomers? Such collaborations should be eliminated/minimized
as much as possible.
"""
line_length: int
normalize_strings: bool
__name__ = "StringTransformer"
@abstractmethod
def do_match(self, line: Line) -> TMatchResult:
"""
Returns:
* Ok(string_idx) such that `line.leaves[string_idx]` is our target
string, if a match was able to be made.
OR
* Err(CannotTransform), if a match was not able to be made.
"""
@abstractmethod
def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
"""
Yields:
* Ok(new_line) where new_line is the new transformed line.
OR
* Err(CannotTransform) if the transformation failed for some reason. The
`do_match(...)` template method should usually be used to reject
the form of the given Line, but in some cases it is difficult to
know whether or not a Line meets the StringTransformer's
requirements until the transformation is already midway.
Side Effects:
This method should NOT mutate @line directly, but it MAY mutate the
Line's underlying Node structure. (WARNING: If the underlying Node
structure IS altered, then this method should NOT be allowed to
yield an CannotTransform after that point.)
"""
def __call__(self, line: Line, _features: Collection[Feature]) -> Iterator[Line]:
"""
StringTransformer instances have a call signature that mirrors that of
the Transformer type.
Raises:
CannotTransform(...) if the concrete StringTransformer class is unable
to transform @line.
"""
# Optimization to avoid calling `self.do_match(...)` when the line does
# not contain any string.
if not any(leaf.type == token.STRING for leaf in line.leaves):
raise CannotTransform("There are no strings in this line.")
match_result = self.do_match(line)
if isinstance(match_result, Err):
cant_transform = match_result.err()
raise CannotTransform(
f"The string transformer {self.__class__.__name__} does not recognize"
" this line as one that it can transform."
) from cant_transform
string_idx = match_result.ok()
for line_result in self.do_transform(line, string_idx):
if isinstance(line_result, Err):
cant_transform = line_result.err()
raise CannotTransform(
"StringTransformer failed while attempting to transform string."
) from cant_transform
line = line_result.ok()
yield line
@dataclass
class CustomSplit:
"""A custom (i.e. manual) string split.
A single CustomSplit instance represents a single substring.
Examples:
Consider the following string:
```
"Hi there friend."
" This is a custom"
f" string {split}."
```
This string will correspond to the following three CustomSplit instances:
```
CustomSplit(False, 16)
CustomSplit(False, 17)
CustomSplit(True, 16)
```
"""
has_prefix: bool
break_idx: int
class CustomSplitMapMixin:
"""
This mixin class is used to map merged strings to a sequence of
CustomSplits, which will then be used to re-split the strings iff none of
the resultant substrings go over the configured max line length.
"""
_Key = Tuple[StringID, str]
_CUSTOM_SPLIT_MAP: Dict[_Key, Tuple[CustomSplit, ...]] = defaultdict(tuple)
@staticmethod
def _get_key(string: str) -> "CustomSplitMapMixin._Key":
"""
Returns:
A unique identifier that is used internally to map @string to a
group of custom splits.
"""
return (id(string), string)
def add_custom_splits(
self, string: str, custom_splits: Iterable[CustomSplit]
) -> None:
"""Custom Split Map Setter Method
Side Effects:
Adds a mapping from @string to the custom splits @custom_splits.
"""
key = self._get_key(string)
self._CUSTOM_SPLIT_MAP[key] = tuple(custom_splits)
def pop_custom_splits(self, string: str) -> List[CustomSplit]:
"""Custom Split Map Getter Method
Returns:
* A list of the custom splits that are mapped to @string, if any
exist.
OR
* [], otherwise.
Side Effects:
Deletes the mapping between @string and its associated custom
splits (which are returned to the caller).
"""
key = self._get_key(string)
custom_splits = self._CUSTOM_SPLIT_MAP[key]
del self._CUSTOM_SPLIT_MAP[key]
return list(custom_splits)
def has_custom_splits(self, string: str) -> bool:
"""
Returns:
True iff @string is associated with a set of custom splits.
"""
key = self._get_key(string)
return key in self._CUSTOM_SPLIT_MAP
class StringMerger(CustomSplitMapMixin, StringTransformer):
"""StringTransformer that merges strings together.
Requirements:
(A) The line contains adjacent strings such that ALL of the validation checks
listed in StringMerger.__validate_msg(...)'s docstring pass.
OR
(B) The line contains a string which uses line continuation backslashes.
Transformations:
Depending on which of the two requirements above where met, either:
(A) The string group associated with the target string is merged.
OR
(B) All line-continuation backslashes are removed from the target string.
Collaborations:
StringMerger provides custom split information to StringSplitter.
"""
def do_match(self, line: Line) -> TMatchResult:
LL = line.leaves
is_valid_index = is_valid_index_factory(LL)
for (i, leaf) in enumerate(LL):
if (
leaf.type == token.STRING
and is_valid_index(i + 1)
and LL[i + 1].type == token.STRING
):
return Ok(i)
if leaf.type == token.STRING and "\\\n" in leaf.value:
return Ok(i)
return TErr("This line has no strings that need merging.")
def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
new_line = line
rblc_result = self.__remove_backslash_line_continuation_chars(
new_line, string_idx
)
if isinstance(rblc_result, Ok):
new_line = rblc_result.ok()
msg_result = self.__merge_string_group(new_line, string_idx)
if isinstance(msg_result, Ok):
new_line = msg_result.ok()
if isinstance(rblc_result, Err) and isinstance(msg_result, Err):
msg_cant_transform = msg_result.err()
rblc_cant_transform = rblc_result.err()
cant_transform = CannotTransform(
"StringMerger failed to merge any strings in this line."
)
# Chain the errors together using `__cause__`.
msg_cant_transform.__cause__ = rblc_cant_transform
cant_transform.__cause__ = msg_cant_transform
yield Err(cant_transform)
else:
yield Ok(new_line)
@staticmethod
def __remove_backslash_line_continuation_chars(
line: Line, string_idx: int
) -> TResult[Line]:
"""
Merge strings that were split across multiple lines using
line-continuation backslashes.
Returns:
Ok(new_line), if @line contains backslash line-continuation
characters.
OR
Err(CannotTransform), otherwise.
"""
LL = line.leaves
string_leaf = LL[string_idx]
if not (
string_leaf.type == token.STRING
and "\\\n" in string_leaf.value
and not has_triple_quotes(string_leaf.value)
):
return TErr(
f"String leaf {string_leaf} does not contain any backslash line"
" continuation characters."
)
new_line = line.clone()
new_line.comments = line.comments.copy()
append_leaves(new_line, line, LL)
new_string_leaf = new_line.leaves[string_idx]
new_string_leaf.value = new_string_leaf.value.replace("\\\n", "")
return Ok(new_line)
def __merge_string_group(self, line: Line, string_idx: int) -> TResult[Line]:
"""
Merges string group (i.e. set of adjacent strings) where the first
string in the group is `line.leaves[string_idx]`.
Returns:
Ok(new_line), if ALL of the validation checks found in
__validate_msg(...) pass.
OR
Err(CannotTransform), otherwise.
"""
LL = line.leaves
is_valid_index = is_valid_index_factory(LL)
vresult = self.__validate_msg(line, string_idx)
if isinstance(vresult, Err):
return vresult
# If the string group is wrapped inside an Atom node, we must make sure
# to later replace that Atom with our new (merged) string leaf.
atom_node = LL[string_idx].parent
# We will place BREAK_MARK in between every two substrings that we
# merge. We will then later go through our final result and use the
# various instances of BREAK_MARK we find to add the right values to
# the custom split map.
BREAK_MARK = "@@@@@ BLACK BREAKPOINT MARKER @@@@@"
QUOTE = LL[string_idx].value[-1]
def make_naked(string: str, string_prefix: str) -> str:
"""Strip @string (i.e. make it a "naked" string)
Pre-conditions:
* assert_is_leaf_string(@string)
Returns:
A string that is identical to @string except that
@string_prefix has been stripped, the surrounding QUOTE
characters have been removed, and any remaining QUOTE
characters have been escaped.
"""
assert_is_leaf_string(string)
RE_EVEN_BACKSLASHES = r"(?:(?<!\\)(?:\\\\)*)"
naked_string = string[len(string_prefix) + 1 : -1]
naked_string = re.sub(
"(" + RE_EVEN_BACKSLASHES + ")" + QUOTE, r"\1\\" + QUOTE, naked_string
)
return naked_string
# Holds the CustomSplit objects that will later be added to the custom
# split map.
custom_splits = []
# Temporary storage for the 'has_prefix' part of the CustomSplit objects.
prefix_tracker = []
# Sets the 'prefix' variable. This is the prefix that the final merged
# string will have.
next_str_idx = string_idx
prefix = ""
while (
not prefix
and is_valid_index(next_str_idx)
and LL[next_str_idx].type == token.STRING
):
prefix = get_string_prefix(LL[next_str_idx].value)
next_str_idx += 1
# The next loop merges the string group. The final string will be
# contained in 'S'.
#
# The following convenience variables are used:
#
# S: string
# NS: naked string
# SS: next string
# NSS: naked next string
S = ""
NS = ""
num_of_strings = 0
next_str_idx = string_idx
while is_valid_index(next_str_idx) and LL[next_str_idx].type == token.STRING:
num_of_strings += 1
SS = LL[next_str_idx].value
next_prefix = get_string_prefix(SS)
# If this is an f-string group but this substring is not prefixed
# with 'f'...
if "f" in prefix and "f" not in next_prefix:
# Then we must escape any braces contained in this substring.
SS = re.subf(r"(\{|\})", "{1}{1}", SS)
NSS = make_naked(SS, next_prefix)
has_prefix = bool(next_prefix)
prefix_tracker.append(has_prefix)
S = prefix + QUOTE + NS + NSS + BREAK_MARK + QUOTE
NS = make_naked(S, prefix)
next_str_idx += 1
S_leaf = Leaf(token.STRING, S)
if self.normalize_strings:
normalize_string_quotes(S_leaf)
# Fill the 'custom_splits' list with the appropriate CustomSplit objects.
temp_string = S_leaf.value[len(prefix) + 1 : -1]
for has_prefix in prefix_tracker:
mark_idx = temp_string.find(BREAK_MARK)
assert (
mark_idx >= 0
), "Logic error while filling the custom string breakpoint cache."
temp_string = temp_string[mark_idx + len(BREAK_MARK) :]
breakpoint_idx = mark_idx + (len(prefix) if has_prefix else 0) + 1
custom_splits.append(CustomSplit(has_prefix, breakpoint_idx))
string_leaf = Leaf(token.STRING, S_leaf.value.replace(BREAK_MARK, ""))
if atom_node is not None:
replace_child(atom_node, string_leaf)
# Build the final line ('new_line') that this method will later return.
new_line = line.clone()
for (i, leaf) in enumerate(LL):
if i == string_idx:
new_line.append(string_leaf)
if string_idx <= i < string_idx + num_of_strings:
for comment_leaf in line.comments_after(LL[i]):
new_line.append(comment_leaf, preformatted=True)
continue
append_leaves(new_line, line, [leaf])
self.add_custom_splits(string_leaf.value, custom_splits)
return Ok(new_line)
@staticmethod
def __validate_msg(line: Line, string_idx: int) -> TResult[None]:
"""Validate (M)erge (S)tring (G)roup
Transform-time string validation logic for __merge_string_group(...).
Returns:
* Ok(None), if ALL validation checks (listed below) pass.
OR
* Err(CannotTransform), if any of the following are true:
- The target string group does not contain ANY stand-alone comments.
- The target string is not in a string group (i.e. it has no
adjacent strings).
- The string group has more than one inline comment.
- The string group has an inline comment that appears to be a pragma.
- The set of all string prefixes in the string group is of
length greater than one and is not equal to {"", "f"}.
- The string group consists of raw strings.
"""
# We first check for "inner" stand-alone comments (i.e. stand-alone
# comments that have a string leaf before them AND after them).
for inc in [1, -1]:
i = string_idx
found_sa_comment = False
is_valid_index = is_valid_index_factory(line.leaves)
while is_valid_index(i) and line.leaves[i].type in [
token.STRING,
STANDALONE_COMMENT,
]:
if line.leaves[i].type == STANDALONE_COMMENT:
found_sa_comment = True
elif found_sa_comment:
return TErr(
"StringMerger does NOT merge string groups which contain "
"stand-alone comments."
)
i += inc
num_of_inline_string_comments = 0
set_of_prefixes = set()
num_of_strings = 0
for leaf in line.leaves[string_idx:]:
if leaf.type != token.STRING:
# If the string group is trailed by a comma, we count the
# comments trailing the comma to be one of the string group's
# comments.
if leaf.type == token.COMMA and id(leaf) in line.comments:
num_of_inline_string_comments += 1
break
if has_triple_quotes(leaf.value):
return TErr("StringMerger does NOT merge multiline strings.")
num_of_strings += 1
prefix = get_string_prefix(leaf.value)
if "r" in prefix:
return TErr("StringMerger does NOT merge raw strings.")
set_of_prefixes.add(prefix)
if id(leaf) in line.comments:
num_of_inline_string_comments += 1
if contains_pragma_comment(line.comments[id(leaf)]):
return TErr("Cannot merge strings which have pragma comments.")
if num_of_strings < 2:
return TErr(
f"Not enough strings to merge (num_of_strings={num_of_strings})."
)
if num_of_inline_string_comments > 1:
return TErr(
f"Too many inline string comments ({num_of_inline_string_comments})."
)
if len(set_of_prefixes) > 1 and set_of_prefixes != {"", "f"}:
return TErr(f"Too many different prefixes ({set_of_prefixes}).")
return Ok(None)
class StringParenStripper(StringTransformer):
"""StringTransformer that strips surrounding parentheses from strings.
Requirements:
The line contains a string which is surrounded by parentheses and:
- The target string is NOT the only argument to a function call.
- The target string is NOT a "pointless" string.
- If the target string contains a PERCENT, the brackets are not
preceeded or followed by an operator with higher precedence than
PERCENT.
Transformations:
The parentheses mentioned in the 'Requirements' section are stripped.
Collaborations:
StringParenStripper has its own inherent usefulness, but it is also
relied on to clean up the parentheses created by StringParenWrapper (in
the event that they are no longer needed).
"""
def do_match(self, line: Line) -> TMatchResult:
LL = line.leaves
is_valid_index = is_valid_index_factory(LL)
for (idx, leaf) in enumerate(LL):
# Should be a string...
if leaf.type != token.STRING:
continue
# If this is a "pointless" string...
if (
leaf.parent
and leaf.parent.parent
and leaf.parent.parent.type == syms.simple_stmt
):
continue
# Should be preceded by a non-empty LPAR...
if (
not is_valid_index(idx - 1)
or LL[idx - 1].type != token.LPAR
or is_empty_lpar(LL[idx - 1])
):
continue
# That LPAR should NOT be preceded by a function name or a closing
# bracket (which could be a function which returns a function or a
# list/dictionary that contains a function)...
if is_valid_index(idx - 2) and (
LL[idx - 2].type == token.NAME or LL[idx - 2].type in CLOSING_BRACKETS
):
continue
string_idx = idx
# Skip the string trailer, if one exists.
string_parser = StringParser()
next_idx = string_parser.parse(LL, string_idx)
# if the leaves in the parsed string include a PERCENT, we need to
# make sure the initial LPAR is NOT preceded by an operator with
# higher or equal precedence to PERCENT
if is_valid_index(idx - 2):
# mypy can't quite follow unless we name this
before_lpar = LL[idx - 2]
if token.PERCENT in {leaf.type for leaf in LL[idx - 1 : next_idx]} and (
(
before_lpar.type
in {
token.STAR,
token.AT,
token.SLASH,
token.DOUBLESLASH,
token.PERCENT,
token.TILDE,
token.DOUBLESTAR,
token.AWAIT,
token.LSQB,
token.LPAR,
}
)
or (
# only unary PLUS/MINUS
before_lpar.parent
and before_lpar.parent.type == syms.factor
and (before_lpar.type in {token.PLUS, token.MINUS})
)
):
continue
# Should be followed by a non-empty RPAR...
if (
is_valid_index(next_idx)
and LL[next_idx].type == token.RPAR
and not is_empty_rpar(LL[next_idx])
):
# That RPAR should NOT be followed by anything with higher
# precedence than PERCENT
if is_valid_index(next_idx + 1) and LL[next_idx + 1].type in {
token.DOUBLESTAR,
token.LSQB,
token.LPAR,
token.DOT,
}:
continue
return Ok(string_idx)
return TErr("This line has no strings wrapped in parens.")
def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
LL = line.leaves
string_parser = StringParser()
rpar_idx = string_parser.parse(LL, string_idx)
for leaf in (LL[string_idx - 1], LL[rpar_idx]):
if line.comments_after(leaf):
yield TErr(
"Will not strip parentheses which have comments attached to them."
)
return
new_line = line.clone()
new_line.comments = line.comments.copy()
try:
append_leaves(new_line, line, LL[: string_idx - 1])
except BracketMatchError:
# HACK: I believe there is currently a bug somewhere in
# right_hand_split() that is causing brackets to not be tracked
# properly by a shared BracketTracker.
append_leaves(new_line, line, LL[: string_idx - 1], preformatted=True)
string_leaf = Leaf(token.STRING, LL[string_idx].value)
LL[string_idx - 1].remove()
replace_child(LL[string_idx], string_leaf)
new_line.append(string_leaf)
append_leaves(
new_line, line, LL[string_idx + 1 : rpar_idx] + LL[rpar_idx + 1 :]
)
LL[rpar_idx].remove()
yield Ok(new_line)
class BaseStringSplitter(StringTransformer):
"""
Abstract class for StringTransformers which transform a Line's strings by splitting
them or placing them on their own lines where necessary to avoid going over
the configured line length.
Requirements:
* The target string value is responsible for the line going over the
line length limit. It follows that after all of black's other line
split methods have been exhausted, this line (or one of the resulting
lines after all line splits are performed) would still be over the
line_length limit unless we split this string.
AND
* The target string is NOT a "pointless" string (i.e. a string that has
no parent or siblings).
AND
* The target string is not followed by an inline comment that appears
to be a pragma.
AND
* The target string is not a multiline (i.e. triple-quote) string.
"""
@abstractmethod
def do_splitter_match(self, line: Line) -> TMatchResult:
"""
BaseStringSplitter asks its clients to override this method instead of
`StringTransformer.do_match(...)`.
Follows the same protocol as `StringTransformer.do_match(...)`.
Refer to `help(StringTransformer.do_match)` for more information.
"""
def do_match(self, line: Line) -> TMatchResult:
match_result = self.do_splitter_match(line)
if isinstance(match_result, Err):
return match_result
string_idx = match_result.ok()
vresult = self.__validate(line, string_idx)
if isinstance(vresult, Err):
return vresult
return match_result
def __validate(self, line: Line, string_idx: int) -> TResult[None]:
"""
Checks that @line meets all of the requirements listed in this classes'
docstring. Refer to `help(BaseStringSplitter)` for a detailed
description of those requirements.
Returns:
* Ok(None), if ALL of the requirements are met.
OR
* Err(CannotTransform), if ANY of the requirements are NOT met.
"""
LL = line.leaves
string_leaf = LL[string_idx]
max_string_length = self.__get_max_string_length(line, string_idx)
if len(string_leaf.value) <= max_string_length:
return TErr(
"The string itself is not what is causing this line to be too long."
)
if not string_leaf.parent or [L.type for L in string_leaf.parent.children] == [
token.STRING,
token.NEWLINE,
]:
return TErr(
f"This string ({string_leaf.value}) appears to be pointless (i.e. has"
" no parent)."
)
if id(line.leaves[string_idx]) in line.comments and contains_pragma_comment(
line.comments[id(line.leaves[string_idx])]
):
return TErr(
"Line appears to end with an inline pragma comment. Splitting the line"
" could modify the pragma's behavior."
)
if has_triple_quotes(string_leaf.value):
return TErr("We cannot split multiline strings.")
return Ok(None)
def __get_max_string_length(self, line: Line, string_idx: int) -> int:
"""
Calculates the max string length used when attempting to determine
whether or not the target string is responsible for causing the line to
go over the line length limit.
WARNING: This method is tightly coupled to both StringSplitter and
(especially) StringParenWrapper. There is probably a better way to
accomplish what is being done here.
Returns:
max_string_length: such that `line.leaves[string_idx].value >
max_string_length` implies that the target string IS responsible
for causing this line to exceed the line length limit.
"""
LL = line.leaves
is_valid_index = is_valid_index_factory(LL)
# We use the shorthand "WMA4" in comments to abbreviate "We must
# account for". When giving examples, we use STRING to mean some/any
# valid string.
#
# Finally, we use the following convenience variables:
#
# P: The leaf that is before the target string leaf.
# N: The leaf that is after the target string leaf.
# NN: The leaf that is after N.
# WMA4 the whitespace at the beginning of the line.
offset = line.depth * 4
if is_valid_index(string_idx - 1):
p_idx = string_idx - 1
if (
LL[string_idx - 1].type == token.LPAR
and LL[string_idx - 1].value == ""
and string_idx >= 2
):
# If the previous leaf is an empty LPAR placeholder, we should skip it.
p_idx -= 1
P = LL[p_idx]
if P.type == token.PLUS:
# WMA4 a space and a '+' character (e.g. `+ STRING`).
offset += 2
if P.type == token.COMMA:
# WMA4 a space, a comma, and a closing bracket [e.g. `), STRING`].
offset += 3
if P.type in [token.COLON, token.EQUAL, token.NAME]:
# This conditional branch is meant to handle dictionary keys,
# variable assignments, 'return STRING' statement lines, and
# 'else STRING' ternary expression lines.
# WMA4 a single space.
offset += 1
# WMA4 the lengths of any leaves that came before that space,
# but after any closing bracket before that space.
for leaf in reversed(LL[: p_idx + 1]):
offset += len(str(leaf))
if leaf.type in CLOSING_BRACKETS:
break
if is_valid_index(string_idx + 1):
N = LL[string_idx + 1]
if N.type == token.RPAR and N.value == "" and len(LL) > string_idx + 2:
# If the next leaf is an empty RPAR placeholder, we should skip it.
N = LL[string_idx + 2]
if N.type == token.COMMA:
# WMA4 a single comma at the end of the string (e.g `STRING,`).
offset += 1
if is_valid_index(string_idx + 2):
NN = LL[string_idx + 2]
if N.type == token.DOT and NN.type == token.NAME:
# This conditional branch is meant to handle method calls invoked
# off of a string literal up to and including the LPAR character.
# WMA4 the '.' character.
offset += 1
if (
is_valid_index(string_idx + 3)
and LL[string_idx + 3].type == token.LPAR
):
# WMA4 the left parenthesis character.
offset += 1
# WMA4 the length of the method's name.
offset += len(NN.value)
has_comments = False
for comment_leaf in line.comments_after(LL[string_idx]):
if not has_comments:
has_comments = True
# WMA4 two spaces before the '#' character.
offset += 2
# WMA4 the length of the inline comment.
offset += len(comment_leaf.value)
max_string_length = self.line_length - offset
return max_string_length
class StringSplitter(CustomSplitMapMixin, BaseStringSplitter):
"""
StringTransformer that splits "atom" strings (i.e. strings which exist on
lines by themselves).
Requirements:
* The line consists ONLY of a single string (with the exception of a
'+' symbol which MAY exist at the start of the line), MAYBE a string
trailer, and MAYBE a trailing comma.
AND
* All of the requirements listed in BaseStringSplitter's docstring.
Transformations:
The string mentioned in the 'Requirements' section is split into as
many substrings as necessary to adhere to the configured line length.
In the final set of substrings, no substring should be smaller than
MIN_SUBSTR_SIZE characters.
The string will ONLY be split on spaces (i.e. each new substring should
start with a space). Note that the string will NOT be split on a space
which is escaped with a backslash.
If the string is an f-string, it will NOT be split in the middle of an
f-expression (e.g. in f"FooBar: {foo() if x else bar()}", {foo() if x
else bar()} is an f-expression).
If the string that is being split has an associated set of custom split
records and those custom splits will NOT result in any line going over
the configured line length, those custom splits are used. Otherwise the
string is split as late as possible (from left-to-right) while still
adhering to the transformation rules listed above.
Collaborations:
StringSplitter relies on StringMerger to construct the appropriate
CustomSplit objects and add them to the custom split map.
"""
MIN_SUBSTR_SIZE = 6
# Matches an "f-expression" (e.g. {var}) that might be found in an f-string.
RE_FEXPR = r"""
(?<!\{) (?:\{\{)* \{ (?!\{)
(?:
[^\{\}]
| \{\{
| \}\}
| (?R)
)+?
(?<!\}) \} (?:\}\})* (?!\})
"""
def do_splitter_match(self, line: Line) -> TMatchResult:
LL = line.leaves
is_valid_index = is_valid_index_factory(LL)
idx = 0
# The first leaf MAY be a '+' symbol...
if is_valid_index(idx) and LL[idx].type == token.PLUS:
idx += 1
# The next/first leaf MAY be an empty LPAR...
if is_valid_index(idx) and is_empty_lpar(LL[idx]):
idx += 1
# The next/first leaf MUST be a string...
if not is_valid_index(idx) or LL[idx].type != token.STRING:
return TErr("Line does not start with a string.")
string_idx = idx
# Skip the string trailer, if one exists.
string_parser = StringParser()
idx = string_parser.parse(LL, string_idx)
# That string MAY be followed by an empty RPAR...
if is_valid_index(idx) and is_empty_rpar(LL[idx]):
idx += 1
# That string / empty RPAR leaf MAY be followed by a comma...
if is_valid_index(idx) and LL[idx].type == token.COMMA:
idx += 1
# But no more leaves are allowed...
if is_valid_index(idx):
return TErr("This line does not end with a string.")
return Ok(string_idx)
def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
LL = line.leaves
QUOTE = LL[string_idx].value[-1]
is_valid_index = is_valid_index_factory(LL)
insert_str_child = insert_str_child_factory(LL[string_idx])
prefix = get_string_prefix(LL[string_idx].value)
# We MAY choose to drop the 'f' prefix from substrings that don't
# contain any f-expressions, but ONLY if the original f-string
# contains at least one f-expression. Otherwise, we will alter the AST
# of the program.
drop_pointless_f_prefix = ("f" in prefix) and re.search(
self.RE_FEXPR, LL[string_idx].value, re.VERBOSE
)
first_string_line = True
starts_with_plus = LL[0].type == token.PLUS
def line_needs_plus() -> bool:
return first_string_line and starts_with_plus
def maybe_append_plus(new_line: Line) -> None:
"""
Side Effects:
If @line starts with a plus and this is the first line we are
constructing, this function appends a PLUS leaf to @new_line
and replaces the old PLUS leaf in the node structure. Otherwise
this function does nothing.
"""
if line_needs_plus():
plus_leaf = Leaf(token.PLUS, "+")
replace_child(LL[0], plus_leaf)
new_line.append(plus_leaf)
ends_with_comma = (
is_valid_index(string_idx + 1) and LL[string_idx + 1].type == token.COMMA
)
def max_last_string() -> int:
"""
Returns:
The max allowed length of the string value used for the last
line we will construct.
"""
result = self.line_length
result -= line.depth * 4
result -= 1 if ends_with_comma else 0
result -= 2 if line_needs_plus() else 0
return result
# --- Calculate Max Break Index (for string value)
# We start with the line length limit
max_break_idx = self.line_length
# The last index of a string of length N is N-1.
max_break_idx -= 1
# Leading whitespace is not present in the string value (e.g. Leaf.value).
max_break_idx -= line.depth * 4
if max_break_idx < 0:
yield TErr(
f"Unable to split {LL[string_idx].value} at such high of a line depth:"
f" {line.depth}"
)
return
# Check if StringMerger registered any custom splits.
custom_splits = self.pop_custom_splits(LL[string_idx].value)
# We use them ONLY if none of them would produce lines that exceed the
# line limit.
use_custom_breakpoints = bool(
custom_splits
and all(csplit.break_idx <= max_break_idx for csplit in custom_splits)
)
# Temporary storage for the remaining chunk of the string line that
# can't fit onto the line currently being constructed.
rest_value = LL[string_idx].value
def more_splits_should_be_made() -> bool:
"""
Returns:
True iff `rest_value` (the remaining string value from the last
split), should be split again.
"""
if use_custom_breakpoints:
return len(custom_splits) > 1
else:
return len(rest_value) > max_last_string()
string_line_results: List[Ok[Line]] = []
while more_splits_should_be_made():
if use_custom_breakpoints:
# Custom User Split (manual)
csplit = custom_splits.pop(0)
break_idx = csplit.break_idx
else:
# Algorithmic Split (automatic)
max_bidx = max_break_idx - 2 if line_needs_plus() else max_break_idx
maybe_break_idx = self.__get_break_idx(rest_value, max_bidx)
if maybe_break_idx is None:
# If we are unable to algorithmically determine a good split
# and this string has custom splits registered to it, we
# fall back to using them--which means we have to start
# over from the beginning.
if custom_splits:
rest_value = LL[string_idx].value
string_line_results = []
first_string_line = True
use_custom_breakpoints = True
continue
# Otherwise, we stop splitting here.
break
break_idx = maybe_break_idx
# --- Construct `next_value`
next_value = rest_value[:break_idx] + QUOTE
if (
# Are we allowed to try to drop a pointless 'f' prefix?
drop_pointless_f_prefix
# If we are, will we be successful?
and next_value != self.__normalize_f_string(next_value, prefix)
):
# If the current custom split did NOT originally use a prefix,
# then `csplit.break_idx` will be off by one after removing
# the 'f' prefix.
break_idx = (
break_idx + 1
if use_custom_breakpoints and not csplit.has_prefix
else break_idx
)
next_value = rest_value[:break_idx] + QUOTE
next_value = self.__normalize_f_string(next_value, prefix)
# --- Construct `next_leaf`
next_leaf = Leaf(token.STRING, next_value)
insert_str_child(next_leaf)
self.__maybe_normalize_string_quotes(next_leaf)
# --- Construct `next_line`
next_line = line.clone()
maybe_append_plus(next_line)
next_line.append(next_leaf)
string_line_results.append(Ok(next_line))
rest_value = prefix + QUOTE + rest_value[break_idx:]
first_string_line = False
yield from string_line_results
if drop_pointless_f_prefix:
rest_value = self.__normalize_f_string(rest_value, prefix)
rest_leaf = Leaf(token.STRING, rest_value)
insert_str_child(rest_leaf)
# NOTE: I could not find a test case that verifies that the following
# line is actually necessary, but it seems to be. Otherwise we risk
# not normalizing the last substring, right?
self.__maybe_normalize_string_quotes(rest_leaf)
last_line = line.clone()
maybe_append_plus(last_line)
# If there are any leaves to the right of the target string...
if is_valid_index(string_idx + 1):
# We use `temp_value` here to determine how long the last line
# would be if we were to append all the leaves to the right of the
# target string to the last string line.
temp_value = rest_value
for leaf in LL[string_idx + 1 :]:
temp_value += str(leaf)
if leaf.type == token.LPAR:
break
# Try to fit them all on the same line with the last substring...
if (
len(temp_value) <= max_last_string()
or LL[string_idx + 1].type == token.COMMA
):
last_line.append(rest_leaf)
append_leaves(last_line, line, LL[string_idx + 1 :])
yield Ok(last_line)
# Otherwise, place the last substring on one line and everything
# else on a line below that...
else:
last_line.append(rest_leaf)
yield Ok(last_line)
non_string_line = line.clone()
append_leaves(non_string_line, line, LL[string_idx + 1 :])
yield Ok(non_string_line)
# Else the target string was the last leaf...
else:
last_line.append(rest_leaf)
last_line.comments = line.comments.copy()
yield Ok(last_line)
def __get_break_idx(self, string: str, max_break_idx: int) -> Optional[int]:
"""
This method contains the algorithm that StringSplitter uses to
determine which character to split each string at.
Args:
@string: The substring that we are attempting to split.
@max_break_idx: The ideal break index. We will return this value if it
meets all the necessary conditions. In the likely event that it
doesn't we will try to find the closest index BELOW @max_break_idx
that does. If that fails, we will expand our search by also
considering all valid indices ABOVE @max_break_idx.
Pre-Conditions:
* assert_is_leaf_string(@string)
* 0 <= @max_break_idx < len(@string)
Returns:
break_idx, if an index is able to be found that meets all of the
conditions listed in the 'Transformations' section of this classes'
docstring.
OR
None, otherwise.
"""
is_valid_index = is_valid_index_factory(string)
assert is_valid_index(max_break_idx)
assert_is_leaf_string(string)
_fexpr_slices: Optional[List[Tuple[Index, Index]]] = None
def fexpr_slices() -> Iterator[Tuple[Index, Index]]:
"""
Yields:
All ranges of @string which, if @string were to be split there,
would result in the splitting of an f-expression (which is NOT
allowed).
"""
nonlocal _fexpr_slices
if _fexpr_slices is None:
_fexpr_slices = []
for match in re.finditer(self.RE_FEXPR, string, re.VERBOSE):
_fexpr_slices.append(match.span())
yield from _fexpr_slices
is_fstring = "f" in get_string_prefix(string)
def breaks_fstring_expression(i: Index) -> bool:
"""
Returns:
True iff returning @i would result in the splitting of an
f-expression (which is NOT allowed).
"""
if not is_fstring:
return False
for (start, end) in fexpr_slices():
if start <= i < end:
return True
return False
def passes_all_checks(i: Index) -> bool:
"""
Returns:
True iff ALL of the conditions listed in the 'Transformations'
section of this classes' docstring would be be met by returning @i.
"""
is_space = string[i] == " "
is_not_escaped = True
j = i - 1
while is_valid_index(j) and string[j] == "\\":
is_not_escaped = not is_not_escaped
j -= 1
is_big_enough = (
len(string[i:]) >= self.MIN_SUBSTR_SIZE
and len(string[:i]) >= self.MIN_SUBSTR_SIZE
)
return (
is_space
and is_not_escaped
and is_big_enough
and not breaks_fstring_expression(i)
)
# First, we check all indices BELOW @max_break_idx.
break_idx = max_break_idx
while is_valid_index(break_idx - 1) and not passes_all_checks(break_idx):
break_idx -= 1
if not passes_all_checks(break_idx):
# If that fails, we check all indices ABOVE @max_break_idx.
#
# If we are able to find a valid index here, the next line is going
# to be longer than the specified line length, but it's probably
# better than doing nothing at all.
break_idx = max_break_idx + 1
while is_valid_index(break_idx + 1) and not passes_all_checks(break_idx):
break_idx += 1
if not is_valid_index(break_idx) or not passes_all_checks(break_idx):
return None
return break_idx
def __maybe_normalize_string_quotes(self, leaf: Leaf) -> None:
if self.normalize_strings:
normalize_string_quotes(leaf)
def __normalize_f_string(self, string: str, prefix: str) -> str:
"""
Pre-Conditions:
* assert_is_leaf_string(@string)
Returns:
* If @string is an f-string that contains no f-expressions, we
return a string identical to @string except that the 'f' prefix
has been stripped and all double braces (i.e. '{{' or '}}') have
been normalized (i.e. turned into '{' or '}').
OR
* Otherwise, we return @string.
"""
assert_is_leaf_string(string)
if "f" in prefix and not re.search(self.RE_FEXPR, string, re.VERBOSE):
new_prefix = prefix.replace("f", "")
temp = string[len(prefix) :]
temp = re.sub(r"\{\{", "{", temp)
temp = re.sub(r"\}\}", "}", temp)
new_string = temp
return f"{new_prefix}{new_string}"
else:
return string
class StringParenWrapper(CustomSplitMapMixin, BaseStringSplitter):
"""
StringTransformer that splits non-"atom" strings (i.e. strings that do not
exist on lines by themselves).
Requirements:
All of the requirements listed in BaseStringSplitter's docstring in
addition to the requirements listed below:
* The line is a return/yield statement, which returns/yields a string.
OR
* The line is part of a ternary expression (e.g. `x = y if cond else
z`) such that the line starts with `else <string>`, where <string> is
some string.
OR
* The line is an assert statement, which ends with a string.
OR
* The line is an assignment statement (e.g. `x = <string>` or `x +=
<string>`) such that the variable is being assigned the value of some
string.
OR
* The line is a dictionary key assignment where some valid key is being
assigned the value of some string.
Transformations:
The chosen string is wrapped in parentheses and then split at the LPAR.
We then have one line which ends with an LPAR and another line that
starts with the chosen string. The latter line is then split again at
the RPAR. This results in the RPAR (and possibly a trailing comma)
being placed on its own line.
NOTE: If any leaves exist to the right of the chosen string (except
for a trailing comma, which would be placed after the RPAR), those
leaves are placed inside the parentheses. In effect, the chosen
string is not necessarily being "wrapped" by parentheses. We can,
however, count on the LPAR being placed directly before the chosen
string.
In other words, StringParenWrapper creates "atom" strings. These
can then be split again by StringSplitter, if necessary.
Collaborations:
In the event that a string line split by StringParenWrapper is
changed such that it no longer needs to be given its own line,
StringParenWrapper relies on StringParenStripper to clean up the
parentheses it created.
"""
def do_splitter_match(self, line: Line) -> TMatchResult:
LL = line.leaves
string_idx = (
self._return_match(LL)
or self._else_match(LL)
or self._assert_match(LL)
or self._assign_match(LL)
or self._dict_match(LL)
)
if string_idx is not None:
string_value = line.leaves[string_idx].value
# If the string has no spaces...
if " " not in string_value:
# And will still violate the line length limit when split...
max_string_length = self.line_length - ((line.depth + 1) * 4)
if len(string_value) > max_string_length:
# And has no associated custom splits...
if not self.has_custom_splits(string_value):
# Then we should NOT put this string on its own line.
return TErr(
"We do not wrap long strings in parentheses when the"
" resultant line would still be over the specified line"
" length and can't be split further by StringSplitter."
)
return Ok(string_idx)
return TErr("This line does not contain any non-atomic strings.")
@staticmethod
def _return_match(LL: List[Leaf]) -> Optional[int]:
"""
Returns:
string_idx such that @LL[string_idx] is equal to our target (i.e.
matched) string, if this line matches the return/yield statement
requirements listed in the 'Requirements' section of this classes'
docstring.
OR
None, otherwise.
"""
# If this line is apart of a return/yield statement and the first leaf
# contains either the "return" or "yield" keywords...
if parent_type(LL[0]) in [syms.return_stmt, syms.yield_expr] and LL[
0
].value in ["return", "yield"]:
is_valid_index = is_valid_index_factory(LL)
idx = 2 if is_valid_index(1) and is_empty_par(LL[1]) else 1
# The next visible leaf MUST contain a string...
if is_valid_index(idx) and LL[idx].type == token.STRING:
return idx
return None
@staticmethod
def _else_match(LL: List[Leaf]) -> Optional[int]:
"""
Returns:
string_idx such that @LL[string_idx] is equal to our target (i.e.
matched) string, if this line matches the ternary expression
requirements listed in the 'Requirements' section of this classes'
docstring.
OR
None, otherwise.
"""
# If this line is apart of a ternary expression and the first leaf
# contains the "else" keyword...
if (
parent_type(LL[0]) == syms.test
and LL[0].type == token.NAME
and LL[0].value == "else"
):
is_valid_index = is_valid_index_factory(LL)
idx = 2 if is_valid_index(1) and is_empty_par(LL[1]) else 1
# The next visible leaf MUST contain a string...
if is_valid_index(idx) and LL[idx].type == token.STRING:
return idx
return None
@staticmethod
def _assert_match(LL: List[Leaf]) -> Optional[int]:
"""
Returns:
string_idx such that @LL[string_idx] is equal to our target (i.e.
matched) string, if this line matches the assert statement
requirements listed in the 'Requirements' section of this classes'
docstring.
OR
None, otherwise.
"""
# If this line is apart of an assert statement and the first leaf
# contains the "assert" keyword...
if parent_type(LL[0]) == syms.assert_stmt and LL[0].value == "assert":
is_valid_index = is_valid_index_factory(LL)
for (i, leaf) in enumerate(LL):
# We MUST find a comma...
if leaf.type == token.COMMA:
idx = i + 2 if is_empty_par(LL[i + 1]) else i + 1
# That comma MUST be followed by a string...
if is_valid_index(idx) and LL[idx].type == token.STRING:
string_idx = idx
# Skip the string trailer, if one exists.
string_parser = StringParser()
idx = string_parser.parse(LL, string_idx)
# But no more leaves are allowed...
if not is_valid_index(idx):
return string_idx
return None
@staticmethod
def _assign_match(LL: List[Leaf]) -> Optional[int]:
"""
Returns:
string_idx such that @LL[string_idx] is equal to our target (i.e.
matched) string, if this line matches the assignment statement
requirements listed in the 'Requirements' section of this classes'
docstring.
OR
None, otherwise.
"""
# If this line is apart of an expression statement or is a function
# argument AND the first leaf contains a variable name...
if (
parent_type(LL[0]) in [syms.expr_stmt, syms.argument, syms.power]
and LL[0].type == token.NAME
):
is_valid_index = is_valid_index_factory(LL)
for (i, leaf) in enumerate(LL):
# We MUST find either an '=' or '+=' symbol...
if leaf.type in [token.EQUAL, token.PLUSEQUAL]:
idx = i + 2 if is_empty_par(LL[i + 1]) else i + 1
# That symbol MUST be followed by a string...
if is_valid_index(idx) and LL[idx].type == token.STRING:
string_idx = idx
# Skip the string trailer, if one exists.
string_parser = StringParser()
idx = string_parser.parse(LL, string_idx)
# The next leaf MAY be a comma iff this line is apart
# of a function argument...
if (
parent_type(LL[0]) == syms.argument
and is_valid_index(idx)
and LL[idx].type == token.COMMA
):
idx += 1
# But no more leaves are allowed...
if not is_valid_index(idx):
return string_idx
return None
@staticmethod
def _dict_match(LL: List[Leaf]) -> Optional[int]:
"""
Returns:
string_idx such that @LL[string_idx] is equal to our target (i.e.
matched) string, if this line matches the dictionary key assignment
statement requirements listed in the 'Requirements' section of this
classes' docstring.
OR
None, otherwise.
"""
# If this line is apart of a dictionary key assignment...
if syms.dictsetmaker in [parent_type(LL[0]), parent_type(LL[0].parent)]:
is_valid_index = is_valid_index_factory(LL)
for (i, leaf) in enumerate(LL):
# We MUST find a colon...
if leaf.type == token.COLON:
idx = i + 2 if is_empty_par(LL[i + 1]) else i + 1
# That colon MUST be followed by a string...
if is_valid_index(idx) and LL[idx].type == token.STRING:
string_idx = idx
# Skip the string trailer, if one exists.
string_parser = StringParser()
idx = string_parser.parse(LL, string_idx)
# That string MAY be followed by a comma...
if is_valid_index(idx) and LL[idx].type == token.COMMA:
idx += 1
# But no more leaves are allowed...
if not is_valid_index(idx):
return string_idx
return None
def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
LL = line.leaves
is_valid_index = is_valid_index_factory(LL)
insert_str_child = insert_str_child_factory(LL[string_idx])
comma_idx = -1
ends_with_comma = False
if LL[comma_idx].type == token.COMMA:
ends_with_comma = True
leaves_to_steal_comments_from = [LL[string_idx]]
if ends_with_comma:
leaves_to_steal_comments_from.append(LL[comma_idx])
# --- First Line
first_line = line.clone()
left_leaves = LL[:string_idx]
# We have to remember to account for (possibly invisible) LPAR and RPAR
# leaves that already wrapped the target string. If these leaves do
# exist, we will replace them with our own LPAR and RPAR leaves.
old_parens_exist = False
if left_leaves and left_leaves[-1].type == token.LPAR:
old_parens_exist = True
leaves_to_steal_comments_from.append(left_leaves[-1])
left_leaves.pop()
append_leaves(first_line, line, left_leaves)
lpar_leaf = Leaf(token.LPAR, "(")
if old_parens_exist:
replace_child(LL[string_idx - 1], lpar_leaf)
else:
insert_str_child(lpar_leaf)
first_line.append(lpar_leaf)
# We throw inline comments that were originally to the right of the
# target string to the top line. They will now be shown to the right of
# the LPAR.
for leaf in leaves_to_steal_comments_from:
for comment_leaf in line.comments_after(leaf):
first_line.append(comment_leaf, preformatted=True)
yield Ok(first_line)
# --- Middle (String) Line
# We only need to yield one (possibly too long) string line, since the
# `StringSplitter` will break it down further if necessary.
string_value = LL[string_idx].value
string_line = Line(
mode=line.mode,
depth=line.depth + 1,
inside_brackets=True,
should_split_rhs=line.should_split_rhs,
magic_trailing_comma=line.magic_trailing_comma,
)
string_leaf = Leaf(token.STRING, string_value)
insert_str_child(string_leaf)
string_line.append(string_leaf)
old_rpar_leaf = None
if is_valid_index(string_idx + 1):
right_leaves = LL[string_idx + 1 :]
if ends_with_comma:
right_leaves.pop()
if old_parens_exist:
assert (
right_leaves and right_leaves[-1].type == token.RPAR
), "Apparently, old parentheses do NOT exist?!"
old_rpar_leaf = right_leaves.pop()
append_leaves(string_line, line, right_leaves)
yield Ok(string_line)
# --- Last Line
last_line = line.clone()
last_line.bracket_tracker = first_line.bracket_tracker
new_rpar_leaf = Leaf(token.RPAR, ")")
if old_rpar_leaf is not None:
replace_child(old_rpar_leaf, new_rpar_leaf)
else:
insert_str_child(new_rpar_leaf)
last_line.append(new_rpar_leaf)
# If the target string ended with a comma, we place this comma to the
# right of the RPAR on the last line.
if ends_with_comma:
comma_leaf = Leaf(token.COMMA, ",")
replace_child(LL[comma_idx], comma_leaf)
last_line.append(comma_leaf)
yield Ok(last_line)
class StringParser:
"""
A state machine that aids in parsing a string's "trailer", which can be
either non-existent, an old-style formatting sequence (e.g. `% varX` or `%
(varX, varY)`), or a method-call / attribute access (e.g. `.format(varX,
varY)`).
NOTE: A new StringParser object MUST be instantiated for each string
trailer we need to parse.
Examples:
We shall assume that `line` equals the `Line` object that corresponds
to the following line of python code:
```
x = "Some {}.".format("String") + some_other_string
```
Furthermore, we will assume that `string_idx` is some index such that:
```
assert line.leaves[string_idx].value == "Some {}."
```
The following code snippet then holds:
```
string_parser = StringParser()
idx = string_parser.parse(line.leaves, string_idx)
assert line.leaves[idx].type == token.PLUS
```
"""
DEFAULT_TOKEN = -1
# String Parser States
START = 1
DOT = 2
NAME = 3
PERCENT = 4
SINGLE_FMT_ARG = 5
LPAR = 6
RPAR = 7
DONE = 8
# Lookup Table for Next State
_goto: Dict[Tuple[ParserState, NodeType], ParserState] = {
# A string trailer may start with '.' OR '%'.
(START, token.DOT): DOT,
(START, token.PERCENT): PERCENT,
(START, DEFAULT_TOKEN): DONE,
# A '.' MUST be followed by an attribute or method name.
(DOT, token.NAME): NAME,
# A method name MUST be followed by an '(', whereas an attribute name
# is the last symbol in the string trailer.
(NAME, token.LPAR): LPAR,
(NAME, DEFAULT_TOKEN): DONE,
# A '%' symbol can be followed by an '(' or a single argument (e.g. a
# string or variable name).
(PERCENT, token.LPAR): LPAR,
(PERCENT, DEFAULT_TOKEN): SINGLE_FMT_ARG,
# If a '%' symbol is followed by a single argument, that argument is
# the last leaf in the string trailer.
(SINGLE_FMT_ARG, DEFAULT_TOKEN): DONE,
# If present, a ')' symbol is the last symbol in a string trailer.
# (NOTE: LPARS and nested RPARS are not included in this lookup table,
# since they are treated as a special case by the parsing logic in this
# classes' implementation.)
(RPAR, DEFAULT_TOKEN): DONE,
}
def __init__(self) -> None:
self._state = self.START
self._unmatched_lpars = 0
def parse(self, leaves: List[Leaf], string_idx: int) -> int:
"""
Pre-conditions:
* @leaves[@string_idx].type == token.STRING
Returns:
The index directly after the last leaf which is apart of the string
trailer, if a "trailer" exists.
OR
@string_idx + 1, if no string "trailer" exists.
"""
assert leaves[string_idx].type == token.STRING
idx = string_idx + 1
while idx < len(leaves) and self._next_state(leaves[idx]):
idx += 1
return idx
def _next_state(self, leaf: Leaf) -> bool:
"""
Pre-conditions:
* On the first call to this function, @leaf MUST be the leaf that
was directly after the string leaf in question (e.g. if our target
string is `line.leaves[i]` then the first call to this method must
be `line.leaves[i + 1]`).
* On the next call to this function, the leaf parameter passed in
MUST be the leaf directly following @leaf.
Returns:
True iff @leaf is apart of the string's trailer.
"""
# We ignore empty LPAR or RPAR leaves.
if is_empty_par(leaf):
return True
next_token = leaf.type
if next_token == token.LPAR:
self._unmatched_lpars += 1
current_state = self._state
# The LPAR parser state is a special case. We will return True until we
# find the matching RPAR token.
if current_state == self.LPAR:
if next_token == token.RPAR:
self._unmatched_lpars -= 1
if self._unmatched_lpars == 0:
self._state = self.RPAR
# Otherwise, we use a lookup table to determine the next state.
else:
# If the lookup table matches the current state to the next
# token, we use the lookup table.
if (current_state, next_token) in self._goto:
self._state = self._goto[current_state, next_token]
else:
# Otherwise, we check if a the current state was assigned a
# default.
if (current_state, self.DEFAULT_TOKEN) in self._goto:
self._state = self._goto[current_state, self.DEFAULT_TOKEN]
# If no default has been assigned, then this parser has a logic
# error.
else:
raise RuntimeError(f"{self.__class__.__name__} LOGIC ERROR!")
if self._state == self.DONE:
return False
return True
def TErr(err_msg: str) -> Err[CannotTransform]:
"""(T)ransform Err
Convenience function used when working with the TResult type.
"""
cant_transform = CannotTransform(err_msg)
return Err(cant_transform)
def contains_pragma_comment(comment_list: List[Leaf]) -> bool:
"""
Returns:
True iff one of the comments in @comment_list is a pragma used by one
of the more common static analysis tools for python (e.g. mypy, flake8,
pylint).
"""
for comment in comment_list:
if comment.value.startswith(("# type:", "# noqa", "# pylint:")):
return True
return False
def insert_str_child_factory(string_leaf: Leaf) -> Callable[[LN], None]:
"""
Factory for a convenience function that is used to orphan @string_leaf
and then insert multiple new leaves into the same part of the node
structure that @string_leaf had originally occupied.
Examples:
Let `string_leaf = Leaf(token.STRING, '"foo"')` and `N =
string_leaf.parent`. Assume the node `N` has the following
original structure:
Node(
expr_stmt, [
Leaf(NAME, 'x'),
Leaf(EQUAL, '='),
Leaf(STRING, '"foo"'),
]
)
We then run the code snippet shown below.
```
insert_str_child = insert_str_child_factory(string_leaf)
lpar = Leaf(token.LPAR, '(')
insert_str_child(lpar)
bar = Leaf(token.STRING, '"bar"')
insert_str_child(bar)
rpar = Leaf(token.RPAR, ')')
insert_str_child(rpar)
```
After which point, it follows that `string_leaf.parent is None` and
the node `N` now has the following structure:
Node(
expr_stmt, [
Leaf(NAME, 'x'),
Leaf(EQUAL, '='),
Leaf(LPAR, '('),
Leaf(STRING, '"bar"'),
Leaf(RPAR, ')'),
]
)
"""
string_parent = string_leaf.parent
string_child_idx = string_leaf.remove()
def insert_str_child(child: LN) -> None:
nonlocal string_child_idx
assert string_parent is not None
assert string_child_idx is not None
string_parent.insert_child(string_child_idx, child)
string_child_idx += 1
return insert_str_child
def has_triple_quotes(string: str) -> bool:
"""
Returns:
True iff @string starts with three quotation characters.
"""
raw_string = string.lstrip(STRING_PREFIX_CHARS)
return raw_string[:3] in {'"""', "'''"}
def parent_type(node: Optional[LN]) -> Optional[NodeType]:
"""
Returns:
@node.parent.type, if @node is not None and has a parent.
OR
None, otherwise.
"""
if node is None or node.parent is None:
return None
return node.parent.type
def is_empty_par(leaf: Leaf) -> bool:
return is_empty_lpar(leaf) or is_empty_rpar(leaf)
def is_empty_lpar(leaf: Leaf) -> bool:
return leaf.type == token.LPAR and leaf.value == ""
def is_empty_rpar(leaf: Leaf) -> bool:
return leaf.type == token.RPAR and leaf.value == ""
def is_valid_index_factory(seq: Sequence[Any]) -> Callable[[int], bool]:
"""
Examples:
```
my_list = [1, 2, 3]
is_valid_index = is_valid_index_factory(my_list)
assert is_valid_index(0)
assert is_valid_index(2)
assert not is_valid_index(3)
assert not is_valid_index(-1)
```
"""
def is_valid_index(idx: int) -> bool:
"""
Returns:
True iff @idx is positive AND seq[@idx] does NOT raise an
IndexError.
"""
return 0 <= idx < len(seq)
return is_valid_index
def line_to_string(line: Line) -> str:
"""Returns the string representation of @line.
WARNING: This is known to be computationally expensive.
"""
return str(line).strip("\n")
def append_leaves(
new_line: Line, old_line: Line, leaves: List[Leaf], preformatted: bool = False
) -> None:
"""
Append leaves (taken from @old_line) to @new_line, making sure to fix the
underlying Node structure where appropriate.
All of the leaves in @leaves are duplicated. The duplicates are then
appended to @new_line and used to replace their originals in the underlying
Node structure. Any comments attached to the old leaves are reattached to
the new leaves.
Pre-conditions:
set(@leaves) is a subset of set(@old_line.leaves).
"""
for old_leaf in leaves:
new_leaf = Leaf(old_leaf.type, old_leaf.value)
replace_child(old_leaf, new_leaf)
new_line.append(new_leaf, preformatted=preformatted)
for comment_leaf in old_line.comments_after(old_leaf):
new_line.append(comment_leaf, preformatted=True)
def replace_child(old_child: LN, new_child: LN) -> None:
"""
Side Effects:
* If @old_child.parent is set, replace @old_child with @new_child in
@old_child's underlying Node structure.
OR
* Otherwise, this function does nothing.
"""
parent = old_child.parent
if not parent:
return
child_idx = old_child.remove()
if child_idx is not None:
parent.insert_child(child_idx, new_child)
def get_string_prefix(string: str) -> str:
"""
Pre-conditions:
* assert_is_leaf_string(@string)
Returns:
@string's prefix (e.g. '', 'r', 'f', or 'rf').
"""
assert_is_leaf_string(string)
prefix = ""
prefix_idx = 0
while string[prefix_idx] in STRING_PREFIX_CHARS:
prefix += string[prefix_idx].lower()
prefix_idx += 1
return prefix
def assert_is_leaf_string(string: str) -> None:
"""
Checks the pre-condition that @string has the format that you would expect
of `leaf.value` where `leaf` is some Leaf such that `leaf.type ==
token.STRING`. A more precise description of the pre-conditions that are
checked are listed below.
Pre-conditions:
* @string starts with either ', ", <prefix>', or <prefix>" where
`set(<prefix>)` is some subset of `set(STRING_PREFIX_CHARS)`.
* @string ends with a quote character (' or ").
Raises:
AssertionError(...) if the pre-conditions listed above are not
satisfied.
"""
dquote_idx = string.find('"')
squote_idx = string.find("'")
if -1 in [dquote_idx, squote_idx]:
quote_idx = max(dquote_idx, squote_idx)
else:
quote_idx = min(squote_idx, dquote_idx)
assert (
0 <= quote_idx < len(string) - 1
), f"{string!r} is missing a starting quote character (' or \")."
assert string[-1] in (
"'",
'"',
), f"{string!r} is missing an ending quote character (' or \")."
assert set(string[:quote_idx]).issubset(
set(STRING_PREFIX_CHARS)
), f"{set(string[:quote_idx])} is NOT a subset of {set(STRING_PREFIX_CHARS)}."
def left_hand_split(line: Line, _features: Collection[Feature] = ()) -> Iterator[Line]:
"""Split line into many lines, starting with the first matching bracket pair.
Note: this usually looks weird, only use this for function definitions.
Prefer RHS otherwise. This is why this function is not symmetrical with
:func:`right_hand_split` which also handles optional parentheses.
"""
tail_leaves: List[Leaf] = []
body_leaves: List[Leaf] = []
head_leaves: List[Leaf] = []
current_leaves = head_leaves
matching_bracket: Optional[Leaf] = None
for leaf in line.leaves:
if (
current_leaves is body_leaves
and leaf.type in CLOSING_BRACKETS
and leaf.opening_bracket is matching_bracket
):
current_leaves = tail_leaves if body_leaves else head_leaves
current_leaves.append(leaf)
if current_leaves is head_leaves:
if leaf.type in OPENING_BRACKETS:
matching_bracket = leaf
current_leaves = body_leaves
if not matching_bracket:
raise CannotSplit("No brackets found")
head = bracket_split_build_line(head_leaves, line, matching_bracket)
body = bracket_split_build_line(body_leaves, line, matching_bracket, is_body=True)
tail = bracket_split_build_line(tail_leaves, line, matching_bracket)
bracket_split_succeeded_or_raise(head, body, tail)
for result in (head, body, tail):
if result:
yield result
def right_hand_split(
line: Line,
line_length: int,
features: Collection[Feature] = (),
omit: Collection[LeafID] = (),
) -> Iterator[Line]:
"""Split line into many lines, starting with the last matching bracket pair.
If the split was by optional parentheses, attempt splitting without them, too.
`omit` is a collection of closing bracket IDs that shouldn't be considered for
this split.
Note: running this function modifies `bracket_depth` on the leaves of `line`.
"""
tail_leaves: List[Leaf] = []
body_leaves: List[Leaf] = []
head_leaves: List[Leaf] = []
current_leaves = tail_leaves
opening_bracket: Optional[Leaf] = None
closing_bracket: Optional[Leaf] = None
for leaf in reversed(line.leaves):
if current_leaves is body_leaves:
if leaf is opening_bracket:
current_leaves = head_leaves if body_leaves else tail_leaves
current_leaves.append(leaf)
if current_leaves is tail_leaves:
if leaf.type in CLOSING_BRACKETS and id(leaf) not in omit:
opening_bracket = leaf.opening_bracket
closing_bracket = leaf
current_leaves = body_leaves
if not (opening_bracket and closing_bracket and head_leaves):
# If there is no opening or closing_bracket that means the split failed and
# all content is in the tail. Otherwise, if `head_leaves` are empty, it means
# the matching `opening_bracket` wasn't available on `line` anymore.
raise CannotSplit("No brackets found")
tail_leaves.reverse()
body_leaves.reverse()
head_leaves.reverse()
head = bracket_split_build_line(head_leaves, line, opening_bracket)
body = bracket_split_build_line(body_leaves, line, opening_bracket, is_body=True)
tail = bracket_split_build_line(tail_leaves, line, opening_bracket)
bracket_split_succeeded_or_raise(head, body, tail)
if (
Feature.FORCE_OPTIONAL_PARENTHESES not in features
# the opening bracket is an optional paren
and opening_bracket.type == token.LPAR
and not opening_bracket.value
# the closing bracket is an optional paren
and closing_bracket.type == token.RPAR
and not closing_bracket.value
# it's not an import (optional parens are the only thing we can split on
# in this case; attempting a split without them is a waste of time)
and not line.is_import
# there are no standalone comments in the body
and not body.contains_standalone_comments(0)
# and we can actually remove the parens
and can_omit_invisible_parens(body, line_length, omit_on_explode=omit)
):
omit = {id(closing_bracket), *omit}
try:
yield from right_hand_split(line, line_length, features=features, omit=omit)
return
except CannotSplit:
if not (
can_be_split(body)
or is_line_short_enough(body, line_length=line_length)
):
raise CannotSplit(
"Splitting failed, body is still too long and can't be split."
)
elif head.contains_multiline_strings() or tail.contains_multiline_strings():
raise CannotSplit(
"The current optional pair of parentheses is bound to fail to"
" satisfy the splitting algorithm because the head or the tail"
" contains multiline strings which by definition never fit one"
" line."
)
ensure_visible(opening_bracket)
ensure_visible(closing_bracket)
for result in (head, body, tail):
if result:
yield result
def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None:
"""Raise :exc:`CannotSplit` if the last left- or right-hand split failed.
Do nothing otherwise.
A left- or right-hand split is based on a pair of brackets. Content before
(and including) the opening bracket is left on one line, content inside the
brackets is put on a separate line, and finally content starting with and
following the closing bracket is put on a separate line.
Those are called `head`, `body`, and `tail`, respectively. If the split
produced the same line (all content in `head`) or ended up with an empty `body`
and the `tail` is just the closing bracket, then it's considered failed.
"""
tail_len = len(str(tail).strip())
if not body:
if tail_len == 0:
raise CannotSplit("Splitting brackets produced the same line")
elif tail_len < 3:
raise CannotSplit(
f"Splitting brackets on an empty body to save {tail_len} characters is"
" not worth it"
)
def bracket_split_build_line(
leaves: List[Leaf], original: Line, opening_bracket: Leaf, *, is_body: bool = False
) -> Line:
"""Return a new line with given `leaves` and respective comments from `original`.
If `is_body` is True, the result line is one-indented inside brackets and as such
has its first leaf's prefix normalized and a trailing comma added when expected.
"""
result = Line(mode=original.mode, depth=original.depth)
if is_body:
result.inside_brackets = True
result.depth += 1
if leaves:
# Since body is a new indent level, remove spurious leading whitespace.
normalize_prefix(leaves[0], inside_brackets=True)
# Ensure a trailing comma for imports and standalone function arguments, but
# be careful not to add one after any comments or within type annotations.
no_commas = (
original.is_def
and opening_bracket.value == "("
and not any(leaf.type == token.COMMA for leaf in leaves)
)
if original.is_import or no_commas:
for i in range(len(leaves) - 1, -1, -1):
if leaves[i].type == STANDALONE_COMMENT:
continue
if leaves[i].type != token.COMMA:
new_comma = Leaf(token.COMMA, ",")
leaves.insert(i + 1, new_comma)
break
# Populate the line
for leaf in leaves:
result.append(leaf, preformatted=True)
for comment_after in original.comments_after(leaf):
result.append(comment_after, preformatted=True)
if is_body and should_split_line(result, opening_bracket):
result.should_split_rhs = True
return result
def dont_increase_indentation(split_func: Transformer) -> Transformer:
"""Normalize prefix of the first leaf in every line returned by `split_func`.
This is a decorator over relevant split functions.
"""
@wraps(split_func)
def split_wrapper(line: Line, features: Collection[Feature] = ()) -> Iterator[Line]:
for line in split_func(line, features):
normalize_prefix(line.leaves[0], inside_brackets=True)
yield line
return split_wrapper
@dont_increase_indentation
def delimiter_split(line: Line, features: Collection[Feature] = ()) -> Iterator[Line]:
"""Split according to delimiters of the highest priority.
If the appropriate Features are given, the split will add trailing commas
also in function signatures and calls that contain `*` and `**`.
"""
try:
last_leaf = line.leaves[-1]
except IndexError:
raise CannotSplit("Line empty")
bt = line.bracket_tracker
try:
delimiter_priority = bt.max_delimiter_priority(exclude={id(last_leaf)})
except ValueError:
raise CannotSplit("No delimiters found")
if delimiter_priority == DOT_PRIORITY:
if bt.delimiter_count_with_priority(delimiter_priority) == 1:
raise CannotSplit("Splitting a single attribute from its owner looks wrong")
current_line = Line(
mode=line.mode, depth=line.depth, inside_brackets=line.inside_brackets
)
lowest_depth = sys.maxsize
trailing_comma_safe = True
def append_to_line(leaf: Leaf) -> Iterator[Line]:
"""Append `leaf` to current line or to new line if appending impossible."""
nonlocal current_line
try:
current_line.append_safe(leaf, preformatted=True)
except ValueError:
yield current_line
current_line = Line(
mode=line.mode, depth=line.depth, inside_brackets=line.inside_brackets
)
current_line.append(leaf)
for leaf in line.leaves:
yield from append_to_line(leaf)
for comment_after in line.comments_after(leaf):
yield from append_to_line(comment_after)
lowest_depth = min(lowest_depth, leaf.bracket_depth)
if leaf.bracket_depth == lowest_depth:
if is_vararg(leaf, within={syms.typedargslist}):
trailing_comma_safe = (
trailing_comma_safe and Feature.TRAILING_COMMA_IN_DEF in features
)
elif is_vararg(leaf, within={syms.arglist, syms.argument}):
trailing_comma_safe = (
trailing_comma_safe and Feature.TRAILING_COMMA_IN_CALL in features
)
leaf_priority = bt.delimiters.get(id(leaf))
if leaf_priority == delimiter_priority:
yield current_line
current_line = Line(
mode=line.mode, depth=line.depth, inside_brackets=line.inside_brackets
)
if current_line:
if (
trailing_comma_safe
and delimiter_priority == COMMA_PRIORITY
and current_line.leaves[-1].type != token.COMMA
and current_line.leaves[-1].type != STANDALONE_COMMENT
):
new_comma = Leaf(token.COMMA, ",")
current_line.append(new_comma)
yield current_line
@dont_increase_indentation
def standalone_comment_split(
line: Line, features: Collection[Feature] = ()
) -> Iterator[Line]:
"""Split standalone comments from the rest of the line."""
if not line.contains_standalone_comments(0):
raise CannotSplit("Line does not have any standalone comments")
current_line = Line(
mode=line.mode, depth=line.depth, inside_brackets=line.inside_brackets
)
def append_to_line(leaf: Leaf) -> Iterator[Line]:
"""Append `leaf` to current line or to new line if appending impossible."""
nonlocal current_line
try:
current_line.append_safe(leaf, preformatted=True)
except ValueError:
yield current_line
current_line = Line(
line.mode, depth=line.depth, inside_brackets=line.inside_brackets
)
current_line.append(leaf)
for leaf in line.leaves:
yield from append_to_line(leaf)
for comment_after in line.comments_after(leaf):
yield from append_to_line(comment_after)
if current_line:
yield current_line
def is_import(leaf: Leaf) -> bool:
"""Return True if the given leaf starts an import statement."""
p = leaf.parent
t = leaf.type
v = leaf.value
return bool(
t == token.NAME
and (
(v == "import" and p and p.type == syms.import_name)
or (v == "from" and p and p.type == syms.import_from)
)
)
def is_type_comment(leaf: Leaf, suffix: str = "") -> bool:
"""Return True if the given leaf is a special comment.
Only returns true for type comments for now."""
t = leaf.type
v = leaf.value
return t in {token.COMMENT, STANDALONE_COMMENT} and v.startswith("# type:" + suffix)
def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
"""Leave existing extra newlines if not `inside_brackets`. Remove everything
else.
Note: don't use backslashes for formatting or you'll lose your voting rights.
"""
if not inside_brackets:
spl = leaf.prefix.split("#")
if "\\" not in spl[0]:
nl_count = spl[-1].count("\n")
if len(spl) > 1:
nl_count -= 1
leaf.prefix = "\n" * nl_count
return
leaf.prefix = ""
def normalize_string_prefix(leaf: Leaf, remove_u_prefix: bool = False) -> None:
"""Make all string prefixes lowercase.
If remove_u_prefix is given, also removes any u prefix from the string.
Note: Mutates its argument.
"""
match = re.match(r"^([" + STRING_PREFIX_CHARS + r"]*)(.*)$", leaf.value, re.DOTALL)
assert match is not None, f"failed to match string {leaf.value!r}"
orig_prefix = match.group(1)
new_prefix = orig_prefix.replace("F", "f").replace("B", "b").replace("U", "u")
if remove_u_prefix:
new_prefix = new_prefix.replace("u", "")
leaf.value = f"{new_prefix}{match.group(2)}"
def normalize_string_quotes(leaf: Leaf) -> None:
"""Prefer double quotes but only if it doesn't cause more escaping.
Adds or removes backslashes as appropriate. Doesn't parse and fix
strings nested in f-strings (yet).
Note: Mutates its argument.
"""
value = leaf.value.lstrip(STRING_PREFIX_CHARS)
if value[:3] == '"""':
return
elif value[:3] == "'''":
orig_quote = "'''"
new_quote = '"""'
elif value[0] == '"':
orig_quote = '"'
new_quote = "'"
else:
orig_quote = "'"
new_quote = '"'
first_quote_pos = leaf.value.find(orig_quote)
if first_quote_pos == -1:
return # There's an internal error
prefix = leaf.value[:first_quote_pos]
unescaped_new_quote = re.compile(rf"(([^\\]|^)(\\\\)*){new_quote}")
escaped_new_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){new_quote}")
escaped_orig_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){orig_quote}")
body = leaf.value[first_quote_pos + len(orig_quote) : -len(orig_quote)]
if "r" in prefix.casefold():
if unescaped_new_quote.search(body):
# There's at least one unescaped new_quote in this raw string
# so converting is impossible
return
# Do not introduce or remove backslashes in raw strings
new_body = body
else:
# remove unnecessary escapes
new_body = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", body)
if body != new_body:
# Consider the string without unnecessary escapes as the original
body = new_body
leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
if "f" in prefix.casefold():
matches = re.findall(
r"""
(?:[^{]|^)\{ # start of the string or a non-{ followed by a single {
([^{].*?) # contents of the brackets except if begins with {{
\}(?:[^}]|$) # A } followed by end of the string or a non-}
""",
new_body,
re.VERBOSE,
)
for m in matches:
if "\\" in str(m):
# Do not introduce backslashes in interpolated expressions
return
if new_quote == '"""' and new_body[-1:] == '"':
# edge case:
new_body = new_body[:-1] + '\\"'
orig_escape_count = body.count("\\")
new_escape_count = new_body.count("\\")
if new_escape_count > orig_escape_count:
return # Do not introduce more escaping
if new_escape_count == orig_escape_count and orig_quote == '"':
return # Prefer double quotes
leaf.value = f"{prefix}{new_quote}{new_body}{new_quote}"
def normalize_numeric_literal(leaf: Leaf) -> None:
"""Normalizes numeric (float, int, and complex) literals.
All letters used in the representation are normalized to lowercase (except
in Python 2 long literals).
"""
text = leaf.value.lower()
if text.startswith(("0o", "0b")):
# Leave octal and binary literals alone.
pass
elif text.startswith("0x"):
text = format_hex(text)
elif "e" in text:
text = format_scientific_notation(text)
elif text.endswith(("j", "l")):
text = format_long_or_complex_number(text)
else:
text = format_float_or_int_string(text)
leaf.value = text
def format_hex(text: str) -> str:
"""
Formats a hexadecimal string like "0x12b3"
Uses lowercase because of similarity between "B" and "8", which
can cause security issues.
see: https://github.com/psf/black/issues/1692
"""
before, after = text[:2], text[2:]
return f"{before}{after.lower()}"
def format_scientific_notation(text: str) -> str:
"""Formats a numeric string utilizing scentific notation"""
before, after = text.split("e")
sign = ""
if after.startswith("-"):
after = after[1:]
sign = "-"
elif after.startswith("+"):
after = after[1:]
before = format_float_or_int_string(before)
return f"{before}e{sign}{after}"
def format_long_or_complex_number(text: str) -> str:
"""Formats a long or complex string like `10L` or `10j`"""
number = text[:-1]
suffix = text[-1]
# Capitalize in "2L" because "l" looks too similar to "1".
if suffix == "l":
suffix = "L"
return f"{format_float_or_int_string(number)}{suffix}"
def format_float_or_int_string(text: str) -> str:
"""Formats a float string like "1.0"."""
if "." not in text:
return text
before, after = text.split(".")
return f"{before or 0}.{after or 0}"
def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
"""Make existing optional parentheses invisible or create new ones.
`parens_after` is a set of string leaf values immediately after which parens
should be put.
Standardizes on visible parentheses for single-element tuples, and keeps
existing visible parentheses for other tuples and generator expressions.
"""
for pc in list_comments(node.prefix, is_endmarker=False):
if pc.value in FMT_OFF:
# This `node` has a prefix with `# fmt: off`, don't mess with parens.
return
check_lpar = False
for index, child in enumerate(list(node.children)):
# Fixes a bug where invisible parens are not properly stripped from
# assignment statements that contain type annotations.
if isinstance(child, Node) and child.type == syms.annassign:
normalize_invisible_parens(child, parens_after=parens_after)
# Add parentheses around long tuple unpacking in assignments.
if (
index == 0
and isinstance(child, Node)
and child.type == syms.testlist_star_expr
):
check_lpar = True
if check_lpar:
if child.type == syms.atom:
if maybe_make_parens_invisible_in_atom(child, parent=node):
wrap_in_parentheses(node, child, visible=False)
elif is_one_tuple(child):
wrap_in_parentheses(node, child, visible=True)
elif node.type == syms.import_from:
# "import from" nodes store parentheses directly as part of
# the statement
if child.type == token.LPAR:
# make parentheses invisible
child.value = "" # type: ignore
node.children[-1].value = "" # type: ignore
elif child.type != token.STAR:
# insert invisible parentheses
node.insert_child(index, Leaf(token.LPAR, ""))
node.append_child(Leaf(token.RPAR, ""))
break
elif not (isinstance(child, Leaf) and is_multiline_string(child)):
wrap_in_parentheses(node, child, visible=False)
check_lpar = isinstance(child, Leaf) and child.value in parens_after
def normalize_fmt_off(node: Node) -> None:
"""Convert content between `# fmt: off`/`# fmt: on` into standalone comments."""
try_again = True
while try_again:
try_again = convert_one_fmt_off_pair(node)
def convert_one_fmt_off_pair(node: Node) -> bool:
"""Convert content of a single `# fmt: off`/`# fmt: on` into a standalone comment.
Returns True if a pair was converted.
"""
for leaf in node.leaves():
previous_consumed = 0
for comment in list_comments(leaf.prefix, is_endmarker=False):
if comment.value not in FMT_PASS:
previous_consumed = comment.consumed
continue
# We only want standalone comments. If there's no previous leaf or
# the previous leaf is indentation, it's a standalone comment in
# disguise.
if comment.value in FMT_PASS and comment.type != STANDALONE_COMMENT:
prev = preceding_leaf(leaf)
if prev:
if comment.value in FMT_OFF and prev.type not in WHITESPACE:
continue
if comment.value in FMT_SKIP and prev.type in WHITESPACE:
continue
ignored_nodes = list(generate_ignored_nodes(leaf, comment))
if not ignored_nodes:
continue
first = ignored_nodes[0] # Can be a container node with the `leaf`.
parent = first.parent
prefix = first.prefix
first.prefix = prefix[comment.consumed :]
hidden_value = "".join(str(n) for n in ignored_nodes)
if comment.value in FMT_OFF:
hidden_value = comment.value + "\n" + hidden_value
if comment.value in FMT_SKIP:
hidden_value += " " + comment.value
if hidden_value.endswith("\n"):
# That happens when one of the `ignored_nodes` ended with a NEWLINE
# leaf (possibly followed by a DEDENT).
hidden_value = hidden_value[:-1]
first_idx: Optional[int] = None
for ignored in ignored_nodes:
index = ignored.remove()
if first_idx is None:
first_idx = index
assert parent is not None, "INTERNAL ERROR: fmt: on/off handling (1)"
assert first_idx is not None, "INTERNAL ERROR: fmt: on/off handling (2)"
parent.insert_child(
first_idx,
Leaf(
STANDALONE_COMMENT,
hidden_value,
prefix=prefix[:previous_consumed] + "\n" * comment.newlines,
),
)
return True
return False
def generate_ignored_nodes(leaf: Leaf, comment: ProtoComment) -> Iterator[LN]:
"""Starting from the container of `leaf`, generate all leaves until `# fmt: on`.
If comment is skip, returns leaf only.
Stops at the end of the block.
"""
container: Optional[LN] = container_of(leaf)
if comment.value in FMT_SKIP:
prev_sibling = leaf.prev_sibling
if comment.value in leaf.prefix and prev_sibling is not None:
leaf.prefix = leaf.prefix.replace(comment.value, "")
siblings = [prev_sibling]
while (
"\n" not in prev_sibling.prefix
and prev_sibling.prev_sibling is not None
):
prev_sibling = prev_sibling.prev_sibling
siblings.insert(0, prev_sibling)
for sibling in siblings:
yield sibling
elif leaf.parent is not None:
yield leaf.parent
return
while container is not None and container.type != token.ENDMARKER:
if is_fmt_on(container):
return
# fix for fmt: on in children
if contains_fmt_on_at_column(container, leaf.column):
for child in container.children:
if contains_fmt_on_at_column(child, leaf.column):
return
yield child
else:
yield container
container = container.next_sibling
def is_fmt_on(container: LN) -> bool:
"""Determine whether formatting is switched on within a container.
Determined by whether the last `# fmt:` comment is `on` or `off`.
"""
fmt_on = False
for comment in list_comments(container.prefix, is_endmarker=False):
if comment.value in FMT_ON:
fmt_on = True
elif comment.value in FMT_OFF:
fmt_on = False
return fmt_on
def contains_fmt_on_at_column(container: LN, column: int) -> bool:
"""Determine if children at a given column have formatting switched on."""
for child in container.children:
if (
isinstance(child, Node)
and first_leaf_column(child) == column
or isinstance(child, Leaf)
and child.column == column
):
if is_fmt_on(child):
return True
return False
def first_leaf_column(node: Node) -> Optional[int]:
"""Returns the column of the first leaf child of a node."""
for child in node.children:
if isinstance(child, Leaf):
return child.column
return None
def maybe_make_parens_invisible_in_atom(node: LN, parent: LN) -> bool:
"""If it's safe, make the parens in the atom `node` invisible, recursively.
Additionally, remove repeated, adjacent invisible parens from the atom `node`
as they are redundant.
Returns whether the node should itself be wrapped in invisible parentheses.
"""
if (
node.type != syms.atom
or is_empty_tuple(node)
or is_one_tuple(node)
or (is_yield(node) and parent.type != syms.expr_stmt)
or max_delimiter_priority_in_atom(node) >= COMMA_PRIORITY
):
return False
if is_walrus_assignment(node):
if parent.type in [syms.annassign, syms.expr_stmt]:
return False
first = node.children[0]
last = node.children[-1]
if first.type == token.LPAR and last.type == token.RPAR:
middle = node.children[1]
# make parentheses invisible
first.value = "" # type: ignore
last.value = "" # type: ignore
maybe_make_parens_invisible_in_atom(middle, parent=parent)
if is_atom_with_invisible_parens(middle):
# Strip the invisible parens from `middle` by replacing
# it with the child in-between the invisible parens
middle.replace(middle.children[1])
return False
return True
def is_atom_with_invisible_parens(node: LN) -> bool:
"""Given a `LN`, determines whether it's an atom `node` with invisible
parens. Useful in dedupe-ing and normalizing parens.
"""
if isinstance(node, Leaf) or node.type != syms.atom:
return False
first, last = node.children[0], node.children[-1]
return (
isinstance(first, Leaf)
and first.type == token.LPAR
and first.value == ""
and isinstance(last, Leaf)
and last.type == token.RPAR
and last.value == ""
)
def is_empty_tuple(node: LN) -> bool:
"""Return True if `node` holds an empty tuple."""
return (
node.type == syms.atom
and len(node.children) == 2
and node.children[0].type == token.LPAR
and node.children[1].type == token.RPAR
)
def unwrap_singleton_parenthesis(node: LN) -> Optional[LN]:
"""Returns `wrapped` if `node` is of the shape ( wrapped ).
Parenthesis can be optional. Returns None otherwise"""
if len(node.children) != 3:
return None
lpar, wrapped, rpar = node.children
if not (lpar.type == token.LPAR and rpar.type == token.RPAR):
return None
return wrapped
def first_child_is_arith(node: Node) -> bool:
"""Whether first child is an arithmetic or a binary arithmetic expression"""
expr_types = {
syms.arith_expr,
syms.shift_expr,
syms.xor_expr,
syms.and_expr,
}
return bool(node.children and node.children[0].type in expr_types)
def wrap_in_parentheses(parent: Node, child: LN, *, visible: bool = True) -> None:
"""Wrap `child` in parentheses.
This replaces `child` with an atom holding the parentheses and the old
child. That requires moving the prefix.
If `visible` is False, the leaves will be valueless (and thus invisible).
"""
lpar = Leaf(token.LPAR, "(" if visible else "")
rpar = Leaf(token.RPAR, ")" if visible else "")
prefix = child.prefix
child.prefix = ""
index = child.remove() or 0
new_child = Node(syms.atom, [lpar, child, rpar])
new_child.prefix = prefix
parent.insert_child(index, new_child)
def is_one_tuple(node: LN) -> bool:
"""Return True if `node` holds a tuple with one element, with or without parens."""
if node.type == syms.atom:
gexp = unwrap_singleton_parenthesis(node)
if gexp is None or gexp.type != syms.testlist_gexp:
return False
return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
return (
node.type in IMPLICIT_TUPLE
and len(node.children) == 2
and node.children[1].type == token.COMMA
)
def is_walrus_assignment(node: LN) -> bool:
"""Return True iff `node` is of the shape ( test := test )"""
inner = unwrap_singleton_parenthesis(node)
return inner is not None and inner.type == syms.namedexpr_test
def is_simple_decorator_trailer(node: LN, last: bool = False) -> bool:
"""Return True iff `node` is a trailer valid in a simple decorator"""
return node.type == syms.trailer and (
(
len(node.children) == 2
and node.children[0].type == token.DOT
and node.children[1].type == token.NAME
)
# last trailer can be arguments
or (
last
and len(node.children) == 3
and node.children[0].type == token.LPAR
# and node.children[1].type == syms.argument
and node.children[2].type == token.RPAR
)
)
def is_simple_decorator_expression(node: LN) -> bool:
"""Return True iff `node` could be a 'dotted name' decorator
This function takes the node of the 'namedexpr_test' of the new decorator
grammar and test if it would be valid under the old decorator grammar.
The old grammar was: decorator: @ dotted_name [arguments] NEWLINE
The new grammar is : decorator: @ namedexpr_test NEWLINE
"""
if node.type == token.NAME:
return True
if node.type == syms.power:
if node.children:
return (
node.children[0].type == token.NAME
and all(map(is_simple_decorator_trailer, node.children[1:-1]))
and (
len(node.children) < 2
or is_simple_decorator_trailer(node.children[-1], last=True)
)
)
return False
def is_yield(node: LN) -> bool:
"""Return True if `node` holds a `yield` or `yield from` expression."""
if node.type == syms.yield_expr:
return True
if node.type == token.NAME and node.value == "yield": # type: ignore
return True
if node.type != syms.atom:
return False
if len(node.children) != 3:
return False
lpar, expr, rpar = node.children
if lpar.type == token.LPAR and rpar.type == token.RPAR:
return is_yield(expr)
return False
def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
"""Return True if `leaf` is a star or double star in a vararg or kwarg.
If `within` includes VARARGS_PARENTS, this applies to function signatures.
If `within` includes UNPACKING_PARENTS, it applies to right hand-side
extended iterable unpacking (PEP 3132) and additional unpacking
generalizations (PEP 448).
"""
if leaf.type not in VARARGS_SPECIALS or not leaf.parent:
return False
p = leaf.parent
if p.type == syms.star_expr:
# Star expressions are also used as assignment targets in extended
# iterable unpacking (PEP 3132). See what its parent is instead.
if not p.parent:
return False
p = p.parent
return p.type in within
def is_multiline_string(leaf: Leaf) -> bool:
"""Return True if `leaf` is a multiline string that actually spans many lines."""
return has_triple_quotes(leaf.value) and "\n" in leaf.value
def is_stub_suite(node: Node) -> bool:
"""Return True if `node` is a suite with a stub body."""
if (
len(node.children) != 4
or node.children[0].type != token.NEWLINE
or node.children[1].type != token.INDENT
or node.children[3].type != token.DEDENT
):
return False
return is_stub_body(node.children[2])
def is_stub_body(node: LN) -> bool:
"""Return True if `node` is a simple statement containing an ellipsis."""
if not isinstance(node, Node) or node.type != syms.simple_stmt:
return False
if len(node.children) != 2:
return False
child = node.children[0]
return (
child.type == syms.atom
and len(child.children) == 3
and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
)
def max_delimiter_priority_in_atom(node: LN) -> Priority:
"""Return maximum delimiter priority inside `node`.
This is specific to atoms with contents contained in a pair of parentheses.
If `node` isn't an atom or there are no enclosing parentheses, returns 0.
"""
if node.type != syms.atom:
return 0
first = node.children[0]
last = node.children[-1]
if not (first.type == token.LPAR and last.type == token.RPAR):
return 0
bt = BracketTracker()
for c in node.children[1:-1]:
if isinstance(c, Leaf):
bt.mark(c)
else:
for leaf in c.leaves():
bt.mark(leaf)
try:
return bt.max_delimiter_priority()
except ValueError:
return 0
def ensure_visible(leaf: Leaf) -> None:
"""Make sure parentheses are visible.
They could be invisible as part of some statements (see
:func:`normalize_invisible_parens` and :func:`visit_import_from`).
"""
if leaf.type == token.LPAR:
leaf.value = "("
elif leaf.type == token.RPAR:
leaf.value = ")"
def should_split_line(line: Line, opening_bracket: Leaf) -> bool:
"""Should `line` be immediately split with `delimiter_split()` after RHS?"""
if not (opening_bracket.parent and opening_bracket.value in "[{("):
return False
# We're essentially checking if the body is delimited by commas and there's more
# than one of them (we're excluding the trailing comma and if the delimiter priority
# is still commas, that means there's more).
exclude = set()
trailing_comma = False
try:
last_leaf = line.leaves[-1]
if last_leaf.type == token.COMMA:
trailing_comma = True
exclude.add(id(last_leaf))
max_priority = line.bracket_tracker.max_delimiter_priority(exclude=exclude)
except (IndexError, ValueError):
return False
return max_priority == COMMA_PRIORITY and (
(line.mode.magic_trailing_comma and trailing_comma)
# always explode imports
or opening_bracket.parent.type in {syms.atom, syms.import_from}
)
def is_one_tuple_between(opening: Leaf, closing: Leaf, leaves: List[Leaf]) -> bool:
"""Return True if content between `opening` and `closing` looks like a one-tuple."""
if opening.type != token.LPAR and closing.type != token.RPAR:
return False
depth = closing.bracket_depth + 1
for _opening_index, leaf in enumerate(leaves):
if leaf is opening:
break
else:
raise LookupError("Opening paren not found in `leaves`")
commas = 0
_opening_index += 1
for leaf in leaves[_opening_index:]:
if leaf is closing:
break
bracket_depth = leaf.bracket_depth
if bracket_depth == depth and leaf.type == token.COMMA:
commas += 1
if leaf.parent and leaf.parent.type in {
syms.arglist,
syms.typedargslist,
}:
commas += 1
break
return commas < 2
def get_features_used(node: Node) -> Set[Feature]:
"""Return a set of (relatively) new Python features used in this file.
Currently looking for:
- f-strings;
- underscores in numeric literals;
- trailing commas after * or ** in function signatures and calls;
- positional only arguments in function signatures and lambdas;
- assignment expression;
- relaxed decorator syntax;
"""
features: Set[Feature] = set()
for n in node.pre_order():
if n.type == token.STRING:
value_head = n.value[:2] # type: ignore
if value_head in {'f"', 'F"', "f'", "F'", "rf", "fr", "RF", "FR"}:
features.add(Feature.F_STRINGS)
elif n.type == token.NUMBER:
if "_" in n.value: # type: ignore
features.add(Feature.NUMERIC_UNDERSCORES)
elif n.type == token.SLASH:
if n.parent and n.parent.type in {syms.typedargslist, syms.arglist}:
features.add(Feature.POS_ONLY_ARGUMENTS)
elif n.type == token.COLONEQUAL:
features.add(Feature.ASSIGNMENT_EXPRESSIONS)
elif n.type == syms.decorator:
if len(n.children) > 1 and not is_simple_decorator_expression(
n.children[1]
):
features.add(Feature.RELAXED_DECORATORS)
elif (
n.type in {syms.typedargslist, syms.arglist}
and n.children
and n.children[-1].type == token.COMMA
):
if n.type == syms.typedargslist:
feature = Feature.TRAILING_COMMA_IN_DEF
else:
feature = Feature.TRAILING_COMMA_IN_CALL
for ch in n.children:
if ch.type in STARS:
features.add(feature)
if ch.type == syms.argument:
for argch in ch.children:
if argch.type in STARS:
features.add(feature)
return features
def detect_target_versions(node: Node) -> Set[TargetVersion]:
"""Detect the version to target based on the nodes used."""
features = get_features_used(node)
return {
version for version in TargetVersion if features <= VERSION_TO_FEATURES[version]
}
def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[LeafID]]:
"""Generate sets of closing bracket IDs that should be omitted in a RHS.
Brackets can be omitted if the entire trailer up to and including
a preceding closing bracket fits in one line.
Yielded sets are cumulative (contain results of previous yields, too). First
set is empty, unless the line should explode, in which case bracket pairs until
the one that needs to explode are omitted.
"""
omit: Set[LeafID] = set()
if not line.magic_trailing_comma:
yield omit
length = 4 * line.depth
opening_bracket: Optional[Leaf] = None
closing_bracket: Optional[Leaf] = None
inner_brackets: Set[LeafID] = set()
for index, leaf, leaf_length in enumerate_with_length(line, reversed=True):
length += leaf_length
if length > line_length:
break
has_inline_comment = leaf_length > len(leaf.value) + len(leaf.prefix)
if leaf.type == STANDALONE_COMMENT or has_inline_comment:
break
if opening_bracket:
if leaf is opening_bracket:
opening_bracket = None
elif leaf.type in CLOSING_BRACKETS:
prev = line.leaves[index - 1] if index > 0 else None
if (
prev
and prev.type == token.COMMA
and not is_one_tuple_between(
leaf.opening_bracket, leaf, line.leaves
)
):
# Never omit bracket pairs with trailing commas.
# We need to explode on those.
break
inner_brackets.add(id(leaf))
elif leaf.type in CLOSING_BRACKETS:
prev = line.leaves[index - 1] if index > 0 else None
if prev and prev.type in OPENING_BRACKETS:
# Empty brackets would fail a split so treat them as "inner"
# brackets (e.g. only add them to the `omit` set if another
# pair of brackets was good enough.
inner_brackets.add(id(leaf))
continue
if closing_bracket:
omit.add(id(closing_bracket))
omit.update(inner_brackets)
inner_brackets.clear()
yield omit
if (
prev
and prev.type == token.COMMA
and not is_one_tuple_between(leaf.opening_bracket, leaf, line.leaves)
):
# Never omit bracket pairs with trailing commas.
# We need to explode on those.
break
if leaf.value:
opening_bracket = leaf.opening_bracket
closing_bracket = leaf
def get_future_imports(node: Node) -> Set[str]:
"""Return a set of __future__ imports in the file."""
imports: Set[str] = set()
def get_imports_from_children(children: List[LN]) -> Generator[str, None, None]:
for child in children:
if isinstance(child, Leaf):
if child.type == token.NAME:
yield child.value
elif child.type == syms.import_as_name:
orig_name = child.children[0]
assert isinstance(orig_name, Leaf), "Invalid syntax parsing imports"
assert orig_name.type == token.NAME, "Invalid syntax parsing imports"
yield orig_name.value
elif child.type == syms.import_as_names:
yield from get_imports_from_children(child.children)
else:
raise AssertionError("Invalid syntax parsing imports")
for child in node.children:
if child.type != syms.simple_stmt:
break
first_child = child.children[0]
if isinstance(first_child, Leaf):
# Continue looking if we see a docstring; otherwise stop.
if (
len(child.children) == 2
and first_child.type == token.STRING
and child.children[1].type == token.NEWLINE
):
continue
break
elif first_child.type == syms.import_from:
module_name = first_child.children[1]
if not isinstance(module_name, Leaf) or module_name.value != "__future__":
break
imports |= set(get_imports_from_children(first_child.children[3:]))
else:
break
return imports
@lru_cache()
def get_gitignore(root: Path) -> PathSpec:
""" Return a PathSpec matching gitignore content if present."""
gitignore = root / ".gitignore"
lines: List[str] = []
if gitignore.is_file():
with gitignore.open() as gf:
lines = gf.readlines()
return PathSpec.from_lines("gitwildmatch", lines)
def normalize_path_maybe_ignore(
path: Path, root: Path, report: "Report"
) -> Optional[str]:
"""Normalize `path`. May return `None` if `path` was ignored.
`report` is where "path ignored" output goes.
"""
try:
abspath = path if path.is_absolute() else Path.cwd() / path
normalized_path = abspath.resolve().relative_to(root).as_posix()
except OSError as e:
report.path_ignored(path, f"cannot be read because {e}")
return None
except ValueError:
if path.is_symlink():
report.path_ignored(path, f"is a symbolic link that points outside {root}")
return None
raise
return normalized_path
def path_is_excluded(
normalized_path: str,
pattern: Optional[Pattern[str]],
) -> bool:
match = pattern.search(normalized_path) if pattern else None
return bool(match and match.group(0))
def gen_python_files(
paths: Iterable[Path],
root: Path,
include: Optional[Pattern[str]],
exclude: Pattern[str],
extend_exclude: Optional[Pattern[str]],
force_exclude: Optional[Pattern[str]],
report: "Report",
gitignore: PathSpec,
) -> Iterator[Path]:
"""Generate all files under `path` whose paths are not excluded by the
`exclude_regex`, `extend_exclude`, or `force_exclude` regexes,
but are included by the `include` regex.
Symbolic links pointing outside of the `root` directory are ignored.
`report` is where output about exclusions goes.
"""
assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
for child in paths:
normalized_path = normalize_path_maybe_ignore(child, root, report)
if normalized_path is None:
continue
# First ignore files matching .gitignore
if gitignore.match_file(normalized_path):
report.path_ignored(child, "matches the .gitignore file content")
continue
# Then ignore with `--exclude` `--extend-exclude` and `--force-exclude` options.
normalized_path = "/" + normalized_path
if child.is_dir():
normalized_path += "/"
if path_is_excluded(normalized_path, exclude):
report.path_ignored(child, "matches the --exclude regular expression")
continue
if path_is_excluded(normalized_path, extend_exclude):
report.path_ignored(
child, "matches the --extend-exclude regular expression"
)
continue
if path_is_excluded(normalized_path, force_exclude):
report.path_ignored(child, "matches the --force-exclude regular expression")
continue
if child.is_dir():
yield from gen_python_files(
child.iterdir(),
root,
include,
exclude,
extend_exclude,
force_exclude,
report,
gitignore,
)
elif child.is_file():
include_match = include.search(normalized_path) if include else True
if include_match:
yield child
@lru_cache()
def find_project_root(srcs: Iterable[str]) -> Path:
"""Return a directory containing .git, .hg, or pyproject.toml.
That directory will be a common parent of all files and directories
passed in `srcs`.
If no directory in the tree contains a marker that would specify it's the
project root, the root of the file system is returned.
"""
if not srcs:
return Path("/").resolve()
path_srcs = [Path(Path.cwd(), src).resolve() for src in srcs]
# A list of lists of parents for each 'src'. 'src' is included as a
# "parent" of itself if it is a directory
src_parents = [
list(path.parents) + ([path] if path.is_dir() else []) for path in path_srcs
]
common_base = max(
set.intersection(*(set(parents) for parents in src_parents)),
key=lambda path: path.parts,
)
for directory in (common_base, *common_base.parents):
if (directory / ".git").exists():
return directory
if (directory / ".hg").is_dir():
return directory
if (directory / "pyproject.toml").is_file():
return directory
return directory
@lru_cache()
def find_user_pyproject_toml() -> Path:
r"""Return the path to the top-level user configuration for black.
This looks for ~\.black on Windows and ~/.config/black on Linux and other
Unix systems.
"""
if sys.platform == "win32":
# Windows
user_config_path = Path.home() / ".black"
else:
config_root = os.environ.get("XDG_CONFIG_HOME", "~/.config")
user_config_path = Path(config_root).expanduser() / "black"
return user_config_path.resolve()
@dataclass
class Report:
"""Provides a reformatting counter. Can be rendered with `str(report)`."""
check: bool = False
diff: bool = False
quiet: bool = False
verbose: bool = False
change_count: int = 0
same_count: int = 0
failure_count: int = 0
def done(self, src: Path, changed: Changed) -> None:
"""Increment the counter for successful reformatting. Write out a message."""
if changed is Changed.YES:
reformatted = "would reformat" if self.check or self.diff else "reformatted"
if self.verbose or not self.quiet:
out(f"{reformatted} {src}")
self.change_count += 1
else:
if self.verbose:
if changed is Changed.NO:
msg = f"{src} already well formatted, good job."
else:
msg = f"{src} wasn't modified on disk since last run."
out(msg, bold=False)
self.same_count += 1
def failed(self, src: Path, message: str) -> None:
"""Increment the counter for failed reformatting. Write out a message."""
err(f"error: cannot format {src}: {message}")
self.failure_count += 1
def path_ignored(self, path: Path, message: str) -> None:
if self.verbose:
out(f"{path} ignored: {message}", bold=False)
@property
def return_code(self) -> int:
"""Return the exit code that the app should use.
This considers the current state of changed files and failures:
- if there were any failures, return 123;
- if any files were changed and --check is being used, return 1;
- otherwise return 0.
"""
# According to http://tldp.org/LDP/abs/html/exitcodes.html starting with
# 126 we have special return codes reserved by the shell.
if self.failure_count:
return 123
elif self.change_count and self.check:
return 1
return 0
def __str__(self) -> str:
"""Render a color report of the current state.
Use `click.unstyle` to remove colors.
"""
if self.check or self.diff:
reformatted = "would be reformatted"
unchanged = "would be left unchanged"
failed = "would fail to reformat"
else:
reformatted = "reformatted"
unchanged = "left unchanged"
failed = "failed to reformat"
report = []
if self.change_count:
s = "s" if self.change_count > 1 else ""
report.append(
click.style(f"{self.change_count} file{s} {reformatted}", bold=True)
)
if self.same_count:
s = "s" if self.same_count > 1 else ""
report.append(f"{self.same_count} file{s} {unchanged}")
if self.failure_count:
s = "s" if self.failure_count > 1 else ""
report.append(
click.style(f"{self.failure_count} file{s} {failed}", fg="red")
)
return ", ".join(report) + "."
def parse_ast(src: str) -> Union[ast.AST, ast3.AST, ast27.AST]:
filename = "<unknown>"
if sys.version_info >= (3, 8):
# TODO: support Python 4+ ;)
for minor_version in range(sys.version_info[1], 4, -1):
try:
return ast.parse(src, filename, feature_version=(3, minor_version))
except SyntaxError:
continue
else:
for feature_version in (7, 6):
try:
return ast3.parse(src, filename, feature_version=feature_version)
except SyntaxError:
continue
if ast27.__name__ == "ast":
raise SyntaxError(
"The requested source code has invalid Python 3 syntax.\n"
"If you are trying to format Python 2 files please reinstall Black"
" with the 'python2' extra: `python3 -m pip install black[python2]`."
)
return ast27.parse(src)
def _fixup_ast_constants(
node: Union[ast.AST, ast3.AST, ast27.AST]
) -> Union[ast.AST, ast3.AST, ast27.AST]:
"""Map ast nodes deprecated in 3.8 to Constant."""
if isinstance(node, (ast.Str, ast3.Str, ast27.Str, ast.Bytes, ast3.Bytes)):
return ast.Constant(value=node.s)
if isinstance(node, (ast.Num, ast3.Num, ast27.Num)):
return ast.Constant(value=node.n)
if isinstance(node, (ast.NameConstant, ast3.NameConstant)):
return ast.Constant(value=node.value)
return node
def _stringify_ast(
node: Union[ast.AST, ast3.AST, ast27.AST], depth: int = 0
) -> Iterator[str]:
"""Simple visitor generating strings to compare ASTs by content."""
node = _fixup_ast_constants(node)
yield f"{' ' * depth}{node.__class__.__name__}("
for field in sorted(node._fields): # noqa: F402
# TypeIgnore has only one field 'lineno' which breaks this comparison
type_ignore_classes = (ast3.TypeIgnore, ast27.TypeIgnore)
if sys.version_info >= (3, 8):
type_ignore_classes += (ast.TypeIgnore,)
if isinstance(node, type_ignore_classes):
break
try:
value = getattr(node, field)
except AttributeError:
continue
yield f"{' ' * (depth+1)}{field}="
if isinstance(value, list):
for item in value:
# Ignore nested tuples within del statements, because we may insert
# parentheses and they change the AST.
if (
field == "targets"
and isinstance(node, (ast.Delete, ast3.Delete, ast27.Delete))
and isinstance(item, (ast.Tuple, ast3.Tuple, ast27.Tuple))
):
for item in item.elts:
yield from _stringify_ast(item, depth + 2)
elif isinstance(item, (ast.AST, ast3.AST, ast27.AST)):
yield from _stringify_ast(item, depth + 2)
elif isinstance(value, (ast.AST, ast3.AST, ast27.AST)):
yield from _stringify_ast(value, depth + 2)
else:
# Constant strings may be indented across newlines, if they are
# docstrings; fold spaces after newlines when comparing. Similarly,
# trailing and leading space may be removed.
if (
isinstance(node, ast.Constant)
and field == "value"
and isinstance(value, str)
):
normalized = re.sub(r" *\n[ \t]*", "\n", value).strip()
else:
normalized = value
yield f"{' ' * (depth+2)}{normalized!r}, # {value.__class__.__name__}"
yield f"{' ' * depth}) # /{node.__class__.__name__}"
def assert_equivalent(src: str, dst: str) -> None:
"""Raise AssertionError if `src` and `dst` aren't equivalent."""
try:
src_ast = parse_ast(src)
except Exception as exc:
raise AssertionError(
"cannot use --safe with this file; failed to parse source file. AST"
f" error message: {exc}"
)
try:
dst_ast = parse_ast(dst)
except Exception as exc:
log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
raise AssertionError(
f"INTERNAL ERROR: Black produced invalid code: {exc}. Please report a bug"
" on https://github.com/psf/black/issues. This invalid output might be"
f" helpful: {log}"
) from None
src_ast_str = "\n".join(_stringify_ast(src_ast))
dst_ast_str = "\n".join(_stringify_ast(dst_ast))
if src_ast_str != dst_ast_str:
log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
raise AssertionError(
"INTERNAL ERROR: Black produced code that is not equivalent to the"
" source. Please report a bug on https://github.com/psf/black/issues. "
f" This diff might be helpful: {log}"
) from None
def assert_stable(src: str, dst: str, mode: Mode) -> None:
"""Raise AssertionError if `dst` reformats differently the second time."""
newdst = format_str(dst, mode=mode)
if dst != newdst:
log = dump_to_file(
str(mode),
diff(src, dst, "source", "first pass"),
diff(dst, newdst, "first pass", "second pass"),
)
raise AssertionError(
"INTERNAL ERROR: Black produced different code on the second pass of the"
" formatter. Please report a bug on https://github.com/psf/black/issues."
f" This diff might be helpful: {log}"
) from None
@mypyc_attr(patchable=True)
def dump_to_file(*output: str, ensure_final_newline: bool = True) -> str:
"""Dump `output` to a temporary file. Return path to the file."""
with tempfile.NamedTemporaryFile(
mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
) as f:
for lines in output:
f.write(lines)
if ensure_final_newline and lines and lines[-1] != "\n":
f.write("\n")
return f.name
@contextmanager
def nullcontext() -> Iterator[None]:
"""Return an empty context manager.
To be used like `nullcontext` in Python 3.7.
"""
yield
def diff(a: str, b: str, a_name: str, b_name: str) -> str:
"""Return a unified diff string between strings `a` and `b`."""
import difflib
a_lines = [line for line in a.splitlines(keepends=True)]
b_lines = [line for line in b.splitlines(keepends=True)]
diff_lines = []
for line in difflib.unified_diff(
a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5
):
# Work around https://bugs.python.org/issue2142
# See https://www.gnu.org/software/diffutils/manual/html_node/Incomplete-Lines.html
if line[-1] == "\n":
diff_lines.append(line)
else:
diff_lines.append(line + "\n")
diff_lines.append("\\ No newline at end of file\n")
return "".join(diff_lines)
def cancel(tasks: Iterable["asyncio.Task[Any]"]) -> None:
"""asyncio signal handler that cancels all `tasks` and reports to stderr."""
err("Aborted!")
for task in tasks:
task.cancel()
def shutdown(loop: asyncio.AbstractEventLoop) -> None:
"""Cancel all pending tasks on `loop`, wait for them, and close the loop."""
try:
if sys.version_info[:2] >= (3, 7):
all_tasks = asyncio.all_tasks
else:
all_tasks = asyncio.Task.all_tasks
# This part is borrowed from asyncio/runners.py in Python 3.7b2.
to_cancel = [task for task in all_tasks(loop) if not task.done()]
if not to_cancel:
return
for task in to_cancel:
task.cancel()
loop.run_until_complete(
asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)
)
finally:
# `concurrent.futures.Future` objects cannot be cancelled once they
# are already running. There might be some when the `shutdown()` happened.
# Silence their logger's spew about the event loop being closed.
cf_logger = logging.getLogger("concurrent.futures")
cf_logger.setLevel(logging.CRITICAL)
loop.close()
def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
"""Replace `regex` with `replacement` twice on `original`.
This is used by string normalization to perform replaces on
overlapping matches.
"""
return regex.sub(replacement, regex.sub(replacement, original))
def re_compile_maybe_verbose(regex: str) -> Pattern[str]:
"""Compile a regular expression string in `regex`.
If it contains newlines, use verbose mode.
"""
if "\n" in regex:
regex = "(?x)" + regex
compiled: Pattern[str] = re.compile(regex)
return compiled
def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
"""Like `reversed(enumerate(sequence))` if that were possible."""
index = len(sequence) - 1
for element in reversed(sequence):
yield (index, element)
index -= 1
def enumerate_with_length(
line: Line, reversed: bool = False
) -> Iterator[Tuple[Index, Leaf, int]]:
"""Return an enumeration of leaves with their length.
Stops prematurely on multiline strings and standalone comments.
"""
op = cast(
Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
enumerate_reversed if reversed else enumerate,
)
for index, leaf in op(line.leaves):
length = len(leaf.prefix) + len(leaf.value)
if "\n" in leaf.value:
return # Multiline strings, we can't continue.
for comment in line.comments_after(leaf):
length += len(comment.value)
yield index, leaf, length
def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
"""Return True if `line` is no longer than `line_length`.
Uses the provided `line_str` rendering, if any, otherwise computes a new one.
"""
if not line_str:
line_str = line_to_string(line)
return (
len(line_str) <= line_length
and "\n" not in line_str # multiline strings
and not line.contains_standalone_comments()
)
def can_be_split(line: Line) -> bool:
"""Return False if the line cannot be split *for sure*.
This is not an exhaustive search but a cheap heuristic that we can use to
avoid some unfortunate formattings (mostly around wrapping unsplittable code
in unnecessary parentheses).
"""
leaves = line.leaves
if len(leaves) < 2:
return False
if leaves[0].type == token.STRING and leaves[1].type == token.DOT:
call_count = 0
dot_count = 0
next = leaves[-1]
for leaf in leaves[-2::-1]:
if leaf.type in OPENING_BRACKETS:
if next.type not in CLOSING_BRACKETS:
return False
call_count += 1
elif leaf.type == token.DOT:
dot_count += 1
elif leaf.type == token.NAME:
if not (next.type == token.DOT or next.type in OPENING_BRACKETS):
return False
elif leaf.type not in CLOSING_BRACKETS:
return False
if dot_count > 1 and call_count > 1:
return False
return True
def can_omit_invisible_parens(
line: Line,
line_length: int,
omit_on_explode: Collection[LeafID] = (),
) -> bool:
"""Does `line` have a shape safe to reformat without optional parens around it?
Returns True for only a subset of potentially nice looking formattings but
the point is to not return false positives that end up producing lines that
are too long.
"""
bt = line.bracket_tracker
if not bt.delimiters:
# Without delimiters the optional parentheses are useless.
return True
max_priority = bt.max_delimiter_priority()
if bt.delimiter_count_with_priority(max_priority) > 1:
# With more than one delimiter of a kind the optional parentheses read better.
return False
if max_priority == DOT_PRIORITY:
# A single stranded method call doesn't require optional parentheses.
return True
assert len(line.leaves) >= 2, "Stranded delimiter"
# With a single delimiter, omit if the expression starts or ends with
# a bracket.
first = line.leaves[0]
second = line.leaves[1]
if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
if _can_omit_opening_paren(line, first=first, line_length=line_length):
return True
# Note: we are not returning False here because a line might have *both*
# a leading opening bracket and a trailing closing bracket. If the
# opening bracket doesn't match our rule, maybe the closing will.
penultimate = line.leaves[-2]
last = line.leaves[-1]
if line.magic_trailing_comma:
try:
penultimate, last = last_two_except(line.leaves, omit=omit_on_explode)
except LookupError:
# Turns out we'd omit everything. We cannot skip the optional parentheses.
return False
if (
last.type == token.RPAR
or last.type == token.RBRACE
or (
# don't use indexing for omitting optional parentheses;
# it looks weird
last.type == token.RSQB
and last.parent
and last.parent.type != syms.trailer
)
):
if penultimate.type in OPENING_BRACKETS:
# Empty brackets don't help.
return False
if is_multiline_string(first):
# Additional wrapping of a multiline string in this situation is
# unnecessary.
return True
if line.magic_trailing_comma and penultimate.type == token.COMMA:
# The rightmost non-omitted bracket pair is the one we want to explode on.
return True
if _can_omit_closing_paren(line, last=last, line_length=line_length):
return True
return False
def _can_omit_opening_paren(line: Line, *, first: Leaf, line_length: int) -> bool:
"""See `can_omit_invisible_parens`."""
remainder = False
length = 4 * line.depth
_index = -1
for _index, leaf, leaf_length in enumerate_with_length(line):
if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
remainder = True
if remainder:
length += leaf_length
if length > line_length:
break
if leaf.type in OPENING_BRACKETS:
# There are brackets we can further split on.
remainder = False
else:
# checked the entire string and line length wasn't exceeded
if len(line.leaves) == _index + 1:
return True
return False
def _can_omit_closing_paren(line: Line, *, last: Leaf, line_length: int) -> bool:
"""See `can_omit_invisible_parens`."""
length = 4 * line.depth
seen_other_brackets = False
for _index, leaf, leaf_length in enumerate_with_length(line):
length += leaf_length
if leaf is last.opening_bracket:
if seen_other_brackets or length <= line_length:
return True
elif leaf.type in OPENING_BRACKETS:
# There are brackets we can further split on.
seen_other_brackets = True
return False
def last_two_except(leaves: List[Leaf], omit: Collection[LeafID]) -> Tuple[Leaf, Leaf]:
"""Return (penultimate, last) leaves skipping brackets in `omit` and contents."""
stop_after = None
last = None
for leaf in reversed(leaves):
if stop_after:
if leaf is stop_after:
stop_after = None
continue
if last:
return leaf, last
if id(leaf) in omit:
stop_after = leaf.opening_bracket
else:
last = leaf
else:
raise LookupError("Last two leaves were also skipped")
def run_transformer(
line: Line,
transform: Transformer,
mode: Mode,
features: Collection[Feature],
*,
line_str: str = "",
) -> List[Line]:
if not line_str:
line_str = line_to_string(line)
result: List[Line] = []
for transformed_line in transform(line, features):
if str(transformed_line).strip("\n") == line_str:
raise CannotTransform("Line transformer returned an unchanged result")
result.extend(transform_line(transformed_line, mode=mode, features=features))
if not (
transform.__name__ == "rhs"
and line.bracket_tracker.invisible
and not any(bracket.value for bracket in line.bracket_tracker.invisible)
and not line.contains_multiline_strings()
and not result[0].contains_uncollapsable_type_comments()
and not result[0].contains_unsplittable_type_ignore()
and not is_line_short_enough(result[0], line_length=mode.line_length)
):
return result
line_copy = line.clone()
append_leaves(line_copy, line, line.leaves)
features_fop = set(features) | {Feature.FORCE_OPTIONAL_PARENTHESES}
second_opinion = run_transformer(
line_copy, transform, mode, features_fop, line_str=line_str
)
if all(
is_line_short_enough(ln, line_length=mode.line_length) for ln in second_opinion
):
result = second_opinion
return result
def get_cache_file(mode: Mode) -> Path:
return CACHE_DIR / f"cache.{mode.get_cache_key()}.pickle"
def read_cache(mode: Mode) -> Cache:
"""Read the cache if it exists and is well formed.
If it is not well formed, the call to write_cache later should resolve the issue.
"""
cache_file = get_cache_file(mode)
if not cache_file.exists():
return {}
with cache_file.open("rb") as fobj:
try:
cache: Cache = pickle.load(fobj)
except (pickle.UnpicklingError, ValueError):
return {}
return cache
def get_cache_info(path: Path) -> CacheInfo:
"""Return the information used to check if a file is already formatted or not."""
stat = path.stat()
return stat.st_mtime, stat.st_size
def filter_cached(cache: Cache, sources: Iterable[Path]) -> Tuple[Set[Path], Set[Path]]:
"""Split an iterable of paths in `sources` into two sets.
The first contains paths of files that modified on disk or are not in the
cache. The other contains paths to non-modified files.
"""
todo, done = set(), set()
for src in sources:
res_src = src.resolve()
if cache.get(str(res_src)) != get_cache_info(res_src):
todo.add(src)
else:
done.add(src)
return todo, done
def write_cache(cache: Cache, sources: Iterable[Path], mode: Mode) -> None:
"""Update the cache file."""
cache_file = get_cache_file(mode)
try:
CACHE_DIR.mkdir(parents=True, exist_ok=True)
new_cache = {
**cache,
**{str(src.resolve()): get_cache_info(src) for src in sources},
}
with tempfile.NamedTemporaryFile(dir=str(cache_file.parent), delete=False) as f:
pickle.dump(new_cache, f, protocol=4)
os.replace(f.name, cache_file)
except OSError:
pass
def patch_click() -> None:
"""Make Click not crash.
On certain misconfigured environments, Python 3 selects the ASCII encoding as the
default which restricts paths that it can access during the lifetime of the
application. Click refuses to work in this scenario by raising a RuntimeError.
In case of Black the likelihood that non-ASCII characters are going to be used in
file paths is minimal since it's Python source code. Moreover, this crash was
spurious on Python 3.7 thanks to PEP 538 and PEP 540.
"""
try:
from click import core
from click import _unicodefun # type: ignore
except ModuleNotFoundError:
return
for module in (core, _unicodefun):
if hasattr(module, "_verify_python3_env"):
module._verify_python3_env = lambda: None
def patched_main() -> None:
freeze_support()
patch_click()
main()
def is_docstring(leaf: Leaf) -> bool:
if not is_multiline_string(leaf):
# For the purposes of docstring re-indentation, we don't need to do anything
# with single-line docstrings.
return False
if prev_siblings_are(
leaf.parent, [None, token.NEWLINE, token.INDENT, syms.simple_stmt]
):
return True
# Multiline docstring on the same line as the `def`.
if prev_siblings_are(leaf.parent, [syms.parameters, token.COLON, syms.simple_stmt]):
# `syms.parameters` is only used in funcdefs and async_funcdefs in the Python
# grammar. We're safe to return True without further checks.
return True
return False
def lines_with_leading_tabs_expanded(s: str) -> List[str]:
"""
Splits string into lines and expands only leading tabs (following the normal
Python rules)
"""
lines = []
for line in s.splitlines():
# Find the index of the first non-whitespace character after a string of
# whitespace that includes at least one tab
match = re.match(r"\s*\t+\s*(\S)", line)
if match:
first_non_whitespace_idx = match.start(1)
lines.append(
line[:first_non_whitespace_idx].expandtabs()
+ line[first_non_whitespace_idx:]
)
else:
lines.append(line)
return lines
def fix_docstring(docstring: str, prefix: str) -> str:
# https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation
if not docstring:
return ""
lines = lines_with_leading_tabs_expanded(docstring)
# Determine minimum indentation (first line doesn't count):
indent = sys.maxsize
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxsize:
last_line_idx = len(lines) - 2
for i, line in enumerate(lines[1:]):
stripped_line = line[indent:].rstrip()
if stripped_line or i == last_line_idx:
trimmed.append(prefix + stripped_line)
else:
trimmed.append("")
return "\n".join(trimmed)
if __name__ == "__main__":
patched_main()
| 34.639538 | 131 | 0.602351 |
32c31dc2009b17fd79954bc641530645e4255416 | 55,857 | py | Python | scripts/labtainer-instructor/assess_bin/ResultParser.py | sliao101/Labtainers | 73c56fa9db675f5dbd114dcd83369aa7752c0cca | [
"Apache-2.0"
] | null | null | null | scripts/labtainer-instructor/assess_bin/ResultParser.py | sliao101/Labtainers | 73c56fa9db675f5dbd114dcd83369aa7752c0cca | [
"Apache-2.0"
] | null | null | null | scripts/labtainer-instructor/assess_bin/ResultParser.py | sliao101/Labtainers | 73c56fa9db675f5dbd114dcd83369aa7752c0cca | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
'''
This software was created by United States Government employees at
The Center for Cybersecurity and Cyber Operations (C3O)
at the Naval Postgraduate School NPS. Please note that within the
United States, copyright protection is not available for any works
created by United States Government employees, pursuant to Title 17
United States Code Section 105. This software is in the public
domain and is not subject to copyright.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
'''
# ResultParser.py
# Description: * Read results.config
# * Parse stdin and stdout files based on results.config
# * Create a json file
import datetime
import json
import glob
from hashlib import md5
import parse
import os
import re
import sys
import time
import MyUtil
import GoalsParser
import ParameterParser
MYHOME = ""
container_exec_proglist = {}
stdoutfnameslist = []
timestamplist = {}
line_types = ['CHECKSUM', 'CONTAINS', 'FILE_REGEX', 'FILE_REGEX_TS', 'LINE', 'STARTSWITH', 'NEXT_STARTSWITH', 'HAVESTRING',
'HAVESTRING_TS', 'LOG_TS', 'LOG_RANGE', 'RANGE_REGEX', 'REGEX', 'REGEX_TS', 'LINE_COUNT', 'PARAM', 'STRING_COUNT', 'COMMAND_COUNT', 'TIME_DELIM', 'SIZE']
just_field_type = ['CHECKSUM', 'LINE_COUNT', 'TIME_DELIM', 'SIZE']
logger = None
resultidlist = {}
def GetExecProgramList(containername, studentlabdir, container_list, targetfile):
# Intended for use when the named program is just a wildcard.
# This will return a list of executable program name matching
# <directory>/.local/result/targetfile.*
# If containername is "" then loop through all directories of studentlabdir/container
# where container is from the container_list
# If containername is non "" then directory is studentlabdir/containername
# NOTE: it excludes prestop files
myexec_proglist = []
mylist = []
if containername == "":
#print "containername is empty - do for all container in the container list"
mylist = container_list
else:
#print "containername is non empty - do for that container only"
mylist.append(containername)
#print "Final container list is "
#print mylist
for cur_container in mylist:
string_to_glob = "%s/%s/.local/result/*.%s.*" % (studentlabdir, cur_container, targetfile)
#print "string_to_glob is (%s)" % string_to_glob
globnames = glob.glob('%s' % string_to_glob)
for name in globnames:
basefilename = os.path.basename(name)
#print "basefilename is %s" % basefilename
split_string = ".%s" % targetfile
#print "split_string is %s" % split_string
namesplit = basefilename.split(split_string)
#print namesplit
if namesplit[0] not in myexec_proglist and namesplit[0] != 'prestop':
myexec_proglist.append(namesplit[0])
return myexec_proglist
def ValidateTokenId(result_value, token_id, logger):
if token_id != 'ALL' and token_id != 'LAST':
try:
int(token_id)
except ValueError:
logger.error("results.config line (%s)\n" % result_value)
logger.error("results.config has invalid token_id")
sys.exit(1)
def findLineIndex(values):
for ltype in line_types:
if ltype in values:
return values.index(ltype)
return None
def ProcessConfigLine(actual_parsing, studentlabdir, container_list, labidname, result_key, result_value, logger):
'''
This function populates a set of global structures used in processing the results
'''
valid_field_types = ['TOKEN', 'GROUP', 'PARENS', 'QUOTES', 'SLASH', 'LINE_COUNT', 'CHECKSUM', 'CONTAINS', 'FILE_REGEX',
'FILE_REGEX_TS', 'SEARCH', 'PARAM', 'STRING_COUNT', 'COMMAND_COUNT', 'SIZE']
if not MyUtil.CheckAlphaDashUnder(result_key):
logger.error("Not allowed characters in results.config's key (%s)" % result_key)
sys.exit(1)
values = []
# See the Labtainer Lab Designer User guide for syntax
# NOTE: Split using ' : ' - i.e., "space colon space"
values = [x.strip() for x in result_value.split(' : ')]
#print values
numvalues = len(values)
logger.debug("result_value is %s -- numvalues is (%d)" % (result_value, numvalues))
if numvalues < 2:
logger.error("found no ':' delimiter in %s" % result_value)
sys.exit(1)
if numvalues < 3 and values[1] not in just_field_type:
logger.error("Offending line: (%s).\n Perhaps there is a missing ':'?" % result_value)
logger.error("results.config expected %s to be one of these: %s." % (values[1], str(just_field_type)))
sys.exit(1)
line_at = findLineIndex(values)
if line_at is None:
logger.error('No line_type in %s' % result_value)
sys.exit(1)
num_splits = line_at+1
#print "line_at is (%d) and num_splits is (%d)" % (line_at, num_splits)
# NOTE: Split using ' : ' - i.e., "space colon space"
values = [x.strip() for x in result_value.split(' : ', num_splits)]
# get optional container name and determine if it is 'stdin' or 'stdout'
newprogname_type = values[0].strip()
logger.debug('newprogname_type is %s' % newprogname_type)
cmd = values[1].strip()
# <cfgcontainername>:<exec_program>.<type>
if ':' in newprogname_type:
'''
DEPRECATED: [container_name:]<prog>.[stdin | stdout] | [container_name:]file_path[:time_program]
[container_name:]<prog>.[stdin | stdout] | [container_name:]file_path
'''
cfgcontainername = ''
parts = newprogname_type.split(':')
if len(parts) == 2:
if parts[0].startswith('/'):
progname_type = parts[0]
if len(container_list) > 1:
logger.error('No container name found in multi container lab entry (%s = %s)' % (result_key, result_value))
sys.exit(1)
else:
cfgcontainername = parts[0]
progname_type = parts[1]
elif len(parts) == 3:
cfgcontainername = parts[0]
progname_type = parts[1]
else:
if len(container_list) > 1:
logger.error('No container name found in multi container lab entry (%s = %s)' % (result_key, result_value))
sys.exit(1)
if newprogname_type.endswith('stdin') or newprogname_type.endswith('stdout') \
or newprogname_type.endswith('prgout'):
cfgcontainername = container_list[0].split('.')[1]
#print('assigned to %s' % cfgcontainername)
else:
cfgcontainername = ""
progname_type = newprogname_type
# Construct proper containername from cfgcontainername
if cfgcontainername == "":
containername = ""
else:
containername = labidname + "." + cfgcontainername + ".student"
logger.debug('Start to populate exec_program_list, progname_type is %s' % progname_type)
# No longer restricted to stdin/stdout filenames
if ('stdin' not in progname_type) and ('stdout' not in progname_type) and ('prgout' not in progname_type):
# Not stdin/stdout - add the full name
logger.debug('Not a STDIN or STDOUT: %s ' % progname_type)
else:
(exec_program, targetfile) = progname_type.rsplit('.', 1)
exec_program_list = []
# Can only parse for wildcard if it is actual parsing - not validation
if exec_program == "*" and actual_parsing:
exec_program_list = GetExecProgramList(containername, studentlabdir, container_list, targetfile)
logger.debug("wildcard, exec_program_list is %s" % exec_program_list)
else:
exec_program_list.append(exec_program)
logger.debug('exec_program %s, append to list, container is %s' % (exec_program, containername))
if containername != "":
#print('containername is %s' % containername)
if containername not in container_exec_proglist:
container_exec_proglist[containername] = []
for cur_exec_program in exec_program_list:
if cur_exec_program not in container_exec_proglist[containername]:
container_exec_proglist[containername].append(cur_exec_program)
logger.debug('proglist is %s' % str(container_exec_proglist[containername]))
else:
if "CURRENT" not in container_exec_proglist:
container_exec_proglist["CURRENT"] = []
for cur_exec_program in exec_program_list:
if cur_exec_program not in container_exec_proglist["CURRENT"]:
container_exec_proglist["CURRENT"].append(cur_exec_program)
#print container_exec_proglist["CURRENT"]
#print container_exec_proglist
# Validate <field_type> - if exists (i.e., line_at == 3)
# - because <field_type> is optional
field_type = None
if line_at == 3:
field_type = values[1].strip()
if field_type not in valid_field_types:
logger.error("results.config line (%s)\n" % result_value)
logger.error("results.config invalid field_type")
sys.exit(1)
# Sanity check for 'PARAM' type
if values[line_at] == 'PARAM':
logger.debug("progname_type is (%s)" % progname_type)
if not progname_type.endswith('stdin'):
logger.error("results.config line (%s)\n" % result_value)
logger.error("PARAM field_type on non stdin file")
sys.exit(1)
paramtoken_id = values[2].strip()
try:
paramindex = int(paramtoken_id)
except:
logger.error("results.config line (%s)\n" % result_value)
logger.error('PARAM field_type could not parse int from %s' % paramtoken_id)
sys.exit(1)
# If line_type1 (line_at != 1) - verify token id
if field_type != 'SEARCH' and line_at != 1:
token_index = 1
if line_at == 3:
token_index = 2
ValidateTokenId(result_value, values[token_index], logger)
if values[line_at] == 'LINE':
try:
int(values[line_at+1])
except:
logger.error('Expected integer following LINE type, got %s in %s' % (values[line_at+1], result_value))
sys.exit(1)
return newprogname_type, cmd
def getToken(linerequested, field_type, token_id, logger):
#print "Line requested is (%s)" % linerequested
if linerequested == None:
token = ''
else:
linetokens = {}
if field_type == 'PARENS':
myre = re.findall('\(.+?\)', linerequested)
linetokenidx = 0
for item in myre:
#print "linetokenidx = %d" % linetokenidx
linetokens[linetokenidx] = item[1:-1]
linetokenidx = linetokenidx + 1
numlinetokens = len(linetokens)
elif field_type == 'QUOTES':
myre = re.findall('".+?"', linerequested)
linetokenidx = 0
for item in myre:
#print "linetokenidx = %d" % linetokenidx
linetokens[linetokenidx] = item[1:-1]
linetokenidx = linetokenidx + 1
numlinetokens = len(linetokens)
elif field_type == 'SLASH':
myre = linerequested.split('/')
linetokenidx = 0
for item in myre:
#print "linetokenidx = %d" % linetokenidx
linetokens[linetokenidx] = item
linetokenidx = linetokenidx + 1
numlinetokens = len(linetokens)
elif field_type == 'SEARCH':
logger.debug('is search token_id %s linerequested %s' % (token_id, linerequested))
search_results = parse.search(token_id, linerequested)
if search_results is not None:
token = str(search_results[0])
else:
token = None
else:
# field_type == "TOKEN"
linetokens = linerequested.split()
numlinetokens = len(linetokens)
if token_id == 'ALL':
token = linerequested.strip()
elif token_id == 'LAST':
if numlinetokens > 0:
token = linetokens[numlinetokens-1]
else:
token = None
elif field_type != 'SEARCH':
#print linetokens
# make sure tokenno <= numlinetokens
tokenno = int(token_id)
#print "tokenno = %d" % tokenno
if tokenno > numlinetokens:
token = ""
#print "setting result to none tokenno > numlinetokens"
else:
token = linetokens[tokenno-1]
return token
def lineHasCommand(line, look_for):
retval = 0
if not look_for.startswith('time ') and line.startswith('time'):
line = line[5:].strip()
if not look_for.startswith('sudo ') and line.startswith('sudo'):
line = line[5:].strip()
commands = line.split(';')
for c in commands:
c = c.strip()
pipes = c.split('|')
for p in pipes:
p = p.strip()
if p.startswith('('):
p = p[1:]
if p.startswith(look_for):
retval += 1
return retval
def getTS(line, quiet):
retval = None
''' try syslog format first '''
ts_string = line[:15]
now = datetime.datetime.now()
ts_string = '%d %s' % (now.year, ts_string)
try:
time_val = datetime.datetime.strptime(ts_string, '%Y %b %d %H:%M:%S')
retval = time_val.strftime("%Y%m%d%H%M%S")
except:
pass
if retval is None:
''' snort format '''
ts_string = line[:14]
ts_string = '%d %s' % (now.year, ts_string)
try:
time_val = datetime.datetime.strptime(ts_string, '%Y %m/%d-%H:%M:%S')
retval = time_val.strftime("%Y%m%d%H%M%S")
except:
pass
if retval is None:
''' httpd format '''
if '[' in line and ']' in line:
ts_string_full = line[line.find("[")+1:line.find("]")]
try:
time_val = datetime.datetime.strptime(ts_string_full.split()[0], '%d/%b/%Y:%H:%M:%S')
retval = time_val.strftime("%Y%m%d%H%M%S")
except:
try:
time_val = datetime.datetime.strptime(ts_string_full, '%d/%b/%Y %H:%M:%S')
retval = time_val.strftime("%Y%m%d%H%M%S")
except:
pass
elif 'T' in line:
ts_string = line[:19]
try:
time_val = datetime.datetime.strptime(ts_string, '%Y-%m-%dT%H:%M:%S')
retval = time_val.strftime("%Y%m%d%H%M%S")
except:
pass
if not quiet and retval is None:
print('ERROR getting timestamp from %s' % line)
return retval
def getTokenFromFile(current_targetfname, command, field_type, token_id, logger, lookupstring, line, result_key):
# Read in corresponding file
targetf = open(current_targetfname, encoding='ascii', errors='ignore')
targetlines = targetf.readlines()
targetf.close()
targetfilelen = len(targetlines)
#print('current_targetfname %s' % current_targetfname)
# command has been validated to be either 'LINE' or 'STARTSWITH' or 'HAVESTRING'
linerequested = None
if command == 'LINE':
# make sure lineno <= targetfilelen
if lineno <= targetfilelen:
linerequested = targetlines[lineno-1]
elif command == 'HAVESTRING':
# command = 'HAVESTRING':
found_lookupstring = False
for currentline in targetlines:
if found_lookupstring == False:
if lookupstring in currentline:
found_lookupstring = True
linerequested = currentline
break
# If not found - set to None
if found_lookupstring == False:
linerequested = None
elif command == 'REGEX':
found_lookupstring = False
for currentline in targetlines:
if found_lookupstring == False:
sobj = re.search(lookupstring, currentline)
if sobj is not None:
found_lookupstring = True
if field_type == 'GROUP':
linerequested = sobj
else:
linerequested = currentline
break
# If not found - set to None
if found_lookupstring == False:
linerequested = None
elif command == 'HAVESTRING_TS' or command == 'LOG_RANGE' or command == 'RANGE_REGEX' or \
command == 'REGEX_TS' or command == 'FILE_REGEX_TS' or command == 'LOG_TS':
return None
elif command == 'LINE_COUNT':
return targetfilelen
elif command == 'SIZE':
return os.path.getsize(current_targetfname)
elif command == 'PARAM':
fname = os.path.basename(current_targetfname).rsplit('.',1)[0]
if fname.endswith('stdin'):
program_name = current_targetfname.rsplit('.', 1)[0]
else:
# Config file 'PARAM' has been validated against stdin
# Treat this as can't find token
logger.debug('PARAM only valid for stdin files: %s' % current_targetfname)
return ''
if 'PROGRAM_ARGUMENTS' in targetlines[0]:
try:
index = int(token_id)
except:
# Config file 'PARAM' has been validated, should not be failing here
# If it does, then should really exit
logger.error('could not parse int from %s' % token_id)
sys.exit(1)
if index == 0:
tagstring = program_name
else:
s = targetlines[0]
param_str = s[s.find("(")+1:s.find(")")]
params = param_str.split()
try:
tagstring = params[index-1]
except:
# Couldn't find the corresponding parameter
# Treat this as can't find token
logger.debug('did not find parameter %d in %s' % (index-1, param_str))
return ''
return tagstring
elif command == 'CHECKSUM':
''' Create a checksum of the targetfile '''
mymd5 = md5()
targetlinestring = "".join(targetlines)
mymd5.update(targetlinestring.encode('utf-8'))
tagstring = mymd5.hexdigest()
return tagstring
elif command == 'CONTAINS':
if 'CONTAINS' in token_id:
''' search entire file, vice searching for line '''
remain = line.split(command,1)[1]
remain = remain.split(':', 1)[1].strip()
tagstring = False
for currentline in targetlines:
if remain in currentline:
tagstring = True
break
return tagstring
elif command == 'FILE_REGEX':
''' search entire file, for line with given regex '''
remain = line.split(command,1)[1]
remain = remain.split(':', 1)[1].strip()
tagstring = False
allofit = ''.join(targetlines)
#print('%s' % allofit)
#print('look for %s' % remain)
sobj = re.findall(remain, allofit, re.MULTILINE | re.DOTALL)
if sobj is not None and len(sobj)>0:
tagstring = True
return tagstring
elif command == 'STRING_COUNT':
''' search entire file, vice searching for line '''
remain = line.split(command,1)[1]
remain = remain.split(':', 1)[1].strip()
count=0
for currentline in targetlines:
#print('look for <%s> in %s' % (remain, currentline))
if remain in currentline:
count += 1
return count
elif command == 'COMMAND_COUNT':
''' intended for bash_history files, look for occurances of what look like commands '''
remain = line.split(command,1)[1]
look_for = remain.split(':', 1)[1].strip()
count=0
for currentline in targetlines:
occurances = lineHasCommand(currentline.strip(), look_for)
count += occurances
return count
elif command == 'STARTSWITH':
#print('is startswith')
found_lookupstring = False
for currentline in targetlines:
if found_lookupstring == False:
if currentline.startswith(lookupstring):
found_lookupstring = True
linerequested = currentline
#print('line requested is %s' % linerequested)
break
# If not found - set to None
if found_lookupstring == False:
logger.debug('*** No line starts with %s ***' % (lookupstring))
linerequested = None
elif command == 'NEXT_STARTSWITH':
found_lookupstring = False
prev_line = None
for currentline in targetlines:
if found_lookupstring == False:
if currentline.startswith(lookupstring) and prev_line is not None:
found_lookupstring = True
linerequested = prev_line
break
prev_line = currentline
# If not found - set to None
if found_lookupstring == False:
logger.debug('*** No next line starts with %s ***' % (lookupstring))
linerequested = None
else:
# config file should have been validated
# - if still unknown command, then should exit
logger.error('unknown command %s' % command)
sys.exit(1)
if command == 'REGEX' and field_type == 'GROUP':
try:
token = linerequested.group(int(token_id))
except:
token = ''
else:
token = getToken(linerequested, field_type, token_id, logger)
logger.debug('field_type %s, token_id %s, got token %s' % (field_type, token_id, token))
return token
def getParamList(MYHOME, studentdir, logger):
lab_instance_seed = GoalsParser.GetLabInstanceSeed(studentdir, logger)
container_user = ""
param_filename = os.path.join(MYHOME, '.local', 'config',
'parameter.config')
pp = ParameterParser.ParameterParser(None, container_user, lab_instance_seed, logger)
parameter_list = pp.ParseParameterConfig(param_filename)
return parameter_list
def getConfigItems(labidname, line, studentlabdir, container_list, logger, parameter_list):
targetlines = None
if '=' not in line:
print('no equals in %s' % line)
return
containername= targetfile= result_key= command= field_type= token_id= lookupstring= result_home = None
#print('line is %s' % line)
logger.debug('line is %s' % line)
(result_key, result_value) = line.split('=', 1)
result_key = result_key.strip()
#print result_key
# Note: config file has been validated
# Split into four parts or five parts
# NOTE: Split using ' : ' - i.e., "space colon space"
values = [x.strip() for x in result_value.split(' : ')]
line_at = findLineIndex(values)
num_splits = line_at+1
# NOTE: Split using ' : ' - i.e., "space colon space"
values = [x.strip() for x in result_value.split(' : ', num_splits)]
newtargetfile = values[0].strip()
logger.debug('line_at is %d newtargetvalue = %s, values: %s' % (line_at, newtargetfile, str(values)))
#print('newtargetfile is %s' % newtargetfile)
# <cfgcontainername>:<exec_program>.<type>
containername = None
if ':' in newtargetfile:
cfgcontainername, targetfile = newtargetfile.split(':', 1)
#print('split got targetfile of %s' % targetfile)
else:
''' default to first container? '''
#print('first cont is %s' % container_list[0])
containername = container_list[0]
targetfile = newtargetfile
# Construct proper containername from cfgcontainername
if containername is None:
containername = labidname + "." + cfgcontainername + ".student"
result_home = '%s/%s/%s' % (studentlabdir, containername, ".local/result/")
if targetfile.startswith('/'):
targetfile = os.path.join(result_home, targetfile[1:])
#print('targetfile is %s containername is %s' % (targetfile, containername))
logger.debug('targetfile is %s, containername is %s' % (targetfile, containername))
if containername is not None and containername not in container_list:
print("Config line (%s) containername %s not in container list (%s), skipping..." % (line, containername, str(container_list)))
logger.error("Config line (%s) containername %s not in container list (%s), skipping..." % (line,
containername, str(container_list)))
return None, None, result_key, None, None, None, None, None
command = values[line_at].strip()
# field_type - if exists (because field_type is optional)
# has been validated to be one of the valid field types.
#
# if it does not exists, default field_type is TOKEN
if line_at == 3:
field_type = values[1].strip()
else:
field_type = "TOKEN"
# command has been validated to be either 'LINE' or 'STARTSWITH' or 'HAVESTRING'
token_index = 1
if line_at == 3:
token_index = 2
if command == 'PARAM':
token_id = values[2].strip()
elif command == 'CHECKSUM':
token_id = None
else:
token_id = values[token_index].strip()
if command == 'LINE':
lineno = int(values[line_at+1].strip())
elif command not in just_field_type:
lookupstring = values[line_at+1].strip()
if lookupstring.startswith('$'):
tstring = lookupstring[1:]
if tstring in parameter_list:
logger.debug('replacing %s with %s' % (lookupstring, parameter_list[tstring]))
lookupstring = parameter_list[tstring]
return containername, targetfile, result_key, command, field_type, token_id, lookupstring, result_home
def handleConfigFileLine(labidname, line, nametags, studentlabdir, container_list, timestamppart, logger, parameter_list, latest_dict):
retval = True
containername, targetfile, result_key, command, field_type, token_id, lookupstring, result_home = getConfigItems(labidname, line, studentlabdir, container_list, logger, parameter_list)
if targetfile is None:
nametags[result_key]=None
logger.error('No target file in %s' % line)
return retval
if result_key.startswith('cw_'):
fname = targetfile
if fname.endswith('stdout'):
fname = targetfile[:-7]
elif fname.endswith('stdin'):
fname = targetfile[:-6]
container_file = '%s:%s' % (containername, fname)
logger.debug('is cw %s ts %s file %s' % (result_key, timestamppart, container_file))
if container_file not in latest_dict or timestamppart != latest_dict[container_file]:
''' is a checkwork (current-state) result and is not the latest timestamp for the file, ignore '''
logger.debug('NOT the latest')
if container_file not in latest_dict:
logger.debug('%s not in dict' % container_file)
else:
logger.debug('not latest, which is %s' % latest_dict[container_file])
return retval
else:
logger.debug('is the latest')
logger.debug('command %s, field_type %s, token_id %s' % (command, field_type, token_id))
targetfname_list = []
if targetfile.startswith('*'):
# Handle 'asterisk' --
#print("Handling asterisk")
#print("containername is %s, targetfile is %s" % (containername, targetfile))
# Replace targetfile as a list of files
targetfileparts = targetfile.split('.')
targetfilestdinstdout = None
if targetfileparts is not None:
targetfilestdinstdout = targetfileparts[1]
if targetfilestdinstdout is not None:
#print("targetfilestdinstdout is %s" % targetfilestdinstdout)
if containername in container_exec_proglist:
myproglist = container_exec_proglist[containername]
else:
myproglist = container_exec_proglist["CURRENT"]
for progname in myproglist:
if timestamppart is not None:
targetfname = '%s%s.%s.%s' % (result_home, progname, targetfilestdinstdout, timestamppart)
if os.path.isfile(targetfname):
targetfname_list.append(targetfname)
#print('appending %s' % targetfname)
else:
#print "Handling non-asterisk"
if timestamppart is not None:
if not targetfile.startswith(result_home):
targetfname = '%s%s.%s' % (result_home, targetfile, timestamppart)
else:
targetfname = '%s.%s' % (targetfile, timestamppart)
else:
''' descrete file, no timestamp. '''
if targetfile.startswith('~/'):
targetfile = targetfile[2:]
targetfname = os.path.join(studentlabdir, containername, targetfile)
#print "labdir is (%s)" % studentlabdir
targetfname_list.append(targetfname)
#print "Current targetfname_list is %s" % targetfname_list
tagstring = None
# Loop through targetfname_list
# Will ONLY contain one entry, except for the case where astrix is used
token = None
#print('len of targetfname_list is %d' % len(targetfname_list))
bool_operators = ['CONTAINS', 'FILE_REGEX']
for current_targetfname in targetfname_list:
if not os.path.exists(current_targetfname):
# If file does not exist, treat as can't find token
logger.debug("No %s file does not exist\n" % current_targetfname)
else:
#print('get cmd %s for %s' % (command, current_targetfname))
token = getTokenFromFile(current_targetfname, command, field_type, token_id, logger, lookupstring, line, result_key)
if token is not None:
#print token
if token == "":
tagstring = ""
elif command in bool_operators:
if token is True:
tagstring = token
#print('BREAKING token is <%s>' % token)
break
elif result_key in nametags and nametags[result_key] is not True:
#print('result_key %s going false' % result_key)
tagstring = token
else:
tagstring = token
# found the token - break out of the main for loop
#print('BREAKING not contains token is <%s>' % token)
break
if tagstring is None and command in bool_operators:
tagstring = False
elif token is None:
tagstring = None
# set nametags - value pair
if tagstring is not None:
nametags[result_key] = tagstring
#print('nametags %s set to %s' % (result_key, tagstring))
return True
else:
return False
def stringMatch(line, sub, command):
retval = False
if 'REGEX' in command:
sobj = re.search(sub, line)
if sobj is not None:
retval = True
else:
if sub in line:
retval = True
return retval
def ParseConfigForTimeRec(studentlabdir, labidname, configfilelines, ts_jsonfname, container_list, logger, parameter_list):
ts_nametags = {}
for line in configfilelines:
linestrip = line.rstrip()
if linestrip is not None and not linestrip.startswith('#') and len(line.strip())>0:
containername, targetfile, result_key, command, field_type, token_id, lookupstring, result_home = getConfigItems(labidname, linestrip, studentlabdir, container_list, logger, parameter_list)
if targetfile is None:
logger.error('Failed to get file from %s' % linestrip)
continue
quiet = False
if 'mysql' in targetfile:
''' some sql log entries have no ts '''
quiet = True
if command == 'HAVESTRING_TS':
if not os.path.isfile(targetfile):
continue
with open(targetfile, encoding='ascii', errors='ignore') as fh:
targetlines = fh.readlines()
for currentline in targetlines:
if lookupstring in currentline:
time_val = getTS(currentline, quiet)
if time_val is None:
continue
ts = str(time_val)
if ts not in ts_nametags:
ts_nametags[ts] = {}
ts_nametags[ts]['PROGRAM_ENDTIME'] = 0
token = getToken(currentline, field_type, token_id, logger)
ts_nametags[ts][result_key] = token
if command == 'LOG_TS':
if not os.path.isfile(targetfile):
continue
with open(targetfile, encoding='ascii', errors='ignore') as fh:
targetlines = fh.readlines()
for currentline in targetlines:
if lookupstring in currentline:
time_val = getTS(currentline, quiet)
if time_val is None:
continue
ts = str(time_val)
if ts not in ts_nametags:
ts_nametags[ts] = {}
ts_nametags[ts]['PROGRAM_ENDTIME'] = 0
ts_nametags[ts][result_key] = True
if command == 'LOG_RANGE' or command == 'RANGE_REGEX':
if not os.path.isfile(targetfile):
continue
with open(targetfile, encoding='ascii', errors='ignore') as fh:
targetlines = fh.readlines()
prev_time_val = None
last_time_val = None
for currentline in targetlines:
time_val = getTS(currentline, quiet)
if time_val is None:
continue
if prev_time_val is None:
prev_time_val = time_val
if stringMatch(currentline, lookupstring, command):
if time_val == prev_time_val:
''' ignore if lacks range '''
continue
last_time_val = time_val
prev_ts = str(prev_time_val)
end_ts = str(time_val)
if prev_ts not in ts_nametags:
ts_nametags[prev_ts] = {}
ts_nametags[prev_ts]['PROGRAM_ENDTIME'] = end_ts
elif ts_nametags[prev_ts]['PROGRAM_ENDTIME'] == 0:
ts_nametags[prev_ts]['PROGRAM_ENDTIME'] = end_ts
ts_nametags[prev_ts][result_key] = True
prev_time_val = time_val
if last_time_val is not None:
prev_ts = str(prev_time_val)
''' set end to end of log '''
end_ts = str(time_val)
if prev_ts not in ts_nametags:
ts_nametags[prev_ts] = {}
ts_nametags[prev_ts]['PROGRAM_ENDTIME'] = end_ts
elif ts_nametags[prev_ts]['PROGRAM_ENDTIME'] == 0:
ts_nametags[prev_ts]['PROGRAM_ENDTIME'] = end_ts
ts_nametags[prev_ts][result_key] = True
elif command == 'REGEX_TS':
if not os.path.isfile(targetfile):
continue
with open(targetfile, encoding='ascii', errors='ignore') as fh:
targetlines = fh.readlines()
for currentline in targetlines:
sobj = re.search(lookupstring, currentline)
if sobj is not None:
time_val = getTS(currentline, quiet)
if time_val is None:
continue
ts = str(time_val)
if ts not in ts_nametags:
ts_nametags[ts] = {}
ts_nametags[ts]['PROGRAM_ENDTIME'] = 0
if field_type == 'GROUP':
try:
token = sobj.group(int(token_id))
except:
token = ''
else:
token = getToken(currentline, field_type, token_id, logger)
ts_nametags[ts][result_key] = token
elif command == 'FILE_REGEX_TS':
if not os.path.isfile(targetfile):
continue
with open(targetfile, encoding='ascii', errors='ignore') as fh:
targetlines = fh.readlines()
for currentline in targetlines:
sobj = re.search(lookupstring, currentline)
if sobj is not None:
time_val = getTS(currentline, quiet)
if time_val is None:
continue
ts = str(time_val)
if ts not in ts_nametags:
ts_nametags[ts] = {}
ts_nametags[ts]['PROGRAM_ENDTIME'] = 0
ts_nametags[ts][result_key] = True
jsonoutput = open(ts_jsonfname, "w")
for ts in ts_nametags:
for key in ts_nametags[ts]:
old = ts_nametags[ts][key]
new = repr(old)
ts_nametags[ts][key] = new
try:
jsondumpsoutput = json.dumps(ts_nametags, indent=4)
except:
logger.error('json dumps failed on %s' % ts_nametags)
exit(1)
#print('dumping %s' % str(jsondumpsoutput))
jsonoutput.write(jsondumpsoutput)
jsonoutput.write('\n')
jsonoutput.close()
def doFileTimeDelim(ts_nametags, result_home, targetfile, result_key, command, lookupstring, logger):
fname, delim_prog = targetfile.split(':')
logger.debug('targetfile is time delim %s delim_prog %s fname %s' % (targetfile, delim_prog, fname))
look_for = os.path.join(result_home,'%s.stdout.*' % delim_prog)
#print('look for %s' % look_for)
delim_list = glob.glob(look_for)
delim_ts_set = []
for delim_ts_file in delim_list:
ts = delim_ts_file.rsplit('.',1)[1]
delim_ts_set.append(ts)
if len(delim_ts_set) == 0:
logger.debug('no ts files for program time delimiter %s' % delim_prog)
return
delim_ts_set.sort()
end_times='99999999999999'
delim_ts_set.append(end_times)
ts = 0
current_ts_end = delim_ts_set[0]
index = 0
quiet = False
if 'mysql' in targetfile:
quiet = True
with open(fname) as fh:
for currentline in fh:
time_val = getTS(currentline, quiet)
logger.debug('ts[index] %s my_time %s' % (delim_ts_set[index], time_val))
if time_val > delim_ts_set[index]:
logger.debug('time greater')
if ts in ts_nametags:
ts_nametags[ts]['PROGRAM_ENDTIME'] = time_val
ts = delim_ts_set[index]
index += 1
if command == 'CONTAINS':
if lookupstring in currentline:
if ts not in ts_nametags:
ts_nametags[ts] = {}
ts_nametags[ts]['PROGRAM_ENDTIME'] = end_times
ts_nametags[ts][result_key] = True
elif command == 'FILE_REGEX':
remain = line.split(command,1)[1]
remain = remain.split(':', 1)[1].strip()
sobj = re.search(remain, currentline)
if sobj is not None:
if ts not in ts_nametags:
ts_nametags[ts] = {}
ts_nametags[ts]['PROGRAM_ENDTIME'] = end_times
ts_nametags[ts][result_key] = True
def ParseConfigForTimeDelim(studentlabdir, labidname, configfilelines, ts_jsonfname, container_list, logger, parameter_list):
'''
HANDLE TIME_DELIM
DEPRECATEND:Handle case of timestamped log files whose names are qualified by a
"time delimiter" program whose start times will
be used to break up a timestamped log file. The quantity of timestamped groupings
of log file results will be one plus the quantity of invocations of the "time delimeter" program.
'''
ts_nametags = {}
for line in configfilelines:
linestrip = line.rstrip()
if linestrip is not None and not linestrip.startswith('#') and len(line.strip())>0:
containername, targetfile, result_key, command, field_type, token_id, lookupstring, result_home = getConfigItems(labidname, linestrip, studentlabdir, container_list, logger, parameter_list)
if False and targetfile is not None and ':' in targetfile:
''' DEPRECATED '''
doFileTimeDelim(ts_nametags, result_home, targetfile, result_key, command, lookupstring, logger)
elif targetfile is not None and command == 'TIME_DELIM':
tf_list = targetfile.split(';')
delim_list = []
for tf in tf_list:
''' set of timestamped values delimited by named program '''
logger.debug('targetfile is time delim %s ' % (tf))
look_for = os.path.join(result_home,'%s.stdout.*' % tf)
#print('look for %s' % look_for)
tf_ts = glob.glob(look_for)
for f in tf_ts:
ts = f.rsplit('.', 1)[1]
if ts not in delim_list:
delim_list.append(ts)
delim_ts_set = []
prev_ts = 0
for ts in sorted(delim_list):
end_time='99999999999999'
if ts not in ts_nametags:
ts_nametags[ts] = {}
ts_nametags[ts]['PROGRAM_ENDTIME'] = end_time
ts_nametags[ts][result_key] = True
if prev_ts != 0:
ts_nametags[prev_ts]['PROGRAM_ENDTIME'] = ts
prev_ts = ts
if len(ts_nametags) > 0:
jsonoutput = open(ts_jsonfname, "w")
for ts in ts_nametags:
for key in ts_nametags[ts]:
old = ts_nametags[ts][key]
new = repr(old)
ts_nametags[ts][key] = new
try:
jsondumpsoutput = json.dumps(ts_nametags, indent=4)
except:
logger.error('json dumps failed on %s' % ts_nametags)
exit(1)
jsonoutput.write(jsondumpsoutput)
jsonoutput.write('\n')
jsonoutput.close()
def ParseConfigForFile(studentlabdir, labidname, configfilelines,
outputjsonfname, container_list, timestamppart, end_time, logger, parameter_list, latest_dict={}):
'''
Invoked for each timestamp to parse results for that timestamp.
Each config file line is assessed against each results file that corresponds
to the given timestamp. If timestamp is None, then look at all files that
match the name found in the configuration file line, (e.g., for log files
without timestamps.)
'''
#print('in ParseConfigForFile outputjsonfile: %s timestamppart %s' % (outputjsonfname, timestamppart))
nametags = {}
got_one = False
for line in configfilelines:
linestrip = line.rstrip()
if linestrip is not None and not linestrip.startswith('#') and len(line.strip())>0:
got_one = got_one | handleConfigFileLine(labidname, linestrip, nametags, studentlabdir,
container_list, timestamppart, logger, parameter_list, latest_dict)
if end_time is not None:
if timestamppart < end_time:
program_end_time = end_time
else:
logger.debug('timestamppart of %s was greater than end_time %s, use it' % (timestamppart, end_time))
program_end_time = timestamppart
else:
program_end_time = 'NONE'
if got_one:
nametags['PROGRAM_ENDTIME'] = program_end_time
#print nametags
#print('will dump to %s' % outputjsonfname)
jsonoutput = open(outputjsonfname, "w")
for key in nametags:
old = nametags[key]
new = repr(old)
nametags[key] = new
#print('nametags[%s] = %s' % (key, new))
try:
jsondumpsoutput = json.dumps(nametags, indent=4)
except:
print('json dumps failed on %s' % nametags)
exit(1)
#print('dumping %s' % str(jsondumpsoutput))
jsonoutput.write(jsondumpsoutput)
jsonoutput.write('\n')
jsonoutput.close()
# Note this can be called directly also
def ParseValidateResultConfig(actual_parsing, homedir, studentlabdir, container_list, labidname, logger_in, parameter_list):
bool_results = []
MYHOME = homedir
logger = logger_in
configfilename = os.path.join(MYHOME,'.local','instr_config', 'results.config')
configfile = open(configfilename)
configfilelines = configfile.readlines()
configfile.close()
for line in configfilelines:
linestrip = line.rstrip()
if linestrip:
if not linestrip.startswith('#'):
#print "Current linestrip is (%s)" % linestrip
try:
(result_key, result_value) = linestrip.split('=', 1)
except:
logger.error('missing "=" character in %s' % linestrip)
sys.exit(1)
result_key = result_key.strip()
progname_type, cmd = ProcessConfigLine(actual_parsing, studentlabdir, container_list, labidname, result_key, result_value, logger)
if result_key not in resultidlist:
resultidlist[result_key] = progname_type
if 'CONTAINS' in cmd or (cmd is not None and cmd.startswith('FILE_REGEX')):
bool_results.append(result_key.strip())
#else:
# print "Skipping empty linestrip is (%s)" % linestrip
return configfilelines, resultidlist, bool_results
def ParseStdinStdout(homedir, studentlabdir, container_list, instructordir, labidname, logger_in):
MYHOME = homedir
logger = logger_in
actual_parsing = True
''' pick a container directory from which to extract the lab instance seed for parameter replacements '''
container_dir = os.path.join(studentlabdir, container_list[0])
parameter_list = getParamList(MYHOME, container_dir, logger)
# Parse and Validate Results configuration file
configfilelines, resultlist, bool_results = ParseValidateResultConfig(actual_parsing, homedir, studentlabdir,
container_list, labidname, logger_in, parameter_list)
''' process all results files (ignore name of function) for a student. These
are distrbuted amongst multiple containers, per container_list.
'''
jsonoutputfilename = labidname
#print("ParseStdinStdout: jsonoutputfilename is (%s) studentlabdir %s" % (jsonoutputfilename, studentlabdir))
logger.debug("ParseStdinStdout: jsonoutputfilename is (%s) studentlabdir %s" % (jsonoutputfilename, studentlabdir))
timestamplist.clear()
#del exec_proglist[:]
del stdoutfnameslist[:]
#print "exec_proglist is: "
#print exec_proglist
OUTPUTRESULTHOME = '%s/%s' % (studentlabdir, ".local/result/")
logger.debug('Done with validate, outputresult to %s' % OUTPUTRESULTHOME)
if not os.path.exists(OUTPUTRESULTHOME):
os.makedirs(OUTPUTRESULTHOME)
bool_results_file = os.path.join(OUTPUTRESULTHOME, 'bool_results.json')
with open(bool_results_file, 'w') as fh:
json.dump(bool_results, fh, indent=4)
latest_dict = {}
'''
A round-about-way of getting all time stamps
'''
for mycontainername in container_list:
RESULTHOME = '%s/%s/%s' % (studentlabdir, mycontainername, ".local/result/")
logger.debug('check results for %s' % RESULTHOME)
if not os.path.exists(RESULTHOME):
''' expected, some containers don't have local results '''
logger.debug('result directory %s does not exist' % RESULTHOME)
pass
if mycontainername not in container_exec_proglist:
logger.debug('%s not in proglist %s' % (mycontainername, str(container_exec_proglist)))
continue
for exec_prog in container_exec_proglist[mycontainername]:
stdinfiles = '%s%s.%s.' % (RESULTHOME, exec_prog, "stdin")
stdoutfiles = '%s%s.%s.' % (RESULTHOME, exec_prog, "stdout")
prgoutfiles = '%s%s.%s.' % (RESULTHOME, exec_prog, "prgout")
logger.debug('stdin %s stdout %s' % (stdinfiles, stdoutfiles))
globstdinfnames = glob.glob('%s*' % stdinfiles)
globstdoutfnames = glob.glob('%s*' % stdoutfiles)
if globstdoutfnames != []:
#print "stdoutfnameglob list is "
#print globstdoutfnames
for stdoutfnames in globstdoutfnames:
#print stdoutfnames
stdoutfnameslist.append(stdoutfnames)
globprgoutfnames = glob.glob('%s*' % prgoutfiles)
if globprgoutfnames != []:
for prgoutfnames in globprgoutfnames:
stdoutfnameslist.append(prgoutfnames)
for stdoutfname in stdoutfnameslist:
# the only purpose of this is to establish the timestamp dictionary
# only stdout is looked at.
#print('for stdout %s' % stdoutfname)
for exec_prog in container_exec_proglist[mycontainername]:
stdoutfiles = '%s%s.%s.' % (RESULTHOME, exec_prog, "stdout")
if stdoutfiles in stdoutfname:
#print "match"
(filenamepart, timestamppart) = stdoutfname.split(stdoutfiles)
targetmtime = os.path.getmtime(stdoutfname)
if timestamppart not in timestamplist:
#print('adding %s' % timestamppart)
timestamplist[timestamppart] = targetmtime
elif targetmtime > timestamplist[timestamppart]:
timestamplist[timestamppart] = targetmtime
container_file = '%s:%s' % (mycontainername, exec_prog)
if container_file not in latest_dict or timestamppart > latest_dict[container_file]:
''' track the most recent of each file for use if result type is checkwork (cw_ prefix) '''
logger.debug('adding latest_dict[%s] = %s' % (container_file, timestamppart))
latest_dict[container_file] = timestamppart
else:
#print "no match"
continue
''' process each timestamped result file. '''
for timestamppart in sorted(timestamplist):
targetmtime_string = datetime.datetime.fromtimestamp(timestamplist[timestamppart])
end_time = targetmtime_string.strftime("%Y%m%d%H%M%S")
outputjsonfname = '%s%s.%s' % (OUTPUTRESULTHOME, jsonoutputfilename, timestamppart)
logger.debug("ParseStdinStdout (1): Outputjsonfname is (%s)" % outputjsonfname)
ParseConfigForFile(studentlabdir, labidname, configfilelines, outputjsonfname,
container_list, timestamppart, end_time, logger, parameter_list, latest_dict=latest_dict)
''' process files without timestamps '''
outputjsonfname = '%s%s' % (OUTPUTRESULTHOME, jsonoutputfilename)
ParseConfigForFile(studentlabdir, labidname, configfilelines, outputjsonfname, container_list, None, None, logger, parameter_list)
ts_jsonfname = outputjsonfname+'_ts'
ParseConfigForTimeRec(studentlabdir, labidname, configfilelines, ts_jsonfname, container_list, logger, parameter_list)
td_jsonfname = outputjsonfname+'_td'
ParseConfigForTimeDelim(studentlabdir, labidname, configfilelines, td_jsonfname, container_list, logger, parameter_list)
| 45.821985 | 201 | 0.572569 |
2fd469a4c2a1dd3a7d155359041c219530a2720f | 1,481 | py | Python | notifications-example/example.py | johnman/openfin-python-adapter | f1e24b870cd80f28079bb92df8bcb7918c81e47c | [
"Apache-2.0"
] | null | null | null | notifications-example/example.py | johnman/openfin-python-adapter | f1e24b870cd80f28079bb92df8bcb7918c81e47c | [
"Apache-2.0"
] | null | null | null | notifications-example/example.py | johnman/openfin-python-adapter | f1e24b870cd80f28079bb92df8bcb7918c81e47c | [
"Apache-2.0"
] | null | null | null | import openfin
client = openfin.OpenFinClient()
def log_message(*args, **kwargs):
print(args, kwargs)
def on_register(val):
print("Registered")
client.subscribe(openfin.SubKey.from_string("notification-relay/outbox"), log_message, on_register)
payload = {
"title": "Important Notification",
"body": "Please open google to search for important information.",
"category": "Signals",
"customData": {
"customId": "12345"
},
"stream": {
"id": "5a2f6e02-5964-48cc-ae88-81df125d9314",
"displayName": "Python Stream"
},
"buttons": [
{
"title": "Open In OpenFin",
"onClick": {
"task": "open-in-openfin",
"url": "https://www.google.com",
"handler": "agent",
"target": "openfin"
}
},
{
"title": "Open In Default",
"onClick": {
"task": "open-in-default",
"url": "https://www.google.com",
"handler": "agent"
}
},
{
"title": "Open In Browser",
"onClick": {
"task": "open-in-browser",
"url": "https://www.google.com",
"handler": "agent",
"target": "browser"
}
}
]
}
for index in range(0, 1):
client.publish("notification-relay/inbox", payload)
text = input("Enter any key to exit")
| 24.278689 | 99 | 0.485483 |
90cd63dd227d65462cfbea53ebe9d91dfe50732d | 15,166 | py | Python | utilities/metadata_parser.py | dhmit/computation_hist | 73265df00d1ba7952942be16f7b84e2a6692b359 | [
"BSD-3-Clause"
] | 5 | 2018-11-16T20:23:19.000Z | 2020-10-02T21:54:03.000Z | utilities/metadata_parser.py | dhmit/computation_hist | 73265df00d1ba7952942be16f7b84e2a6692b359 | [
"BSD-3-Clause"
] | 236 | 2018-11-17T01:56:47.000Z | 2019-12-05T01:57:03.000Z | utilities/metadata_parser.py | dhmit/computation_hist | 73265df00d1ba7952942be16f7b84e2a6692b359 | [
"BSD-3-Clause"
] | 26 | 2018-11-09T21:16:25.000Z | 2019-06-11T04:38:12.000Z | # python
import csv
# django
from django.contrib.postgres.search import SearchVector
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.db.models import Count, Prefetch
from django.utils.text import slugify
# project
from config.settings import METADATA_CSV, DATABASES, DATA_DIR
from apps.archives.models import (
Organization,
Person,
Box,
Folder,
Document
)
from .common import get_file_path, store_pickle
from .name_parser import PeopleDatabase
def populate_from_metadata(metadata_filename=None):
'''
:param metadata_filename: is a path to a csv file (relative or actual)
:return: populates the django database, but returns nothing
how to run:
open up terminal (with virtual environment):
> cd djweb
> python manage.py shell
in shell:
> from utilities.metadata_parser import populate_from_metadata
> populate_from_metadata()
The 'r' in front of the file location isn't necessary but can help to prevent strange errors.
Utilizes interpret_organization_person to add authors, recipients, and cced.
'''
if metadata_filename is None:
metadata_filename = METADATA_CSV
# the aliases_to_full_name_dict maps from raw (csv) names to authoritative full names, e.g.
# e.g. 'Corbatò, F. J.' -> 'Corbató, Fernando J.'
people_db = PeopleDatabase()
people_db.extract_names_from_metadata_sheet()
aliases_to_full_name_dict = people_db.get_aliases_to_full_name_dict()
with open(metadata_filename, encoding='utf-8') as file:
csv_file = csv.DictReader(file)
count_added = 0
count_skipped = 0
count_invalid = 0
names = {}
for line_id, line in enumerate(csv_file):
# Skip empty lines
if "".join(line.values()) == '':
continue
missing_metadata = []
for attr in ['box', 'folder_number', 'doc_id', 'filename', 'author',
'title', 'first_page', 'last_page']:
if not line[attr]:
missing_metadata.append(attr)
if missing_metadata:
print(f'WARNING: Line {line_id+1} is incomplete (skipping).\
\n\tMissing fields: {missing_metadata} - FIXME in the metadata!')
count_skipped += 1
continue
# NOTE(ra) 2019-05-09: we don't know what's going on with this folder,
# so we're skipping adding these until Erica has a chance to go see it
# in person on Monday 5/13
if line['foldername_short'] == 'morse_1956_1958_rikita':
continue
try:
add_one_document(line, aliases_to_full_name_dict, line_id+1, names)
count_added += 1
except ValidationError as e:
count_invalid += 1
print(f'{e}. Line: {line}.')
print('Adding search vectors...')
Document.objects.update(text_search_vector=SearchVector('text'))
print(f'''\n################################################################################
IMPORT COMPLETE
################################################################################
Added {count_added} documents from {metadata_filename}.
Skipped {count_skipped} documents because of incomplete metadata.
{count_invalid} had invalid data.\r\n''')
# display name variants for manual fixing with the help of Ctrl-F
# may be too long to fit in PyCharm terminal, so you may have to write to file
print(f'''NAME VARIANTS\r\n''')
for last_name in sorted(list(names.keys())):
if len(names[last_name]) > 1:
print("Last name:")
print("\t" + last_name)
first_names = sorted(list(names[last_name]), key=lambda name: (name[0] if len(name) > 0 else '', -len(name)))
print("First name variants:")
for first_name in first_names:
print("\t" + first_name)
print("")
print('Pickling data for list views and timeline...')
pickle_for_list_views()
pickle_docs_by_year()
print('Done!')
def pickle_docs_by_year():
"""
The timeline view shows all documents, grouped into year ranges.
We pickle this here for speed.
"""
documents = (Document.objects.order_by('date').exclude(date=None))
last_year = documents.last().date.year
documents_by_year = {}
documents_by_year["1945-1949"] = []
for i in range(1950, last_year + 1):
documents_by_year[i] = []
for document in documents:
year = document.date.year
if year < 1950:
documents_by_year["1945-1949"].append(document)
else:
documents_by_year[year].append(document)
store_pickle(documents_by_year, 'documents_by_year')
def pickle_for_list_views():
"""
We need a list of people with number of documents authored and received.
However, doing that for each query with the orm is obscenely slow.
The data doesn't change after the update -> just create it on import and
load it when requested.
:return:
"""
person_list = []
for person in Person.objects.annotate(Count('author_person', distinct=True),
Count('recipient_person', distinct=True),
Count('cced_person', distinct=True)):
name = str(person) # Person.__str__ is smart about unknown names
person_list.append({
'name': f'<a href="{person.url}">{name}</a>',
'docs_authored': person.author_person__count,
'docs_received': person.recipient_person__count + person.cced_person__count
})
store_pickle(person_list, 'people_list')
org_list = []
for org in Organization.objects.all():
org_list.append({
'name': f'<a href="{org.url}">{str(org)}</a>',
'docs_authored': org.author_organization.count(),
'docs_received': org.recipient_organization.count() + org.cced_organization.count()
})
store_pickle(org_list, 'organizations_list')
folder_list = []
for folder in Folder.objects.all():
folder_list.append({
'folder_name': f'<a href="{folder.url}">{str(folder)}</a>',
'folder_number': '<a href="{}">Box: {}. Folder: {:02d}</a>'.format(folder.url,
folder.box.number,
folder.number)
})
store_pickle(folder_list, 'folders_list')
def add_one_document(csv_line, aliases_to_full_name_dict, line_no=None, names={}):
"""
Processes one line from a metadata csv file and add it to the database.
Note: This function does not check if the metadata is complete. It is only supposed to be
accessed by populate_from_metadata.
>>> from collections import OrderedDict
>>> csv_line = OrderedDict([('box', '1'), ('folder_number', '1'), ('foldername_short',
... 'committee_on_machine_methods'), ('foldername_full', 'Committee on Machine Methods'),
... ('doc_id', '17'), ('filename', '1_1_committee_on_machine_methods_17'),
... ('author', 'Morse, Philip M.'), ('title', 'Minutes of the Seventeenth...'),
... ('date', '1951-05-16'), ('first_page', '29'), ('last_page', '29'),
... ('metadata_added_by', 'mingfei'), ('doc_type', 'minutes'), ('recipients', 'unknown'),
... ('cced', 'unknown'), ('notes', ''), ('metadata_specialist_notes', '')])
>>> add_one_document(csv_line)
:param csv_line: OrderedDict
:param line_no: int
:param names: dict
:return:
"""
# NOTE(ra): number of pages
number_of_pages = int(csv_line['last_page']) - int(csv_line['first_page']) + 1
file_name = csv_line['filename']
slug = slugify(file_name)
doc_id = csv_line['doc_id']
new_doc = Document(number_of_pages=number_of_pages,
doc_id=doc_id,
title=csv_line['title'],
type=csv_line['doc_type'],
notes=csv_line['notes'],
first_page=csv_line['first_page'], # should this be an int?
last_page=csv_line['last_page'],
file_name=file_name,
slug=slug)
txt_path = get_file_path(box=int(csv_line['box']), folder=int(csv_line['folder_number']),
foldername_short=csv_line['foldername_short'],
doc_id=doc_id, path_type='absolute', file_type='txt')
try:
with open(txt_path, 'r', encoding='utf8') as f:
new_doc.text = f.read()
except FileNotFoundError:
print(f'skipped {txt_path}')
new_doc.text = ''
# Date
if csv_line['date'] != '' and csv_line['date'][0] == '1':
new_doc.date = csv_line['date']
# Folder
box_num = csv_line['box']
new_box, _unused_box_exist = Box.objects.get_or_create(
number=box_num,
slug=slugify(box_num)
)
folder_name = csv_line['foldername_short']
new_folder, folder_exist = Folder.objects.get_or_create(
name=folder_name,
defaults={
'box': new_box,
'number': csv_line['folder_number'],
'full': csv_line['foldername_full'],
},
slug=slugify((box_num, csv_line['folder_number'], folder_name))
)
new_doc.folder = new_folder
# Author, Recipient, cced
# This would be better with create_or_update so that changed values get updated.
# Not super important, though, as flushing the db will also update the values
try:
new_doc.save()
interpret_person_organization(csv_line['author'],
"author_organization",
"author_person",
new_doc,
aliases_to_full_name_dict,
line_no,
names,
)
interpret_person_organization(csv_line['recipients'],
"recipient_organization",
"recipient_person",
new_doc,
aliases_to_full_name_dict,
line_no,
names,
)
interpret_person_organization(csv_line['cced'],
"cced_organization",
"cced_person",
new_doc,
aliases_to_full_name_dict,
line_no,
names,
)
new_doc.save()
except IntegrityError:
pass
def interpret_person_organization(field, item_organization, item_person, new_doc,
aliases_to_full_name_dict, line_no=None, names_so_far={}):
# Adds people and organizations as an author, recipient, or CC'ed.
field_split = [person_or_organization.strip() for person_or_organization in field.split(';')]
for person_or_organization in field_split:
# skip useless / empty values
if person_or_organization in {'', 'none', 'None', 'unknown',
'Multiple', 'copy of above'}:
continue
split_name = person_or_organization.split(',')
# if no comma -> likely organization
if len(split_name) == 1:
org_name = split_name[0]
# spell out ONR for the different offices
org_name = org_name.replace('ONR', 'Office of Naval Research')
new_org, _unused_org_created = Organization.objects.get_or_create(
name=org_name,
slug=slugify(org_name)
)
bound_attr = getattr(new_doc, item_organization)
bound_attr.add(new_org)
# else: likely a person
else:
# check for commas
if len(split_name) > 2:
print("There seem to be too many commas in this name", split_name, "in line",
line_no)
else:
last_name, first_name = aliases_to_full_name_dict[person_or_organization].split(',')
if last_name == 'unknown':
last_name = ''
if first_name == 'unknown':
first_name = ''
# # add first name, last name pair to names
if last_name != '':
# unfixed_first_name = split_name[1].strip()
if last_name not in names_so_far:
names_so_far[last_name] = {first_name}
else:
names_so_far[last_name].add(first_name)
new_person, _unused_person_created = Person.objects.get_or_create(
last=last_name,
first=first_name,
slug=slugify((first_name, last_name))
)
bound_attr = getattr(new_doc, item_person)
bound_attr.add(new_person)
def network_json(output_path=None):
"""
Writes a JSON file to /static/json (or otherwise specified location) listing the nodes,
edges, and weights of each person in the network
:param output_path:
:return:
"""
from collections import Counter
from pathlib import Path, PurePath
import json
if output_path is None:
output_path = Path('static', 'json', 'network.json')
docs = Document.objects.prefetch_related('author_person', 'recipient_person')
node_count = Counter()
edge_count = Counter()
slugs = dict()
# Count instances of each author/recipient
for document in docs:
authors = document.author_person.all()
recipients = document.recipient_person.all()
for author in authors:
node_count[str(author)] += 1
if str(author) not in slugs:
slugs[str(author)] = author.slug
for recipient in recipients:
node_count[str(recipient)] += 1
edge_count[(str(author), str(recipient))] += 1
if str(recipient) not in slugs:
slugs[str(recipient)] = recipient.slug
edge_list = list()
for letter in edge_count:
edge_list.append({
'source': letter[0],
'target': letter[1],
'value': edge_count[letter]
})
node_list = list()
for author in node_count:
node_list.append({
'id': author,
'weight': node_count[author],
'slug': slugs[author]
})
graph_dict = {'nodes': node_list, 'links': edge_list}
output_path.write_text(json.dumps(graph_dict))
| 37.820449 | 121 | 0.563695 |
100be64037649a65bb6c9eb4b03ea416f17ee7a1 | 5,665 | py | Python | ssd1306.py | Fliens/Mini-Gas-Pump | 50b28f888d00a978c9d12082d44c7b7e7ce561c7 | [
"CC0-1.0"
] | null | null | null | ssd1306.py | Fliens/Mini-Gas-Pump | 50b28f888d00a978c9d12082d44c7b7e7ce561c7 | [
"CC0-1.0"
] | null | null | null | ssd1306.py | Fliens/Mini-Gas-Pump | 50b28f888d00a978c9d12082d44c7b7e7ce561c7 | [
"CC0-1.0"
] | null | null | null | #MicroPython SSD1306 OLED driver, I2C and SPI interfaces created by Adafruit
import time
import framebuf
# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xa4)
SET_NORM_INV = const(0xa6)
SET_DISP = const(0xae)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xa0)
SET_MUX_RATIO = const(0xa8)
SET_COM_OUT_DIR = const(0xc0)
SET_DISP_OFFSET = const(0xd3)
SET_COM_PIN_CFG = const(0xda)
SET_DISP_CLK_DIV = const(0xd5)
SET_PRECHARGE = const(0xd9)
SET_VCOM_DESEL = const(0xdb)
SET_CHARGE_PUMP = const(0x8d)
class SSD1306:
def __init__(self, width, height, external_vcc):
self.width = width
self.height = height
self.external_vcc = external_vcc
self.pages = self.height // 8
# Note the subclass must initialize self.framebuf to a framebuffer.
# This is necessary because the underlying data buffer is different
# between I2C and SPI implementations (I2C needs an extra byte).
self.poweron()
self.init_display()
def init_display(self):
for cmd in (
SET_DISP | 0x00, # off
# address setting
SET_MEM_ADDR, 0x00, # horizontal
# resolution and layout
SET_DISP_START_LINE | 0x00,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO, self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET, 0x00,
SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12,
# timing and driving scheme
SET_DISP_CLK_DIV, 0x80,
SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1,
SET_VCOM_DESEL, 0x30, # 0.83*Vcc
# display
SET_CONTRAST, 0xff, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
# charge pump
SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01): # on
self.write_cmd(cmd)
self.fill(0)
self.show()
def poweroff(self):
self.write_cmd(SET_DISP | 0x00)
def contrast(self, contrast):
self.write_cmd(SET_CONTRAST)
self.write_cmd(contrast)
def invert(self, invert):
self.write_cmd(SET_NORM_INV | (invert & 1))
def show(self):
x0 = 0
x1 = self.width - 1
if self.width == 64:
# displays with width of 64 pixels are shifted by 32
x0 += 32
x1 += 32
self.write_cmd(SET_COL_ADDR)
self.write_cmd(x0)
self.write_cmd(x1)
self.write_cmd(SET_PAGE_ADDR)
self.write_cmd(0)
self.write_cmd(self.pages - 1)
self.write_framebuf()
def fill(self, col):
self.framebuf.fill(col)
def pixel(self, x, y, col):
self.framebuf.pixel(x, y, col)
def scroll(self, dx, dy):
self.framebuf.scroll(dx, dy)
def text(self, string, x, y, col=1):
self.framebuf.text(str(string), x, y, col)
class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False):
self.i2c = i2c
self.addr = addr
self.temp = bytearray(2)
# Add an extra byte to the data buffer to hold an I2C data/command byte
# to use hardware-compatible I2C transactions. A memoryview of the
# buffer is used to mask this byte from the framebuffer operations
# (without a major memory hit as memoryview doesn't copy to a separate
# buffer).
self.buffer = bytearray(((height // 8) * width) + 1)
self.buffer[0] = 0x40 # Set first byte of data buffer to Co=0, D/C=1
self.framebuf = framebuf.FrameBuffer1(memoryview(self.buffer)[1:], width, height)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[1] = cmd
self.i2c.writeto(self.addr, self.temp)
def write_framebuf(self):
# Blast out the frame buffer using a single I2C transaction to support
# hardware I2C interfaces.
self.i2c.writeto(self.addr, self.buffer)
def poweron(self):
pass
class SSD1306_SPI(SSD1306):
def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
self.rate = 10 * 1024 * 1024
dc.init(dc.OUT, value=0)
res.init(res.OUT, value=0)
cs.init(cs.OUT, value=1)
self.spi = spi
self.dc = dc
self.res = res
self.cs = cs
self.buffer = bytearray((height // 8) * width)
self.framebuf = framebuf.FrameBuffer1(self.buffer, width, height)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs.high()
self.dc.low()
self.cs.low()
self.spi.write(bytearray([cmd]))
self.cs.high()
def write_framebuf(self):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs.high()
self.dc.high()
self.cs.low()
self.spi.write(self.buffer)
self.cs.high()
def poweron(self):
self.res.high()
time.sleep_ms(1)
self.res.low()
time.sleep_ms(10)
self.res.high() | 33.922156 | 90 | 0.584996 |
17de562a4ff8394ed60027932c1112e493b1b49e | 24,112 | py | Python | keystone/federation/idp.py | ISCAS-VDI/keystone | 11af181c06d78026c89a873f62931558e80f3192 | [
"Apache-2.0"
] | null | null | null | keystone/federation/idp.py | ISCAS-VDI/keystone | 11af181c06d78026c89a873f62931558e80f3192 | [
"Apache-2.0"
] | null | null | null | keystone/federation/idp.py | ISCAS-VDI/keystone | 11af181c06d78026c89a873f62931558e80f3192 | [
"Apache-2.0"
] | null | null | null | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import datetime
import os
import subprocess # nosec : see comments in the code below
import uuid
from oslo_config import cfg
from oslo_log import log
from oslo_utils import fileutils
from oslo_utils import importutils
from oslo_utils import timeutils
import saml2
from saml2 import client_base
from saml2 import md
from saml2.profile import ecp
from saml2 import saml
from saml2 import samlp
from saml2.schema import soapenv
from saml2 import sigver
xmldsig = importutils.try_import("saml2.xmldsig")
if not xmldsig:
xmldsig = importutils.try_import("xmldsig")
from keystone.common import utils
from keystone import exception
from keystone.i18n import _, _LE
LOG = log.getLogger(__name__)
CONF = cfg.CONF
class SAMLGenerator(object):
"""A class to generate SAML assertions."""
def __init__(self):
self.assertion_id = uuid.uuid4().hex
def samlize_token(self, issuer, recipient, user, user_domain_name, roles,
project, project_domain_name, expires_in=None):
"""Convert Keystone attributes to a SAML assertion.
:param issuer: URL of the issuing party
:type issuer: string
:param recipient: URL of the recipient
:type recipient: string
:param user: User name
:type user: string
:param user_domain_name: User Domain name
:type user_domain_name: string
:param roles: List of role names
:type roles: list
:param project: Project name
:type project: string
:param project_domain_name: Project Domain name
:type project_domain_name: string
:param expires_in: Sets how long the assertion is valid for, in seconds
:type expires_in: int
:returns: XML <Response> object
"""
expiration_time = self._determine_expiration_time(expires_in)
status = self._create_status()
saml_issuer = self._create_issuer(issuer)
subject = self._create_subject(user, expiration_time, recipient)
attribute_statement = self._create_attribute_statement(
user, user_domain_name, roles, project, project_domain_name)
authn_statement = self._create_authn_statement(issuer, expiration_time)
signature = self._create_signature()
assertion = self._create_assertion(saml_issuer, signature,
subject, authn_statement,
attribute_statement)
assertion = _sign_assertion(assertion)
response = self._create_response(saml_issuer, status, assertion,
recipient)
return response
def _determine_expiration_time(self, expires_in):
if expires_in is None:
expires_in = CONF.saml.assertion_expiration_time
now = timeutils.utcnow()
future = now + datetime.timedelta(seconds=expires_in)
return utils.isotime(future, subsecond=True)
def _create_status(self):
"""Create an object that represents a SAML Status.
<ns0:Status xmlns:ns0="urn:oasis:names:tc:SAML:2.0:protocol">
<ns0:StatusCode
Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</ns0:Status>
:returns: XML <Status> object
"""
status = samlp.Status()
status_code = samlp.StatusCode()
status_code.value = samlp.STATUS_SUCCESS
status_code.set_text('')
status.status_code = status_code
return status
def _create_issuer(self, issuer_url):
"""Create an object that represents a SAML Issuer.
<ns0:Issuer
xmlns:ns0="urn:oasis:names:tc:SAML:2.0:assertion"
Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">
https://acme.com/FIM/sps/openstack/saml20</ns0:Issuer>
:returns: XML <Issuer> object
"""
issuer = saml.Issuer()
issuer.format = saml.NAMEID_FORMAT_ENTITY
issuer.set_text(issuer_url)
return issuer
def _create_subject(self, user, expiration_time, recipient):
"""Create an object that represents a SAML Subject.
<ns0:Subject>
<ns0:NameID>
[email protected]</ns0:NameID>
<ns0:SubjectConfirmation
Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<ns0:SubjectConfirmationData
NotOnOrAfter="2014-08-19T11:53:57.243106Z"
Recipient="http://beta.com/Shibboleth.sso/SAML2/POST" />
</ns0:SubjectConfirmation>
</ns0:Subject>
:returns: XML <Subject> object
"""
name_id = saml.NameID()
name_id.set_text(user)
subject_conf_data = saml.SubjectConfirmationData()
subject_conf_data.recipient = recipient
subject_conf_data.not_on_or_after = expiration_time
subject_conf = saml.SubjectConfirmation()
subject_conf.method = saml.SCM_BEARER
subject_conf.subject_confirmation_data = subject_conf_data
subject = saml.Subject()
subject.subject_confirmation = subject_conf
subject.name_id = name_id
return subject
def _create_attribute_statement(self, user, user_domain_name, roles,
project, project_domain_name):
"""Create an object that represents a SAML AttributeStatement.
<ns0:AttributeStatement>
<ns0:Attribute Name="openstack_user">
<ns0:AttributeValue
xsi:type="xs:string">test_user</ns0:AttributeValue>
</ns0:Attribute>
<ns0:Attribute Name="openstack_user_domain">
<ns0:AttributeValue
xsi:type="xs:string">Default</ns0:AttributeValue>
</ns0:Attribute>
<ns0:Attribute Name="openstack_roles">
<ns0:AttributeValue
xsi:type="xs:string">admin</ns0:AttributeValue>
<ns0:AttributeValue
xsi:type="xs:string">member</ns0:AttributeValue>
</ns0:Attribute>
<ns0:Attribute Name="openstack_project">
<ns0:AttributeValue
xsi:type="xs:string">development</ns0:AttributeValue>
</ns0:Attribute>
<ns0:Attribute Name="openstack_project_domain">
<ns0:AttributeValue
xsi:type="xs:string">Default</ns0:AttributeValue>
</ns0:Attribute>
</ns0:AttributeStatement>
:returns: XML <AttributeStatement> object
"""
def _build_attribute(attribute_name, attribute_values):
attribute = saml.Attribute()
attribute.name = attribute_name
for value in attribute_values:
attribute_value = saml.AttributeValue()
attribute_value.set_text(value)
attribute.attribute_value.append(attribute_value)
return attribute
user_attribute = _build_attribute('openstack_user', [user])
roles_attribute = _build_attribute('openstack_roles', roles)
project_attribute = _build_attribute('openstack_project', [project])
project_domain_attribute = _build_attribute(
'openstack_project_domain', [project_domain_name])
user_domain_attribute = _build_attribute(
'openstack_user_domain', [user_domain_name])
attribute_statement = saml.AttributeStatement()
attribute_statement.attribute.append(user_attribute)
attribute_statement.attribute.append(roles_attribute)
attribute_statement.attribute.append(project_attribute)
attribute_statement.attribute.append(project_domain_attribute)
attribute_statement.attribute.append(user_domain_attribute)
return attribute_statement
def _create_authn_statement(self, issuer, expiration_time):
"""Create an object that represents a SAML AuthnStatement.
<ns0:AuthnStatement xmlns:ns0="urn:oasis:names:tc:SAML:2.0:assertion"
AuthnInstant="2014-07-30T03:04:25Z" SessionIndex="47335964efb"
SessionNotOnOrAfter="2014-07-30T03:04:26Z">
<ns0:AuthnContext>
<ns0:AuthnContextClassRef>
urn:oasis:names:tc:SAML:2.0:ac:classes:Password
</ns0:AuthnContextClassRef>
<ns0:AuthenticatingAuthority>
https://acme.com/FIM/sps/openstack/saml20
</ns0:AuthenticatingAuthority>
</ns0:AuthnContext>
</ns0:AuthnStatement>
:returns: XML <AuthnStatement> object
"""
authn_statement = saml.AuthnStatement()
authn_statement.authn_instant = utils.isotime()
authn_statement.session_index = uuid.uuid4().hex
authn_statement.session_not_on_or_after = expiration_time
authn_context = saml.AuthnContext()
authn_context_class = saml.AuthnContextClassRef()
authn_context_class.set_text(saml.AUTHN_PASSWORD)
authn_authority = saml.AuthenticatingAuthority()
authn_authority.set_text(issuer)
authn_context.authn_context_class_ref = authn_context_class
authn_context.authenticating_authority = authn_authority
authn_statement.authn_context = authn_context
return authn_statement
def _create_assertion(self, issuer, signature, subject, authn_statement,
attribute_statement):
"""Create an object that represents a SAML Assertion.
<ns0:Assertion
ID="35daed258ba647ba8962e9baff4d6a46"
IssueInstant="2014-06-11T15:45:58Z"
Version="2.0">
<ns0:Issuer> ... </ns0:Issuer>
<ns1:Signature> ... </ns1:Signature>
<ns0:Subject> ... </ns0:Subject>
<ns0:AuthnStatement> ... </ns0:AuthnStatement>
<ns0:AttributeStatement> ... </ns0:AttributeStatement>
</ns0:Assertion>
:returns: XML <Assertion> object
"""
assertion = saml.Assertion()
assertion.id = self.assertion_id
assertion.issue_instant = utils.isotime()
assertion.version = '2.0'
assertion.issuer = issuer
assertion.signature = signature
assertion.subject = subject
assertion.authn_statement = authn_statement
assertion.attribute_statement = attribute_statement
return assertion
def _create_response(self, issuer, status, assertion, recipient):
"""Create an object that represents a SAML Response.
<ns0:Response
Destination="http://beta.com/Shibboleth.sso/SAML2/POST"
ID="c5954543230e4e778bc5b92923a0512d"
IssueInstant="2014-07-30T03:19:45Z"
Version="2.0" />
<ns0:Issuer> ... </ns0:Issuer>
<ns0:Assertion> ... </ns0:Assertion>
<ns0:Status> ... </ns0:Status>
</ns0:Response>
:returns: XML <Response> object
"""
response = samlp.Response()
response.id = uuid.uuid4().hex
response.destination = recipient
response.issue_instant = utils.isotime()
response.version = '2.0'
response.issuer = issuer
response.status = status
response.assertion = assertion
return response
def _create_signature(self):
"""Create an object that represents a SAML <Signature>.
This must be filled with algorithms that the signing binary will apply
in order to sign the whole message.
Currently we enforce X509 signing.
Example of the template::
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod
Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<SignatureMethod
Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#<Assertion ID>">
<Transforms>
<Transform
Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue />
</Reference>
</SignedInfo>
<SignatureValue />
<KeyInfo>
<X509Data />
</KeyInfo>
</Signature>
:returns: XML <Signature> object
"""
canonicalization_method = xmldsig.CanonicalizationMethod()
canonicalization_method.algorithm = xmldsig.ALG_EXC_C14N
signature_method = xmldsig.SignatureMethod(
algorithm=xmldsig.SIG_RSA_SHA1)
transforms = xmldsig.Transforms()
envelope_transform = xmldsig.Transform(
algorithm=xmldsig.TRANSFORM_ENVELOPED)
c14_transform = xmldsig.Transform(algorithm=xmldsig.ALG_EXC_C14N)
transforms.transform = [envelope_transform, c14_transform]
digest_method = xmldsig.DigestMethod(algorithm=xmldsig.DIGEST_SHA1)
digest_value = xmldsig.DigestValue()
reference = xmldsig.Reference()
reference.uri = '#' + self.assertion_id
reference.digest_method = digest_method
reference.digest_value = digest_value
reference.transforms = transforms
signed_info = xmldsig.SignedInfo()
signed_info.canonicalization_method = canonicalization_method
signed_info.signature_method = signature_method
signed_info.reference = reference
key_info = xmldsig.KeyInfo()
key_info.x509_data = xmldsig.X509Data()
signature = xmldsig.Signature()
signature.signed_info = signed_info
signature.signature_value = xmldsig.SignatureValue()
signature.key_info = key_info
return signature
def _sign_assertion(assertion):
"""Sign a SAML assertion.
This method utilizes ``xmlsec1`` binary and signs SAML assertions in a
separate process. ``xmlsec1`` cannot read input data from stdin so the
prepared assertion needs to be serialized and stored in a temporary
file. This file will be deleted immediately after ``xmlsec1`` returns.
The signed assertion is redirected to a standard output and read using
subprocess.PIPE redirection. A ``saml.Assertion`` class is created
from the signed string again and returned.
Parameters that are required in the CONF::
* xmlsec_binary
* private key file path
* public key file path
:returns: XML <Assertion> object
"""
xmlsec_binary = CONF.saml.xmlsec1_binary
idp_private_key = CONF.saml.keyfile
idp_public_key = CONF.saml.certfile
# xmlsec1 --sign --privkey-pem privkey,cert --id-attr:ID <tag> <file>
certificates = '%(idp_private_key)s,%(idp_public_key)s' % {
'idp_public_key': idp_public_key,
'idp_private_key': idp_private_key
}
command_list = [xmlsec_binary, '--sign', '--privkey-pem', certificates,
'--id-attr:ID', 'Assertion']
file_path = None
try:
# NOTE(gyee): need to make the namespace prefixes explicit so
# they won't get reassigned when we wrap the assertion into
# SAML2 response
file_path = fileutils.write_to_tempfile(assertion.to_string(
nspair={'saml': saml2.NAMESPACE,
'xmldsig': xmldsig.NAMESPACE}))
command_list.append(file_path)
stdout = subprocess.check_output(command_list, # nosec : The contents
# of the command list are coming from
# a trusted source because the
# executable and arguments all either
# come from the config file or are
# hardcoded. The command list is
# initialized earlier in this function
# to a list and it's still a list at
# this point in the function. There is
# no opportunity for an attacker to
# attempt command injection via string
# parsing.
stderr=subprocess.STDOUT)
except Exception as e:
msg = _LE('Error when signing assertion, reason: %(reason)s%(output)s')
LOG.error(msg,
{'reason': e,
'output': ' ' + e.output if hasattr(e, 'output') else ''})
raise exception.SAMLSigningError(reason=e)
finally:
try:
if file_path:
os.remove(file_path)
except OSError: # nosec
# The file is already gone, good.
pass
return saml2.create_class_from_xml_string(saml.Assertion, stdout)
class MetadataGenerator(object):
"""A class for generating SAML IdP Metadata."""
def generate_metadata(self):
"""Generate Identity Provider Metadata.
Generate and format metadata into XML that can be exposed and
consumed by a federated Service Provider.
:returns: XML <EntityDescriptor> object.
:raises keystone.exception.ValidationError: If the required
config options aren't set.
"""
self._ensure_required_values_present()
entity_descriptor = self._create_entity_descriptor()
entity_descriptor.idpsso_descriptor = (
self._create_idp_sso_descriptor())
return entity_descriptor
def _create_entity_descriptor(self):
ed = md.EntityDescriptor()
ed.entity_id = CONF.saml.idp_entity_id
return ed
def _create_idp_sso_descriptor(self):
def get_cert():
try:
return sigver.read_cert_from_file(CONF.saml.certfile, 'pem')
except (IOError, sigver.CertificateError) as e:
msg = _('Cannot open certificate %(cert_file)s. '
'Reason: %(reason)s')
msg = msg % {'cert_file': CONF.saml.certfile, 'reason': e}
LOG.error(msg)
raise IOError(msg)
def key_descriptor():
cert = get_cert()
return md.KeyDescriptor(
key_info=xmldsig.KeyInfo(
x509_data=xmldsig.X509Data(
x509_certificate=xmldsig.X509Certificate(text=cert)
)
), use='signing'
)
def single_sign_on_service():
idp_sso_endpoint = CONF.saml.idp_sso_endpoint
return md.SingleSignOnService(
binding=saml2.BINDING_URI,
location=idp_sso_endpoint)
def organization():
name = md.OrganizationName(lang=CONF.saml.idp_lang,
text=CONF.saml.idp_organization_name)
display_name = md.OrganizationDisplayName(
lang=CONF.saml.idp_lang,
text=CONF.saml.idp_organization_display_name)
url = md.OrganizationURL(lang=CONF.saml.idp_lang,
text=CONF.saml.idp_organization_url)
return md.Organization(
organization_display_name=display_name,
organization_url=url, organization_name=name)
def contact_person():
company = md.Company(text=CONF.saml.idp_contact_company)
given_name = md.GivenName(text=CONF.saml.idp_contact_name)
surname = md.SurName(text=CONF.saml.idp_contact_surname)
email = md.EmailAddress(text=CONF.saml.idp_contact_email)
telephone = md.TelephoneNumber(
text=CONF.saml.idp_contact_telephone)
contact_type = CONF.saml.idp_contact_type
return md.ContactPerson(
company=company, given_name=given_name, sur_name=surname,
email_address=email, telephone_number=telephone,
contact_type=contact_type)
def name_id_format():
return md.NameIDFormat(text=saml.NAMEID_FORMAT_TRANSIENT)
idpsso = md.IDPSSODescriptor()
idpsso.protocol_support_enumeration = samlp.NAMESPACE
idpsso.key_descriptor = key_descriptor()
idpsso.single_sign_on_service = single_sign_on_service()
idpsso.name_id_format = name_id_format()
if self._check_organization_values():
idpsso.organization = organization()
if self._check_contact_person_values():
idpsso.contact_person = contact_person()
return idpsso
def _ensure_required_values_present(self):
"""Ensure idp_sso_endpoint and idp_entity_id have values."""
if CONF.saml.idp_entity_id is None:
msg = _('Ensure configuration option idp_entity_id is set.')
raise exception.ValidationError(msg)
if CONF.saml.idp_sso_endpoint is None:
msg = _('Ensure configuration option idp_sso_endpoint is set.')
raise exception.ValidationError(msg)
def _check_contact_person_values(self):
"""Determine if contact information is included in metadata."""
# Check if we should include contact information
params = [CONF.saml.idp_contact_company,
CONF.saml.idp_contact_name,
CONF.saml.idp_contact_surname,
CONF.saml.idp_contact_email,
CONF.saml.idp_contact_telephone]
for value in params:
if value is None:
return False
# Check if contact type is an invalid value
valid_type_values = ['technical', 'other', 'support', 'administrative',
'billing']
if CONF.saml.idp_contact_type not in valid_type_values:
msg = _('idp_contact_type must be one of: [technical, other, '
'support, administrative or billing.')
raise exception.ValidationError(msg)
return True
def _check_organization_values(self):
"""Determine if organization information is included in metadata."""
params = [CONF.saml.idp_organization_name,
CONF.saml.idp_organization_display_name,
CONF.saml.idp_organization_url]
for value in params:
if value is None:
return False
return True
class ECPGenerator(object):
"""A class for generating an ECP assertion."""
@staticmethod
def generate_ecp(saml_assertion, relay_state_prefix):
ecp_generator = ECPGenerator()
header = ecp_generator._create_header(relay_state_prefix)
body = ecp_generator._create_body(saml_assertion)
envelope = soapenv.Envelope(header=header, body=body)
return envelope
def _create_header(self, relay_state_prefix):
relay_state_text = relay_state_prefix + uuid.uuid4().hex
relay_state = ecp.RelayState(actor=client_base.ACTOR,
must_understand='1',
text=relay_state_text)
header = soapenv.Header()
header.extension_elements = (
[saml2.element_to_extension_element(relay_state)])
return header
def _create_body(self, saml_assertion):
body = soapenv.Body()
body.extension_elements = (
[saml2.element_to_extension_element(saml_assertion)])
return body
| 39.206504 | 79 | 0.626535 |
0c94a9335846c609e72b2cda62723576c7b102b2 | 2,357 | py | Python | Phrasers/macphraser.py | kyan001/UserDefinedPhraser | b2148101f48da805e459d7780c74c370184fda42 | [
"MIT"
] | 4 | 2020-10-22T00:25:08.000Z | 2021-12-16T08:55:38.000Z | Phrasers/macphraser.py | kyan001/UserDefinedPhraser | b2148101f48da805e459d7780c74c370184fda42 | [
"MIT"
] | null | null | null | Phrasers/macphraser.py | kyan001/UserDefinedPhraser | b2148101f48da805e459d7780c74c370184fda42 | [
"MIT"
] | 2 | 2021-05-17T13:24:09.000Z | 2021-06-26T04:10:56.000Z | import os
from bs4 import BeautifulSoup
from bs4 import Doctype
from .phraser import Phraser
class MacPhraser(Phraser):
def from_file(self, filepath: str):
""" Read file into objects."""
if not filepath:
raise Exception("No filepath provided")
with open(filepath, encoding='utf8') as f:
plist_str = f.read()
self.from_plist(plist_str)
def to_file(self, filepath: str):
if not filepath:
raise Exception("No filepath provided")
if os.path.exists(filepath):
raise Exception("File '{}' already exists!".format(filepath))
with open(filepath, 'w', encoding='utf8') as f:
f.write(self.to_plist())
def from_plist(self, plist_str: str):
soup = BeautifulSoup(plist_str, 'xml')
for dct in soup.find_all('dict'):
phrase = dct.find_all('string')[0].string
shortcut = dct.find_all('string')[1].string
self.phrases.append({'phrase': phrase, 'shortcut': shortcut})
def to_plist(self):
def prettify(soup):
return str(soup).replace("<array>", "\n <array>").replace("<dict>", "\n <dict>").replace("<key>", "\n <key>").replace("<string>", "\n <string>").replace("</dict>", "\n </dict>").replace("</array>", "\n </array>").replace("</plist>", "\n</plist>")
soup = BeautifulSoup('', 'xml')
doctype = Doctype('plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"')
soup.append(doctype)
soup.append(soup.new_tag('plist', version="1.0"))
soup.plist.append(soup.new_tag('array'))
for itm in self.phrases:
dct = soup.new_tag('dict')
phrase_key = soup.new_tag('key')
phrase_key.string = "phrase"
phrase_string = soup.new_tag('string')
phrase_string.string = itm['phrase']
shortcut_key = soup.new_tag('key')
shortcut_key.string = "shortcut"
shortcut_string = soup.new_tag('string')
shortcut_string.string = itm['shortcut']
dct.append(phrase_key)
dct.append(phrase_string)
dct.append(shortcut_key)
dct.append(shortcut_string)
soup.array.append(dct)
return prettify(soup)
| 41.350877 | 300 | 0.576156 |
858cf3b9f92aa1c289a7b1cfe48ead01be7a558f | 879 | py | Python | ListShuffler.py | Sonophoto/PythonNotes | a6f04ce9967dfb508953e270f1241424aebacc43 | [
"BSD-2-Clause"
] | null | null | null | ListShuffler.py | Sonophoto/PythonNotes | a6f04ce9967dfb508953e270f1241424aebacc43 | [
"BSD-2-Clause"
] | null | null | null | ListShuffler.py | Sonophoto/PythonNotes | a6f04ce9967dfb508953e270f1241424aebacc43 | [
"BSD-2-Clause"
] | null | null | null | #!/usr/bin/env python3
"""
Create a random distribution of nibbles with exactly
4 of each of the 16 possible values and output as a
comma delimited string
Implementation (c) 2017 Brig Young (github.com/Sonophoto)
License: BSD-2c, i.e. Cite.
"""
import random as shuffler
shufflee = [
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
]
shuffler.shuffle(shufflee)
shuffled_hex = ", ".join(str(hex(x)) for x in shufflee)
print(shuffled_hex, "\n")
| 32.555556 | 59 | 0.624573 |
c0c9d643c06980758fde7ddb898013fdf8da4543 | 2,056 | py | Python | tests/conftest.py | obestwalter/loslassa | 2127479cb8075a01fd12fe8b8a3f7820e14758d3 | [
"BSD-3-Clause"
] | null | null | null | tests/conftest.py | obestwalter/loslassa | 2127479cb8075a01fd12fe8b8a3f7820e14758d3 | [
"BSD-3-Clause"
] | 5 | 2016-04-26T16:29:20.000Z | 2016-04-26T16:29:59.000Z | tests/conftest.py | obestwalter/loslassa | 2127479cb8075a01fd12fe8b8a3f7820e14758d3 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import print_function
from contextlib import contextmanager
from plumbum.machines.local import local
import pytest
from loslassa._loslassa import LoslassaProject
@pytest.fixture
def work_in_example_project(request):
"""Change into example project and back on exit"""
return chdir_in_and_out(request, LoslassaProject.EXAMPLE_PROJECT)
@pytest.fixture
def work_in_empty_tmpdir(request, tmpdir):
"""Change into empty tmpdir and back on exit"""
return chdir_in_and_out(request, tmpdir)
def create_dummy_projects(path, numProjects=1):
"""create minimal projects with generic names
:returns: paths of the created projects
"""
assert path.exists()
with pytest.raises(StopIteration):
next(path.walk())
projectPaths = []
for idx in range(numProjects):
name = "dummy_project_%s" % (idx)
root = path / name
dummyProject = LoslassaProject(root)
dummyProject.create_project()
return projectPaths
# noinspection PyUnusedLocal
@pytest.fixture
def work_in_dummy_project(work_in_empty_tmpdir):
return create_dummy_projects(local.cwd)
@contextmanager
def assert_exc_contains(exc, content):
"""check if exception of type `exc` is raised with content
:param exc: Exception type
:param content: content that should be part of the exception message
:type content: str or list
"""
try:
yield
except Exception as e:
assert type(e) == exc
message = e.args[0] # warning might not always work
if isinstance(content, str):
assert content in message
else:
assert all(m in message for m in content)
else:
raise Exception("Did not raise %s with %s" % (exc, content))
def chdir_in_and_out(request, path):
"""change into path and change back on exit"""
oldWorkDirStr = str(local.cwd)
workDir = local.cwd
workDir.chdir(path)
request.addfinalizer(lambda: workDir.chdir(oldWorkDirStr))
return type("", (), {"oldWorkDirStr": oldWorkDirStr})
| 28.164384 | 72 | 0.699903 |
cf02e979b442072556db2ae99d019a0be8445020 | 1,712 | py | Python | contrib/rtl_433_mqtt/mqtt.py | pferreir/clima-sensors | d4e7b158d2c5f7ef2ceb2742181a1a5b22aacd34 | [
"MIT"
] | 1 | 2021-11-15T15:02:31.000Z | 2021-11-15T15:02:31.000Z | contrib/rtl_433_mqtt/mqtt.py | pferreir/clima-sensors | d4e7b158d2c5f7ef2ceb2742181a1a5b22aacd34 | [
"MIT"
] | null | null | null | contrib/rtl_433_mqtt/mqtt.py | pferreir/clima-sensors | d4e7b158d2c5f7ef2ceb2742181a1a5b22aacd34 | [
"MIT"
] | null | null | null | import re
import sys
import json
import click
from paho.mqtt import client as mqtt
KLIMALOGG_MAP = {
30180: 'office',
31223: 'bedroom',
31850: 'andres-room'
}
RADIOHEAD_MAP = {
237: ('living-room', 'temperature'),
238: ('living-room', 'humidity'),
239: ('living-room', 'co2')
}
def handle_klimalogg(data):
m = re.match(r'^([\d\.]+) C$', data['temperature_C'])
sensor_id = data['id']
room = KLIMALOGG_MAP[sensor_id]
yield (room, 'temperature', m.group(1))
yield (room, 'humidity', str(data['humidity']))
def handle_radiohead(data):
pl = data['payload']
(room, measure) = RADIOHEAD_MAP[data['id']]
val = pl[1] * 256 + pl[0]
if measure == 'temperature':
val /= 100
yield (room, measure, str(val))
def iter_stdin():
for line in sys.stdin:
data = json.loads(line)
model = data.get('model')
if model is None:
continue
if model.startswith('Klima'):
yield from handle_klimalogg(data)
else:
yield from handle_radiohead(data)
@click.command()
@click.argument("host")
@click.option("--port", default=1883)
@click.option("--username")
@click.option("--password")
def main(host, port, username, password):
client = mqtt.Client()
if username and password:
client.username_pw_set(username, password)
client.connect(host, port=port)
client.loop_start()
for (room, sensor, value) in iter_stdin():
(err, mid) = client.publish(f"home/sensors/{room}/{sensor}", value, qos=1)
if err != mqtt.MQTT_ERR_SUCCESS:
print(mqtt.error_string(err))
# send msg
if __name__ == '__main__':
main()
| 21.948718 | 82 | 0.60514 |
8717fa5367459c0639332f395daf0b309a6c827f | 52,474 | py | Python | sdk/powerbidedicated/azure-mgmt-powerbidedicated/azure/mgmt/powerbidedicated/aio/operations/_capacities_operations.py | mohamedshabanofficial/azure-sdk-for-python | 81c585f310cd2ec23d2ad145173958914a075a58 | [
"MIT"
] | 2 | 2019-08-23T21:14:00.000Z | 2021-09-07T18:32:34.000Z | sdk/powerbidedicated/azure-mgmt-powerbidedicated/azure/mgmt/powerbidedicated/aio/operations/_capacities_operations.py | mohamedshabanofficial/azure-sdk-for-python | 81c585f310cd2ec23d2ad145173958914a075a58 | [
"MIT"
] | 2 | 2021-11-03T06:10:36.000Z | 2021-12-01T06:29:39.000Z | sdk/powerbidedicated/azure-mgmt-powerbidedicated/azure/mgmt/powerbidedicated/aio/operations/_capacities_operations.py | mohamedshabanofficial/azure-sdk-for-python | 81c585f310cd2ec23d2ad145173958914a075a58 | [
"MIT"
] | 1 | 2021-05-19T02:55:10.000Z | 2021-05-19T02:55:10.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class CapacitiesOperations:
"""CapacitiesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.powerbidedicated.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def get_details(
self,
resource_group_name: str,
dedicated_capacity_name: str,
**kwargs
) -> "_models.DedicatedCapacity":
"""Gets details about the specified dedicated capacity.
:param resource_group_name: The name of the Azure Resource group of which a given
PowerBIDedicated capacity is part. This name must be at least 1 character in length, and no
more than 90.
:type resource_group_name: str
:param dedicated_capacity_name: The name of the dedicated capacity. It must be a minimum of 3
characters, and a maximum of 63.
:type dedicated_capacity_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: DedicatedCapacity, or the result of cls(response)
:rtype: ~azure.mgmt.powerbidedicated.models.DedicatedCapacity
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.DedicatedCapacity"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
accept = "application/json"
# Construct URL
url = self.get_details.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('DedicatedCapacity', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_details.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}'} # type: ignore
async def _create_initial(
self,
resource_group_name: str,
dedicated_capacity_name: str,
capacity_parameters: "_models.DedicatedCapacity",
**kwargs
) -> "_models.DedicatedCapacity":
cls = kwargs.pop('cls', None) # type: ClsType["_models.DedicatedCapacity"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(capacity_parameters, 'DedicatedCapacity')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('DedicatedCapacity', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('DedicatedCapacity', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}'} # type: ignore
async def begin_create(
self,
resource_group_name: str,
dedicated_capacity_name: str,
capacity_parameters: "_models.DedicatedCapacity",
**kwargs
) -> AsyncLROPoller["_models.DedicatedCapacity"]:
"""Provisions the specified Dedicated capacity based on the configuration specified in the
request.
:param resource_group_name: The name of the Azure Resource group of which a given
PowerBIDedicated capacity is part. This name must be at least 1 character in length, and no
more than 90.
:type resource_group_name: str
:param dedicated_capacity_name: The name of the Dedicated capacity. It must be a minimum of 3
characters, and a maximum of 63.
:type dedicated_capacity_name: str
:param capacity_parameters: Contains the information used to provision the Dedicated capacity.
:type capacity_parameters: ~azure.mgmt.powerbidedicated.models.DedicatedCapacity
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either DedicatedCapacity or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.powerbidedicated.models.DedicatedCapacity]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.DedicatedCapacity"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_initial(
resource_group_name=resource_group_name,
dedicated_capacity_name=dedicated_capacity_name,
capacity_parameters=capacity_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('DedicatedCapacity', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}'} # type: ignore
async def _delete_initial(
self,
resource_group_name: str,
dedicated_capacity_name: str,
**kwargs
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}'} # type: ignore
async def begin_delete(
self,
resource_group_name: str,
dedicated_capacity_name: str,
**kwargs
) -> AsyncLROPoller[None]:
"""Deletes the specified Dedicated capacity.
:param resource_group_name: The name of the Azure Resource group of which a given
PowerBIDedicated capacity is part. This name must be at least 1 character in length, and no
more than 90.
:type resource_group_name: str
:param dedicated_capacity_name: The name of the Dedicated capacity. It must be at least 3
characters in length, and no more than 63.
:type dedicated_capacity_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial(
resource_group_name=resource_group_name,
dedicated_capacity_name=dedicated_capacity_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}'} # type: ignore
async def _update_initial(
self,
resource_group_name: str,
dedicated_capacity_name: str,
capacity_update_parameters: "_models.DedicatedCapacityUpdateParameters",
**kwargs
) -> "_models.DedicatedCapacity":
cls = kwargs.pop('cls', None) # type: ClsType["_models.DedicatedCapacity"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(capacity_update_parameters, 'DedicatedCapacityUpdateParameters')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('DedicatedCapacity', pipeline_response)
if response.status_code == 202:
deserialized = self._deserialize('DedicatedCapacity', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}'} # type: ignore
async def begin_update(
self,
resource_group_name: str,
dedicated_capacity_name: str,
capacity_update_parameters: "_models.DedicatedCapacityUpdateParameters",
**kwargs
) -> AsyncLROPoller["_models.DedicatedCapacity"]:
"""Updates the current state of the specified Dedicated capacity.
:param resource_group_name: The name of the Azure Resource group of which a given
PowerBIDedicated capacity is part. This name must be at least 1 character in length, and no
more than 90.
:type resource_group_name: str
:param dedicated_capacity_name: The name of the Dedicated capacity. It must be at least 3
characters in length, and no more than 63.
:type dedicated_capacity_name: str
:param capacity_update_parameters: Request object that contains the updated information for the
capacity.
:type capacity_update_parameters: ~azure.mgmt.powerbidedicated.models.DedicatedCapacityUpdateParameters
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either DedicatedCapacity or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.powerbidedicated.models.DedicatedCapacity]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.DedicatedCapacity"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._update_initial(
resource_group_name=resource_group_name,
dedicated_capacity_name=dedicated_capacity_name,
capacity_update_parameters=capacity_update_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('DedicatedCapacity', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}'} # type: ignore
async def _suspend_initial(
self,
resource_group_name: str,
dedicated_capacity_name: str,
**kwargs
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
# Construct URL
url = self._suspend_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
request = self._client.post(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_suspend_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}/suspend'} # type: ignore
async def begin_suspend(
self,
resource_group_name: str,
dedicated_capacity_name: str,
**kwargs
) -> AsyncLROPoller[None]:
"""Suspends operation of the specified dedicated capacity instance.
:param resource_group_name: The name of the Azure Resource group of which a given
PowerBIDedicated capacity is part. This name must be at least 1 character in length, and no
more than 90.
:type resource_group_name: str
:param dedicated_capacity_name: The name of the Dedicated capacity. It must be at least 3
characters in length, and no more than 63.
:type dedicated_capacity_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._suspend_initial(
resource_group_name=resource_group_name,
dedicated_capacity_name=dedicated_capacity_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_suspend.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}/suspend'} # type: ignore
async def _resume_initial(
self,
resource_group_name: str,
dedicated_capacity_name: str,
**kwargs
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
# Construct URL
url = self._resume_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
request = self._client.post(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_resume_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}/resume'} # type: ignore
async def begin_resume(
self,
resource_group_name: str,
dedicated_capacity_name: str,
**kwargs
) -> AsyncLROPoller[None]:
"""Resumes operation of the specified Dedicated capacity instance.
:param resource_group_name: The name of the Azure Resource group of which a given
PowerBIDedicated capacity is part. This name must be at least 1 character in length, and no
more than 90.
:type resource_group_name: str
:param dedicated_capacity_name: The name of the Dedicated capacity. It must be at least 3
characters in length, and no more than 63.
:type dedicated_capacity_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._resume_initial(
resource_group_name=resource_group_name,
dedicated_capacity_name=dedicated_capacity_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_resume.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}/resume'} # type: ignore
def list_by_resource_group(
self,
resource_group_name: str,
**kwargs
) -> AsyncIterable["_models.DedicatedCapacities"]:
"""Gets all the Dedicated capacities for the given resource group.
:param resource_group_name: The name of the Azure Resource group of which a given
PowerBIDedicated capacity is part. This name must be at least 1 character in length, and no
more than 90.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either DedicatedCapacities or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.powerbidedicated.models.DedicatedCapacities]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.DedicatedCapacities"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_resource_group.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('DedicatedCapacities', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities'} # type: ignore
def list(
self,
**kwargs
) -> AsyncIterable["_models.DedicatedCapacities"]:
"""Lists all the Dedicated capacities for the given subscription.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either DedicatedCapacities or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.powerbidedicated.models.DedicatedCapacities]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.DedicatedCapacities"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('DedicatedCapacities', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PowerBIDedicated/capacities'} # type: ignore
async def list_skus(
self,
**kwargs
) -> "_models.SkuEnumerationForNewResourceResult":
"""Lists eligible SKUs for PowerBI Dedicated resource provider.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SkuEnumerationForNewResourceResult, or the result of cls(response)
:rtype: ~azure.mgmt.powerbidedicated.models.SkuEnumerationForNewResourceResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SkuEnumerationForNewResourceResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
accept = "application/json"
# Construct URL
url = self.list_skus.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('SkuEnumerationForNewResourceResult', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_skus.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PowerBIDedicated/skus'} # type: ignore
async def list_skus_for_capacity(
self,
resource_group_name: str,
dedicated_capacity_name: str,
**kwargs
) -> "_models.SkuEnumerationForExistingResourceResult":
"""Lists eligible SKUs for a PowerBI Dedicated resource.
:param resource_group_name: The name of the Azure Resource group of which a given
PowerBIDedicated capacity is part. This name must be at least 1 character in length, and no
more than 90.
:type resource_group_name: str
:param dedicated_capacity_name: The name of the Dedicated capacity. It must be at least 3
characters in length, and no more than 63.
:type dedicated_capacity_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SkuEnumerationForExistingResourceResult, or the result of cls(response)
:rtype: ~azure.mgmt.powerbidedicated.models.SkuEnumerationForExistingResourceResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SkuEnumerationForExistingResourceResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
accept = "application/json"
# Construct URL
url = self.list_skus_for_capacity.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'dedicatedCapacityName': self._serialize.url("dedicated_capacity_name", dedicated_capacity_name, 'str', max_length=63, min_length=3, pattern=r'^[a-z][a-z0-9]*$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('SkuEnumerationForExistingResourceResult', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
list_skus_for_capacity.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PowerBIDedicated/capacities/{dedicatedCapacityName}/skus'} # type: ignore
async def check_name_availability(
self,
location: str,
capacity_parameters: "_models.CheckCapacityNameAvailabilityParameters",
**kwargs
) -> "_models.CheckCapacityNameAvailabilityResult":
"""Check the name availability in the target location.
:param location: The region name which the operation will lookup into.
:type location: str
:param capacity_parameters: The name of the capacity.
:type capacity_parameters: ~azure.mgmt.powerbidedicated.models.CheckCapacityNameAvailabilityParameters
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CheckCapacityNameAvailabilityResult, or the result of cls(response)
:rtype: ~azure.mgmt.powerbidedicated.models.CheckCapacityNameAvailabilityResult
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckCapacityNameAvailabilityResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.check_name_availability.metadata['url'] # type: ignore
path_format_arguments = {
'location': self._serialize.url("location", location, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(capacity_parameters, 'CheckCapacityNameAvailabilityParameters')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('CheckCapacityNameAvailabilityResult', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
check_name_availability.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.PowerBIDedicated/locations/{location}/checkNameAvailability'} # type: ignore
| 52.05754 | 208 | 0.675839 |
48cc962cb4654c33f87a87ade5d5a2fa1020d16e | 313 | py | Python | src/preparation/__init__.py | JustinRuan/Pathological-images | 478f0b568068e591e282e9566786e683ec39a108 | [
"MIT"
] | 2 | 2022-01-17T12:04:02.000Z | 2022-03-08T21:59:39.000Z | src/preparation/__init__.py | JustinRuan/Pathological-images | 478f0b568068e591e282e9566786e683ec39a108 | [
"MIT"
] | null | null | null | src/preparation/__init__.py | JustinRuan/Pathological-images | 478f0b568068e591e282e9566786e683ec39a108 | [
"MIT"
] | 1 | 2020-03-08T09:00:43.000Z | 2020-03-08T09:00:43.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__author__ = 'Justin'
__mtime__ = '2018-05-23'
"""
from preparation.PatchSampler import PatchSampler
from preparation.PatchPack import PatchPack
from preparation.normalization import HistNormalization
__all__ = ["PatchSampler", "PatchPack", "HistNormalization"] | 26.083333 | 60 | 0.760383 |
6e476e5cef8f96a424649e5cd2e21eb5d92f1949 | 1,602 | py | Python | aliyun-python-sdk-cdn/aliyunsdkcdn/request/v20180510/DescribeTopDomainsByFlowRequest.py | liusc27/aliyun-openapi-python-sdk | 5e3db3535dd21de987dc5981e71151327d5a884f | [
"Apache-2.0"
] | 1 | 2019-12-23T12:36:43.000Z | 2019-12-23T12:36:43.000Z | aliyun-python-sdk-cdn/aliyunsdkcdn/request/v20180510/DescribeTopDomainsByFlowRequest.py | liusc27/aliyun-openapi-python-sdk | 5e3db3535dd21de987dc5981e71151327d5a884f | [
"Apache-2.0"
] | null | null | null | aliyun-python-sdk-cdn/aliyunsdkcdn/request/v20180510/DescribeTopDomainsByFlowRequest.py | liusc27/aliyun-openapi-python-sdk | 5e3db3535dd21de987dc5981e71151327d5a884f | [
"Apache-2.0"
] | null | null | null | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
class DescribeTopDomainsByFlowRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Cdn', '2018-05-10', 'DescribeTopDomainsByFlow')
def get_StartTime(self):
return self.get_query_params().get('StartTime')
def set_StartTime(self,StartTime):
self.add_query_param('StartTime',StartTime)
def get_Limit(self):
return self.get_query_params().get('Limit')
def set_Limit(self,Limit):
self.add_query_param('Limit',Limit)
def get_EndTime(self):
return self.get_query_params().get('EndTime')
def set_EndTime(self,EndTime):
self.add_query_param('EndTime',EndTime)
def get_OwnerId(self):
return self.get_query_params().get('OwnerId')
def set_OwnerId(self,OwnerId):
self.add_query_param('OwnerId',OwnerId) | 33.375 | 77 | 0.757179 |
88ae58caf14a01f55fc1e0d0c25e4533283a0212 | 11,438 | py | Python | lib/streamlit/elements/altair.py | kamito/streamlit | af68a915b3a1f37ddd411d081e430dad70869c45 | [
"Apache-2.0"
] | 5 | 2020-01-22T01:06:39.000Z | 2021-06-11T19:26:16.000Z | lib/streamlit/elements/altair.py | kamito/streamlit | af68a915b3a1f37ddd411d081e430dad70869c45 | [
"Apache-2.0"
] | 221 | 2020-10-16T08:15:02.000Z | 2022-03-29T10:25:00.000Z | lib/streamlit/elements/altair.py | kamito/streamlit | af68a915b3a1f37ddd411d081e430dad70869c45 | [
"Apache-2.0"
] | 1 | 2020-08-27T21:54:18.000Z | 2020-08-27T21:54:18.000Z | # Copyright 2018-2021 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A Python wrapper around Altair.
Altair is a Python visualization library based on Vega-Lite,
a nice JSON schema for expressing graphs and charts."""
from datetime import date
from typing import cast
import streamlit
from streamlit import type_util
from streamlit.proto.VegaLiteChart_pb2 import VegaLiteChart as VegaLiteChartProto
import streamlit.elements.vega_lite as vega_lite
import altair as alt
import pandas as pd
from .utils import last_index_for_melted_dataframes
class AltairMixin:
def line_chart(self, data=None, width=0, height=0, use_container_width=True):
"""Display a line chart.
This is syntax-sugar around st.altair_chart. The main difference
is this command uses the data's own column and indices to figure out
the chart's spec. As a result this is easier to use for many "just plot
this" scenarios, while being less customizable.
If st.line_chart does not guess the data specification
correctly, try specifying your desired chart using st.altair_chart.
Parameters
----------
data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict
or None
Data to be plotted.
width : int
The chart width in pixels. If 0, selects the width automatically.
height : int
The chart width in pixels. If 0, selects the height automatically.
use_container_width : bool
If True, set the chart width to the column width. This takes
precedence over the width argument.
Example
-------
>>> chart_data = pd.DataFrame(
... np.random.randn(20, 3),
... columns=['a', 'b', 'c'])
...
>>> st.line_chart(chart_data)
.. output::
https://static.streamlit.io/0.50.0-td2L/index.html?id=BdxXG3MmrVBfJyqS2R2ki8
height: 220px
"""
vega_lite_chart_proto = VegaLiteChartProto()
chart = generate_chart("line", data, width, height)
marshall(vega_lite_chart_proto, chart, use_container_width)
last_index = last_index_for_melted_dataframes(data)
return self.dg._enqueue(
"line_chart", vega_lite_chart_proto, last_index=last_index
)
def area_chart(self, data=None, width=0, height=0, use_container_width=True):
"""Display an area chart.
This is just syntax-sugar around st.altair_chart. The main difference
is this command uses the data's own column and indices to figure out
the chart's spec. As a result this is easier to use for many "just plot
this" scenarios, while being less customizable.
If st.area_chart does not guess the data specification
correctly, try specifying your desired chart using st.altair_chart.
Parameters
----------
data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, or dict
Data to be plotted.
width : int
The chart width in pixels. If 0, selects the width automatically.
height : int
The chart width in pixels. If 0, selects the height automatically.
use_container_width : bool
If True, set the chart width to the column width. This takes
precedence over the width argument.
Example
-------
>>> chart_data = pd.DataFrame(
... np.random.randn(20, 3),
... columns=['a', 'b', 'c'])
...
>>> st.area_chart(chart_data)
.. output::
https://static.streamlit.io/0.50.0-td2L/index.html?id=Pp65STuFj65cJRDfhGh4Jt
height: 220px
"""
vega_lite_chart_proto = VegaLiteChartProto()
chart = generate_chart("area", data, width, height)
marshall(vega_lite_chart_proto, chart, use_container_width)
last_index = last_index_for_melted_dataframes(data)
return self.dg._enqueue(
"area_chart", vega_lite_chart_proto, last_index=last_index
)
def bar_chart(self, data=None, width=0, height=0, use_container_width=True):
"""Display a bar chart.
This is just syntax-sugar around st.altair_chart. The main difference
is this command uses the data's own column and indices to figure out
the chart's spec. As a result this is easier to use for many "just plot
this" scenarios, while being less customizable.
If st.bar_chart does not guess the data specification
correctly, try specifying your desired chart using st.altair_chart.
Parameters
----------
data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, or dict
Data to be plotted.
width : int
The chart width in pixels. If 0, selects the width automatically.
height : int
The chart width in pixels. If 0, selects the height automatically.
use_container_width : bool
If True, set the chart width to the column width. This takes
precedence over the width argument.
Example
-------
>>> chart_data = pd.DataFrame(
... np.random.randn(50, 3),
... columns=["a", "b", "c"])
...
>>> st.bar_chart(chart_data)
.. output::
https://static.streamlit.io/0.66.0-2BLtg/index.html?id=GaYDn6vxskvBUkBwsGVEaL
height: 220px
"""
vega_lite_chart_proto = VegaLiteChartProto()
chart = generate_chart("bar", data, width, height)
marshall(vega_lite_chart_proto, chart, use_container_width)
last_index = last_index_for_melted_dataframes(data)
return self.dg._enqueue(
"bar_chart", vega_lite_chart_proto, last_index=last_index
)
def altair_chart(self, altair_chart, use_container_width=False):
"""Display a chart using the Altair library.
Parameters
----------
altair_chart : altair.vegalite.v2.api.Chart
The Altair chart object to display.
use_container_width : bool
If True, set the chart width to the column width. This takes
precedence over Altair's native `width` value.
Example
-------
>>> import pandas as pd
>>> import numpy as np
>>> import altair as alt
>>>
>>> df = pd.DataFrame(
... np.random.randn(200, 3),
... columns=['a', 'b', 'c'])
...
>>> c = alt.Chart(df).mark_circle().encode(
... x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])
>>>
>>> st.altair_chart(c, use_container_width=True)
.. output::
https://static.streamlit.io/0.25.0-2JkNY/index.html?id=8jmmXR8iKoZGV4kXaKGYV5
height: 200px
Examples of Altair charts can be found at
https://altair-viz.github.io/gallery/.
"""
vega_lite_chart_proto = VegaLiteChartProto()
marshall(
vega_lite_chart_proto,
altair_chart,
use_container_width=use_container_width,
)
return self.dg._enqueue("vega_lite_chart", vega_lite_chart_proto)
@property
def dg(self) -> "streamlit.delta_generator.DeltaGenerator":
"""Get our DeltaGenerator."""
return cast("streamlit.delta_generator.DeltaGenerator", self)
def _is_date_column(df, name):
"""True if the column with the given name stores datetime.date values.
This function just checks the first value in the given column, so
it's meaningful only for columns whose values all share the same type.
Parameters
----------
df : pd.DataFrame
name : str
The column name
Returns
-------
bool
"""
column = df[name]
if column.size == 0:
return False
return isinstance(column[0], date)
def generate_chart(chart_type, data, width=0, height=0):
if data is None:
# Use an empty-ish dict because if we use None the x axis labels rotate
# 90 degrees. No idea why. Need to debug.
data = {"": []}
if not isinstance(data, pd.DataFrame):
data = type_util.convert_anything_to_df(data)
index_name = data.index.name
if index_name is None:
index_name = "index"
data = pd.melt(data.reset_index(), id_vars=[index_name])
if chart_type == "area":
opacity = {"value": 0.7}
else:
opacity = {"value": 1.0}
# Set the X and Y axes' scale to "utc" if they contain date values.
# This causes time data to be displayed in UTC, rather the user's local
# time zone. (By default, vega-lite displays time data in the browser's
# local time zone, regardless of which time zone the data specifies:
# https://vega.github.io/vega-lite/docs/timeunit.html#output).
x_scale = (
alt.Scale(type="utc") if _is_date_column(data, index_name) else alt.Undefined
)
y_scale = alt.Scale(type="utc") if _is_date_column(data, "value") else alt.Undefined
x_type = alt.Undefined
# Bar charts should have a discrete (ordinal) x-axis, UNLESS type is date/time
# https://github.com/streamlit/streamlit/pull/2097#issuecomment-714802475
if chart_type == "bar" and not _is_date_column(data, index_name):
x_type = "ordinal"
chart = (
getattr(alt.Chart(data, width=width, height=height), "mark_" + chart_type)()
.encode(
alt.X(index_name, title="", scale=x_scale, type=x_type),
alt.Y("value", title="", scale=y_scale),
alt.Color("variable", title="", type="nominal"),
alt.Tooltip([index_name, "value", "variable"]),
opacity=opacity,
)
.interactive()
)
return chart
def marshall(vega_lite_chart, altair_chart, use_container_width=False, **kwargs):
import altair as alt
# Normally altair_chart.to_dict() would transform the dataframe used by the
# chart into an array of dictionaries. To avoid that, we install a
# transformer that replaces datasets with a reference by the object id of
# the dataframe. We then fill in the dataset manually later on.
datasets = {}
def id_transform(data):
"""Altair data transformer that returns a fake named dataset with the
object id."""
datasets[id(data)] = data
return {"name": str(id(data))}
alt.data_transformers.register("id", id_transform)
with alt.data_transformers.enable("id"):
chart_dict = altair_chart.to_dict()
# Put datasets back into the chart dict but note how they weren't
# transformed.
chart_dict["datasets"] = datasets
vega_lite.marshall(
vega_lite_chart,
chart_dict,
use_container_width=use_container_width,
**kwargs,
)
| 34.041667 | 88 | 0.63359 |
3daaff319f52d86bb1baa771c6eb96fb5f1d7a97 | 1,010 | py | Python | docs/conf.py | dlaidig/vqf | 694eeb55031382d396f14a6c977c4ad2d940bf66 | [
"MIT"
] | 1 | 2021-11-13T17:33:55.000Z | 2021-11-13T17:33:55.000Z | docs/conf.py | dlaidig/vqf | 694eeb55031382d396f14a6c977c4ad2d940bf66 | [
"MIT"
] | null | null | null | docs/conf.py | dlaidig/vqf | 694eeb55031382d396f14a6c977c4ad2d940bf66 | [
"MIT"
] | null | null | null | # SPDX-FileCopyrightText: 2021 Daniel Laidig <[email protected]>
#
# SPDX-License-Identifier: MIT
# cf. https://www.sphinx-doc.org/en/master/usage/configuration.html
import os
import subprocess
# always run doxygen automatically and abort if there is an error
subprocess.check_call('cd .. && mkdir -p build/doxygen && doxygen', shell=True)
project = 'VQF'
copyright = '2021, Daniel Laidig'
author = 'Daniel Laidig'
extensions = [
'sphinx_rtd_theme',
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'breathe',
'sphinxcontrib.matlab',
'matplotlib.sphinxext.plot_directive',
]
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
breathe_projects = {'vqf': '../build/doxygen/xml/'}
breathe_default_project = 'vqf'
matlab_src_dir = os.path.abspath('../vqf/')
html_theme = 'sphinx_rtd_theme'
# html_static_path = ['_static']
autoclass_content = 'both'
autodoc_member_order = 'bysource'
| 26.578947 | 79 | 0.718812 |
ad12b91d1817891987d28479ae8576df5de61701 | 57,110 | py | Python | src/transformers/models/gpt2/modeling_gpt2.py | arunraja-hub/transformers | eb2e006b35938e7b6476d3bfc55343ebfe5ec501 | [
"Apache-2.0"
] | 17 | 2020-10-13T06:53:25.000Z | 2022-02-22T06:12:17.000Z | src/transformers/models/gpt2/modeling_gpt2.py | 4nalog/transformers | 76cadb7943c8492ec481f4f3925e9e8793a32c9d | [
"Apache-2.0"
] | 13 | 2020-10-13T11:41:11.000Z | 2022-02-16T14:13:31.000Z | src/transformers/models/gpt2/modeling_gpt2.py | 4nalog/transformers | 76cadb7943c8492ec481f4f3925e9e8793a32c9d | [
"Apache-2.0"
] | 13 | 2020-10-04T05:06:00.000Z | 2022-02-09T01:14:59.000Z | # coding=utf-8
# Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PyTorch OpenAI GPT-2 model."""
import os
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss
from ...activations import ACT2FN
from ...file_utils import (
ModelOutput,
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
replace_return_docstrings,
)
from ...modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
SequenceClassifierOutputWithPast,
)
from ...modeling_utils import (
Conv1D,
PreTrainedModel,
SequenceSummary,
find_pruneable_heads_and_indices,
prune_conv1d_layer,
)
from ...utils import logging
from ...utils.model_parallel_utils import assert_device_map, get_device_map
from .configuration_gpt2 import GPT2Config
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "gpt2"
_CONFIG_FOR_DOC = "GPT2Config"
_TOKENIZER_FOR_DOC = "GPT2Tokenizer"
GPT2_PRETRAINED_MODEL_ARCHIVE_LIST = [
"gpt2",
"gpt2-medium",
"gpt2-large",
"gpt2-xl",
"distilgpt2",
# See all GPT-2 models at https://huggingface.co/models?filter=gpt2
]
def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):
"""Load tf checkpoints in a pytorch model"""
try:
import re
import tensorflow as tf
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions."
)
raise
tf_path = os.path.abspath(gpt2_checkpoint_path)
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
# Load weights from TF model
init_vars = tf.train.list_variables(tf_path)
names = []
arrays = []
for name, shape in init_vars:
logger.info(f"Loading TF weight {name} with shape {shape}")
array = tf.train.load_variable(tf_path, name)
names.append(name)
arrays.append(array.squeeze())
for name, array in zip(names, arrays):
name = name[6:] # skip "model/"
name = name.split("/")
pointer = model
for m_name in name:
if re.fullmatch(r"[A-Za-z]+\d+", m_name):
scope_names = re.split(r"(\d+)", m_name)
else:
scope_names = [m_name]
if scope_names[0] == "w" or scope_names[0] == "g":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "b":
pointer = getattr(pointer, "bias")
elif scope_names[0] == "wpe" or scope_names[0] == "wte":
pointer = getattr(pointer, scope_names[0])
pointer = getattr(pointer, "weight")
else:
pointer = getattr(pointer, scope_names[0])
if len(scope_names) >= 2:
num = int(scope_names[1])
pointer = pointer[num]
try:
assert (
pointer.shape == array.shape
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
except AssertionError as e:
e.args += (pointer.shape, array.shape)
raise
logger.info(f"Initialize PyTorch weight {name}")
pointer.data = torch.from_numpy(array)
return model
class GPT2Attention(nn.Module):
def __init__(self, config, is_cross_attention=False):
super().__init__()
max_positions = config.max_position_embeddings
self.register_buffer(
"bias",
torch.tril(torch.ones((max_positions, max_positions), dtype=torch.uint8)).view(
1, 1, max_positions, max_positions
),
)
self.register_buffer("masked_bias", torch.tensor(-1e4))
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim // self.num_heads
self.split_size = self.embed_dim
if self.head_dim * self.num_heads != self.embed_dim:
raise ValueError(
f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})."
)
self.scale_attn_weights = config.scale_attn_weights
self.is_cross_attention = is_cross_attention
if self.is_cross_attention:
self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
else:
self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
self.attn_dropout = nn.Dropout(config.attn_pdrop)
self.resid_dropout = nn.Dropout(config.resid_pdrop)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
# Prune conv1d layers
self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
# Update hyper params
self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
self.num_heads = self.num_heads - len(heads)
self.pruned_heads = self.pruned_heads.union(heads)
def _attn(self, query, key, value, attention_mask=None, head_mask=None):
attn_weights = torch.matmul(query, key.transpose(-1, -2))
if self.scale_attn_weights:
attn_weights = attn_weights / (float(value.size(-1)) ** 0.5)
if not self.is_cross_attention:
# if only "normal" attention layer implements causal mask
query_length, key_length = query.size(-2), key.size(-2)
causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length].bool()
attn_weights = torch.where(causal_mask, attn_weights, self.masked_bias.to(attn_weights.dtype))
if attention_mask is not None:
# Apply the attention mask
attn_weights = attn_weights + attention_mask
attn_weights = nn.Softmax(dim=-1)(attn_weights)
attn_weights = self.attn_dropout(attn_weights)
# Mask heads if we want to
if head_mask is not None:
attn_weights = attn_weights * head_mask
attn_output = torch.matmul(attn_weights, value)
return attn_output, attn_weights
def _split_heads(self, tensor, num_heads, attn_head_size):
"""
Splits hidden_size dim into attn_head_size and num_heads
"""
new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
tensor = tensor.view(*new_shape)
return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
def _merge_heads(self, tensor, num_heads, attn_head_size):
"""
Merges attn_head_size dim and num_attn_heads dim into hidden_size
"""
tensor = tensor.permute(0, 2, 1, 3).contiguous()
new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
return tensor.view(new_shape)
def forward(
self,
hidden_states,
layer_past=None,
attention_mask=None,
head_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
use_cache=False,
output_attentions=False,
):
if encoder_hidden_states is not None:
if not hasattr(self, "q_attn"):
raise ValueError(
"If class is used as cross attention, the weights `q_attn` have to be defined. "
"Please make sure to instantiate class with `GPT2Attention(..., is_cross_attention=True)`."
)
query = self.q_attn(hidden_states)
key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
attention_mask = encoder_attention_mask
else:
query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
query = self._split_heads(query, self.num_heads, self.head_dim)
key = self._split_heads(key, self.num_heads, self.head_dim)
value = self._split_heads(value, self.num_heads, self.head_dim)
if layer_past is not None:
past_key, past_value = layer_past
key = torch.cat((past_key, key), dim=-2)
value = torch.cat((past_value, value), dim=-2)
if use_cache is True:
present = (key, value)
else:
present = None
attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
attn_output = self.c_proj(attn_output)
attn_output = self.resid_dropout(attn_output)
outputs = (attn_output, present)
if output_attentions:
outputs += (attn_weights,)
return outputs # a, present, (attentions)
class GPT2MLP(nn.Module):
def __init__(self, intermediate_size, config):
super().__init__()
embed_dim = config.hidden_size
self.c_fc = Conv1D(intermediate_size, embed_dim)
self.c_proj = Conv1D(embed_dim, intermediate_size)
self.act = ACT2FN[config.activation_function]
self.dropout = nn.Dropout(config.resid_pdrop)
def forward(self, hidden_states):
hidden_states = self.c_fc(hidden_states)
hidden_states = self.act(hidden_states)
hidden_states = self.c_proj(hidden_states)
hidden_states = self.dropout(hidden_states)
return hidden_states
class GPT2Block(nn.Module):
def __init__(self, config):
super().__init__()
hidden_size = config.hidden_size
inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
self.attn = GPT2Attention(config)
self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
if config.add_cross_attention:
self.crossattention = GPT2Attention(config, is_cross_attention=True)
self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
self.mlp = GPT2MLP(inner_dim, config)
def forward(
self,
hidden_states,
layer_past=None,
attention_mask=None,
head_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
use_cache=False,
output_attentions=False,
):
residual = hidden_states
hidden_states = self.ln_1(hidden_states)
attn_outputs = self.attn(
hidden_states,
layer_past=layer_past,
attention_mask=attention_mask,
head_mask=head_mask,
use_cache=use_cache,
output_attentions=output_attentions,
)
attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
outputs = attn_outputs[1:]
# residual connection
hidden_states = attn_output + residual
if encoder_hidden_states is not None:
# add one self-attention block for cross-attention
if not hasattr(self, "crossattention"):
raise ValueError(
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
"cross-attention layers by setting `config.add_cross_attention=True`"
)
residual = hidden_states
hidden_states = self.ln_cross_attn(hidden_states)
cross_attn_outputs = self.crossattention(
hidden_states,
attention_mask=attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_attentions=output_attentions,
)
attn_output = cross_attn_outputs[0]
# residual connection
hidden_states = residual + attn_output
outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
residual = hidden_states
hidden_states = self.ln_2(hidden_states)
feed_forward_hidden_states = self.mlp(hidden_states)
# residual connection
hidden_states = residual + feed_forward_hidden_states
if use_cache:
outputs = (hidden_states,) + outputs
else:
outputs = (hidden_states,) + outputs[1:]
return outputs # hidden_states, present, (attentions, cross_attentions)
class GPT2PreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = GPT2Config
load_tf_weights = load_tf_weights_in_gpt2
base_model_prefix = "transformer"
is_parallelizable = True
def __init__(self, *inputs, **kwargs):
super().__init__(*inputs, **kwargs)
def _init_weights(self, module):
"""Initialize the weights."""
if isinstance(module, (nn.Linear, Conv1D)):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
@dataclass
class GPT2DoubleHeadsModelOutput(ModelOutput):
"""
Base class for outputs of models predicting if two sentences are consecutive or not.
Args:
loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when ``labels`` is provided):
Language modeling loss.
mc_loss (:obj:`torch.FloatTensor` of shape :obj:`(1,)`, `optional`, returned when :obj:`mc_labels` is provided):
Multiple choice classification loss.
logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, num_choices, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
mc_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, num_choices)`):
Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]`, `optional`, returned when ``use_cache=True`` is passed or when ``config.use_cache=True``):
Tuple of length :obj:`config.n_layers`, containing tuples of tensors of shape :obj:`(batch_size, num_heads,
sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see
:obj:`past_key_values` input) to speed up sequential decoding.
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads,
sequence_length, sequence_length)`.
GPT2Attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads.
"""
loss: Optional[torch.FloatTensor] = None
mc_loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
mc_logits: torch.FloatTensor = None
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
GPT2_START_DOCSTRING = r"""
This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic
methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
pruning heads etc.)
This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__
subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
general usage and behavior.
Parameters:
config (:class:`~transformers.GPT2Config`): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model
weights.
"""
GPT2_INPUTS_DOCSTRING = r"""
Args:
input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, input_ids_length)`):
:obj:`input_ids_length` = ``sequence_length`` if :obj:`past_key_values` is ``None`` else
``past_key_values[0][0].shape[-2]`` (``sequence_length`` of input past key value states). Indices of input
sequence tokens in the vocabulary.
If :obj:`past_key_values` is used, only ``input_ids`` that do not have their past calculated should be
passed as ``input_ids``.
Indices can be obtained using :class:`~transformers.GPT2Tokenizer`. See
:meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__` for
details.
`What are input IDs? <../glossary.html#input-ids>`__
past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers`):
Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
:obj:`past_key_values` output below). Can be used to speed up sequential decoding. The ``input_ids`` which
have their past given to this model should not be passed as ``input_ids`` as they have already been
computed.
attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
`What are attention masks? <../glossary.html#attention-mask>`__
token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, input_ids_length)`, `optional`):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0,
1]``:
- 0 corresponds to a `sentence A` token,
- 1 corresponds to a `sentence B` token.
`What are token type IDs? <../glossary.html#token-type-ids>`_
position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0,
config.max_position_embeddings - 1]``.
`What are position IDs? <../glossary.html#position-ids>`_
head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
vectors than the model's internal embedding lookup matrix.
If :obj:`past_key_values` is used, optionally only the last :obj:`inputs_embeds` have to be input (see
:obj:`past_key_values`).
use_cache (:obj:`bool`, `optional`):
If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
decoding (see :obj:`past_key_values`).
output_attentions (:obj:`bool`, `optional`):
Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
tensors for more detail.
output_hidden_states (:obj:`bool`, `optional`):
Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
more detail.
return_dict (:obj:`bool`, `optional`):
Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
"""
PARALLELIZE_DOCSTRING = r"""
This is an experimental feature and is a subject to change at a moment's notice.
Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
it will evenly distribute blocks across all devices.
Args:
device_map (:obj:`Dict[int, list]`, optional, defaults to None):
A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
automatically mapped to the first device (for esoteric reasons). That means that the first device should
have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
following number of attention modules:
- gpt2: 12
- gpt2-medium: 24
- gpt2-large: 36
- gpt2-xl: 48
Example::
# Here is an example of a device map on a machine with 4 GPUs using gpt2-xl, which has a total of 48 attention modules:
model = GPT2LMHeadModel.from_pretrained('gpt2-xl')
device_map = {0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]}
model.parallelize(device_map)
"""
DEPARALLELIZE_DOCSTRING = r"""
Moves the model to cpu from a model parallel state.
Example::
# On a 4 GPU machine with gpt2-large:
model = GPT2LMHeadModel.from_pretrained('gpt2-large')
device_map = {0: [0, 1, 2, 3, 4, 5, 6, 7],
1: [8, 9, 10, 11, 12, 13, 14, 15],
2: [16, 17, 18, 19, 20, 21, 22, 23],
3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]}
model.parallelize(device_map) # Splits the model across several devices
model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
"""
@add_start_docstrings(
"The bare GPT2 Model transformer outputting raw hidden-states without any specific head on top.",
GPT2_START_DOCSTRING,
)
class GPT2Model(GPT2PreTrainedModel):
_keys_to_ignore_on_load_missing = ["attn.masked_bias"]
def __init__(self, config):
super().__init__(config)
self.embed_dim = config.hidden_size
self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
self.drop = nn.Dropout(config.embd_pdrop)
self.h = nn.ModuleList([GPT2Block(config) for _ in range(config.num_hidden_layers)])
self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
self.init_weights()
# Model parallel
self.model_parallel = False
self.device_map = None
@add_start_docstrings(PARALLELIZE_DOCSTRING)
def parallelize(self, device_map=None):
# Check validity of device_map
self.device_map = (
get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
)
assert_device_map(self.device_map, len(self.h))
self.model_parallel = True
self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
self.last_device = "cuda:" + str(max(self.device_map.keys()))
self.wte = self.wte.to(self.first_device)
self.wpe = self.wpe.to(self.first_device)
# Load onto devices
for k, v in self.device_map.items():
for block in v:
cuda_device = "cuda:" + str(k)
self.h[block] = self.h[block].to(cuda_device)
# ln_f to last
self.ln_f = self.ln_f.to(self.last_device)
@add_start_docstrings(DEPARALLELIZE_DOCSTRING)
def deparallelize(self):
self.model_parallel = False
self.device_map = None
self.first_device = "cpu"
self.last_device = "cpu"
self.wte = self.wte.to("cpu")
self.wpe = self.wpe.to("cpu")
for index in range(len(self.h)):
self.h[index] = self.h[index].to("cpu")
self.ln_f = self.ln_f.to("cpu")
torch.cuda.empty_cache()
def get_input_embeddings(self):
return self.wte
def set_input_embeddings(self, new_embeddings):
self.wte = new_embeddings
def _prune_heads(self, heads_to_prune):
"""
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
"""
for layer, heads in heads_to_prune.items():
self.h[layer].attn.prune_heads(heads)
@add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
tokenizer_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=BaseModelOutputWithPastAndCrossAttentions,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
batch_size = input_ids.shape[0]
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
batch_size = inputs_embeds.shape[0]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
device = input_ids.device if input_ids is not None else inputs_embeds.device
if token_type_ids is not None:
token_type_ids = token_type_ids.view(-1, input_shape[-1])
if position_ids is not None:
position_ids = position_ids.view(-1, input_shape[-1])
if past_key_values is None:
past_length = 0
past_key_values = tuple([None] * len(self.h))
else:
past_length = past_key_values[0][0].size(-2)
if position_ids is None:
position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
# GPT2Attention mask.
if attention_mask is not None:
assert batch_size > 0, "batch_size has to be defined and > 0"
attention_mask = attention_mask.view(batch_size, -1)
# We create a 3D attention mask from a 2D tensor mask.
# Sizes are [batch_size, 1, 1, to_seq_length]
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
# this attention mask is more simple than the triangular masking of causal attention
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
attention_mask = attention_mask[:, None, None, :]
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
# positions we want to attend and -10000.0 for masked positions.
# Since we are adding it to the raw scores before the softmax, this is
# effectively the same as removing these entirely.
attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
attention_mask = (1.0 - attention_mask) * -10000.0
# If a 2D ou 3D attention mask is provided for the cross-attention
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
if self.config.add_cross_attention and encoder_hidden_states is not None:
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
if encoder_attention_mask is None:
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
else:
encoder_attention_mask = None
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# head_mask has shape n_layer x batch x n_heads x N x N
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
if inputs_embeds is None:
inputs_embeds = self.wte(input_ids)
position_embeds = self.wpe(position_ids)
hidden_states = inputs_embeds + position_embeds
if token_type_ids is not None:
token_type_embeds = self.wte(token_type_ids)
hidden_states = hidden_states + token_type_embeds
hidden_states = self.drop(hidden_states)
output_shape = input_shape + (hidden_states.size(-1),)
presents = () if use_cache else None
all_self_attentions = () if output_attentions else None
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
all_hidden_states = () if output_hidden_states else None
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
# Model parallel
if self.model_parallel:
torch.cuda.set_device(hidden_states.device)
# Ensure layer_past is on same device as hidden_states (might not be correct)
if layer_past is not None:
layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
# Ensure that attention_mask is always on the same device as hidden_states
if attention_mask is not None:
attention_mask = attention_mask.to(hidden_states.device)
if isinstance(head_mask, torch.Tensor):
head_mask = head_mask.to(hidden_states.device)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if getattr(self.config, "gradient_checkpointing", False) and self.training:
if use_cache:
logger.warning(
"`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting "
"`use_cache=False`..."
)
use_cache = False
def create_custom_forward(module):
def custom_forward(*inputs):
# None for past_key_value
return module(*inputs, use_cache, output_attentions)
return custom_forward
outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(block),
hidden_states,
None,
attention_mask,
head_mask[i],
encoder_hidden_states,
encoder_attention_mask,
)
else:
outputs = block(
hidden_states,
layer_past=layer_past,
attention_mask=attention_mask,
head_mask=head_mask[i],
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
use_cache=use_cache,
output_attentions=output_attentions,
)
hidden_states = outputs[0]
if use_cache is True:
presents = presents + (outputs[1],)
if output_attentions:
all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
if self.config.add_cross_attention:
all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
# Model Parallel: If it's the last layer for that device, put things on the next device
if self.model_parallel:
for k, v in self.device_map.items():
if i == v[-1] and "cuda:" + str(k) != self.last_device:
hidden_states = hidden_states.to("cuda:" + str(k + 1))
hidden_states = self.ln_f(hidden_states)
hidden_states = hidden_states.view(*output_shape)
# Add last hidden state
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=presents,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
cross_attentions=all_cross_attentions,
)
@add_start_docstrings(
"""
The GPT2 Model transformer with a language modeling head on top (linear layer with weights tied to the input
embeddings).
""",
GPT2_START_DOCSTRING,
)
class GPT2LMHeadModel(GPT2PreTrainedModel):
_keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
def __init__(self, config):
super().__init__(config)
self.transformer = GPT2Model(config)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self.init_weights()
# Model parallel
self.model_parallel = False
self.device_map = None
@add_start_docstrings(PARALLELIZE_DOCSTRING)
def parallelize(self, device_map=None):
self.device_map = (
get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
if device_map is None
else device_map
)
assert_device_map(self.device_map, len(self.transformer.h))
self.transformer.parallelize(self.device_map)
self.lm_head = self.lm_head.to(self.transformer.first_device)
self.model_parallel = True
@add_start_docstrings(DEPARALLELIZE_DOCSTRING)
def deparallelize(self):
self.transformer.deparallelize()
self.transformer = self.transformer.to("cpu")
self.lm_head = self.lm_head.to("cpu")
self.model_parallel = False
torch.cuda.empty_cache()
def get_output_embeddings(self):
return self.lm_head
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings
def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
token_type_ids = kwargs.get("token_type_ids", None)
# only last token for inputs_ids if past is defined in kwargs
if past:
input_ids = input_ids[:, -1].unsqueeze(-1)
if token_type_ids is not None:
token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
attention_mask = kwargs.get("attention_mask", None)
position_ids = kwargs.get("position_ids", None)
if attention_mask is not None and position_ids is None:
# create position_ids on the fly for batch generation
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
if past:
position_ids = position_ids[:, -1].unsqueeze(-1)
else:
position_ids = None
return {
"input_ids": input_ids,
"past_key_values": past,
"use_cache": kwargs.get("use_cache"),
"position_ids": position_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids,
}
@add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
tokenizer_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=CausalLMOutputWithCrossAttentions,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
labels=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
``labels = input_ids`` Indices are selected in ``[-100, 0, ..., config.vocab_size]`` All labels set to
``-100`` are ignored (masked), the loss is only computed for labels in ``[0, ..., config.vocab_size]``
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = transformer_outputs[0]
# Set device for model parallelism
if self.model_parallel:
torch.cuda.set_device(self.transformer.first_device)
hidden_states = hidden_states.to(self.lm_head.weight.device)
lm_logits = self.lm_head(hidden_states)
loss = None
if labels is not None:
# Shift so that tokens < n predict n
shift_logits = lm_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
if not return_dict:
output = (lm_logits,) + transformer_outputs[1:]
return ((loss,) + output) if loss is not None else output
return CausalLMOutputWithCrossAttentions(
loss=loss,
logits=lm_logits,
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
cross_attentions=transformer_outputs.cross_attentions,
)
@staticmethod
def _reorder_cache(past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]:
"""
This function is used to re-order the :obj:`past_key_values` cache if
:meth:`~transformers.PreTrainedModel.beam_search` or :meth:`~transformers.PreTrainedModel.beam_sample` is
called. This is required to match :obj:`past_key_values` with the correct beam_idx at every generation step.
"""
return tuple(
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
for layer_past in past
)
@add_start_docstrings(
"""
The GPT2 Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
input embeddings, the classification head takes as input the input of a specified classification token index in the
input sequence).
""",
GPT2_START_DOCSTRING,
)
class GPT2DoubleHeadsModel(GPT2PreTrainedModel):
_keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
def __init__(self, config):
super().__init__(config)
config.num_labels = 1
self.transformer = GPT2Model(config)
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self.multiple_choice_head = SequenceSummary(config)
self.init_weights()
# Model parallel
self.model_parallel = False
self.device_map = None
@add_start_docstrings(PARALLELIZE_DOCSTRING)
def parallelize(self, device_map=None):
self.device_map = (
get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
if device_map is None
else device_map
)
assert_device_map(self.device_map, len(self.transformer.h))
self.transformer.parallelize(self.device_map)
self.lm_head = self.lm_head.to(self.transformer.first_device)
self.multiple_choice_head = self.multiple_choice_head.to(self.transformer.first_device)
self.model_parallel = True
@add_start_docstrings(DEPARALLELIZE_DOCSTRING)
def deparallelize(self):
self.transformer.deparallelize()
self.transformer = self.transformer.to("cpu")
self.lm_head = self.lm_head.to("cpu")
self.multiple_choice_head = self.multiple_choice_head.to("cpu")
self.model_parallel = False
torch.cuda.empty_cache()
def get_output_embeddings(self):
return self.lm_head
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings
def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
token_type_ids = kwargs.get("token_type_ids", None)
# only last token for inputs_ids if past is defined in kwargs
if past:
input_ids = input_ids[:, -1].unsqueeze(-1)
if token_type_ids is not None:
token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
attention_mask = kwargs.get("attention_mask", None)
position_ids = kwargs.get("position_ids", None)
if attention_mask is not None and position_ids is None:
# create position_ids on the fly for batch generation
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
if past:
position_ids = position_ids[:, -1].unsqueeze(-1)
else:
position_ids = None
return {
"input_ids": input_ids,
"past_key_values": past,
"use_cache": kwargs.get("use_cache"),
"position_ids": position_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids,
}
@add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=GPT2DoubleHeadsModelOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
mc_token_ids=None,
labels=None,
mc_labels=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
**kwargs,
):
r"""
mc_token_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, num_choices)`, `optional`, default to index of the last token of the input):
Index of the classification token in each input sequence. Selected in the range ``[0, input_ids.size(-1) -
1[``.
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
``labels = input_ids`` Indices are selected in ``[-100, 0, ..., config.vocab_size - 1]`` All labels set to
``-100`` are ignored (masked), the loss is only computed for labels in ``[0, ..., config.vocab_size - 1]``
mc_labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size)`, `optional`):
Labels for computing the multiple choice classification loss. Indices should be in ``[0, ...,
num_choices]`` where `num_choices` is the size of the second dimension of the input tensors. (see
`input_ids` above)
Return:
Example::
>>> import torch
>>> from transformers import GPT2Tokenizer, GPT2DoubleHeadsModel
>>> tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
>>> model = GPT2DoubleHeadsModel.from_pretrained('gpt2')
>>> # Add a [CLS] to the vocabulary (we should train it also!)
>>> num_added_tokens = tokenizer.add_special_tokens({'cls_token': '[CLS]'})
>>> embedding_layer = model.resize_token_embeddings(len(tokenizer)) # Update the model embeddings with the new vocabulary size
>>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
>>> encoded_choices = [tokenizer.encode(s) for s in choices]
>>> cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]
>>> input_ids = torch.tensor(encoded_choices).unsqueeze(0) # Batch size: 1, number of choices: 2
>>> mc_token_ids = torch.tensor([cls_token_location]) # Batch size: 1
>>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
>>> lm_logits = outputs.logits
>>> mc_logits = outputs.mc_logits
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = transformer_outputs[0]
# Set device for model parallelism
if self.model_parallel:
torch.cuda.set_device(self.transformer.first_device)
hidden_states = hidden_states.to(self.lm_head.weight.device)
lm_logits = self.lm_head(hidden_states)
mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)
mc_loss = None
if mc_labels is not None:
loss_fct = CrossEntropyLoss()
mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))
lm_loss = None
if labels is not None:
shift_logits = lm_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
loss_fct = CrossEntropyLoss()
lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
if not return_dict:
output = (lm_logits, mc_logits) + transformer_outputs[1:]
if mc_loss is not None:
output = (mc_loss,) + output
return ((lm_loss,) + output) if lm_loss is not None else output
return GPT2DoubleHeadsModelOutput(
loss=lm_loss,
mc_loss=mc_loss,
logits=lm_logits,
mc_logits=mc_logits,
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
@staticmethod
def _reorder_cache(past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]:
"""
This function is used to re-order the :obj:`past_key_values` cache if
:meth:`~transformers.PreTrainedModel.beam_search` or :meth:`~transformers.PreTrainedModel.beam_sample` is
called. This is required to match :obj:`past_key_values` with the correct beam_idx at every generation step.
"""
return tuple(
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
for layer_past in past
)
@add_start_docstrings(
"""
The GPT2 Model transformer with a sequence classification head on top (linear layer).
:class:`~transformers.GPT2ForSequenceClassification` uses the last token in order to do the classification, as
other causal models (e.g. GPT-1) do.
Since it does classification on the last token, it requires to know the position of the last token. If a
:obj:`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each
row. If no :obj:`pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot
guess the padding tokens when :obj:`inputs_embeds` are passed instead of :obj:`input_ids`, it does the same (take
the last value in each row of the batch).
""",
GPT2_START_DOCSTRING,
)
class GPT2ForSequenceClassification(GPT2PreTrainedModel):
_keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head\.weight"]
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.transformer = GPT2Model(config)
self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
self.init_weights()
# Model parallel
self.model_parallel = False
self.device_map = None
@add_start_docstrings_to_model_forward(GPT2_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
tokenizer_class=_TOKENIZER_FOR_DOC,
checkpoint="microsoft/DialogRPT-updown",
output_type=SequenceClassifierOutputWithPast,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
past_key_values=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,
config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.transformer(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = transformer_outputs[0]
logits = self.score(hidden_states)
if input_ids is not None:
batch_size, sequence_length = input_ids.shape[:2]
else:
batch_size, sequence_length = inputs_embeds.shape[:2]
assert (
self.config.pad_token_id is not None or batch_size == 1
), "Cannot handle batch sizes > 1 if no padding token is defined."
if self.config.pad_token_id is None:
sequence_lengths = -1
else:
if input_ids is not None:
sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
else:
sequence_lengths = -1
logger.warning(
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
f"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
)
pooled_logits = logits[range(batch_size), sequence_lengths]
loss = None
if labels is not None:
if self.num_labels == 1:
# We are doing regression
loss_fct = MSELoss()
loss = loss_fct(pooled_logits.view(-1), labels.to(self.dtype).view(-1))
else:
loss_fct = CrossEntropyLoss()
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
if not return_dict:
output = (pooled_logits,) + transformer_outputs[1:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutputWithPast(
loss=loss,
logits=pooled_logits,
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
| 42.97216 | 168 | 0.644038 |
6b2a28e6352ebaca8d5396f928705e6af0085937 | 460 | py | Python | tests/legacy_pytests/getcwd_exec_test/testme.py | depaul-dice/provenance-to-use | e16e2824fbbe0b4e09cc50f0d2bcec3400bf4b87 | [
"BSD-3-Clause"
] | null | null | null | tests/legacy_pytests/getcwd_exec_test/testme.py | depaul-dice/provenance-to-use | e16e2824fbbe0b4e09cc50f0d2bcec3400bf4b87 | [
"BSD-3-Clause"
] | null | null | null | tests/legacy_pytests/getcwd_exec_test/testme.py | depaul-dice/provenance-to-use | e16e2824fbbe0b4e09cc50f0d2bcec3400bf4b87 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python2
import sys
sys.path.insert(0, '..')
from cde_test_common import *
def checker_func():
assert os.path.isfile(CDE_ROOT_DIR + '/home/pgbovine/CDE/tests/test_file.txt')
assert os.path.isfile(CDE_ROOT_DIR + '/home/pgbovine/CDE/tests/getcwd_exec_test/getcwd_exec_test.py')
assert os.path.isfile(CDE_ROOT_DIR + '/home/pgbovine/CDE/tests/getcwd_exec_test/hello.txt')
generic_test_runner(["python", "getcwd_exec_test.py"], checker_func)
| 35.384615 | 103 | 0.769565 |
ba57afe072fec1e9c7c5146797a16d456a880b56 | 514 | py | Python | website/oauth/utils.py | DanielSBrown/osf.io | 98dda2ac237377197acacce78274bc0a4ce8f303 | [
"Apache-2.0"
] | 1 | 2015-10-02T18:35:53.000Z | 2015-10-02T18:35:53.000Z | website/oauth/utils.py | DanielSBrown/osf.io | 98dda2ac237377197acacce78274bc0a4ce8f303 | [
"Apache-2.0"
] | 20 | 2020-03-24T16:48:03.000Z | 2022-03-08T22:38:38.000Z | website/oauth/utils.py | DanielSBrown/osf.io | 98dda2ac237377197acacce78274bc0a4ce8f303 | [
"Apache-2.0"
] | 1 | 2021-10-04T21:16:56.000Z | 2021-10-04T21:16:56.000Z | from framework.auth.oauth_scopes import public_scopes
# This dict is built through the metaclass applied to ExternalProvider.
# It is intentionally empty here, and should remain empty.
PROVIDER_LOOKUP = dict()
def get_service(name):
"""Given a service name, return the provider class"""
return PROVIDER_LOOKUP[name]()
def get_available_scopes():
return sorted([(name, data.description)
for name, data in public_scopes.iteritems()
if data.is_public is True])
| 32.125 | 71 | 0.708171 |
220fc415e9791449c49a9d41ee1a99e54d1a2f89 | 1,030 | py | Python | texttospeech/google/cloud/texttospeech_v1beta1/__init__.py | nielm/google-cloud-python | fd126fdea34206109eb00d675374ff7dc4dcc5ef | [
"Apache-2.0"
] | 1 | 2019-01-23T21:54:51.000Z | 2019-01-23T21:54:51.000Z | texttospeech/google/cloud/texttospeech_v1beta1/__init__.py | nielm/google-cloud-python | fd126fdea34206109eb00d675374ff7dc4dcc5ef | [
"Apache-2.0"
] | 1 | 2018-04-06T19:51:23.000Z | 2018-04-06T19:51:23.000Z | texttospeech/google/cloud/texttospeech_v1beta1/__init__.py | nielm/google-cloud-python | fd126fdea34206109eb00d675374ff7dc4dcc5ef | [
"Apache-2.0"
] | 1 | 2020-04-14T10:47:41.000Z | 2020-04-14T10:47:41.000Z | # -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from google.cloud.texttospeech_v1beta1 import types
from google.cloud.texttospeech_v1beta1.gapic import enums
from google.cloud.texttospeech_v1beta1.gapic import text_to_speech_client
class TextToSpeechClient(text_to_speech_client.TextToSpeechClient):
__doc__ = text_to_speech_client.TextToSpeechClient.__doc__
enums = enums
__all__ = ("enums", "types", "TextToSpeechClient")
| 34.333333 | 74 | 0.784466 |
09cdc5951a74a3663bdd994992c7edc8757f1f4d | 5,320 | py | Python | drift_dac/prior_shift.py | dataiku-research/performance_prediction_under_shift | 6ca75afc5d0925a7c463370c5603a0b85fa5d0fc | [
"Apache-2.0"
] | null | null | null | drift_dac/prior_shift.py | dataiku-research/performance_prediction_under_shift | 6ca75afc5d0925a7c463370c5603a0b85fa5d0fc | [
"Apache-2.0"
] | null | null | null | drift_dac/prior_shift.py | dataiku-research/performance_prediction_under_shift | 6ca75afc5d0925a7c463370c5603a0b85fa5d0fc | [
"Apache-2.0"
] | null | null | null | import numpy as np
from math import ceil
import copy
from drift_dac.perturbation_shared_utils import Shift, PerturbationConstants
__all__ = ['OnlyOne', 'KnockOut', 'Rebalance']
class OnlyOne(Shift):
""" Sample data to keep only one class.
Args:
keep_cl (int or str): class to keep
Attributes:
keep_cl (int or str): class to keep
name (str): name of the perturbation
feature_type (int): identifier of the type of feature for which this perturbation is valid
(see PerturbationConstants).
"""
def __init__(self, keep_cl=0):
super(OnlyOne, self).__init__()
self.keep_cl = keep_cl
self.name = 'oo_shift_%s' % keep_cl
self.feature_type = PerturbationConstants.ANY
def transform(self, X, y):
""" Apply the perturbation to a dataset.
Args:
X (numpy.ndarray): feature data.
y (numpy.ndarray): target data.
"""
Xt = copy.deepcopy(X)
yt = copy.deepcopy(y)
Xt, yt = only_one_shift(Xt, yt, self.keep_cl)
return Xt, yt
class KnockOut(Shift):
""" Sample data to remove a portion of a given class.
Args:
cl (int or str): class to subsample
Attributes:
cl (int or str): class to subsample
name (str): name of the perturbation
feature_type (int): identifier of the type of feature for which this perturbation is valid
(see PerturbationConstants).
"""
def __init__(self, cl=0, samples_fraction=1.0):
super(KnockOut, self).__init__()
self.cl = cl
self.samples_fraction = samples_fraction
self.name = 'ko_shift_%s_%.2f' % (cl, samples_fraction)
self.feature_type = PerturbationConstants.ANY
def transform(self, X, y):
""" Apply the perturbation to a dataset.
Args:
X (numpy.ndarray): feature data.
y (numpy.ndarray): target data.
"""
Xt = copy.deepcopy(X)
yt = copy.deepcopy(y)
Xt, yt = knockout_shift(Xt, yt, self.cl, self.samples_fraction)
return Xt, yt
class Rebalance(Shift):
""" Sample data to match a given distribution of classes.
Args:
priors (array-like): desired classes frequencies
Attributes:
priors (array-like): desired classes frequencies
name (str): name of the perturbation
feature_type (int): identifier of the type of feature for which this perturbation is valid
(see PerturbationConstants).
"""
def __init__(self, priors):
super(Rebalance, self).__init__()
self.priors = priors
self.name = 'rebalance_shift'
for p in priors:
self.name += '_%.2f' % p
self.feature_type = PerturbationConstants.ANY
def transform(self, X, y):
""" Apply the perturbation to a dataset.
Args:
X (numpy.ndarray): feature data.
y (numpy.ndarray): target data.
"""
Xt = copy.deepcopy(X)
yt = copy.deepcopy(y)
Xt, yt = rebalance_shift(Xt, yt, self.priors)
return Xt, yt
# Resample instances of all classes by given priors.
def rebalance_shift(x, y, priors):
labels, counts = np.unique(y, return_counts=True)
n_labels = len(labels)
n_priors = len(priors)
assert (n_labels == n_priors)
assert (np.sum(priors) == 1.)
n_to_sample = y.shape[0]
for label_idx, prior in enumerate(priors):
if prior > 0:
n_samples_label = counts[label_idx]
max_n_to_sample = np.round(n_samples_label / prior)
if n_to_sample > max_n_to_sample:
n_to_sample = max_n_to_sample
resampled_counts = [int(np.round(prior * n_to_sample)) for prior in priors]
resampled_indices = []
for cl, res_count in zip(labels, resampled_counts):
if res_count:
cl_indices = np.where(y == cl)[0]
cl_res_indices = np.random.choice(cl_indices, res_count, replace=False)
resampled_indices.extend(cl_res_indices)
resampled_indices = np.random.choice(resampled_indices, x.shape[0], replace=True)
x = x[resampled_indices, :]
y = y[resampled_indices]
return x, y
# Remove instances of a single class.
def knockout_shift(x, y, cl, delta):
n_rows = x.shape[0]
del_indices = np.where(y == cl)[0]
until_index = ceil(delta * len(del_indices))
if until_index % 2 != 0:
until_index = until_index + 1
del_indices = del_indices[:until_index]
x = np.delete(x, del_indices, axis=0)
y = np.delete(y, del_indices, axis=0)
indices_cl = np.where(y == cl)[0]
indices_not_cl = np.where(y != cl)[0]
repeat_indices = np.random.choice(indices_not_cl, n_rows-len(indices_cl), replace=True)
x_not_cl = x[repeat_indices, :]
y_not_cl = y[repeat_indices]
x = np.concatenate((x_not_cl, x[indices_cl, :]))
y = np.concatenate((y_not_cl, y[indices_cl]))
permuted_indices = np.random.permutation(n_rows)
x = x[permuted_indices, :]
y = y[permuted_indices]
return x, y
# Remove all classes except for one via multiple knock-out.
def only_one_shift(x, y, keep_cl):
labels = np.unique(y)
for cl in labels:
if cl != keep_cl:
x, y = knockout_shift(x, y, cl, 1.0)
return x, y
| 32.839506 | 98 | 0.626692 |
10a540a8e269a3f80bef8f24eca11e9cb1aa6974 | 5,577 | py | Python | attic/PhotoADaySheep.py | charlesreid1/tripos-bot | d9b7dae25ab697606010b21211039766f7e6025d | [
"MIT"
] | null | null | null | attic/PhotoADaySheep.py | charlesreid1/tripos-bot | d9b7dae25ab697606010b21211039766f7e6025d | [
"MIT"
] | null | null | null | attic/PhotoADaySheep.py | charlesreid1/tripos-bot | d9b7dae25ab697606010b21211039766f7e6025d | [
"MIT"
] | null | null | null | import rainbowmindmachine as rmm
import twitter
import logging
import glob
import time
from datetime import datetime
class PhotoADaySheep(rmm.MediaSheep):
"""
This sheep will tweet a photo a day.
This overrides Sheep's default
inner/outer timing loop and tweet behavior,
but re-uses a lot of other stuff.
Constructor takes a dictionary of parameters,
stored in self.params
Parameters:
images_dir: directory containing images
Collective actions:
photo_a_day: tweet an image a day
"""
def perform_action(self,action,params):
"""
Performs action indicated by string (action),
passing a dictionary of parameters (params)
Actions:
photo_a_day: tweet an image a day
"""
rmm.Sheep.perform_action(self,action,params)
if action=='photo_a_day':
self.photo_a_day(params)
def populate_queue(self,params):
"""
Load parameters and prepare the tweet queue.
This is actually just a list of image files, indexed by
the day of the year that they should be tweeted out.
This method is only called by the public tweet() method.
"""
# The format of this file can be whatever we'd like.
#
# Opening a json file with contents like
# { "1" : "001.png",
# seems wasteful.
# Cut to the chase with glob.
return glob.glob(params['images_dir']+"/*.jpg")
def photo_a_day(self,params):
"""
Tweets an image a day,
at 8 o'clock or so.
Parameters:
upload: boolean, upload media or not
publish: boolean, publish or not
"""
# --------------------------
# Process parameters
tweet_params = params
# Default parameter values
defaults = {}
defaults['publish'] = False
# populate missing params with default values
for dk in defaults.keys():
if dk not in tweet_params.keys():
tweet_params[dk] = defaults[dk]
# --------------------------
# Start The Calendar
remcycle = 3600
prior_dd = 0
while True:
try:
# Repopulate in case there are changes
twit_images = self.populate_queue(tweet_params)
now = datetime.now()
yy, mm, dd, hh, mm = (now.year, now.month, now.day, now.hour, now.minute)
# offset for server +8 london time
offset = 8
if( abs(dd-prior_dd)>0 and hh>(8 + offset)):
# Index = days since beginning of year
index = (datetime.now() - datetime(yy,1,1,0,0,0)).days
# If there is a photo for this date,
if(index < len(twit_images)):
# Get photo for this date
tweet_params['image_file'] = twit_images[index]
img_info = {}
# Upload image
if(tweet_params['upload']):
img_info = self.upload_image_to_twitter(tweet_params)
if(tweet_params['upload'] and tweet_params['publish']):
twit = {
'status': 'Your daily Mathematical Tripos question.',
'media_ids': img_info['media_id_string']
}
self._tweet(twit)
msg = self.timestamp_message(">>> Twitted a twit...")
logging.info(msg)
else:
self._print("Testing image tweet: %s"%(tweet_params['image_file']))
# Update prior_dd
prior_dd = dd
msg = self.timestamp_message("Sleeping...")
logging.info(msg)
time.sleep(remcycle)
except Exception as err:
# oops!
msg1 = self.timestamp_message("Sheep encountered an exception. More info:")
# Fix this:
msg2 = self.timestamp_message(str(err))
msg3 = self.timestamp_message("Sheep is continuing...")
logging.info(msg1)
logging.info(msg2)
logging.info(msg3)
# For debugging:
raise Exception(err)
time.sleep(remcycle)
except AssertionError:
raise Exception("Error: tweet queue was empty. Check your populate_queue() method definition.")
def _tweet(self,twit):
try:
# tweet:
stats = self.t.statuses.update(
status = twit['status'],
media_ids = twit['media_ids']
)
msg = self.timestamp_message(">>> Tweet was successful")
except twitter.TwitterError as e:
if e.message[0]['code'] == 185:
msg = self.timestamp_message("Twitter error: Daily message limit reached")
logging.info(msg)
elif e.message[0]['code'] == 187:
msg = self.timestamp_message("Twitter error: Duplicate error")
logging.info(msg)
else:
msg = self.timestamp_message("Twitter error: "+e.message)
logging.info(msg)
| 28.6 | 111 | 0.506903 |
59508d15156fb309a940f63332f480310a6fd65d | 9,713 | py | Python | reports/configs/only_logd_dgin6_2/other_config.py | hengwei-chan/graph_network_demo | 542f2a59b1b9708abdc718d77db7111f3ba2df96 | [
"MIT"
] | 1 | 2021-10-18T03:44:53.000Z | 2021-10-18T03:44:53.000Z | reports/configs/only_logd_dgin6_2/other_config.py | hengwei-chan/graph_network_demo | 542f2a59b1b9708abdc718d77db7111f3ba2df96 | [
"MIT"
] | null | null | null | reports/configs/only_logd_dgin6_2/other_config.py | hengwei-chan/graph_network_demo | 542f2a59b1b9708abdc718d77db7111f3ba2df96 | [
"MIT"
] | 1 | 2022-02-22T08:32:01.000Z | 2022-02-22T08:32:01.000Z | from dataclasses import dataclass, field
from typing import List
import tensorflow as tf
from graph_networks.utilities import *
import logging
import os
ATOM_FEATURE_DIM = DGIN6_ATOM_FEATURE_DIM
EDGE_FEATURE_DIM = DGIN6_EDGE_FEATURE_DIM
@dataclass
class BasicModelConfig:
"""
Config for model1/2/3 run file.
General model parameters
"""
model_name: str = 'only_logd_dgin6_2' # without h_w in DGIN gin part - added h_v_0 instead
# whole train/eval split - no more double split within train data set
# random train/test split in get_data_sd - only change overall_seed
# CHANGES dgin3 10.02.2021:
# *added new bondFeaturesDGIN2 and atomFeaturesDGIN2; DGIN2_ATOM_FEATURE_DIM; DGIN2_EDGE_FEATURE_DIM
# *from project_path+'data/processed/lipo/pickled/train_frags3/' to project_path+'data/processed/lipo/pickled/test_frags3/'
# CHANGES dgin3 16.02.2021:
# *added new bondFeaturesDGIN3 and atomFeaturesDGIN3; DGIN3_ATOM_FEATURE_DIM; DGIN3_EDGE_FEATURE_DIM
# *from project_path+'data/processed/lipo/pickled/train_frags_dgin3/' to project_path+'data/processed/lipo/pickled/test_frags_dgin3/'
# CHANGES dgin4 16.02.2021:
# *added add_species bool in model1 config - previously not there; for dgin2 featurization adds the species type after the dgin
# encoding before logD prediction
# test_frags_dgin4 was added for species inclusion in model2 call()
batch_size: int =15
override_if_exists: bool = True
overall_seed: int = 2
# path to the project folder
project_path:str = "./"
retrain_model: bool = False
retrain_model_name: str = ''
retrain_model_epoch: str = ''
retrain_model_weights_dir: str = project_path+'reports/model_weights/'+retrain_model_name+'/epoch_'+retrain_model_epoch+'/checkp_'+retrain_model_epoch
train_data_dir: str = project_path+'data/processed/lipo/pickled/train_dgin6_logd/'
test_data_dir: str = project_path+'data/processed/lipo/pickled/test_dgin6_logd/'
combined_dataset: bool = False
add_train_data_dir: str = project_path+'data/processed/lipo/pickled/train_dgin6_logs/'
add_test_data_dir: str = project_path+'data/processed/lipo/pickled/test_dgin6_logs/'
test_model: bool = False
test_model_epoch: str = '887'
# define the number or test runs for the CI.
# the mean and std of the RMSE and r^2 of the combined runs are taken as the output.
test_n_times: int = 1
# do you want to test the model with consensus mode?
# if yes, a defined ML model will be included in the consensus predictions during the testing.
consensus: bool = False
# include dropout during testing?
include_dropout: bool = False
test_model_weights_dir: str = project_path+'reports/model_weights/'+model_name+'/epoch_'+test_model_epoch+'/checkp_'+test_model_epoch
# To save the prediction values for each property set to True
# When this flag is True - the whole test dataset is taken an test_n_times is set to zero!
save_predictions: bool = False
# define the folder where you want to save the predictions.
# For each property, a file is created under the property name ("./logd.txt","./logs.txt","./logp.txt","./others.txt")
test_prediction_output_folder: str = project_path+"reports/predictions/"+model_name+"/"
encode_hidden: bool = False
log_dir: str = project_path+'reports/logs/'+model_name+'.log'
verbosity_level = logging.INFO
plot_dir: str = project_path+'reports/figures/'+model_name+'/'
tensorboard_log_dir: str = project_path+'reports/tensorboard/'+model_name+'/'
config_log_dir: str = project_path+'reports/configs/'+model_name+'/'
model_weights_dir: str = project_path+'reports/model_weights/'+model_name+'/'
stats_log_dir: str = project_path+'reports/stats/'+model_name+'/'
@dataclass
class DGINConfig:
"""
Config for direcpted-mpnn class.
"""
dropout_aggregate_dmpnn: bool = False
layernorm_aggregate_dmpnn: bool = True
dropout_passing_dmpnn: bool = False
layernorm_passing_dmpnn: bool = True
dropout_aggregate_gin: bool = False
layernorm_aggregate_gin: bool = True
dropout_passing_gin: bool = False
layernorm_passing_gin: bool = True
gin_aggregate_bias: bool = False
dmpnn_passing_bias: bool = False
init_bias: bool = False
massge_iteration_dmpnn: int = 4
message_iterations_gin: int = 4
dropout_rate: float = 0.15
input_size: int = (ATOM_FEATURE_DIM+EDGE_FEATURE_DIM) # combination of node feature len (33) and edge feature len (12)
passing_hidden_size: int = 56 # this can be changed
input_size_gin: int = (ATOM_FEATURE_DIM+passing_hidden_size)
return_hv: bool = True # model3 parameter
@dataclass
class Model1Config:
"""
Config model1 class - no subclass configs are defined here.
"""
validation_split: float = 0.90
learning_rate: float = 0.004
clip_rate: float = 0.6
optimizer = tf.keras.optimizers.Adam(learning_rate)
lipo_loss_mse = tf.keras.losses.mse
lipo_loss_mae = tf.keras.losses.mae
logP_loss_mse = tf.keras.losses.mse
logS_loss_mse = tf.keras.losses.mse
other_loss_mse = tf.keras.losses.mse
mw_loss_mse = tf.keras.losses.mse
metric = tf.keras.losses.mae
epochs: int = 1600
# define the number of epochs for each test run.
save_after_epoch: int = 3
# dropout rate for the general model - mainly the MLP for the different log predictions
dropout_rate: float = 0.15 # the overall dropout rate of the readout functions
# the seed to shuffle the training/validation dataset; For the same dataset, even when
# combined_dataset is True, it is the same training/valiation instances
train_data_seed: int = 0
dropout_rate: float = 0.15 # the overall dropout rate of the readout functions
train_data_seed: int = 0
hidden_readout_1: int = 32
hidden_readout_2: int = 14
activation_func_readout = tf.nn.relu
include_logD: bool = True
include_logS: bool = False
include_logP: bool = False
include_other: bool = False
include_mw: bool = False
include_rot_bond: bool = False
include_HBA: bool = False
include_HBD: bool = False
# define the starting threshold for the RMSE of the model. When the comnbined RMSE
# is below this threshold, the model weights are being safed and a new threshold
# is set. It only serves as a starting threshold so that not too many models
# are being safed. Depends on how many log endpoints are being taken into
# consideration - as three endpoints have a higher combined RMSE as only one
# endpoint.
best_evaluation_threshold: float = 2.45 #was introduced on the 25.03.2021/
# define the individual thresholds. If one model is better, the corresponding
# model weights are being saved.
best_evaluation_threshold_logd: float = 1.85
best_evaluation_threshold_logp: float = 1.65
best_evaluation_threshold_logs: float = 2.15
best_evaluation_threshold_other: float = 2.15
# 2.45 for all_logs
# 0.70 logP
# 0.75 logD
# 1.00 logS
# 1.75 logSD
# 1.70 logSP
# 1.45 logDP
include_fragment_conv: bool = False # was introduced on the 4.12.2020
use_rmse: bool = True # uses RMSE instead of MSE for only lipo_loss
shuffle_inside: bool = True # reshuffles the train/valid test seach in each epoch (generalizes)
add_species: bool = False # 16.02 introduction; previously not there; for dgin3 adds the species type after the dgin encoding before logD prediction
@dataclass
class FrACConfig:
"""
Config fragment aggregation class - no subclass configs are defined here.
"""
input_size_gin: int = 28
layernorm_aggregate: bool = True
reduce_mean: bool = True # when false -> reduce_sum
@dataclass
class MLConfig:
"""
Configs for the ML algorithm
"""
# which algorithm do you want to use for the consensus?
# possibilities are: "SVM", "RF", "KNN" or "LR" - all are regression models!
# SVM: Support Vector Machine; RF: Random Forest, KNN: K-Nearest Neigbors; LR: Linear Regression;
algorithm: str = "SVM"
# which fingerprint to use - possibilities are: "ECFP" or "MACCS"
fp_types: str = "ECFP"
# If 'ECFP' fingerprint is used, define the number of bits - maximum is 2048!
n_bits: int = 2048
# If "ECFP" fingerprint is used, define the radius
radius: int = 4
# define if descriptors should be included into the non-GNN molecular representation
include_descriptors: bool = True
# define if the descriptors should be standardizedby scaling and centering (Sklearn)
standardize: bool = True
@dataclass
class Config():
"""
Overall config class for model2 and run file.
Includes all submodels config
"""
basic_model_config: BasicModelConfig
model1_config: Model1Config
d_gin_config: DGINConfig
frag_acc_config: FrACConfig
ml_config: MLConfig
model: str = 'model10' | 43.950226 | 169 | 0.670442 |
7db39e9dfef43ac083c02c0c9b4cf2a21addbe82 | 551 | py | Python | product_details/version_compare/decorators.py | pmclanahan/django-mozilla-product-details | 36ef06539d6b34c4f345fd0d3e16937d0db9a752 | [
"BSD-3-Clause"
] | null | null | null | product_details/version_compare/decorators.py | pmclanahan/django-mozilla-product-details | 36ef06539d6b34c4f345fd0d3e16937d0db9a752 | [
"BSD-3-Clause"
] | null | null | null | product_details/version_compare/decorators.py | pmclanahan/django-mozilla-product-details | 36ef06539d6b34c4f345fd0d3e16937d0db9a752 | [
"BSD-3-Clause"
] | null | null | null | import cPickle
import functools
def memoize(fctn):
"""
Memoizing decorator, courtesy of:
http://pko.ch/2008/08/22/memoization-in-python-easier-than-what-it-should-be/
"""
memory = {}
@functools.wraps(fctn)
def memo(*args,**kwargs):
haxh = cPickle.dumps((args, sorted(kwargs.iteritems())))
if haxh not in memory:
memory[haxh] = fctn(*args,**kwargs)
return memory[haxh]
if memo.__doc__:
memo.__doc__ = "\n".join([memo.__doc__,"This function is memoized."])
return memo
| 25.045455 | 81 | 0.618875 |
14af8a650faca41e55b9c3d3f3e9169a0892745d | 1,017 | py | Python | lib/text.py | matthelliwell2/grammer | 19b5c87fc0a887e269082ebcc67d008f6f4adee6 | [
"MIT"
] | null | null | null | lib/text.py | matthelliwell2/grammer | 19b5c87fc0a887e269082ebcc67d008f6f4adee6 | [
"MIT"
] | null | null | null | lib/text.py | matthelliwell2/grammer | 19b5c87fc0a887e269082ebcc67d008f6f4adee6 | [
"MIT"
] | null | null | null | import re
specialCharacterTranslations = {
"?\\question-mark": "?",
":\\colon": ":",
";\\semicolon": ";",
"*\\asterisk": "*",
"~\\tilde": "~",
",\\comma": ",",
".\\period": ".",
".\\dot": ".",
"/\\slash": "/",
"_\\underscore": "_",
"!\\exclamation-mark": "!",
"@\\at-sign": "@",
"\\backslash": "\\",
"(\\left-parenthesis": "(",
")\\right-parenthesis": ")",
"[\\left-square-bracket": "[",
"]\\right-square-bracket": "]",
"{\\left-curly-bracket": "{",
"}\\right-curly-bracket": "}",
"<\\left-angle-bracket": "<",
">\\right-angle-bracket": ">",
"|\\vertical-bar": "|",
"$\\dollar-sign": "$",
"=\\equals-sign": "=",
"+\\plus-sign": "+",
"-\\minus-sign": "-",
"--\\dash": "-",
"\x96\\dash": "-",
"-\\hyphen": "-",
"\"\\right-double-quote": "\"",
"\"\\left-double-quote": "\"",
}
specialCharacterTranslationsRe = re.compile('|'.join(re.escape(key) for key in specialCharacterTranslations.keys()))
| 26.763158 | 116 | 0.450344 |
48661aa714ee07b7aa8989adfebee64b5c57efb9 | 7,481 | py | Python | tensorflow/python/keras/distribute/dataset_creator_model_fit_test_base.py | bhanuprakashbv/tensorflow | d2e62d5da7bf210f9adfd60054f23ece97329aef | [
"Apache-2.0"
] | null | null | null | tensorflow/python/keras/distribute/dataset_creator_model_fit_test_base.py | bhanuprakashbv/tensorflow | d2e62d5da7bf210f9adfd60054f23ece97329aef | [
"Apache-2.0"
] | null | null | null | tensorflow/python/keras/distribute/dataset_creator_model_fit_test_base.py | bhanuprakashbv/tensorflow | d2e62d5da7bf210f9adfd60054f23ece97329aef | [
"Apache-2.0"
] | null | null | null | # Lint as: python3
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `DatasetCreator` with `Model.fit` across usages and strategies."""
import os
from absl.testing import parameterized
import numpy as np
from tensorflow.python import keras
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.distribute import parameter_server_strategy_v2
from tensorflow.python.distribute import sharded_variable
from tensorflow.python.framework import config
from tensorflow.python.keras import callbacks as callbacks_lib
from tensorflow.python.keras.distribute import multi_worker_testing_utils
from tensorflow.python.keras.engine import sequential
from tensorflow.python.keras.layers import core as core_layers
from tensorflow.python.keras.layers.preprocessing import string_lookup
from tensorflow.python.keras.optimizer_v2 import gradient_descent
from tensorflow.python.keras.utils import dataset_creator
from tensorflow.python.ops import random_ops
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging
class DatasetCreatorModelFitTestBase(test.TestCase, parameterized.TestCase):
"""The base class for DatasetCreator with Model.fit tests."""
def _get_dataset_fn(self, use_lookup_layer):
if use_lookup_layer:
filepath = os.path.join(self.get_temp_dir(), "vocab")
with open(filepath, "w") as f:
f.write("\n".join(["earth", "wind", "and", "fire"]))
def dataset_fn(input_context):
del input_context
lookup_layer = string_lookup.StringLookup(
num_oov_indices=1, vocabulary=filepath)
x = np.array([["earth", "wind", "and", "fire"],
["fire", "and", "earth", "michigan"]])
y = np.array([0, 1])
map_fn = lambda x, y: (lookup_layer(x), y)
return dataset_ops.DatasetV2.from_tensor_slices(
(x, y)).shuffle(10).repeat().batch(2).map(map_fn)
else:
def dataset_fn(input_context):
del input_context
x = random_ops.random_uniform((10, 10))
y = random_ops.random_uniform((10,))
return dataset_ops.DatasetV2.from_tensor_slices(
(x, y)).shuffle(10).repeat().batch(2)
return dataset_fn
def _model_compile(self,
strategy,
steps_per_execution=1,
run_eagerly=False,
with_normalization_layer=False,
use_lookup_layer=False):
class ResultAssertingCallback(callbacks_lib.Callback):
"""A callback that asserts the result of the tests."""
def __init__(self):
self._prev_epoch = -1
def on_epoch_end(self, epoch, logs=None):
logging.info("testModelFit: epoch=%r, logs=%r", epoch, logs)
if epoch <= self._prev_epoch:
raise RuntimeError("Epoch is supposed to be larger than previous.")
self._prev_epoch = epoch
is_loss_float = (
logs.get("loss", None) is not None and
isinstance(logs["loss"], (float, np.floating)))
if not is_loss_float:
raise RuntimeError("loss is supposed to be in the logs and float.")
def on_train_end(self, logs=None):
if self._prev_epoch != 9:
raise RuntimeError("Unexpected last epoch: {}".format(
self._prev_epoch))
# TODO(b/182193218): Use ParameterServerStrategy as a proper strategy
# combination.
if strategy == "ParameterServerStrategy":
gpu_devices = config.list_physical_devices("GPU")
if len(gpu_devices) > 1:
self.skipTest("b/178452835: Multi-GPUs not supported in "
"ParameterServerStrategy.")
strategy = parameter_server_strategy_v2.ParameterServerStrategyV2(
multi_worker_testing_utils.make_parameter_server_cluster(3, 2),
variable_partitioner=sharded_variable.FixedShardsPartitioner(2))
with strategy.scope():
model = sequential.Sequential([core_layers.Dense(10)])
if with_normalization_layer:
norm = keras.layers.BatchNormalization(
axis=-1, input_shape=(4, 4, 3), momentum=0.8)
model.add(norm)
model.add(core_layers.Dense(1, activation="sigmoid"))
self._metric = keras.metrics.Accuracy()
model.compile(
gradient_descent.SGD(),
loss="binary_crossentropy",
metrics=[self._metric],
steps_per_execution=steps_per_execution,
run_eagerly=run_eagerly)
return model, [ResultAssertingCallback()]
def _model_fit(self,
strategy,
steps_per_execution=1,
validation_data=None,
x=None,
steps_per_epoch=10,
run_eagerly=False,
with_normalization_layer=False,
callbacks=None,
use_lookup_layer=False):
if callbacks is None:
callbacks = []
model, default_callbacks = self._model_compile(strategy,
steps_per_execution,
run_eagerly,
with_normalization_layer,
use_lookup_layer)
callbacks += default_callbacks
x = x or dataset_creator.DatasetCreator(
self._get_dataset_fn(use_lookup_layer))
validation_data = (
validation_data or
dataset_creator.DatasetCreator(self._get_dataset_fn(use_lookup_layer)))
model.fit(
x,
epochs=10,
steps_per_epoch=steps_per_epoch,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=steps_per_epoch)
return model
def _model_evaluate(self,
strategy,
steps_per_execution=1,
validation_data=None,
steps=10,
run_eagerly=False,
with_normalization_layer=False,
callbacks=None):
if callbacks is None:
callbacks = []
model, default_callbacks = self._model_compile(strategy,
steps_per_execution,
run_eagerly,
with_normalization_layer)
callbacks += default_callbacks
def dataset_fn(input_context):
del input_context
x = random_ops.random_uniform((10, 10))
y = random_ops.random_uniform((10, 1))
return dataset_ops.DatasetV2.from_tensor_slices(
(x, y)).shuffle(10).repeat().batch(8)
validation_data = (
validation_data or dataset_creator.DatasetCreator(dataset_fn))
model.evaluate(x=validation_data, steps=steps, callbacks=callbacks)
return model
| 39.167539 | 80 | 0.634541 |
21e9be6b0f31ec3031499909869ce44dbfaeaeb9 | 324 | py | Python | communities/admin.py | askmeaboutlo0m/website | 3df97d061a425e7fbb3f173c78ff01d831575aa0 | [
"MIT"
] | 9 | 2017-06-04T15:46:05.000Z | 2021-09-04T23:28:03.000Z | communities/admin.py | askmeaboutlo0m/website | 3df97d061a425e7fbb3f173c78ff01d831575aa0 | [
"MIT"
] | 24 | 2018-02-10T04:29:00.000Z | 2021-10-01T16:01:04.000Z | communities/admin.py | askmeaboutlo0m/website | 3df97d061a425e7fbb3f173c78ff01d831575aa0 | [
"MIT"
] | 4 | 2020-03-23T03:42:32.000Z | 2022-03-16T17:01:09.000Z | from django.contrib import admin
from . import models
class MembershipAdmin(admin.TabularInline):
model = models.Membership
raw_id_fields = ('user',)
extra = 0
@admin.register(models.Community)
class CommunityAdmin(admin.ModelAdmin):
list_display = ('title', 'status',)
inlines = (MembershipAdmin,)
| 20.25 | 43 | 0.719136 |
ef9bd0ac42cbb4915cc5070be8de863f8f0ee101 | 1,333 | py | Python | examples/plotting/file/hover.py | gitter-badger/bokeh | 5481346de1642a4e6710d32b70262fd6c2674360 | [
"BSD-3-Clause"
] | 2 | 2015-07-23T21:19:52.000Z | 2016-01-25T17:00:15.000Z | examples/plotting/file/hover.py | gitter-badger/bokeh | 5481346de1642a4e6710d32b70262fd6c2674360 | [
"BSD-3-Clause"
] | null | null | null | examples/plotting/file/hover.py | gitter-badger/bokeh | 5481346de1642a4e6710d32b70262fd6c2674360 | [
"BSD-3-Clause"
] | 2 | 2015-12-22T04:13:10.000Z | 2021-07-06T21:18:04.000Z | from __future__ import division
import numpy as np
from six.moves import zip
from collections import OrderedDict
from bokeh.plotting import *
from bokeh.objects import HoverTool
TOOLS="pan,wheel_zoom,box_zoom,reset,hover,previewsave"
xx, yy = np.meshgrid(range(0,101,4), range(0,101,4))
x = xx.flatten()
y = yy.flatten()
N = len(x)
inds = [str(i) for i in np.arange(N)]
radii = np.random.random(size=N)*0.4 + 1.7
colors = [
"#%02x%02x%02x" % (r, g, 150) for r, g in zip(np.floor(50+2*x), np.floor(30+2*y))
]
foo = list(itertools.permutations("abcdef"))[:N]
bar = np.random.normal(size=N)
source = ColumnDataSource(
data=dict(
x=x,
y=y,
radius=radii,
colors=colors,
foo=foo,
bar=bar,
)
)
output_file("hover.html")
hold()
circle(x, y, radius=radii, source=source, tools=TOOLS,
fill_color=colors, fill_alpha=0.6,
line_color=None, Title="Hoverful Scatter")
text(x, y, text=inds, alpha=0.5, text_font_size="5pt",
text_baseline="middle", text_align="center", angle=0)
hover = curplot().select(dict(type=HoverTool))
hover.tooltips = OrderedDict([
("index", "$index"),
("(x,y)", "($x, $y)"),
("radius", "@radius"),
("fill color", "$color[hex, swatch]:fill_color"),
("foo", "@foo"),
("bar", "@bar"),
])
show() # open a browser
| 23.385965 | 85 | 0.627907 |
f09ac49dca2374c85978859ef77b1a7d54b75803 | 6,514 | py | Python | fidimag/atomistic/atomistic_driver.py | computationalmodelling/fidimag | 07a275c897a44ad1e0d7e8ef563f10345fdc2a6e | [
"BSD-2-Clause"
] | 53 | 2016-02-27T09:40:21.000Z | 2022-01-19T21:37:44.000Z | fidimag/atomistic/atomistic_driver.py | computationalmodelling/fidimag | 07a275c897a44ad1e0d7e8ef563f10345fdc2a6e | [
"BSD-2-Clause"
] | 132 | 2016-02-26T13:18:58.000Z | 2021-12-01T21:52:42.000Z | fidimag/atomistic/atomistic_driver.py | computationalmodelling/fidimag | 07a275c897a44ad1e0d7e8ef563f10345fdc2a6e | [
"BSD-2-Clause"
] | 32 | 2016-02-26T13:21:40.000Z | 2022-03-08T08:54:51.000Z | from __future__ import division
from __future__ import print_function
from fidimag.common.driver_base import DriverBase
import fidimag.extensions.clib as clib
import fidimag.extensions.cvode as cvode
from fidimag.common.vtk import VTK
import fidimag.common.constant as const
import numpy as np
class AtomisticDriver(DriverBase):
"""
A class with shared methods and properties for different drivers to solve
the Landau-Lifshitz-Gilbert equation
Variables that are proper of the driver class:
* alpha (damping)
* mu_s_const
* t
* spin_last
* dm_dt
* integrator_tolerances_set
* step
* n (from mesh)
* n_nonzero (from mesh and set_Ms method in Simulation)
* gamma
* do_precession
* default_c (correction factor to keep the magnetisation normalised
during the LLG equation integration. See the
fidimag/atomistic/lib/llg.c file for more details)
From DriverBase: t, spin_last, dm_dt, integrator_tolerances_set, step
"""
def __init__(self, mesh, spin, mu_s, mu_s_inv, field, pins,
interactions,
name,
data_saver,
use_jac,
integrator='sundials'
):
super(AtomisticDriver, self).__init__()
# These are (ideally) references to arrays taken from the Simulation
# class. Variables with underscore are arrays changed by a property in
# the simulation class
self.mesh = mesh
self.spin = spin
self._mu_s = mu_s
self._mu_s_inv = mu_s_inv
# Only for LLG STT: (??)
self.mu_s_const = 0
self.field = field
self._pins = pins
self.interactions = interactions
# Strings are not referenced, this is a copy:
self.name = name
# The following are proper of the driver class: (see DriverBase) ------
# See also the set_default_options() function
self.n = self.mesh.n
self.n_nonzero = self.mesh.n # number of spins that are not zero
# We check this in the set_Ms function
self.initiate_variables(self.n)
self.set_default_options()
# Integrator options --------------------------------------------------
# In the old code, it seemed that self.sundials_jtn was not defined
# anywhere else. Here, we will use the same integrators than in the
# micromagnetic code, where we have self.sundials_jtimes instead of jtn
self.set_integrator(integrator, use_jac)
self.set_tols()
# When initialising the integrator in the self.integrator call, the
# CVOde class calls the set_initial_value function (with flag_m=0),
# which initialises a new integrator and allocates memory in this
# process. Now, when we set the magnetisation, we will use the same
# memory setting this flag_m to 1, so instead of calling CVodeInit we
# call CVodeReInit. If don't, memory is allocated in every call of
# set_m
self.flag_m = 1
# Factor for the dmdt magnitude in the relaxation function
self._dmdt_factor = 1.
# Savers --------------------------------------------------------------
# VTK saver for the magnetisation/spin field
self.VTK = VTK(self.mesh,
directory='{}_vtks'.format(self.name),
filename='m'
)
self.data_saver = data_saver
# Initialise the table for the data file with the simulation
# information:
# self.saver.entities['skx_num'] = {
# 'unit': '<>',
# 'get': lambda sim: sim.skyrmion_number(),
# 'header': 'skx_num'}
# self.saver.update_entity_order()
# ---------------------------------------------------------------------
def set_default_options(self, gamma=1, mu_s=1, alpha=0.1):
"""
Default option for the integrator
* The value of gamma (gyromagnetic ratio) for a free electron
is 1.76e11
"""
self.default_c = -1
self._alpha[:] = alpha
# When we create the simulation, mu_s is set to the default value. This
# is overriden when calling the set_mu_s method from the Simulation
# class or when setting mu_s directly (property)
# David Tue 19 Jun 2018: Not a very clear thing to do, we must set a
# WARNING
self._mu_s[:] = mu_s
self._mu_s_inv[:] = 1. / mu_s
self.mu_s_const = mu_s
self.gamma = gamma
self.do_precession = True
# Don't know the uselfulness of this function:
# def set_options(self, rtol=1e-8, atol=1e-10):
# self.set_tols(rtol, atol)
def sundials_rhs(self, t, y, ydot):
"""
Defined in the corresponding driver class
"""
pass
def sundials_jtn(self, mp, Jmp, t, m, fy):
# we can not copy mp to self.spin since m and self.spin is one object.
#self.spin[:] = mp[:]
print('NO jac...........')
self.compute_effective_field_jac(t, mp)
clib.compute_llg_jtimes(Jmp,
m, fy,
mp, self.field,
self.alpha,
self._pins,
self.gamma,
self.n,
self.do_precession,
self.default_c)
return 0
# -------------------------------------------------------------------------
# Save functions ----------------------------------------------------------
# -------------------------------------------------------------------------
def save_vtk(self):
"""
Save a VTK file with the magnetisation vector field and magnetic
moments as cell data. Magnetic moments are saved in units of
Bohr magnetons
NOTE: It is recommended to use a *cell to point data* filter in
Paraview or Mayavi to plot the vector field
"""
self.VTK.reset_data()
# Here we save both Ms and spins as cell data
self.VTK.save_scalar(self._mu_s / const.mu_B, name='mu_s')
self.VTK.save_vector(self.spin.reshape(-1, 3), name='spins')
self.VTK.write_file(step=self.step)
| 33.927083 | 79 | 0.547436 |
a279d14d3d013ced9b2d67ef8df1ab479fb216e3 | 7,964 | py | Python | ezodf2/meta.py | iwschris/ezodf2 | 061c4aa3f26e9157ad46155d8ce92db7187b0574 | [
"MIT"
] | 4 | 2015-03-15T22:32:35.000Z | 2019-12-23T12:13:13.000Z | ezodf2/meta.py | iwschris/ezodf2 | 061c4aa3f26e9157ad46155d8ce92db7187b0574 | [
"MIT"
] | 3 | 2017-08-17T09:36:42.000Z | 2021-12-13T19:43:28.000Z | ezodf2/meta.py | iwschris/ezodf2 | 061c4aa3f26e9157ad46155d8ce92db7187b0574 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
#coding:utf-8
# Purpose: ODF meta.xml document management
# Created: 28.12.2010
# Copyright (C) 2010, Manfred Moitzi
# License: MIT
from __future__ import unicode_literals, print_function, division
__author__ = "mozman <[email protected]>"
from datetime import datetime
from .compatibility import tostr
from .xmlns import CN, subelement, etree, register_class, XMLMixin
from .const import META_NSMAP, GENERATOR, META_NS
TAGS = {
'generator': 'meta:generator',
'title': 'dc:title',
'description': 'dc:description',
'subject': 'dc:subject',
'initial-creator': 'meta:initial-creator',
'creator': 'dc:creator',
'creation-date': 'meta:creation-date',
'date': 'dc:date',
'editing-cycles': 'meta:editing-cycles',
'language': 'dc:language',
}
@register_class
class OfficeDocumentMeta(XMLMixin):
TAG = CN('office:document-meta')
generator = GENERATOR
def __init__(self, xmlnode=None):
if xmlnode is None:
self.xmlnode = etree.Element(self.TAG, nsmap=META_NSMAP)
elif xmlnode.tag == self.TAG:
self.xmlnode = xmlnode
else:
raise ValueError("Unexpected root node: %s" % xmlnode.tag)
self._setup()
self.keywords = Keywords(self.meta)
self.usertags = Usertags(self.meta)
stats = self.meta.find(CN('meta:document-statistic'))
if stats is None:
stats = etree.SubElement(self.meta, CN('meta:document-statistic'))
self.count = Statistic(stats)
def _setup(self):
self.meta = self.xmlnode.find(CN('office:meta'))
if self.meta is None: # this is a new document
self.meta = subelement(self.xmlnode, CN('office:meta'))
self.xmlnode.set(CN('grddl:transformation'), "http://docs.oasis-open.org/office/1.2/xslt/odf2rdf.xsl")
self['creation-date'] = datetime.now().isoformat()
self.touch()
def clear(self):
""" Delete all metatags. """
self.meta.clear()
self.count.stats = etree.SubElement(self.meta, CN('meta:document-statistic'))
def touch(self):
self['date'] = datetime.now().isoformat()
self['generator'] = OfficeDocumentMeta.generator
def __setitem__(self, key, value):
cnkey = CN(TAGS[key]) # key in clark notation
element = subelement(self.meta, cnkey)
element.text = value
def __getitem__(self, key):
element = self.meta.find(CN(TAGS[key]))
if element is not None:
return element.text
else:
raise KeyError(key)
def inc_editing_cycles(self):
try:
count = self['editing-cycles']
try:
count = int(count) + 1
except ValueError:
count = 1
except KeyError:
count = 1
self['editing-cycles'] = tostr(count)
class Keywords(object):
def __init__(self, meta):
self.meta = meta
def __iter__(self):
""" Iterate over all keywords. """
for keyword in self.meta.findall(CN('meta:keyword')):
yield keyword.text
def __contains__(self, keyword):
""" True if 'keyword' exists, else False. """
return self._find(keyword) is not None
def add(self, keyword):
""" Add 'keyword' to meta data. """
tag = self._find(keyword)
if tag is None:
tag = etree.SubElement(self.meta, CN('meta:keyword'))
tag.text = keyword
def remove(self, keyword):
""" Remove 'keyword' from meta data. """
tag = self._find(keyword)
if tag is not None:
self.meta.remove(tag)
def clear(self):
""" Delete all keywords. """
for tag in self.meta.findall(CN('meta:keyword')):
self.meta.remove(tag)
def _find(self, keyword):
""" Find XML element for `keyword`. """
for tag in self.meta.findall(CN('meta:keyword')):
if keyword == tag.text:
return tag
return None
class Usertags(object):
def __init__(self, meta):
self.meta = meta
def __iter__(self):
""" Iterate over all user-defined metatags.
:returns: (name, value) tuples
"""
for metatag in self.meta.findall(CN('meta:user-defined')):
yield (metatag.get(CN('meta:name')), metatag.text)
def __contains__(self, name):
return self._find(name) is not None
def set(self, name, value, value_type=None):
""" Set/Replace user-defined metatag.
"""
tag = self._find(name)
if tag is None:
tag = etree.SubElement(self.meta, CN('meta:user-defined'))
tag.set(CN('meta:name'), name)
tag.text = tostr(value)
if value_type is not None:
tag.set(CN('meta:value-type'), value_type)
def __setitem__(self, name, value):
self.set(name, value)
def __getitem__(self, name):
""" Get value of user-defined metatag 'name'.
Raises KeyError, if 'name' not exist.
"""
tag = self._find(name)
if tag is not None:
return tag.text
raise KeyError(name)
def __delitem__(self, name):
""" Remove user defined metatag 'name'.
Raises KeyError, if 'name' not exist.
"""
tag = self._find(name)
if tag is not None:
self.meta.remove(tag)
else:
raise KeyError(name)
def typeof(self, name):
""" Get type of user defined tag `name`. """
tag = self._find(name)
if tag is not None:
return tag.get(CN('meta:value-type'), 'string')
raise KeyError(name)
def update(self, d):
""" Set user defined tags from dict `d`. """
for key, value in d.items():
self.__setitem__(key, value)
def clear(self):
""" Delete all user defined tags. """
for tag in self.meta.findall(CN('meta:user-defined')):
self.meta.remove(tag)
def _find(self, name):
for tag in self.meta.findall(CN('meta:user-defined')):
if name == tag.get(CN('meta:name')):
return tag
return None
class Statistic(object):
TYPES = frozenset(['page', 'table', 'draw', 'image', 'object',
'ole-object', 'paragraph', 'word', 'character',
'row', 'frame', 'sentence', 'syllable',
'non-whitespace-character', 'cell'])
NS = '{' + META_NS + '}%s-count'
def __init__(self, stats):
self.stats = stats
def __getitem__(self, key):
if key in Statistic.TYPES:
val = self.stats.get(Statistic.NS % key)
retval = 0
try:
retval = int(val)
except ValueError:
pass # it's not an int, should not happen (but shit happens)
except TypeError:
pass # None, no stats for `key`
return retval
else:
raise KeyError(key)
def __setitem__(self, key, value):
if key in Statistic.TYPES:
self.stats.set(Statistic.NS % key, tostr(value))
else:
raise KeyError(key)
def __iter__(self):
""" Iterate over all statistics.
:returns: (name, value) tulples
"""
prefix = len(META_NS) + 2
for key, value in self.stats.items():
yield (key[prefix:-6], int(value))
def update(self, d):
""" Set statistics from dict `d`. """
for key, value in d.items():
self.__setitem__(key, value)
def clear(self):
""" Clear all statistics. """
self.stats.clear()
| 31.983936 | 115 | 0.550226 |
10e71055c4a91ed3cf0cd6a87e0788f71c7003c3 | 1,577 | py | Python | code/venv/lib/python3.8/site-packages/datadog_api_client/v1/model/cancel_downtimes_by_scope_request.py | Valisback/hiring-engineers | 7196915dd5a429ae27c21fa43d527f0332e662ed | [
"Apache-2.0"
] | null | null | null | code/venv/lib/python3.8/site-packages/datadog_api_client/v1/model/cancel_downtimes_by_scope_request.py | Valisback/hiring-engineers | 7196915dd5a429ae27c21fa43d527f0332e662ed | [
"Apache-2.0"
] | null | null | null | code/venv/lib/python3.8/site-packages/datadog_api_client/v1/model/cancel_downtimes_by_scope_request.py | Valisback/hiring-engineers | 7196915dd5a429ae27c21fa43d527f0332e662ed | [
"Apache-2.0"
] | null | null | null | # Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
from datadog_api_client.v1.model_utils import (
ModelNormal,
cached_property,
)
class CancelDowntimesByScopeRequest(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
validations = {}
@cached_property
def openapi_types():
return {
"scope": (str,),
}
attribute_map = {
"scope": "scope",
}
read_only_vars = {}
def __init__(self, scope, *args, **kwargs):
"""CancelDowntimesByScopeRequest - a model defined in OpenAPI
Args:
scope (str): The scope(s) to which the downtime applies. For example, `host:app2`. Provide multiple scopes as a comma-separated list like `env:dev,env:prod`. The resulting downtime applies to sources that matches ALL provided scopes (`env:dev` **AND** `env:prod`).
Keyword Args:
"""
super().__init__(kwargs)
self._check_pos_args(args)
self.scope = scope
@classmethod
def _from_openapi_data(cls, scope, *args, **kwargs):
"""Helper creating a new instance from a response."""
self = super(CancelDowntimesByScopeRequest, cls)._from_openapi_data(kwargs)
self._check_pos_args(args)
self.scope = scope
return self
| 27.666667 | 276 | 0.65948 |
539117f1816050210fe78304e8265cc4f0a1dd3f | 851 | py | Python | LeetCodeSolutions/LeetCode_1373.py | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | 24 | 2020-03-28T06:10:25.000Z | 2021-11-23T05:01:29.000Z | LeetCodeSolutions/LeetCode_1373.py | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | null | null | null | LeetCodeSolutions/LeetCode_1373.py | lih627/python-algorithm-templates | a61fd583e33a769b44ab758990625d3381793768 | [
"MIT"
] | 8 | 2020-05-18T02:43:16.000Z | 2021-05-24T18:11:38.000Z | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxSumBST(self, root: TreeNode) -> int:
inf = 10 ** 9
res = 0
def helper(node):
nonlocal res
# isBST, cur_sum, leftmax, rightmin
if not node:
return True, 0, -inf, inf
lbst, l_sum, llmax, lrmin = helper(node.left)
rbst, r_sum, rrmax, rrmin = helper(node.right)
if lbst and rbst and llmax < node.val < rrmin:
cur_sum = l_sum + r_sum + node.val
res = max(res, cur_sum)
return (True, cur_sum, node.val, node.val)
else:
return False, 0, -inf, inf
helper(root)
return res
| 28.366667 | 58 | 0.508813 |
1758e7ab35e6a891224943172b2c6523f5a104f0 | 1,657 | py | Python | presidio-analyzer/setup.py | rakan41/presidio | 67cb019ff059ed772a8aacbf2f0f334390dca6ce | [
"MIT"
] | 1 | 2021-09-23T06:54:31.000Z | 2021-09-23T06:54:31.000Z | presidio-analyzer/setup.py | rakan41/presidio | 67cb019ff059ed772a8aacbf2f0f334390dca6ce | [
"MIT"
] | 1 | 2022-01-27T20:34:16.000Z | 2022-01-27T20:34:16.000Z | presidio-analyzer/setup.py | rakan41/presidio | 67cb019ff059ed772a8aacbf2f0f334390dca6ce | [
"MIT"
] | null | null | null | """Setup.py for Presidio Analyzer."""
import os.path
from os import path
import setuptools
__version__ = ""
this_directory = path.abspath(path.dirname(__file__))
parent_directory = os.path.abspath(os.path.join(this_directory, os.pardir))
with open(path.join(this_directory, "README.MD"), encoding="utf-8") as f:
long_description = f.read()
try:
with open(os.path.join(parent_directory, "VERSION")) as version_file:
__version__ = version_file.read().strip()
except Exception:
__version__ = os.environ.get("PRESIDIO_VERSION", "0.0.1-alpha")
setuptools.setup(
name="presidio_analyzer",
version=__version__,
description="Presidio analyzer package",
url="https://github.com/Microsoft/presidio",
packages=[
"presidio_analyzer",
"presidio_analyzer.predefined_recognizers",
"presidio_analyzer.nlp_engine",
"presidio_analyzer.recognizer_registry",
],
trusted_host=["pypi.org"],
tests_require=["pytest", "flake8==3.7.9"],
install_requires=[
"spacy==3.0.6",
"regex==2020.11.13",
"tldextract==3.1.0",
"pyyaml==5.4.1",
"pydantic==1.7.4",
"phonenumbers==8.12.24",
],
include_package_data=True,
license="MIT",
classifiers=[
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
],
long_description=long_description,
long_description_content_type="text/markdown",
)
| 30.685185 | 75 | 0.64997 |
dfcceb82a2f4b31cd6d464b698216db5ffceb315 | 554 | py | Python | kansha/models.py | AnomalistDesignLLC/kansha | 85b5816da126b1c7098707c98f217d8b2e524ff2 | [
"BSD-3-Clause"
] | 161 | 2015-04-27T17:07:40.000Z | 2021-10-14T23:14:56.000Z | kansha/models.py | AnomalistDesignLLC/kansha | 85b5816da126b1c7098707c98f217d8b2e524ff2 | [
"BSD-3-Clause"
] | 228 | 2015-05-27T15:47:31.000Z | 2018-11-24T04:05:11.000Z | kansha/models.py | AnomalistDesignLLC/kansha | 85b5816da126b1c7098707c98f217d8b2e524ff2 | [
"BSD-3-Clause"
] | 38 | 2015-05-27T15:16:15.000Z | 2021-03-24T05:34:08.000Z | # -*- coding:utf-8 -*-
#--
# Copyright (c) 2012-2014 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
#--
from __future__ import absolute_import
from elixir import EntityBase
from elixir import EntityMeta
from kansha import pickle
class Entity(EntityBase, pickle.UnpicklableMixin):
__metaclass__ = EntityMeta
@classmethod
def exists(cls, **kw):
return cls.query.filter_by(**kw).count() > 0
| 22.16 | 66 | 0.723827 |
a57652cf4f487c2ed29e8fcd3bfc01a5e4ddc9df | 1,968 | py | Python | Day01-15/code/Day11/json1.py | bdfd/Python_Zero2Hero_DS | 9dafe90b8112fdc3d07e1aa02e41ed3f019f733c | [
"MIT"
] | 3 | 2022-01-15T19:06:19.000Z | 2022-01-18T16:47:27.000Z | Day01-15/code/Day11/json1.py | bdfd/4.5_Data-Science-Python-Zero2Hero- | 9dafe90b8112fdc3d07e1aa02e41ed3f019f733c | [
"MIT"
] | null | null | null | Day01-15/code/Day11/json1.py | bdfd/4.5_Data-Science-Python-Zero2Hero- | 9dafe90b8112fdc3d07e1aa02e41ed3f019f733c | [
"MIT"
] | 1 | 2022-01-09T00:18:49.000Z | 2022-01-09T00:18:49.000Z | """
读取JSON数据
Version: 0.1
Author: BDFD
Date: 2018-03-13
"""
import json
import csv2
json_str = '{"name": "BDFD", "age": 38, "title": "叫兽"}'
result = json.loads(json_str)
print(result)
print(type(result))
print(result['name'])
print(result['age'])
# 把转换得到的字典作为关键字参数传入Teacher的构造器
teacher = csv2.Teacher(**result)
print(teacher)
print(teacher.name)
print(teacher.age)
print(teacher.title)
# 请思考如何将下面JSON格式的天气数据转换成对象并获取我们需要的信息
# 稍后我们会讲解如何通过网络API获取我们需要的JSON格式的数据
"""
{
"wendu": "29",
"ganmao": "各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。",
"forecast": [
{
"fengxiang": "南风",
"fengli": "3-4级",
"high": "高温 32℃",
"type": "多云",
"low": "低温 17℃",
"date": "16日星期二"
},
{
"fengxiang": "南风",
"fengli": "微风级",
"high": "高温 34℃",
"type": "晴",
"low": "低温 19℃",
"date": "17日星期三"
},
{
"fengxiang": "南风",
"fengli": "微风级",
"high": "高温 35℃",
"type": "晴",
"low": "低温 22℃",
"date": "18日星期四"
},
{
"fengxiang": "南风",
"fengli": "微风级",
"high": "高温 35℃",
"type": "多云",
"low": "低温 22℃",
"date": "19日星期五"
},
{
"fengxiang": "南风",
"fengli": "3-4级",
"high": "高温 34℃",
"type": "晴",
"low": "低温 21℃",
"date": "20日星期六"
}
],
"yesterday": {
"fl": "微风",
"fx": "南风",
"high": "高温 28℃",
"type": "晴",
"low": "低温 15℃",
"date": "15日星期一"
},
"aqi": "72",
"city": "北京"
}
"""
| 22.883721 | 58 | 0.359248 |
61741ee83cfdf93fcde6ffae5f2176e1ab367806 | 616 | py | Python | thingsboard_gateway/extensions/odbc/__init__.py | ferguscan/thingsboard-gateway | bc20fdb8e46f840b8538a010db2714ec6071fa5b | [
"Apache-2.0"
] | 1,123 | 2017-02-07T13:09:40.000Z | 2022-03-30T10:40:48.000Z | thingsboard_gateway/extensions/odbc/__init__.py | ferguscan/thingsboard-gateway | bc20fdb8e46f840b8538a010db2714ec6071fa5b | [
"Apache-2.0"
] | 655 | 2017-03-07T17:25:55.000Z | 2022-03-31T07:59:53.000Z | thingsboard_gateway/extensions/odbc/__init__.py | ferguscan/thingsboard-gateway | bc20fdb8e46f840b8538a010db2714ec6071fa5b | [
"Apache-2.0"
] | 648 | 2017-02-07T13:32:30.000Z | 2022-03-31T05:17:55.000Z | # Copyright 2020. ThingsBoard
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| 44 | 78 | 0.714286 |
685465e4f30cf099363f182b3671a86061b8c2eb | 2,007 | py | Python | RPi_Weather.py | JasonKarle/rpi_weather | a05edfa69358c1f867b0de62b6af114036b3a30a | [
"MIT"
] | null | null | null | RPi_Weather.py | JasonKarle/rpi_weather | a05edfa69358c1f867b0de62b6af114036b3a30a | [
"MIT"
] | null | null | null | RPi_Weather.py | JasonKarle/rpi_weather | a05edfa69358c1f867b0de62b6af114036b3a30a | [
"MIT"
] | null | null | null | #!/usr/bin/env python
"""
This is the core program enabling the local weather and date and time
to be read for a location and parsed. This is intended to provide
the base data to then be graphically displayed on a RPi 3" LCD screen,
which will (may) be executed in a separate module
"""
__author__ = "Jason Karle"
__copyright__ = "Copyright 2020, The RPi Weather Project"
__credits__ = ["nil"]
__license__ = "MIT"
__version__ = "0.1.0"
__maintainer__ = "Jason Karle"
__email__ = "[email protected]"
__status__ = "Development"
#test
# module imports
import requests
import datetime
# variables
# weather API key, location and formatting
url = "http://api.openweathermap.org/data/2.5/forecast?id=6324729&APPID=a93c2213b87caa16add92c8d0470c01d&units=metric"
# gets current DTG
now = datetime.datetime.now()
#defines degree symbology
degree = "\u00B0"
degreeC = "\u2103"
degreeF = "\u2109"
json_data = requests.get(url).json() # grabs weather data from OpenWeatherMap.org in JSON format
# extracts specific weather data from jason_data and sets in dedicated variable
current_temp = round(json_data['list'][0]['main']['temp'])
feels_like_temp = round(json_data['list'][0]['main']['feels_like'])
weather_desc = json_data['list'][0]['weather'][0]['description']
icon = json_data['list'][0]['weather'][0]['icon'] # place holder for graphic symbol once GUI is implemented
clouds = json_data['list'][0]['clouds']['all']
wind_speed = json_data['list'][0]['wind']['speed']
wind_kph = round(wind_speed * ((60*60)/1000))
wind_dir = json_data['list'][0]['wind']['deg']
time = now.strftime("%H:%M")
date = now.strftime(("%d %b %Y"))
#prints the desired information to screen
print(f"The time is: {time}, {date}\n")
print(f"The current temperature is: {current_temp}{degreeC}")
print(f"But it feels like: {feels_like_temp}{degreeC}")
print(f"It is currently: {weather_desc}")
print(f"{icon} {clouds}% cloud coverage")
print(f"The wind is coming from {wind_dir}{degree} at {wind_kph} kph")
| 35.210526 | 118 | 0.722471 |
a24600376cb73e663d43dd40bc8d44f9daf6cf45 | 11,513 | py | Python | u-boot-2019.01+gitAUTOINC+333c3e72d3-g333c3e72d3/test/py/tests/test_dfu.py | rlourette/TI_SDK_u-boot-2019.01 | 3000a07c021e84d717e6792a74efcf895a7d7188 | [
"MIT"
] | 1,144 | 2018-12-18T09:46:47.000Z | 2022-03-07T14:51:46.000Z | u-boot-2019.01+gitAUTOINC+333c3e72d3-g333c3e72d3/test/py/tests/test_dfu.py | rlourette/TI_SDK_u-boot-2019.01 | 3000a07c021e84d717e6792a74efcf895a7d7188 | [
"MIT"
] | 16 | 2019-01-28T06:08:40.000Z | 2019-12-04T10:26:41.000Z | u-boot-2019.01+gitAUTOINC+333c3e72d3-g333c3e72d3/test/py/tests/test_dfu.py | rlourette/TI_SDK_u-boot-2019.01 | 3000a07c021e84d717e6792a74efcf895a7d7188 | [
"MIT"
] | 129 | 2018-12-18T09:46:50.000Z | 2022-03-30T07:30:13.000Z | # SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
# Test U-Boot's "dfu" command. The test starts DFU in U-Boot, waits for USB
# device enumeration on the host, executes dfu-util multiple times to test
# various transfer sizes, many of which trigger USB driver edge cases, and
# finally aborts the "dfu" command in U-Boot.
import os
import os.path
import pytest
import u_boot_utils
"""
Note: This test relies on:
a) boardenv_* to contain configuration values to define which USB ports are
available for testing. Without this, this test will be automatically skipped.
For example:
env__usb_dev_ports = (
{
"fixture_id": "micro_b",
"tgt_usb_ctlr": "0",
"host_usb_dev_node": "/dev/usbdev-p2371-2180",
# This parameter is optional /if/ you only have a single board
# attached to your host at a time.
"host_usb_port_path": "3-13",
},
)
# Optional entries (required only when "alt_id_test_file" and
# "alt_id_dummy_file" are specified).
test_file_name = "/dfu_test.bin"
dummy_file_name = "/dfu_dummy.bin"
# Above files are used to generate proper "alt_info" entry
"alt_info": "/%s ext4 0 2;/%s ext4 0 2" % (test_file_name, dummy_file_name),
env__dfu_configs = (
# eMMC, partition 1
{
"fixture_id": "emmc",
"alt_info": "/dfu_test.bin ext4 0 1;/dfu_dummy.bin ext4 0 1",
"cmd_params": "mmc 0",
# This value is optional.
# If present, it specified the set of transfer sizes tested.
# If missing, a default list of sizes will be used, which covers
# various useful corner cases.
# Manually specifying test sizes is useful if you wish to test 4 DFU
# configurations, but don't want to test every single transfer size
# on each, to avoid bloating the overall time taken by testing.
"test_sizes": (63, 64, 65),
# This value is optional.
# The name of the environment variable that the the dfu command reads
# alt info from. If unspecified, this defaults to dfu_alt_info, which is
# valid for most systems. Some systems use a different variable name.
# One example is the Odroid XU3, which automatically generates
# $dfu_alt_info, each time the dfu command is run, by concatenating
# $dfu_alt_boot and $dfu_alt_system.
"alt_info_env_name": "dfu_alt_system",
# This value is optional.
# For boards which require the "test file" alt setting number other than
# default (0) it is possible to specify exact file name to be used as
# this parameter.
"alt_id_test_file": test_file_name,
# This value is optional.
# For boards which require the "dummy file" alt setting number other
# than default (1) it is possible to specify exact file name to be used
# as this parameter.
"alt_id_dummy_file": dummy_file_name,
},
)
b) udev rules to set permissions on devices nodes, so that sudo is not
required. For example:
ACTION=="add", SUBSYSTEM=="block", SUBSYSTEMS=="usb", KERNELS=="3-13", MODE:="666"
(You may wish to change the group ID instead of setting the permissions wide
open. All that matters is that the user ID running the test can access the
device.)
c) An optional udev rule to give you a persistent value to use in
host_usb_dev_node. For example:
IMPORT{builtin}="path_id"
ENV{ID_PATH}=="?*", ENV{.ID_PORT}=="", SYMLINK+="bus/usb/by-path/$env{ID_PATH}"
ENV{ID_PATH}=="?*", ENV{.ID_PORT}=="?*", SYMLINK+="bus/usb/by-path/$env{ID_PATH}-port$env{.ID_PORT}"
"""
# The set of file sizes to test. These values trigger various edge-cases such
# as one less than, equal to, and one greater than typical USB max packet
# sizes, and similar boundary conditions.
test_sizes_default = (
64 - 1,
64,
64 + 1,
128 - 1,
128,
128 + 1,
960 - 1,
960,
960 + 1,
4096 - 1,
4096,
4096 + 1,
1024 * 1024 - 1,
1024 * 1024,
8 * 1024 * 1024,
)
first_usb_dev_port = None
@pytest.mark.buildconfigspec('cmd_dfu')
@pytest.mark.requiredtool('dfu-util')
def test_dfu(u_boot_console, env__usb_dev_port, env__dfu_config):
"""Test the "dfu" command; the host system must be able to enumerate a USB
device when "dfu" is running, various DFU transfers are tested, and the
USB device must disappear when "dfu" is aborted.
Args:
u_boot_console: A U-Boot console connection.
env__usb_dev_port: The single USB device-mode port specification on
which to run the test. See the file-level comment above for
details of the format.
env__dfu_config: The single DFU (memory region) configuration on which
to run the test. See the file-level comment above for details
of the format.
Returns:
Nothing.
"""
def start_dfu():
"""Start U-Boot's dfu shell command.
This also waits for the host-side USB enumeration process to complete.
Args:
None.
Returns:
Nothing.
"""
u_boot_utils.wait_until_file_open_fails(
env__usb_dev_port['host_usb_dev_node'], True)
fh = u_boot_utils.attempt_to_open_file(
env__usb_dev_port['host_usb_dev_node'])
if fh:
fh.close()
raise Exception('USB device present before dfu command invoked')
u_boot_console.log.action(
'Starting long-running U-Boot dfu shell command')
dfu_alt_info_env = env__dfu_config.get('alt_info_env_name', \
'dfu_alt_info')
cmd = 'setenv "%s" "%s"' % (dfu_alt_info_env,
env__dfu_config['alt_info'])
u_boot_console.run_command(cmd)
cmd = 'dfu 0 ' + env__dfu_config['cmd_params']
u_boot_console.run_command(cmd, wait_for_prompt=False)
u_boot_console.log.action('Waiting for DFU USB device to appear')
fh = u_boot_utils.wait_until_open_succeeds(
env__usb_dev_port['host_usb_dev_node'])
fh.close()
def stop_dfu(ignore_errors):
"""Stop U-Boot's dfu shell command from executing.
This also waits for the host-side USB de-enumeration process to
complete.
Args:
ignore_errors: Ignore any errors. This is useful if an error has
already been detected, and the code is performing best-effort
cleanup. In this case, we do not want to mask the original
error by "honoring" any new errors.
Returns:
Nothing.
"""
try:
u_boot_console.log.action(
'Stopping long-running U-Boot dfu shell command')
u_boot_console.ctrlc()
u_boot_console.log.action(
'Waiting for DFU USB device to disappear')
u_boot_utils.wait_until_file_open_fails(
env__usb_dev_port['host_usb_dev_node'], ignore_errors)
except:
if not ignore_errors:
raise
def run_dfu_util(alt_setting, fn, up_dn_load_arg):
"""Invoke dfu-util on the host.
Args:
alt_setting: The DFU "alternate setting" identifier to interact
with.
fn: The host-side file name to transfer.
up_dn_load_arg: '-U' or '-D' depending on whether a DFU upload or
download operation should be performed.
Returns:
Nothing.
"""
cmd = ['dfu-util', '-a', alt_setting, up_dn_load_arg, fn]
if 'host_usb_port_path' in env__usb_dev_port:
cmd += ['-p', env__usb_dev_port['host_usb_port_path']]
u_boot_utils.run_and_log(u_boot_console, cmd)
u_boot_console.wait_for('Ctrl+C to exit ...')
def dfu_write(alt_setting, fn):
"""Write a file to the target board using DFU.
Args:
alt_setting: The DFU "alternate setting" identifier to interact
with.
fn: The host-side file name to transfer.
Returns:
Nothing.
"""
run_dfu_util(alt_setting, fn, '-D')
def dfu_read(alt_setting, fn):
"""Read a file from the target board using DFU.
Args:
alt_setting: The DFU "alternate setting" identifier to interact
with.
fn: The host-side file name to transfer.
Returns:
Nothing.
"""
# dfu-util fails reads/uploads if the host file already exists
if os.path.exists(fn):
os.remove(fn)
run_dfu_util(alt_setting, fn, '-U')
def dfu_write_read_check(size):
"""Test DFU transfers of a specific size of data
This function first writes data to the board then reads it back and
compares the written and read back data. Measures are taken to avoid
certain types of false positives.
Args:
size: The data size to test.
Returns:
Nothing.
"""
test_f = u_boot_utils.PersistentRandomFile(u_boot_console,
'dfu_%d.bin' % size, size)
readback_fn = u_boot_console.config.result_dir + '/dfu_readback.bin'
u_boot_console.log.action('Writing test data to DFU primary ' +
'altsetting')
dfu_write(alt_setting_test_file, test_f.abs_fn)
u_boot_console.log.action('Writing dummy data to DFU secondary ' +
'altsetting to clear DFU buffers')
dfu_write(alt_setting_dummy_file, dummy_f.abs_fn)
u_boot_console.log.action('Reading DFU primary altsetting for ' +
'comparison')
dfu_read(alt_setting_test_file, readback_fn)
u_boot_console.log.action('Comparing written and read data')
written_hash = test_f.content_hash
read_back_hash = u_boot_utils.md5sum_file(readback_fn, size)
assert(written_hash == read_back_hash)
# This test may be executed against multiple USB ports. The test takes a
# long time, so we don't want to do the whole thing each time. Instead,
# execute the full test on the first USB port, and perform a very limited
# test on other ports. In the limited case, we solely validate that the
# host PC can enumerate the U-Boot USB device.
global first_usb_dev_port
if not first_usb_dev_port:
first_usb_dev_port = env__usb_dev_port
if env__usb_dev_port == first_usb_dev_port:
sizes = env__dfu_config.get('test_sizes', test_sizes_default)
else:
sizes = []
dummy_f = u_boot_utils.PersistentRandomFile(u_boot_console,
'dfu_dummy.bin', 1024)
alt_setting_test_file = env__dfu_config.get('alt_id_test_file', '0')
alt_setting_dummy_file = env__dfu_config.get('alt_id_dummy_file', '1')
ignore_cleanup_errors = True
try:
start_dfu()
u_boot_console.log.action(
'Overwriting DFU primary altsetting with dummy data')
dfu_write(alt_setting_test_file, dummy_f.abs_fn)
for size in sizes:
with u_boot_console.log.section('Data size %d' % size):
dfu_write_read_check(size)
# Make the status of each sub-test obvious. If the test didn't
# pass, an exception was thrown so this code isn't executed.
u_boot_console.log.status_pass('OK')
ignore_cleanup_errors = False
finally:
stop_dfu(ignore_cleanup_errors)
| 35.866044 | 100 | 0.641362 |
a9cd539ad56b5563776a2e45ec35c7e1711d8dfe | 1,483 | py | Python | pandas_ta/momentum/mom.py | bartua/pandas-ta | 3bbd5bef4a906f8e810cd557cf20bf92870851c0 | [
"MIT"
] | null | null | null | pandas_ta/momentum/mom.py | bartua/pandas-ta | 3bbd5bef4a906f8e810cd557cf20bf92870851c0 | [
"MIT"
] | null | null | null | pandas_ta/momentum/mom.py | bartua/pandas-ta | 3bbd5bef4a906f8e810cd557cf20bf92870851c0 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from pandas_ta.utils import get_offset, verify_series
def mom(close, length=None, offset=None, **kwargs):
"""Indicator: Momentum (MOM)"""
# Validate Arguments
length = int(length) if length and length > 0 else 10
close = verify_series(close, length)
offset = get_offset(offset)
if close is None: return
# Calculate Result
mom = close.diff(length)
# Offset
if offset != 0:
mom = mom.shift(offset)
# Handle fills
if "fillna" in kwargs:
mom.fillna(kwargs["fillna"], inplace=True)
if "fill_method" in kwargs:
mom.fillna(method=kwargs["fill_method"], inplace=True)
# Name and Categorize it
mom.name = f"MOM_{length}"
mom.category = "momentum"
return mom
mom.__doc__ = \
"""Momentum (MOM)
Momentum is an indicator used to measure a security's speed (or strength) of
movement. Or simply the change in price.
Sources:
http://www.onlinetradingconcepts.com/TechnicalAnalysis/Momentum.html
Calculation:
Default Inputs:
length=1
MOM = close.diff(length)
Args:
close (pd.Series): Series of 'close's
length (int): It's period. Default: 1
offset (int): How many periods to offset the result. Default: 0
Kwargs:
fillna (value, optional): pd.DataFrame.fillna(value)
fill_method (value, optional): Type of fill method
Returns:
pd.Series: New feature generated.
"""
| 24.716667 | 77 | 0.639919 |
9a4df1c375bdbb2d3b00d72c146947453a1a1941 | 15,835 | py | Python | mlflow/projects/__init__.py | vinijaiswal/mlflow | 4daf07ae5a6cad1d280fe75d1a4279639c65dae8 | [
"Apache-2.0"
] | null | null | null | mlflow/projects/__init__.py | vinijaiswal/mlflow | 4daf07ae5a6cad1d280fe75d1a4279639c65dae8 | [
"Apache-2.0"
] | null | null | null | mlflow/projects/__init__.py | vinijaiswal/mlflow | 4daf07ae5a6cad1d280fe75d1a4279639c65dae8 | [
"Apache-2.0"
] | null | null | null | """
The ``mlflow.projects`` module provides an API for running MLflow projects locally or remotely.
"""
import json
import yaml
import os
import logging
import mlflow.projects.databricks
import mlflow.tracking as tracking
from mlflow.entities import RunStatus
from mlflow.exceptions import ExecutionException, MlflowException
from mlflow.projects.submitted_run import SubmittedRun
from mlflow.projects.utils import (
PROJECT_SYNCHRONOUS,
get_entry_point_command,
get_run_env_vars,
fetch_and_validate_project,
get_or_create_run,
load_project,
MLFLOW_LOCAL_BACKEND_RUN_ID_CONFIG,
PROJECT_USE_CONDA,
PROJECT_STORAGE_DIR,
PROJECT_DOCKER_ARGS,
)
from mlflow.projects.backend import loader
from mlflow.tracking.fluent import _get_experiment_id
from mlflow.utils.mlflow_tags import MLFLOW_PROJECT_ENV, MLFLOW_PROJECT_BACKEND, MLFLOW_RUN_NAME
import mlflow.utils.uri
_logger = logging.getLogger(__name__)
def _resolve_experiment_id(experiment_name=None, experiment_id=None):
"""
Resolve experiment.
Verifies either one or other is specified - cannot be both selected.
If ``experiment_name`` is provided and does not exist, an experiment
of that name is created and its id is returned.
:param experiment_name: Name of experiment under which to launch the run.
:param experiment_id: ID of experiment under which to launch the run.
:return: str
"""
if experiment_name and experiment_id:
raise MlflowException("Specify only one of 'experiment_name' or 'experiment_id'.")
if experiment_id:
return str(experiment_id)
if experiment_name:
client = tracking.MlflowClient()
exp = client.get_experiment_by_name(experiment_name)
if exp:
return exp.experiment_id
else:
print("INFO: '{}' does not exist. Creating a new experiment".format(experiment_name))
return client.create_experiment(experiment_name)
return _get_experiment_id()
def _run(
uri,
experiment_id,
entry_point,
version,
parameters,
docker_args,
backend_name,
backend_config,
use_conda,
storage_dir,
synchronous,
run_name,
):
"""
Helper that delegates to the project-running method corresponding to the passed-in backend.
Returns a ``SubmittedRun`` corresponding to the project run.
"""
tracking_store_uri = tracking.get_tracking_uri()
backend_config[PROJECT_USE_CONDA] = use_conda
backend_config[PROJECT_SYNCHRONOUS] = synchronous
backend_config[PROJECT_DOCKER_ARGS] = docker_args
backend_config[PROJECT_STORAGE_DIR] = storage_dir
# TODO: remove this check once kubernetes execution has been refactored
if backend_name not in {"databricks", "kubernetes"}:
backend = loader.load_backend(backend_name)
if backend:
submitted_run = backend.run(
uri,
entry_point,
parameters,
version,
backend_config,
tracking_store_uri,
experiment_id,
)
tracking.MlflowClient().set_tag(
submitted_run.run_id, MLFLOW_PROJECT_BACKEND, backend_name
)
if run_name is not None:
tracking.MlflowClient().set_tag(submitted_run.run_id, MLFLOW_RUN_NAME, run_name)
return submitted_run
work_dir = fetch_and_validate_project(uri, version, entry_point, parameters)
project = load_project(work_dir)
_validate_execution_environment(project, backend_name)
active_run = get_or_create_run(
None, uri, experiment_id, work_dir, version, entry_point, parameters
)
if run_name is not None:
tracking.MlflowClient().set_tag(active_run.info.run_id, MLFLOW_RUN_NAME, run_name)
if backend_name == "databricks":
tracking.MlflowClient().set_tag(
active_run.info.run_id, MLFLOW_PROJECT_BACKEND, "databricks"
)
from mlflow.projects.databricks import run_databricks
return run_databricks(
remote_run=active_run,
uri=uri,
entry_point=entry_point,
work_dir=work_dir,
parameters=parameters,
experiment_id=experiment_id,
cluster_spec=backend_config,
)
elif backend_name == "kubernetes":
from mlflow.projects.docker import (
build_docker_image,
validate_docker_env,
validate_docker_installation,
)
from mlflow.projects import kubernetes as kb
tracking.MlflowClient().set_tag(active_run.info.run_id, MLFLOW_PROJECT_ENV, "docker")
tracking.MlflowClient().set_tag(
active_run.info.run_id, MLFLOW_PROJECT_BACKEND, "kubernetes"
)
validate_docker_env(project)
validate_docker_installation()
kube_config = _parse_kubernetes_config(backend_config)
image = build_docker_image(
work_dir=work_dir,
repository_uri=kube_config["repository-uri"],
base_image=project.docker_env.get("image"),
run_id=active_run.info.run_id,
)
image_digest = kb.push_image_to_registry(image.tags[0])
submitted_run = kb.run_kubernetes_job(
project.name,
active_run,
image.tags[0],
image_digest,
get_entry_point_command(project, entry_point, parameters, storage_dir),
get_run_env_vars(
run_id=active_run.info.run_uuid, experiment_id=active_run.info.experiment_id
),
kube_config.get("kube-context", None),
kube_config["kube-job-template"],
)
return submitted_run
supported_backends = ["databricks", "kubernetes"] + list(loader.MLFLOW_BACKENDS.keys())
raise ExecutionException(
"Got unsupported execution mode %s. Supported "
"values: %s" % (backend_name, supported_backends)
)
def run(
uri,
entry_point="main",
version=None,
parameters=None,
docker_args=None,
experiment_name=None,
experiment_id=None,
backend="local",
backend_config=None,
use_conda=True,
storage_dir=None,
synchronous=True,
run_id=None,
run_name=None,
):
"""
Run an MLflow project. The project can be local or stored at a Git URI.
MLflow provides built-in support for running projects locally or remotely on a Databricks or
Kubernetes cluster. You can also run projects against other targets by installing an appropriate
third-party plugin. See `Community Plugins <../plugins.html#community-plugins>`_ for more
information.
For information on using this method in chained workflows, see `Building Multistep Workflows
<../projects.html#building-multistep-workflows>`_.
:raises: :py:class:`mlflow.exceptions.ExecutionException` If a run launched in blocking mode
is unsuccessful.
:param uri: URI of project to run. A local filesystem path
or a Git repository URI (e.g. https://github.com/mlflow/mlflow-example)
pointing to a project directory containing an MLproject file.
:param entry_point: Entry point to run within the project. If no entry point with the specified
name is found, runs the project file ``entry_point`` as a script,
using "python" to run ``.py`` files and the default shell (specified by
environment variable ``$SHELL``) to run ``.sh`` files.
:param version: For Git-based projects, either a commit hash or a branch name.
:param parameters: Parameters (dictionary) for the entry point command.
:param docker_args: Arguments (dictionary) for the docker command.
:param experiment_name: Name of experiment under which to launch the run.
:param experiment_id: ID of experiment under which to launch the run.
:param backend: Execution backend for the run: MLflow provides built-in support for "local",
"databricks", and "kubernetes" (experimental) backends. If running against
Databricks, will run against a Databricks workspace determined as follows:
if a Databricks tracking URI of the form ``databricks://profile`` has been set
(e.g. by setting the MLFLOW_TRACKING_URI environment variable), will run
against the workspace specified by <profile>. Otherwise, runs against the
workspace specified by the default Databricks CLI profile.
:param backend_config: A dictionary, or a path to a JSON file (must end in '.json'), which will
be passed as config to the backend. The exact content which should be
provided is different for each execution backend and is documented
at https://www.mlflow.org/docs/latest/projects.html.
:param use_conda: If True (the default), create a new Conda environment for the run and
install project dependencies within that environment. Otherwise, run the
project in the current environment without installing any project
dependencies.
:param storage_dir: Used only if ``backend`` is "local". MLflow downloads artifacts from
distributed URIs passed to parameters of type ``path`` to subdirectories of
``storage_dir``.
:param synchronous: Whether to block while waiting for a run to complete. Defaults to True.
Note that if ``synchronous`` is False and ``backend`` is "local", this
method will return, but the current process will block when exiting until
the local run completes. If the current process is interrupted, any
asynchronous runs launched via this method will be terminated. If
``synchronous`` is True and the run fails, the current process will
error out as well.
:param run_id: Note: this argument is used internally by the MLflow project APIs and should
not be specified. If specified, the run ID will be used instead of
creating a new run.
:param run_name: The name to give the MLflow Run associated with the project execution.
If ``None``, the MLflow Run name is left unset.
:return: :py:class:`mlflow.projects.SubmittedRun` exposing information (e.g. run ID)
about the launched run.
.. code-block:: python
:caption: Example
import mlflow
project_uri = "https://github.com/mlflow/mlflow-example"
params = {"alpha": 0.5, "l1_ratio": 0.01}
# Run MLflow project and create a reproducible conda environment
# on a local host
mlflow.run(project_uri, parameters=params)
.. code-block:: text
:caption: Output
...
...
Elasticnet model (alpha=0.500000, l1_ratio=0.010000):
RMSE: 0.788347345611717
MAE: 0.6155576449938276
R2: 0.19729662005412607
... mlflow.projects: === Run (ID '6a5109febe5e4a549461e149590d0a7c') succeeded ===
"""
backend_config_dict = backend_config if backend_config is not None else {}
if (
backend_config
and type(backend_config) != dict
and os.path.splitext(backend_config)[-1] == ".json"
):
with open(backend_config, "r") as handle:
try:
backend_config_dict = json.load(handle)
except ValueError:
_logger.error(
"Error when attempting to load and parse JSON cluster spec from file %s",
backend_config,
)
raise
if backend == "databricks":
mlflow.projects.databricks.before_run_validations(mlflow.get_tracking_uri(), backend_config)
elif backend == "local" and run_id is not None:
backend_config_dict[MLFLOW_LOCAL_BACKEND_RUN_ID_CONFIG] = run_id
experiment_id = _resolve_experiment_id(
experiment_name=experiment_name, experiment_id=experiment_id
)
submitted_run_obj = _run(
uri=uri,
experiment_id=experiment_id,
entry_point=entry_point,
version=version,
parameters=parameters,
docker_args=docker_args,
backend_name=backend,
backend_config=backend_config_dict,
use_conda=use_conda,
storage_dir=storage_dir,
synchronous=synchronous,
run_name=run_name,
)
if synchronous:
_wait_for(submitted_run_obj)
return submitted_run_obj
def _wait_for(submitted_run_obj):
"""Wait on the passed-in submitted run, reporting its status to the tracking server."""
run_id = submitted_run_obj.run_id
active_run = None
# Note: there's a small chance we fail to report the run's status to the tracking server if
# we're interrupted before we reach the try block below
try:
active_run = tracking.MlflowClient().get_run(run_id) if run_id is not None else None
if submitted_run_obj.wait():
_logger.info("=== Run (ID '%s') succeeded ===", run_id)
_maybe_set_run_terminated(active_run, "FINISHED")
else:
_maybe_set_run_terminated(active_run, "FAILED")
raise ExecutionException("Run (ID '%s') failed" % run_id)
except KeyboardInterrupt:
_logger.error("=== Run (ID '%s') interrupted, cancelling run ===", run_id)
submitted_run_obj.cancel()
_maybe_set_run_terminated(active_run, "FAILED")
raise
def _maybe_set_run_terminated(active_run, status):
"""
If the passed-in active run is defined and still running (i.e. hasn't already been terminated
within user code), mark it as terminated with the passed-in status.
"""
if active_run is None:
return
run_id = active_run.info.run_id
cur_status = tracking.MlflowClient().get_run(run_id).info.status
if RunStatus.is_terminated(cur_status):
return
tracking.MlflowClient().set_terminated(run_id, status)
def _validate_execution_environment(project, backend):
if project.docker_env and backend == "databricks":
raise ExecutionException(
"Running docker-based projects on Databricks is not yet supported."
)
def _parse_kubernetes_config(backend_config):
"""
Creates build context tarfile containing Dockerfile and project code, returning path to tarfile
"""
if not backend_config:
raise ExecutionException("Backend_config file not found.")
kube_config = backend_config.copy()
if "kube-job-template-path" not in backend_config.keys():
raise ExecutionException(
"'kube-job-template-path' attribute must be specified in " "backend_config."
)
kube_job_template = backend_config["kube-job-template-path"]
if os.path.exists(kube_job_template):
with open(kube_job_template, "r") as job_template:
yaml_obj = yaml.safe_load(job_template.read())
kube_job_template = yaml_obj
kube_config["kube-job-template"] = kube_job_template
else:
raise ExecutionException(
"Could not find 'kube-job-template-path': {}".format(kube_job_template)
)
if "kube-context" not in backend_config.keys():
_logger.debug(
"Could not find kube-context in backend_config."
" Using current context or in-cluster config."
)
if "repository-uri" not in backend_config.keys():
raise ExecutionException("Could not find 'repository-uri' in backend_config.")
return kube_config
__all__ = ["run", "SubmittedRun"]
| 40.088608 | 100 | 0.664035 |
a63cc518f595e3deb0baef0e19022d88312aac58 | 1,049 | py | Python | models/feature_extractors.py | Bhaskers-Blu-Org2/Distilled-Sentence-Embedding | 092b70830564c65a2efe8cadecd5da2d5dfdfba9 | [
"MIT"
] | 23 | 2019-12-11T14:52:54.000Z | 2021-09-23T16:03:14.000Z | models/feature_extractors.py | Bhaskers-Blu-Org2/Distilled-Sentence-Embedding | 092b70830564c65a2efe8cadecd5da2d5dfdfba9 | [
"MIT"
] | 7 | 2020-07-17T11:18:48.000Z | 2022-03-12T00:05:57.000Z | models/feature_extractors.py | microsoft/Distilled-Sentence-Embedding | 7e3e87bf6d854c45fb9e5fde6695aa9524325ae7 | [
"MIT"
] | 9 | 2020-01-03T13:26:39.000Z | 2021-09-13T12:31:35.000Z | from abc import ABCMeta, abstractmethod
import torch
class CombinedFeaturesExtractor(metaclass=ABCMeta):
@abstractmethod
def extract_combined_features(self, first_input, second_input):
raise NotImplementedError
@abstractmethod
def get_combined_features_size(self, first_input_size):
raise NotImplementedError
class ConcatCompareCombinedFeaturesExtractor(CombinedFeaturesExtractor):
def extract_combined_features(self, first_input, second_input):
hadamaard = first_input * second_input
abs_diff = torch.abs(first_input - second_input)
return torch.cat([first_input, second_input, hadamaard, abs_diff], dim=1)
def get_combined_features_size(self, input_size):
return 4 * input_size
class DotProductCombinedFeaturesExtractor(CombinedFeaturesExtractor):
def extract_combined_features(self, first_input, second_input):
return (first_input * second_input).sum(dim=1, keepdim=True)
def get_combined_features_size(self, first_input_size):
return 1
| 29.971429 | 81 | 0.768351 |
73b3d68c72a8a82fbf3e56b837f547fd61c8b0ab | 3,558 | py | Python | chmap/data/corrections/iit/IIT_pipeline_example.py | predsci/CHD | 35f29d1b62861f4ffed57b38d18689b282664bcf | [
"Apache-2.0"
] | 3 | 2021-06-29T00:23:47.000Z | 2021-09-17T18:29:05.000Z | chmap/data/corrections/iit/IIT_pipeline_example.py | predsci/CHD | 35f29d1b62861f4ffed57b38d18689b282664bcf | [
"Apache-2.0"
] | null | null | null | chmap/data/corrections/iit/IIT_pipeline_example.py | predsci/CHD | 35f29d1b62861f4ffed57b38d18689b282664bcf | [
"Apache-2.0"
] | 1 | 2021-12-08T06:26:18.000Z | 2021-12-08T06:26:18.000Z | """
Use the IIT pipeline functions to calculate the correction
"""
import os
import datetime
import numpy as np
from chmap.settings.app import App
from chmap.database.db_funs import init_db_conn_old
import chmap.database.db_classes as db_class
import chmap.data.corrections.iit.IIT_pipeline_funcs as iit_funcs
####### ------ UPDATABLE PARAMETERS ------ #########
# TIME RANGE FOR LBC CORRECTION AND IIT HISTOGRAM CREATION
lbc_query_time_min = datetime.datetime(2011, 1, 1, 0, 0, 0)
lbc_query_time_max = datetime.datetime(2012, 1, 1, 0, 0, 0)
# TIME RANGE FOR FIT PARAMETER CALCULATION
calc_query_time_min = datetime.datetime(2011, 4, 1, 0, 0, 0)
calc_query_time_max = datetime.datetime(2011, 10, 1, 0, 0, 0)
weekday = 0 # start at 0 for Monday
number_of_days = 180 # days for moving average
# TIME WINDOWS FOR IMAGE INCLUSION
image_freq = 2 # number of hours between window centers
image_del = np.timedelta64(30, 'm') # one-half window width
# TIME RANGE FOR IIT CORRECTION AND IMAGE PLOTTING
iit_query_time_min = datetime.datetime(2011, 4, 1, 0, 0, 0)
iit_query_time_max = datetime.datetime(2011, 10, 1, 0, 0, 0)
plot = True # true if you want to plot resulting images
n_images_plot = 1 # number of images to plot
# TIME RANGE FOR HISTOGRAM CREATION
hist_query_time_min = datetime.datetime(2011, 4, 1, 0, 0, 0)
hist_query_time_max = datetime.datetime(2011, 10, 1, 0, 0, 0)
# INSTRUMENTS
inst_list = ["AIA", "EUVI-A", "EUVI-B"]
ref_inst = "AIA" # reference instrument to fit histograms to
wavelengths = [193, 195]
# declare map and binning parameters
n_mu_bins = 18
n_intensity_bins = 200
R0 = 1.01
log10 = True
lat_band = [-np.pi / 2.4, np.pi / 2.4]
# define database paths
raw_data_dir = App.RAW_DATA_HOME
hdf_data_dir = App.PROCESSED_DATA_HOME
database_dir = App.DATABASE_HOME
sqlite_filename = App.DATABASE_FNAME
# setup database connection
create = True # true if you want to add to database
use_db = "sqlite"
sqlite_path = os.path.join(database_dir, sqlite_filename)
db_session = init_db_conn_old(db_name=use_db, chd_base=db_class.Base, sqlite_path=sqlite_path)
##### ------ INTER INSTRUMENT TRANSFORMATION FUNCTIONS BELOW ------- ########
##### STEP ONE: CREATE 1D HISTOGRAMS AND SAVE TO DATABASE ######
iit_funcs.create_histograms(db_session, inst_list, lbc_query_time_min, lbc_query_time_max, hdf_data_dir,
n_intensity_bins=n_intensity_bins, lat_band=lat_band, log10=log10, R0=R0,
wavelengths=wavelengths)
##### STEP TWO: CALCULATE INTER-INSTRUMENT TRANSFORMATION COEFFICIENTS AND SAVE TO DATABASE ######
iit_funcs.calc_iit_coefficients(db_session, inst_list, ref_inst, calc_query_time_min, calc_query_time_max,
weekday=weekday, number_of_days=number_of_days, image_freq=image_freq,
image_del=image_del, n_intensity_bins=n_intensity_bins,
lat_band=lat_band, create=create, wavelengths=wavelengths)
##### STEP THREE: APPLY TRANSFORMATION AND PLOT NEW IMAGES ######
iit_funcs.apply_iit_correction(db_session, hdf_data_dir, iit_query_time_min, iit_query_time_max, inst_list, ref_inst,
n_intensity_bins=n_intensity_bins, R0=R0, n_images_plot=n_images_plot, plot=plot)
###### STEP FOUR: GENERATE NEW HISTOGRAM PLOTS ######
iit_funcs.plot_iit_histograms(db_session, hdf_data_dir, hist_query_time_min, hist_query_time_max, inst_list, ref_inst,
n_intensity_bins=n_intensity_bins, lat_band=lat_band, R0=R0, log10=log10)
| 43.925926 | 118 | 0.725126 |
8e192f6ba10d6ecaa9f26a6ba77fa8363d5acdb6 | 4,394 | py | Python | datasets/fake_news_english/fake_news_english.py | dkajtoch/datasets | 12ef7f0d541a5aca5b29ebc2dddf5e1214f0e3e9 | [
"Apache-2.0"
] | 9 | 2021-04-26T14:43:52.000Z | 2021-11-08T09:47:24.000Z | datasets/fake_news_english/fake_news_english.py | dkajtoch/datasets | 12ef7f0d541a5aca5b29ebc2dddf5e1214f0e3e9 | [
"Apache-2.0"
] | null | null | null | datasets/fake_news_english/fake_news_english.py | dkajtoch/datasets | 12ef7f0d541a5aca5b29ebc2dddf5e1214f0e3e9 | [
"Apache-2.0"
] | 1 | 2022-02-23T19:09:42.000Z | 2022-02-23T19:09:42.000Z | # coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Fake News vs Satire: A Dataset and Analysis."""
from __future__ import absolute_import, division, print_function
import os
import openpyxl # noqa: requires this pandas optional dependency for reading xlsx files
import pandas as pd
import datasets
_CITATION = """
@inproceedings{inproceedings,
author = {Golbeck, Jennifer and Everett, Jennine and Falak, Waleed and Gieringer, Carl and Graney, Jack and Hoffman, Kelly and Huth, Lindsay and Ma, Zhenya and Jha, Mayanka and Khan, Misbah and Kori, Varsha and Mauriello, Matthew and Lewis, Elo and Mirano, George and IV, William and Mussenden, Sean and Nelson, Tammie and Mcwillie, Sean and Pant, Akshat and Cheakalos, Paul},
year = {2018},
month = {05},
pages = {17-21},
title = {Fake News vs Satire: A Dataset and Analysis},
doi = {10.1145/3201064.3201100}
}
"""
_DESCRIPTION = """
Fake news has become a major societal issue and a technical challenge for social media companies to identify. This content is difficult to identify because the term "fake news" covers intentionally false, deceptive stories as well as factual errors, satire, and sometimes, stories that a person just does not like. Addressing the problem requires clear definitions and examples. In this work, we present a dataset of fake news and satire stories that are hand coded, verified, and, in the case of fake news, include rebutting stories. We also include a thematic content analysis of the articles, identifying major themes that include hyperbolic support or condemnation of a gure, conspiracy theories, racist themes, and discrediting of reliable sources. In addition to releasing this dataset for research use, we analyze it and show results based on language that are promising for classification purposes. Overall, our contribution of a dataset and initial analysis are designed to support future work by fake news researchers.
"""
_HOMEPAGE = "https://dl.acm.org/doi/10.1145/3201064.3201100"
# _LICENSE = ""
_URLs = "https://github.com/jgolbeck/fakenews/raw/master/FakeNewsData.zip"
class FakeNewsEnglish(datasets.GeneratorBasedBuilder):
"""Fake News vs Satire: A Dataset and Analysis"""
VERSION = datasets.Version("1.1.0")
def _info(self):
features = datasets.Features(
{
"article_number": datasets.Value("int32"),
"url_of_article": datasets.Value("string"),
"fake_or_satire": datasets.ClassLabel(names=["Satire", "Fake"]),
"url_of_rebutting_article": datasets.Value("string"),
}
)
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=features,
supervised_keys=None,
homepage=_HOMEPAGE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
data_dir = dl_manager.download_and_extract(_URLs)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
# These kwargs will be passed to _generate_examples
gen_kwargs={"filepath": os.path.join(data_dir, "FakeNewsData", "Fake News Stories.xlsx")},
)
]
def _generate_examples(self, filepath):
""" Yields examples. """
with open(filepath, "rb") as f:
f = pd.read_excel(f, engine="openpyxl")
for id_, row in f.iterrows():
yield id_, {
"article_number": row["Article Number"],
"url_of_article": str(row["URL of article"]),
"fake_or_satire": str(row["Fake or Satire?"]),
"url_of_rebutting_article": str(row["URL of rebutting article"]),
}
| 47.247312 | 1,028 | 0.690942 |
1e0f358ccc6e08baaa9cb6eac6f313f48132fea8 | 3,059 | py | Python | alipay/aop/api/domain/AlipayBossFncGfsettleprodInvoiceCancelModel.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 213 | 2018-08-27T16:49:32.000Z | 2021-12-29T04:34:12.000Z | alipay/aop/api/domain/AlipayBossFncGfsettleprodInvoiceCancelModel.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 29 | 2018-09-29T06:43:00.000Z | 2021-09-02T03:27:32.000Z | alipay/aop/api/domain/AlipayBossFncGfsettleprodInvoiceCancelModel.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 59 | 2018-08-27T16:59:26.000Z | 2022-03-25T10:08:15.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayBossFncGfsettleprodInvoiceCancelModel(object):
def __init__(self):
self._invoice_id = None
self._invoice_no = None
self._operator = None
self._operator_type = None
self._settle_ip_role_id = None
@property
def invoice_id(self):
return self._invoice_id
@invoice_id.setter
def invoice_id(self, value):
self._invoice_id = value
@property
def invoice_no(self):
return self._invoice_no
@invoice_no.setter
def invoice_no(self, value):
self._invoice_no = value
@property
def operator(self):
return self._operator
@operator.setter
def operator(self, value):
self._operator = value
@property
def operator_type(self):
return self._operator_type
@operator_type.setter
def operator_type(self, value):
self._operator_type = value
@property
def settle_ip_role_id(self):
return self._settle_ip_role_id
@settle_ip_role_id.setter
def settle_ip_role_id(self, value):
self._settle_ip_role_id = value
def to_alipay_dict(self):
params = dict()
if self.invoice_id:
if hasattr(self.invoice_id, 'to_alipay_dict'):
params['invoice_id'] = self.invoice_id.to_alipay_dict()
else:
params['invoice_id'] = self.invoice_id
if self.invoice_no:
if hasattr(self.invoice_no, 'to_alipay_dict'):
params['invoice_no'] = self.invoice_no.to_alipay_dict()
else:
params['invoice_no'] = self.invoice_no
if self.operator:
if hasattr(self.operator, 'to_alipay_dict'):
params['operator'] = self.operator.to_alipay_dict()
else:
params['operator'] = self.operator
if self.operator_type:
if hasattr(self.operator_type, 'to_alipay_dict'):
params['operator_type'] = self.operator_type.to_alipay_dict()
else:
params['operator_type'] = self.operator_type
if self.settle_ip_role_id:
if hasattr(self.settle_ip_role_id, 'to_alipay_dict'):
params['settle_ip_role_id'] = self.settle_ip_role_id.to_alipay_dict()
else:
params['settle_ip_role_id'] = self.settle_ip_role_id
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = AlipayBossFncGfsettleprodInvoiceCancelModel()
if 'invoice_id' in d:
o.invoice_id = d['invoice_id']
if 'invoice_no' in d:
o.invoice_no = d['invoice_no']
if 'operator' in d:
o.operator = d['operator']
if 'operator_type' in d:
o.operator_type = d['operator_type']
if 'settle_ip_role_id' in d:
o.settle_ip_role_id = d['settle_ip_role_id']
return o
| 30.287129 | 85 | 0.609676 |