hexsha
stringlengths 40
40
| size
int64 6
782k
| ext
stringclasses 7
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
237
| max_stars_repo_name
stringlengths 6
72
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
list | max_stars_count
int64 1
53k
⌀ | 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
184
| max_issues_repo_name
stringlengths 6
72
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
list | max_issues_count
int64 1
27.1k
⌀ | 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
184
| max_forks_repo_name
stringlengths 6
72
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
list | max_forks_count
int64 1
12.2k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 6
782k
| avg_line_length
float64 2.75
664k
| max_line_length
int64 5
782k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ecf969d277c9c380a85d39c972fd99951dc1371c
| 256 |
py
|
Python
|
python/requests/python_requests_library_guide/set_cookie.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
python/requests/python_requests_library_guide/set_cookie.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
python/requests/python_requests_library_guide/set_cookie.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
import requests
s = requests.Session()
# 쿠키값 sessionkie를 123456789으로 설정
s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
# 내 쿠키값 가져오기
r = s.get('https://httpbin.org/cookies')
print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'
| 21.333333 | 64 | 0.710938 |
a65682627380ca763287b167d2edc08522c75a03
| 389 |
py
|
Python
|
Packs/PHash/Scripts/PHash/PHash.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 799 |
2016-08-02T06:43:14.000Z
|
2022-03-31T11:10:11.000Z
|
Packs/PHash/Scripts/PHash/PHash.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 9,317 |
2016-08-07T19:00:51.000Z
|
2022-03-31T21:56:04.000Z
|
Packs/PHash/Scripts/PHash/PHash.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 1,297 |
2016-08-04T13:59:00.000Z
|
2022-03-31T23:43:06.000Z
|
import demistomock as demisto # noqa: F401
import imagehash
from CommonServerPython import * # noqa: F401
from PIL import Image
ImageID = demisto.args()['image']
ImageFilePath = demisto.getFilePath(ImageID)
hash = imagehash.phash(Image.open(ImageFilePath['path']))
context = {
"PHash": str(hash)
}
command_results = CommandResults(outputs=context)
return_results(command_results)
| 24.3125 | 57 | 0.768638 |
5be6d51cc39f06beb439c234c4f993b78f3b7ac2
| 293 |
py
|
Python
|
algorithms/implementation/angry_professor.py
|
PlamenHristov/HackerRank
|
2c875995f0d51d7026c5cf92348d9fb94fa509d6
|
[
"MIT"
] | null | null | null |
algorithms/implementation/angry_professor.py
|
PlamenHristov/HackerRank
|
2c875995f0d51d7026c5cf92348d9fb94fa509d6
|
[
"MIT"
] | null | null | null |
algorithms/implementation/angry_professor.py
|
PlamenHristov/HackerRank
|
2c875995f0d51d7026c5cf92348d9fb94fa509d6
|
[
"MIT"
] | null | null | null |
import sys
if __name__ == '__main__':
T = int(sys.stdin.readline())
for _ in range(T):
N, K = list(map(int, sys.stdin.readline().split()))
X = list(map(int, sys.stdin.readline().split()))
print('YES' if sum(1 for x in X if x <= 0) < K else 'NO')
| 26.636364 | 65 | 0.532423 |
f3c9446e4dde13e8b75b75b094a48c7a9f2f6aa4
| 94 |
py
|
Python
|
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-003/pg-3.5-ex-string.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-003/pg-3.5-ex-string.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-003/pg-3.5-ex-string.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
s = '100'
print(s)
s = 'abc1234-09232<>?323'
print(s)
s = 'abc 123'
print(s)
s = ' '
print(s)
| 10.444444 | 25 | 0.553191 |
9474089d2e84c2a30d93fa7ed7588fd9fb3e4642
| 1,802 |
py
|
Python
|
PINp/2014/Platonova Olga/task_8_21.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
PINp/2014/Platonova Olga/task_8_21.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
PINp/2014/Platonova Olga/task_8_21.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
# Задача 8. Вариант 21.
#Доработайте игру "Анаграммы" (см. М.Доусон Программируем на Python. Гл.4) так, чтобы к каждому слову полагалась подсказка. Игрок должен получать право на подсказку в том случае, если у него нет никаких предположений. Разработайте систему начисления очков, по которой бы игроки, отгадавшие слово без подсказки, получали больше тех, кто запросил подсказку.
# Platonova O. A.
# 29.05.2016
import random
words=("кортежи","списки","словари","циклы","ветвление","работа","компьютер")
onegame="y"
while onegame=="y" or onegame=="д":
compword=random.choice(words)
correct=compword
jumble=""
hint=""
point=100
while compword:
position=random.randrange(len(compword))
jumble+=compword[position]
compword=compword[:position]+compword[(position+1):]
print(
"""
Добро пожаловать в игру 'Анаграммы'!
Надо переставить буквы так, чтобы получилось осмысленное слово.
(Для выхода нажмите Enter, не вводя своей версии.)
"""
)
print("Попробуйте разгадать анаграмму:",jumble)
guess=" "
while guess!=correct and guess!="":
guess=input('Попробуйте отгадать загаданное слово, если вы не значете, напишите "подсказка": ')
if guess=="подсказка":
hint=(correct [:position+1])
print(hint)
point-=10
position+=1
elif guess==correct:
print("Да, именно так! Вы отгадали\n")
print("Ваши баллы",point)
elif guess!=correct:
print("Не отгадали, попробуйте еще раз ")
print("Спасибо за игру.")
onegame=input("Если хотите сыграть ещё раз, введите д или y")
input("\n\nНажмите Enter, чтобы выйти.")
| 40.954545 | 355 | 0.623751 |
ca436664571c958cfeef2abe50203c233abb5ff0
| 367 |
py
|
Python
|
docker/django/restaurant/restapps/admin.py
|
gitmehedi/cloudtuts
|
3008b1cf7fbf22728c9bb2c059c4bd196043a93e
|
[
"Unlicense"
] | 3 |
2019-08-29T10:14:40.000Z
|
2021-03-05T09:50:15.000Z
|
docker/django/restaurant/restapps/admin.py
|
gitmehedi/cloudtuts
|
3008b1cf7fbf22728c9bb2c059c4bd196043a93e
|
[
"Unlicense"
] | null | null | null |
docker/django/restaurant/restapps/admin.py
|
gitmehedi/cloudtuts
|
3008b1cf7fbf22728c9bb2c059c4bd196043a93e
|
[
"Unlicense"
] | 1 |
2021-03-05T09:50:29.000Z
|
2021-03-05T09:50:29.000Z
|
from django.contrib import admin
from .models import Restaurant, Menu
class RestaurantAdmin(admin.ModelAdmin):
list_display = ('name', 'contact', 'active')
admin.site.register(Restaurant, RestaurantAdmin)
class MenuAdmin(admin.ModelAdmin):
list_display = ('name', 'price', 'current_date', 'restaurant', 'active')
admin.site.register(Menu, MenuAdmin)
| 20.388889 | 76 | 0.741144 |
04a9a964813caf3199b7ddbba8b88f02fe951c38
| 863 |
py
|
Python
|
notebooks/util/vespa_helper/result_formatter.py
|
dbmdz/webarchiv-dh-bestandsausbau
|
98c271a09cdb026d1d58133f49dcb3e1c9fcf9b6
|
[
"MIT"
] | null | null | null |
notebooks/util/vespa_helper/result_formatter.py
|
dbmdz/webarchiv-dh-bestandsausbau
|
98c271a09cdb026d1d58133f49dcb3e1c9fcf9b6
|
[
"MIT"
] | null | null | null |
notebooks/util/vespa_helper/result_formatter.py
|
dbmdz/webarchiv-dh-bestandsausbau
|
98c271a09cdb026d1d58133f49dcb3e1c9fcf9b6
|
[
"MIT"
] | null | null | null |
def write_table_row(key, value):
row = f"<tr><td>{key}</td><td>{value}</td></tr>"
return row
def write_doc_entry(idx, domain):
fields = domain.get("fields")
doc_entry = f'<tr><th colspan="2">Link {idx}</th></tr>'
doc_entry += write_table_row(
"URL",
f"<a target=\"_blank\" rel=\"noopener noreferrer\" href=\"//www.{fields.get('url')}\">{fields.get('url')}</a>",
)
doc_entry += write_table_row("Kontext", fields.get("context"))
doc_entry += write_table_row("", "")
return doc_entry
def write_domain_table(domain_group):
domain_table = "<table><style>th, td { padding-left: 15px; text-align: left; vertical-align: top;}</style>"
for i, domain in enumerate(domain_group.get("children", [])):
domain_table += write_doc_entry(i + 1, domain)
domain_table += "</table>"
return domain_table
| 35.958333 | 119 | 0.628042 |
f3dd3eb9c0de52bf0b070ce94c5e2d8dce80939a
| 2,057 |
py
|
Python
|
test/test_npu/test_onnx/torch.onnx/custom_ops_demo/test_custom_ops_demo.py
|
Ascend/pytorch
|
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
|
[
"BSD-3-Clause"
] | 1 |
2021-12-02T03:07:35.000Z
|
2021-12-02T03:07:35.000Z
|
test/test_npu/test_onnx/torch.onnx/custom_ops_demo/test_custom_ops_demo.py
|
Ascend/pytorch
|
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
|
[
"BSD-3-Clause"
] | 1 |
2021-11-12T07:23:03.000Z
|
2021-11-12T08:28:13.000Z
|
test/test_npu/test_onnx/torch.onnx/custom_ops_demo/test_custom_ops_demo.py
|
Ascend/pytorch
|
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
|
[
"BSD-3-Clause"
] | null | null | null |
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# Copyright (c) 2019, Facebook CORPORATION.
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# 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 torch
import torch.utils.cpp_extension
import numpy as np
def do_export(model, inputs, *args, **kwargs):
out = torch.onnx._export(model, inputs, "custom_demo.onnx", *args, **kwargs)
###########################################################
def test_custom_add():
op_source = """
#include <torch/script.h>
torch::Tensor custom_add(torch::Tensor self, torch::Tensor other) {
return self + other;
}
static auto registry =
torch::RegisterOperators("custom_namespace::custom_add", &custom_add);
"""
torch.utils.cpp_extension.load_inline(
name="custom_add",
cpp_sources=op_source,
is_python_module=False,
verbose=True,
)
test_custom_add()
############################################################
class CustomAddModel(torch.nn.Module):
def forward(self, a, b):
return torch.ops.custom_namespace.custom_add(a, b)
############################################################
def symbolic_custom_add(g, self, other):
return g.op('custom_namespace::custom_add', self, other)
from torch.onnx import register_custom_op_symbolic
register_custom_op_symbolic('custom_namespace::custom_add', symbolic_custom_add, 9)
x = torch.randn(2, 3, 4, requires_grad=False)
y = torch.randn(2, 3, 4, requires_grad=False)
model = CustomAddModel()
do_export(model, (x, y), opset_version=11)
| 25.7125 | 83 | 0.654837 |
ed9e8890fc8f7ed6a4fa787b1c512b52f4aa635c
| 183 |
py
|
Python
|
etl/core/exceptions.py
|
cloud-cds/cds-stack
|
d68a1654d4f604369a071f784cdb5c42fc855d6e
|
[
"Apache-2.0"
] | 6 |
2018-06-27T00:09:55.000Z
|
2019-03-07T14:06:53.000Z
|
etl/core/exceptions.py
|
cloud-cds/cds-stack
|
d68a1654d4f604369a071f784cdb5c42fc855d6e
|
[
"Apache-2.0"
] | 3 |
2021-03-31T18:37:46.000Z
|
2021-06-01T21:49:41.000Z
|
etl/core/exceptions.py
|
cloud-cds/cds-stack
|
d68a1654d4f604369a071f784cdb5c42fc855d6e
|
[
"Apache-2.0"
] | 3 |
2020-01-24T16:40:49.000Z
|
2021-09-30T02:28:55.000Z
|
class TransformError(Exception):
def __init__(self, func_name, reason, context=''):
self.func_name = func_name
self.reason = reason
self.context = context
| 30.5 | 54 | 0.661202 |
b65daeb6d8f9277e6a364aa0a069ea645ae372e3
| 2,989 |
py
|
Python
|
pyntcloud/ransac/samplers.py
|
bernssolg/pyntcloud-master
|
84cf000b7a7f69a2c1b36f9624f05f65160bf992
|
[
"MIT"
] | 1,142 |
2016-10-10T08:55:30.000Z
|
2022-03-30T04:46:16.000Z
|
pyntcloud/ransac/samplers.py
|
bernssolg/pyntcloud-master
|
84cf000b7a7f69a2c1b36f9624f05f65160bf992
|
[
"MIT"
] | 195 |
2016-10-10T08:30:37.000Z
|
2022-02-17T12:51:17.000Z
|
pyntcloud/ransac/samplers.py
|
bernssolg/pyntcloud-master
|
84cf000b7a7f69a2c1b36f9624f05f65160bf992
|
[
"MIT"
] | 215 |
2017-02-28T00:50:29.000Z
|
2022-03-22T17:01:31.000Z
|
import numpy as np
from abc import ABC, abstractmethod
from ..structures import VoxelGrid
class RansacSampler(ABC):
""" Base class for ransac samplers.
Parameters
----------
points : ndarray
(N, M) ndarray where N is the number of points and M is the number
scalar fields associated to each of those points.
M is usually 3 for representing the x, y, and z coordinates of each point.
k : int
The number of points that will be sampled in each call of get_sample().
This number depends on the model used. See ransac/models.py.
"""
def __init__(self, points, k):
self.points = points
self.k = k
@abstractmethod
def get_sample(self):
pass
class RandomRansacSampler(RansacSampler):
""" Sample random points.
Inherits from RansacSampler.
"""
def __init__(self, points, k):
super().__init__(points, k)
def get_sample(self):
""" Get k unique random points.
"""
sample = np.random.choice(len(self.points), self.k, replace=False)
return self.points[sample]
class VoxelgridRansacSampler(RansacSampler):
""" Sample random points inside the same random voxel.
Inherits from RansacSampler.
Parameters
----------
points: (N, 3) numpy.array
k: int
Numbber of points to sample.
n_x, n_y, n_z : int, optional
Default: 1
The number of segments in which each axis will be divided.
Ignored if corresponding size_x, size_y or size_z is not None.
size_x, size_y, size_z : float, optional
Default: None
The desired voxel size along each axis.
If not None, the corresponding n_x, n_y or n_z will be ignored.
regular_bounding_box : bool, optional
Default: True
If True, the bounding box of the point cloud will be adjusted
in order to have all the dimensions of equal length.
"""
def __init__(self,
points, k, n_x=1, n_y=1, n_z=1, size_x=None, size_y=None, size_z=None, regular_bounding_box=True):
super().__init__(points, k)
self.voxelgrid = VoxelGrid(
points=self.points, n_x=n_x, n_y=n_y, n_z=n_z, size_x=size_x, size_y=size_y, size_z=size_z,
regular_bounding_box=regular_bounding_box)
self.voxelgrid.compute()
def get_sample(self):
""" Get k unique random points from the same voxel of one randomly picked point.
"""
# pick one point and get its voxel index
idx = np.random.randint(0, len(self.points))
voxel = self.voxelgrid.voxel_n[idx]
# get index of points inside that voxel and convert to probabilities
points_in_voxel = (self.voxelgrid.voxel_n == voxel).astype(int)
points_in_voxel = points_in_voxel / points_in_voxel.sum()
sample = np.random.choice(
len(self.points), self.k, replace=False, p=points_in_voxel)
return self.points[sample]
| 31.463158 | 115 | 0.644697 |
b68f9abad8c450140f0ab1f54eee797085f6f051
| 3,127 |
py
|
Python
|
test/test_npu/test_all.py
|
Ascend/pytorch
|
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
|
[
"BSD-3-Clause"
] | 1 |
2021-12-02T03:07:35.000Z
|
2021-12-02T03:07:35.000Z
|
test/test_npu/test_all.py
|
Ascend/pytorch
|
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
|
[
"BSD-3-Clause"
] | 1 |
2021-11-12T07:23:03.000Z
|
2021-11-12T08:28:13.000Z
|
test/test_npu/test_all.py
|
Ascend/pytorch
|
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
|
[
"BSD-3-Clause"
] | null | null | null |
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# 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 torch
import numpy as np
import sys
import copy
from common_utils import TestCase, run_tests
from common_device_type import dtypes, instantiate_device_type_tests
from util_test import create_common_tensor
class TestAll(TestCase):
def cpu_op_exec1(self, input):
output = torch.all(input)
output = output.numpy()
return output
def npu_op_exec1(self, input):
input = input.to("npu")
output = torch.all(input)
output = output.to("cpu")
output = output.numpy()
return output
def cpu_op_exec3(self, input, axis, keepdim):
output = torch.all(input, axis, keepdim)
output = output.numpy()
return output
def npu_op_exec3(self, input, axis, keepdim):
input = input.to("npu")
output = torch.all(input, axis, keepdim)
output = output.to("cpu")
output = output.numpy()
return output
def test_all_noaxis_notkeedim_bool(self, device):
shape_format = [
[np.bool_, -1, (4, 2, 5)],
[np.bool_, -1, (7, 4, 5, 8)]
]
for item in shape_format:
cpu_input, npu_input = create_common_tensor(item, 0, 2)
cpu_output = self.cpu_op_exec1(cpu_input)
npu_output = self.npu_op_exec1(npu_input)
self.assertRtolEqual(cpu_output, npu_output)
def test_all_axis_notkeedim_bool(self, device):
shape_format = [
[[np.bool_, -1, (4, 2, 5)], 3],
[[np.bool_, -1, (4, 2, 5, 8)], 4]
]
for item in shape_format:
for i in range(item[1]):
cpu_input, npu_input = create_common_tensor(item[0], 0, 2)
cpu_output = self.cpu_op_exec3(cpu_input, i, False)
npu_output = self.npu_op_exec3(npu_input, i, False)
self.assertRtolEqual(cpu_output, npu_output)
def test_all_axis_keedim_bool(self, device):
shape_format = [
[[np.bool_, -1, (4, 2, 5)], 3],
[[np.bool_, -1, (4, 2, 5, 8)], 4]
]
for item in shape_format:
for i in range(item[1]):
cpu_input, npu_input = create_common_tensor(item[0], 0, 2)
cpu_output = self.cpu_op_exec3(cpu_input, i, True)
npu_output = self.npu_op_exec3(npu_input, i, True)
self.assertRtolEqual(cpu_output, npu_output)
instantiate_device_type_tests(TestAll, globals(), except_for='cpu')
if __name__ == "__main__":
run_tests()
| 36.788235 | 74 | 0.625839 |
bfad0bf897c11a2732fa3a7c4abec4e1637dc3bf
| 3,392 |
py
|
Python
|
indl/regularizers.py
|
SachsLab/indl
|
531d2e0c2ee765004aedc553af40e258262f86cb
|
[
"Apache-2.0"
] | 1 |
2021-02-22T01:39:50.000Z
|
2021-02-22T01:39:50.000Z
|
indl/regularizers.py
|
SachsLab/indl
|
531d2e0c2ee765004aedc553af40e258262f86cb
|
[
"Apache-2.0"
] | null | null | null |
indl/regularizers.py
|
SachsLab/indl
|
531d2e0c2ee765004aedc553af40e258262f86cb
|
[
"Apache-2.0"
] | null | null | null |
import numpy as np
import tensorflow as tf
from typing import Iterable
__all__ = ['KernelLengthRegularizer']
class KernelLengthRegularizer(tf.keras.regularizers.Regularizer):
"""
Regularize a kernel by its length. Added loss is a int mask of 1s where abs(weight) is above threshold,
and 0s otherwise, multiplied by a window. The window is typically shaped to penalize the presence of
non-zero weights further away from the middle of the kernel. Use this regularizer if you want to
try to find a minimal-length kernel. (after training, kernel can be shortened for faster inference).
"""
def __init__(self, kernel_size: Iterable[int], window_scale: float = 1e-2, window_func: str = 'poly',
poly_exp: int = 2, threshold: float = tf.keras.backend.epsilon()):
"""
Args:
kernel_size: length(s) of kernel(s)
window_scale: scale factor to apply to window
window_func: 'hann', 'hamming', 'poly' (default)
poly_exp: exponent used when window_func=='poly'
threshold: weight threshold, below which weights will not be penalized.
"""
self.kernel_size = kernel_size
self.window_scale = window_scale
self.window_func = window_func
self.poly_exp = poly_exp
self.threshold = threshold
self.rebuild_window()
def rebuild_window(self):
windows = []
for win_dim, win_len in enumerate(self.kernel_size):
if win_len == 1:
window = np.ones((1,), dtype=np.float32)
else:
if self.window_func == 'hann':
window = 1 - tf.signal.hann_window(win_len, periodic=False)
elif self.window_func == 'hamming':
window = 1 - tf.signal.hamming_window(win_len, periodic=False)
else: # if window_func == 'linear':
hl = win_len // 2
window = np.zeros((win_len,), dtype=np.float32)
window[:hl] = np.arange(1, hl + 1)[::-1] # Negative slope line to 0 for first half.
window[-hl:] = np.arange(1, hl + 1) # Positive slope line from 0 for second half.
window = window / hl # Scale so it's -1 -- 0 -- 1
window = window ** self.poly_exp # Exponent
win_shape = [1] * (len(self.kernel_size) + 2)
win_shape[win_dim] = win_len
window = tf.reshape(window, win_shape)
windows.append(window)
self.window = tf.linalg.matmul(*windows)
self.window = self.window / tf.reduce_max(self.window)
def get_config(self) -> dict:
return {'kernel_size': self.kernel_size,
'window_scale': self.window_scale,
'window_func': self.window_func,
'poly_exp': self.poly_exp,
'threshold': self.threshold}
def __call__(self, weights):
weights = tf.sqrt(tf.square(weights)) # Differentiable abs
# non_zero = tf.cast(weights > self.threshold, tf.float32)
non_zero = tf.nn.sigmoid(weights - self.threshold)
regularization = self.window_scale * self.window * non_zero
# regularization = tf.reduce_max(regularization, axis=[0, 1], keepdims=True)
regularization = tf.reduce_sum(regularization)
return regularization
| 44.631579 | 107 | 0.606132 |
bfd07ebea55ae687b8fd6d334ef166b87b5960e4
| 156 |
py
|
Python
|
Proyecto21dias/views.py
|
sergioandrespenarandatarazona/Tesis1
|
24ad878189aefa932895b2f42e8059a9720fcf1f
|
[
"MIT"
] | null | null | null |
Proyecto21dias/views.py
|
sergioandrespenarandatarazona/Tesis1
|
24ad878189aefa932895b2f42e8059a9720fcf1f
|
[
"MIT"
] | null | null | null |
Proyecto21dias/views.py
|
sergioandrespenarandatarazona/Tesis1
|
24ad878189aefa932895b2f42e8059a9720fcf1f
|
[
"MIT"
] | null | null | null |
""" URLs module."""
from django.http import HttpResponse
def hello_world(request):
"""Return a greeting."""
return HttpResponse('Hello, world!')
| 17.333333 | 40 | 0.679487 |
44dc3aa81669f6ee82ce7c263f2faede5348f903
| 92 |
py
|
Python
|
2015/01/sp/graphic_config.py
|
nprapps/graphics-archive
|
97b0ef326b46a959df930f5522d325e537f7a655
|
[
"FSFAP"
] | 14 |
2015-05-08T13:41:51.000Z
|
2021-02-24T12:34:55.000Z
|
graphic_templates/table/graphic_config.py
|
tophtucker/dailygraphics
|
abc8fa7fb0e4d15800bb3edcf2c864fe98f40197
|
[
"MIT"
] | null | null | null |
graphic_templates/table/graphic_config.py
|
tophtucker/dailygraphics
|
abc8fa7fb0e4d15800bb3edcf2c864fe98f40197
|
[
"MIT"
] | 7 |
2015-04-04T04:45:54.000Z
|
2021-02-18T11:12:48.000Z
|
#!/usr/bin/env python
COPY_GOOGLE_DOC_KEY = '1ciRc--h8HuBpQzMebVygC4x_y9dvKxp6OA45ccRrIX4'
| 23 | 68 | 0.826087 |
44ebb1386893966f91b865f959755b8287e28104
| 904 |
py
|
Python
|
sys/1/start.py
|
wittrup/crap
|
a77474588fd54a5a998e24df7b1e6e2ab473ded1
|
[
"MIT"
] | 1 |
2017-12-12T13:58:08.000Z
|
2017-12-12T13:58:08.000Z
|
sys/1/start.py
|
wittrup/crap
|
a77474588fd54a5a998e24df7b1e6e2ab473ded1
|
[
"MIT"
] | null | null | null |
sys/1/start.py
|
wittrup/crap
|
a77474588fd54a5a998e24df7b1e6e2ab473ded1
|
[
"MIT"
] | 1 |
2019-11-03T10:16:35.000Z
|
2019-11-03T10:16:35.000Z
|
import requests
import re
from os.path import isfile
from time import sleep
from time import strftime as now
from random import shuffle, randrange
FORMAT = '%Y-%m-%d %H:%M:%S'
def log(data, file='fetch.log'):
with open(file, 'a+') as f:
f.write(now(FORMAT) + ' ' + str(data) + '\n')
f.close()
if input('Are you sure? ') != 'YES':
exit()
m = [l.strip() for l in open("../ignore/sys_1_misc.txt").readlines()]
details = {"username": m[1], "password": m[2]}
login = requests.Session()
login = login.post(m[0], data=details)
bids = list(range(1, int(m[3])+1))
shuffle(bids)
for i in bids:
url = m[4] + str(i) + m[5]
fname = 'b/' + str(i) + '.html'
if not isfile(fname):
log('Fetching %s' % (fname))
r = requests.get(url, cookies=login.cookies)
print(r.text, file=open(fname, 'w', encoding='utf-8'))
sleep(randrange(1337, 1719) / 1000)
| 26.588235 | 69 | 0.596239 |
e5aad9c3d7f5720d182117a938d13b218c7f4258
| 657 |
py
|
Python
|
source/pkgsrc/lang/python27/patches/patch-Lib_ctypes_____init____.py
|
Scottx86-64/dotfiles-1
|
51004b1e2b032664cce6b553d2052757c286087d
|
[
"Unlicense"
] | 1 |
2021-11-20T22:46:39.000Z
|
2021-11-20T22:46:39.000Z
|
source/pkgsrc/lang/python27/patches/patch-Lib_ctypes_____init____.py
|
Scottx86-64/dotfiles-1
|
51004b1e2b032664cce6b553d2052757c286087d
|
[
"Unlicense"
] | null | null | null |
source/pkgsrc/lang/python27/patches/patch-Lib_ctypes_____init____.py
|
Scottx86-64/dotfiles-1
|
51004b1e2b032664cce6b553d2052757c286087d
|
[
"Unlicense"
] | null | null | null |
$NetBSD: patch-Lib_ctypes_____init____.py,v 1.1 2020/09/01 09:26:54 schmonz Exp $
Avoid MemoryError from "import ctypes" on OpenBSD.
--- Lib/ctypes/__init__.py.orig Sun Apr 19 21:13:39 2020
+++ Lib/ctypes/__init__.py
@@ -273,7 +273,8 @@ def _reset_cache():
# function is needed for the unittests on Win64 to succeed. This MAY
# be a compiler bug, since the problem occurs only when _ctypes is
# compiled with the MS SDK compiler. Or an uninitialized variable?
- CFUNCTYPE(c_int)(lambda: None)
+ if not _sys.platform.startswith('openbsd'):
+ CFUNCTYPE(c_int)(lambda: None)
try:
from _ctypes import set_conversion_mode
| 38.647059 | 81 | 0.710807 |
8220ee1455505e060ab25e9c2e7664a9d42648e8
| 3,245 |
py
|
Python
|
src/visitpy/visit_utils/tests/test_qannote_basic.py
|
visit-dav/vis
|
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
|
[
"BSD-3-Clause"
] | 226 |
2018-12-29T01:13:49.000Z
|
2022-03-30T19:16:31.000Z
|
src/visitpy/visit_utils/tests/test_qannote_basic.py
|
visit-dav/vis
|
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
|
[
"BSD-3-Clause"
] | 5,100 |
2019-01-14T18:19:25.000Z
|
2022-03-31T23:08:36.000Z
|
src/visitpy/visit_utils/tests/test_qannote_basic.py
|
visit-dav/vis
|
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
|
[
"BSD-3-Clause"
] | 84 |
2019-01-24T17:41:50.000Z
|
2022-03-10T10:01:46.000Z
|
# Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
# Project developers. See the top-level LICENSE file for dates and other
# details. No copyright assignment is required to contribute to VisIt.
"""
author: Cyrus Harrison ([email protected])
description:
Tests for qannote module.
"""
import unittest
import os
from os.path import join as pjoin
from visit_test import *
from visit_utils.qannote import *
try:
import PySide2.QtCore
except:
pass
output_dir = pjoin(os.path.split(__file__)[0],"_output")
data_dir = pjoin(os.path.split(__file__)[0],"_data")
def out_path(fname):
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
odir = pjoin(output_dir,"qannote")
if not os.path.isdir(odir):
os.mkdir(odir)
return pjoin(odir,fname)
class TestBasic(unittest.TestCase):
def setUp(self):
txt = Text( {"text": "Text Overlay!",
"x": 100,
"y": 200,
"color": (255,255,255,255),
"vert_align":"center",
"horz_align":"center",
"font/name": "Times New Roman",
"font/size": 22})
img = Image( {"image":pjoin(data_dir,"blue.box.png"),
"x": 130, "y": 180})
arr = Arrow( {"x0": 10, "y0":10,
"x1":100,"y1":175,"tip_len":20})
rect = Rect( {"x":400,"y":400,
"width":100,"height":200,
"color":(0,255,0,255)})
box = Rect( {"x":200,"y":200,
"width":100,"height":100,
"color":(0,255,0,255),"outline":True})
self.items = [img,txt,arr,rect,box]
@pyside_test
def test_00_basic(self):
test_output = out_path("test.basic.00.png")
Canvas.render(self.items,(600,600),test_output)
@pyside_test
def test_01_basic(self):
test_output = out_path("test.basic.01.png")
bg = Image( {"image":pjoin(data_dir,"black.bg.png")})
items = [bg]
items.extend(self.items)
Canvas.render(items,bg.size(),test_output)
@pyside_test
def test_02_view(self):
test_output = out_path("test.basic.02.png")
bg = Image( {"image":pjoin(data_dir,"black.bg.png"),
"x":-10,"y":-10})
items = [bg]
items.extend(self.items)
sz = bg.size()
Canvas.render(items,sz,test_output,(-10,-10,sz[0],sz[1]))
@pyside_test
def test_03_textbox(self):
test_output = out_path("test.basic.03.png")
bg = Image( {"image":pjoin(data_dir,"black.bg.png"),
"x":-10,"y":-10})
items = [bg]
txt = "Testing text box with wrap capability with a long sentence.\nWith some new lines for good measure.\nFinal."
items.append(TextBox({"x":200,"y":200,
"width":300,"height":200,
"font/size":20,
"text":txt}))
sz = bg.size()
Canvas.render(items,sz,test_output,(-10,-10,sz[0],sz[1]))
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
| 34.157895 | 122 | 0.536826 |
ec35cbe7db78b769c8006428df8025f03849e37f
| 635 |
py
|
Python
|
INBa/2015/Shemenev_A_V/task_6_30.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
INBa/2015/Shemenev_A_V/task_6_30.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
INBa/2015/Shemenev_A_V/task_6_30.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
# Задача 6. Вариант 30.
# Создайте игру, в которой компьютер загадывает название одного из двенадцати месяцев, а игрок должен его угадать.
# Shemenev A.V
# 11.04.2016
import random
month=["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"] #Список месяцев
print("Данная программа предлагает вам угадать загаданную компьютером месяц")
x=random.choice(month)
print ("Какой месяц загадал компьютер?")
y=input("Введите ваш ответ (например 'Январь' без кавычек: ")
if x==y:
print("Правильно!")
if x!=y:
print("Неправильно!,правильный ответ-"+x)
input ("нажмите Enter для выхода")
| 37.352941 | 127 | 0.733858 |
6b944d3a4924ec77fe9d8ae602cfd5401958c63b
| 1,643 |
py
|
Python
|
tools/pythonpkg/tests/fast/pandas/test_same_name.py
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | 2,816 |
2018-06-26T18:52:52.000Z
|
2021-04-06T10:39:15.000Z
|
tools/pythonpkg/tests/fast/pandas/test_same_name.py
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | 1,310 |
2021-04-06T16:04:52.000Z
|
2022-03-31T13:52:53.000Z
|
tools/pythonpkg/tests/fast/pandas/test_same_name.py
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | 270 |
2021-04-09T06:18:28.000Z
|
2022-03-31T11:55:37.000Z
|
import pytest
import duckdb
import pandas as pd
class TestMultipleColumnsSameName(object):
def test_multiple_columns_with_same_name(self, duckdb_cursor):
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8], 'd': [9, 10, 11, 12]})
df = df.rename(columns={ df.columns[1]: "a" })
df_original = df.copy(True)
con = duckdb.connect()
con.register('df_view', df)
assert con.execute("DESCRIBE df_view;").fetchall() == [('a', 'BIGINT', 'YES', None, None, None), ('a_1', 'BIGINT', 'YES', None, None, None), ('d', 'BIGINT', 'YES', None, None, None)]
assert con.execute("select a_1 from df_view;").fetchall() == [(5,), (6,), (7,), (8,)]
assert con.execute("select a from df_view;").fetchall() == [(1,), (2,), (3,), (4,)]
# Verify we are not changing original dataframe
assert df_original.equals(df)
def test_multiple_columns_with_same_name_2(self, duckdb_cursor):
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8], 'a_1': [9, 10, 11, 12]})
df = df.rename(columns={ df.columns[1]: "a_1" })
con = duckdb.connect()
con.register('df_view', df)
assert con.execute("DESCRIBE df_view;").fetchall() == [('a', 'BIGINT', 'YES', None, None, None), ('a_1', 'BIGINT', 'YES', None, None, None), ('a_1_1', 'BIGINT', 'YES', None, None, None)]
assert con.execute("select a_1 from df_view;").fetchall() == [(5,), (6,), (7,), (8,)]
assert con.execute("select a from df_view;").fetchall() == [(1,), (2,), (3,), (4,)]
assert con.execute("select a_1_1 from df_view;").fetchall() == [(9,), (10,), (11,), (12,)]
| 54.766667 | 194 | 0.566038 |
d84a852a922004ec2496f367b86b02e6931a52bf
| 119 |
py
|
Python
|
fuzzsvc/app/config.py
|
ifoundthetao/FuzzFlow
|
86559ac7f85fc89510c0d9647e02880edb95aa2a
|
[
"MIT"
] | null | null | null |
fuzzsvc/app/config.py
|
ifoundthetao/FuzzFlow
|
86559ac7f85fc89510c0d9647e02880edb95aa2a
|
[
"MIT"
] | null | null | null |
fuzzsvc/app/config.py
|
ifoundthetao/FuzzFlow
|
86559ac7f85fc89510c0d9647e02880edb95aa2a
|
[
"MIT"
] | null | null | null |
import os
DATABASE_URI = "sqlite:///fuzzflow.db"
CLIENT_FOLDER = "client"
UPLOAD_FOLDER = 'static' + os.sep + 'upload'
| 23.8 | 44 | 0.714286 |
cfa8edf57a7627fbafa12446431741d903610b78
| 7,580 |
py
|
Python
|
keyboards/signum/3_0/elitec/keymaps/default/generate_km.py
|
fzf/qmk_toolbox
|
10d6b425bd24b45002555022baf16fb11254118b
|
[
"MIT"
] | null | null | null |
keyboards/signum/3_0/elitec/keymaps/default/generate_km.py
|
fzf/qmk_toolbox
|
10d6b425bd24b45002555022baf16fb11254118b
|
[
"MIT"
] | null | null | null |
keyboards/signum/3_0/elitec/keymaps/default/generate_km.py
|
fzf/qmk_toolbox
|
10d6b425bd24b45002555022baf16fb11254118b
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import layout
import os
import re
def gen_uc_iter():
length = len(layout.uc_dict)
for key, value in sorted(layout.uc_dict.items()):
length -= 1
if length:
yield (key, value, False)
else:
yield (key, value, True)
def _translate(s):
if re.match("^[0-9]$", s):
return ("KC_{0}".format(s), " {0} ".format(s))
elif re.match("^[a-z]$", s):
return ("KC_{0}".format(s.upper()), " {0} ".format(s))
elif re.match("^[A-Z]$", s):
return ("S(KC_{0})".format(s), " {0} ".format(s))
elif re.match("^F[0-9]{1,2}$", s): # Fn, works from F0 to F99
return ("KC_{0}".format(s), "{0:^7}".format(s))
elif re.match("^DF[0-9]{1,2}$", s): # DFn, works from DF0 to DF99
return ("DF({0})".format(s[2:]), "{0:^7}".format(s))
elif re.match("^MO[0-9]{1,2}$", s): # MOn, works from MO0 to MO99
return ("MO({0})".format(s[2:]), "{0:^7}".format(s))
elif re.match("^OSL[0-9]{1,2}$", s): # OSLn, works from OSL0 to OSL99
return ("OSL({0})".format(s[3:]), "{0:^7}".format(s))
elif re.match("^TG[0-9]{1,2}$", s): # TGn, works from TG0 to TG99
return ("TG({0})".format(s[2:]), "{0:^7}".format(s))
elif re.match("^TO[0-9]{1,2}$", s): # Tn, works from TO0 to TO99
return ("TO({0})".format(s[2:]), "{0:^7}".format(s))
elif re.match("^TT[0-9]{1,2}$", s): # Tn, works from TT0 to TT99
return ("TT({0})".format(s[2:]), "{0:^7}".format(s))
elif s in layout.uc_dict:
return ("X("+s+")", " {0} ".format(chr(int(layout.uc_dict[s], 0))))
elif s in layout.qmk_dict:
return (layout.qmk_dict[s], "{0:^7}".format(s))
elif s == s.upper() and s.startswith("KC_"):
return (s, "{0:^7}".format(s[2:]))
else:
return ("XXXXXXX", " {0} ".format(chr(128165)))
def toKC(s):
return _translate(s)[0]
def toLgd(s):
return _translate(s)[1]
def quoteC(text):
yield "/*"
for line in text:
yield " * " + line
yield " */\n"
def getKeymapText(id, layer, columns, rows):
keymap = []
keymap.append("Layer %d" % id)
keymap.append("------------------------------------------------- -------------------------------------------------")
keymap.append("|{0}|{1}|{2}|{3}|{4}|{5}| |{6}|{7}|{8}|{9}|{10}|{11}|".format(*map(toLgd, layer[:12])))
keymap.append("------------------------------------------------- -------------------------------------------------")
keymap.append("|{0}|{1}|{2}|{3}|{4}|{5}| |{6}|{7}|{8}|{9}|{10}|{11}|".format(*map(toLgd, layer[12:24])))
keymap.append("------------------------------------------------- -------------------------------------------------")
keymap.append("|{0}|{1}|{2}|{3}|{4}|{5}| |{6}|{7}|{8}|{9}|{10}|{11}|".format(*map(toLgd, layer[24:36])))
keymap.append("-----------------------------------------------------------------------------------------------------------------")
keymap.append(" {0} {1} {2} |{3}|{4}|{5}|{6}|{7}|{8}| {9} {10} {11}".format(*map(toLgd, layer[36:48])).rstrip())
keymap.append(" -------------------------------------------------")
return keymap
def writeKeymap(f_template, f_keymap, layers, columns, rows):
doCopy = False
for line in f_template:
doCopy = True
if line.startswith("//<enum/>"):
doCopy = False
# f_keymap.write(str(layout.uc_dict))
for k, v, isLast in gen_uc_iter():
if isLast:
f_keymap.write(k + "\n")
else:
f_keymap.write(k + ",\n")
elif line.startswith("//<uc_map/>"):
doCopy = False
for k, v, isLast in gen_uc_iter():
if isLast:
f_keymap.write(u"\t[{0}] = {1} // {2}\n".format(k, v, chr(int(v, 0))))
else:
f_keymap.write(u"\t[{0}] = {1}, // {2}\n".format(k, v, chr(int(v, 0))))
elif line.startswith("//<keymaps/>"):
doCopy = False
for layer, L in enumerate(layers):
r_counter = rows
f_keymap.write('\n'.join(quoteC(getKeymapText(layer, L, columns, rows))))
l_code = '\tLAYOUT_ortho_4x12(\n'
for r in range(r_counter):
r_counter -= 1
c_counter = columns
l_code += '\t\t'
for c in range(c_counter):
c_counter -= 1
if c != 0:
l_code += " "
l_code += "%s" % toKC(L[r*columns + columns-c_counter-1])
if r_counter or c_counter:
l_code += ","
l_code += '\n'
if layer + 1 != len(layout.layers):
l_code += "\t),\n\n"
else:
l_code += "\t)\n"
f_keymap.write(l_code)
if doCopy:
f_keymap.write(line)
def getKeymapJSON(keyboard, keymap, layout, layers):
return json.dumps({
'keyboard': keyboard,
'keymap': keymap,
'layout': layout,
'layers': layers
}, sort_keys=True, indent=4)
def getKeymapAsciidoc(title, layers, columns, rows):
yield '= ' + title
yield ''
for id, layer in enumerate(layers):
keymap = getKeymapText(id, layer, columns, rows)
if len(keymap):
yield '.' + keymap[0]
yield '--------------------------'
for line in keymap[1:]:
yield ' ' + line
yield '--------------------------'
yield ''
def layersToKC(layers):
return [list(map(toKC, layer)) for layer in layers]
def pathToKeymap(path):
head, keymap = os.path.split(path)
_, keymapsdir = os.path.split(head)
if keymapsdir == 'keymaps':
return keymap
def pathToKeyboard(path):
head, keymap = os.path.split(path)
head, keymapsdir = os.path.split(head)
if keymapsdir == 'keymaps':
head, dir = os.path.split(head)
while dir not in ('/', 'keyboards'):
yield dir
head, dir = os.path.split(head)
if __name__ == "__main__":
with open("km_template.txt", mode="r") as f_template:
with open("keymap.c", mode="w", encoding='utf-8') as f_keymap:
writeKeymap(f_template, f_keymap, layout.layers, columns=12, rows=4)
abspath = os.path.dirname(os.path.abspath(__file__))
keyboard = list(reversed(list(pathToKeyboard(abspath))))
keymap = pathToKeymap(abspath)
keyboard_layout = 'LAYOUT_ortho_4x12'
with open("%s_%s.json" % ('_'.join(keyboard), keymap), mode="w") as f_keymapjson:
f_keymapjson.write(
getKeymapJSON(
'/'.join(keyboard),
keymap,
keyboard_layout,
layersToKC(layout.layers))
)
with open("keymap.adoc", mode="w") as f_keymapasciidoc:
f_keymapasciidoc.write('\n'.join(getKeymapAsciidoc('Signum 3.0 %s_%s' % ('_'.join(keyboard), keymap), layout.layers, columns=12, rows=4)))
print("Run the following command to generate a PDF from the keymap")
print("a2x -f pdf --xsltproc-opts '--stringparam page.orientation landscape --stringparam body.font.master 12' --fop -v keymap.adoc")
| 38.871795 | 146 | 0.465435 |
8fa7dbf800f89cf32d1f717ade893043af2132a0
| 1,221 |
py
|
Python
|
Packs/PrismaCloudCompute/Scripts/PrismaCloudComputeParseComplianceAlert/PrismaCloudComputeParseComplianceAlert.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 799 |
2016-08-02T06:43:14.000Z
|
2022-03-31T11:10:11.000Z
|
Packs/PrismaCloudCompute/Scripts/PrismaCloudComputeParseComplianceAlert/PrismaCloudComputeParseComplianceAlert.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 9,317 |
2016-08-07T19:00:51.000Z
|
2022-03-31T21:56:04.000Z
|
Packs/PrismaCloudCompute/Scripts/PrismaCloudComputeParseComplianceAlert/PrismaCloudComputeParseComplianceAlert.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 1,297 |
2016-08-04T13:59:00.000Z
|
2022-03-31T23:43:06.000Z
|
import demistomock as demisto
from CommonServerPython import *
import json
def parse_compliance(raw_json):
data = json.loads(raw_json)
if data.get('kind') != 'compliance':
raise ValueError(f'Input should be a raw JSON compliance alert, received: {raw_json}')
outputs = {'PrismaCloudCompute.ComplianceAlert': data}
# remove unneeded fields from human readable results
headers: list = []
for field in data.keys():
if field not in ['_id', 'kind', 'compliance']:
headers.append(field)
headers.sort()
readable_outputs = tableToMarkdown('Compliance Information',
data,
headers=headers)
# add another table for compliance issues
readable_outputs += tableToMarkdown('Compliance', data.get('compliance'))
return (
readable_outputs,
outputs,
raw_json
)
def main():
try:
return_outputs(*parse_compliance(demisto.args().get('alert_raw_json', '')))
except Exception as ex:
return_error(f'Failed to execute PrismaCloudComputeParseComplianceAlert. Error: {str(ex)}')
if __name__ in ('__builtin__', 'builtins'):
main()
| 27.75 | 99 | 0.634726 |
85905318aa0e704e3495bf516e995629a787dae9
| 9,402 |
py
|
Python
|
tests/test_jsonld.py
|
DanielGrams/gsevp
|
e94034f7b64de76f38754b56455e83092378261f
|
[
"MIT"
] | 1 |
2021-06-01T14:49:18.000Z
|
2021-06-01T14:49:18.000Z
|
tests/test_jsonld.py
|
DanielGrams/gsevp
|
e94034f7b64de76f38754b56455e83092378261f
|
[
"MIT"
] | 286 |
2020-12-04T14:13:00.000Z
|
2022-03-09T19:05:16.000Z
|
tests/test_jsonld.py
|
DanielGrams/gsevpt
|
a92f71694388e227e65ed1b24446246ee688d00e
|
[
"MIT"
] | null | null | null |
import pytest
def test_get_sd_for_admin_unit(client, app, db, seeder):
user_id, admin_unit_id = seeder.setup_base()
with app.app_context():
from project.jsonld import get_sd_for_admin_unit
from project.models import AdminUnit
admin_unit = AdminUnit.query.get(admin_unit_id)
admin_unit.url = "http://www.goslar.de"
result = get_sd_for_admin_unit(admin_unit)
assert result["url"] == "http://www.goslar.de"
def test_get_sd_for_organizer(client, app, db, seeder):
user_id, admin_unit_id = seeder.setup_base()
organizer_id = seeder.upsert_default_event_organizer(admin_unit_id)
with app.app_context():
from project.jsonld import get_sd_for_organizer
from project.models import EventOrganizer
organizer = EventOrganizer.query.get(organizer_id)
organizer.email = "[email protected]"
organizer.phone = "12345"
organizer.fax = "67890"
organizer.url = "http://www.goslar.de"
result = get_sd_for_organizer(organizer)
assert result["email"] == "[email protected]"
assert result["phone"] == "12345"
assert result["faxNumber"] == "67890"
assert result["url"] == "http://www.goslar.de"
def test_get_sd_for_place(client, app, db, utils, seeder):
user_id, admin_unit_id = seeder.setup_base()
place_id = seeder.upsert_default_event_place(admin_unit_id)
with app.app_context():
from math import isclose
from project.jsonld import get_sd_for_place
from project.models import EventPlace, Image, Location
place = EventPlace.query.get(place_id)
place.url = "http://www.goslar.de"
photo = Image()
photo.data = b"something"
place.photo = photo
location = Location()
location.street = "Markt 7"
location.postalCode = "38640"
location.city = "Goslar"
location.latitude = 51.9077888
location.longitude = 10.4333312
place.location = location
db.session.commit()
with app.test_request_context():
result = get_sd_for_place(place)
assert result["photo"] == utils.get_image_url(photo)
assert result["url"] == "http://www.goslar.de"
assert result["address"]["streetAddress"] == "Markt 7"
assert result["address"]["postalCode"] == "38640"
assert result["address"]["addressLocality"] == "Goslar"
assert isclose(result["geo"]["latitude"], 51.9077888)
assert isclose(result["geo"]["longitude"], 10.4333312)
def test_get_sd_for_place_noCoordinates(client, app, db, utils, seeder):
user_id, admin_unit_id = seeder.setup_base()
place_id = seeder.upsert_default_event_place(admin_unit_id)
with app.app_context():
from project.jsonld import get_sd_for_place
from project.models import EventPlace, Location
place = EventPlace.query.get(place_id)
location = Location()
location.street = "Markt 7"
location.postalCode = "38640"
location.city = "Goslar"
place.location = location
db.session.commit()
result = get_sd_for_place(place)
assert "geo" not in result
def test_get_sd_for_event_date(client, app, db, seeder, utils):
user_id, admin_unit_id = seeder.setup_base()
event_id = seeder.create_event(admin_unit_id)
with app.app_context():
from project.dateutils import create_berlin_date
from project.jsonld import get_sd_for_event_date
from project.models import Event, Image
from project.services.event import update_event
event = Event.query.get(event_id)
date_definition = event.date_definitions[0]
date_definition.start = create_berlin_date(2030, 12, 31, 14, 30)
date_definition.end = create_berlin_date(2030, 12, 31, 16, 30)
event.previous_start_date = create_berlin_date(2030, 12, 30, 14, 30)
event.external_link = "www.goslar.de"
event.ticket_link = "www.tickets.de"
event.accessible_for_free = True
photo = Image()
photo.data = b"something"
event.photo = photo
update_event(event)
db.session.commit()
event_date = event.dates[0]
with app.test_request_context():
result = get_sd_for_event_date(event_date)
assert result["startDate"] == date_definition.start
assert result["endDate"] == date_definition.end
assert result["previousStartDate"] == event.previous_start_date
assert result["isAccessibleForFree"]
assert result["url"][0] == utils.get_url("event_date", id=event_date.id)
assert result["url"][1] == "www.goslar.de"
assert result["url"][2] == "www.tickets.de"
assert result["image"] == utils.get_image_url(photo)
def test_get_sd_for_event_date_allday(client, app, db, seeder, utils):
user_id, admin_unit_id = seeder.setup_base()
event_id = seeder.create_event(admin_unit_id)
with app.app_context():
import json
from project.dateutils import create_berlin_date
from project.jsonld import DateTimeEncoder, get_sd_for_event_date
from project.models import Event
from project.services.event import update_event
event = Event.query.get(event_id)
date_definition = event.date_definitions[0]
date_definition.start = create_berlin_date(2030, 12, 31, 14, 30)
date_definition.end = create_berlin_date(2030, 12, 31, 16, 30)
date_definition.allday = True
update_event(event)
db.session.commit()
event_date = event.dates[0]
with app.test_request_context():
structured_data = json.dumps(
get_sd_for_event_date(event_date), indent=2, cls=DateTimeEncoder
)
assert '"startDate": "2030-12-31"' in structured_data
assert '"endDate": "2030-12-31"' in structured_data
def test_get_sd_for_event_date_with_co_organizer(client, app, db, seeder, utils):
user_id, admin_unit_id = seeder.setup_base()
event_id, organizer_a_id, organizer_b_id = seeder.create_event_with_co_organizers(
admin_unit_id
)
with app.app_context():
from project.jsonld import get_sd_for_event_date
from project.models import Event
event = Event.query.get(event_id)
event_date = event.dates[0]
with app.test_request_context():
data = get_sd_for_event_date(event_date)
assert len(data["organizer"]) == 4
@pytest.mark.parametrize(
"age_from, age_to, typicalAgeRange",
[(18, None, "18-"), (None, 14, "-14"), (9, 99, "9-99")],
)
def test_get_sd_for_event_date_ageRange(
client, app, db, seeder, utils, age_from, age_to, typicalAgeRange
):
user_id, admin_unit_id = seeder.setup_base()
event_id = seeder.create_event(admin_unit_id)
with app.app_context():
from project.jsonld import get_sd_for_event_date
from project.models import Event
from project.services.event import update_event
event = Event.query.get(event_id)
event.age_from = age_from
event.age_to = age_to
update_event(event)
db.session.commit()
event_date = event.dates[0]
with app.test_request_context():
result = get_sd_for_event_date(event_date)
assert result["typicalAgeRange"] == typicalAgeRange
@pytest.mark.parametrize(
"attendance_mode, eventAttendanceMode",
[
(1, "OfflineEventAttendanceMode"),
(2, "OnlineEventAttendanceMode"),
(3, "MixedEventAttendanceMode"),
],
)
def test_get_sd_for_event_date_eventAttendanceMode(
client, app, db, seeder, utils, attendance_mode, eventAttendanceMode
):
user_id, admin_unit_id = seeder.setup_base()
event_id = seeder.create_event(admin_unit_id)
with app.app_context():
from project.jsonld import get_sd_for_event_date
from project.models import Event, EventAttendanceMode
from project.services.event import update_event
event = Event.query.get(event_id)
event.attendance_mode = EventAttendanceMode(attendance_mode)
update_event(event)
db.session.commit()
event_date = event.dates[0]
with app.test_request_context():
result = get_sd_for_event_date(event_date)
assert result["eventAttendanceMode"] == eventAttendanceMode
@pytest.mark.parametrize(
"status, eventStatus",
[
(1, "EventScheduled"),
(2, "EventCancelled"),
(3, "EventMovedOnline"),
(4, "EventPostponed"),
(5, "EventRescheduled"),
],
)
def test_get_sd_for_event_date_eventStatus(
client, app, db, seeder, utils, status, eventStatus
):
user_id, admin_unit_id = seeder.setup_base()
event_id = seeder.create_event(admin_unit_id)
with app.app_context():
from project.jsonld import get_sd_for_event_date
from project.models import Event, EventStatus
from project.services.event import update_event
event = Event.query.get(event_id)
event.status = EventStatus(status)
update_event(event)
db.session.commit()
event_date = event.dates[0]
with app.test_request_context():
result = get_sd_for_event_date(event_date)
assert result["eventStatus"] == eventStatus
| 33.222615 | 86 | 0.668049 |
a4415f75eceb433cbac1b16aa47cf701bd9b7812
| 2,020 |
py
|
Python
|
projects/g3h1-cp-fml-interpreter/src/fml_parser/grammar.py
|
keybrl/xdu-coursework
|
9d0e905bef28c18d87d3b97643de0d32f9f08ee0
|
[
"MIT"
] | null | null | null |
projects/g3h1-cp-fml-interpreter/src/fml_parser/grammar.py
|
keybrl/xdu-coursework
|
9d0e905bef28c18d87d3b97643de0d32f9f08ee0
|
[
"MIT"
] | null | null | null |
projects/g3h1-cp-fml-interpreter/src/fml_parser/grammar.py
|
keybrl/xdu-coursework
|
9d0e905bef28c18d87d3b97643de0d32f9f08ee0
|
[
"MIT"
] | null | null | null |
# Grammar
# =======
#
# Program -> { Statement SEMICOLON }
#
# Statement -> OriginStatement | ScaleStatement | RotStatement | ForStatement | ColorStatement | BgStatement
#
# OriginStatement -> ORIGIN IS L_BRACKET Expression COMMA Expression R_BRACKET
# ScaleStatement -> SCALE IS L_BRACKET Expression COMMA Expression R_BRACKET
# RotStatement -> ROT IS Expression
# ColorStatement -> COLOR IS L_BRACKET Expression COMMA Expression COMMA Expression R_BRACKET
# BgStatement -> BACKGROUND IS L_BRACKET Expression COMMA Expression COMMA Expression R_BRACKET
# ForStatement -> FOR T
# FROM Expression
# TO Expression
# STEP Expression
# DRAW L_BRACKET Expression COMMA Expression R_BRACKET
#
# Expression -> Term { ( PLUS | MINUS ) Term }
# Term -> Factor { ( MUL | DIV ) Factor }
# Factor -> ( PLUS | MINUS ) Factor | Component
# Component -> Atom [ POWER Component ]
# Atom -> CONST_ID | T | NUM |
# FUNC L_BRACKET Expression R_BRACKET |
# L_BRACKET Expression R_BRACKET
from enum import Enum, unique
from lexer import Token
@unique
class NonTerminals(Enum):
PROGRAM = 0
STATEMENT = 1
ORIGIN_STATEMENT = 11
SCALE_STATEMENT = 12
ROT_STATEMENT = 13
FOR_STATEMENT = 14
COLOR_STATEMENT = 15
BG_STATEMENT = 16
EXPRESSION = 2
TERM = 21
FACTOR = 22
COMPONENT = 23
ATOM = 24
@unique
class Terminals(Enum):
ORIGIN = Token.ORIGIN
SCALE = Token.SCALE
ROT = Token.ROT
COLOR = Token.COLOR
BACKGROUND = Token.BACKGROUND
IS = Token.IS
FOR = Token.FOR
FROM = Token.FROM
TO = Token.TO
STEP = Token.STEP
DRAW = Token.DRAW
SEMICOLON = Token.SEMICOLON
COMMA = Token.COMMA
L_BRACKET = Token.L_BRACKET
R_BRACKET = Token.R_BRACKET
PLUS = Token.PLUS
MINUS = Token.MINUS
MUL = Token.MUL
DIV = Token.DIV
POWER = Token.POWER
CONST_ID = Token.CONST_ID
T = Token.T
NUM = Token.NUM
FUNC = Token.FUNC
NONE = 0
| 24.634146 | 108 | 0.657921 |
742a4278bb7f1dceb958050491d1dc68471f9ec9
| 607 |
py
|
Python
|
website-addons-14.0/website_login_background/__manifest__.py
|
Reathline/DOD_PODCAST
|
ffadd4bd11f268d9983668b87348f29dd2f4a6a5
|
[
"MIT"
] | null | null | null |
website-addons-14.0/website_login_background/__manifest__.py
|
Reathline/DOD_PODCAST
|
ffadd4bd11f268d9983668b87348f29dd2f4a6a5
|
[
"MIT"
] | null | null | null |
website-addons-14.0/website_login_background/__manifest__.py
|
Reathline/DOD_PODCAST
|
ffadd4bd11f268d9983668b87348f29dd2f4a6a5
|
[
"MIT"
] | null | null | null |
{
"name": """Website login background""",
"summary": """Random background image to your taste at the website login page""",
"category": "Website",
"images": ["images/5.png"],
"version": "14.0.1.0.3",
"author": "IT-Projects LLC",
"support": "[email protected]",
"website": "https://twitter.com/OdooFree",
"license": "Other OSI approved licence", # MIT
"depends": ["web_login_background", "website"],
"external_dependencies": {"python": [], "bin": []},
"data": ["templates.xml"],
"demo": ["demo/demo.xml"],
"installable": True,
"auto_install": True,
}
| 33.722222 | 85 | 0.586491 |
77e9ef301e9610123057b8002ee9e16a64741013
| 550 |
py
|
Python
|
Algorithms/Warmup/Compare the Triplets.py
|
vinayvinu500/Hackerrank
|
e185ae9d3c7dc5cd661761142e436f5df6a3f0f1
|
[
"MIT"
] | null | null | null |
Algorithms/Warmup/Compare the Triplets.py
|
vinayvinu500/Hackerrank
|
e185ae9d3c7dc5cd661761142e436f5df6a3f0f1
|
[
"MIT"
] | null | null | null |
Algorithms/Warmup/Compare the Triplets.py
|
vinayvinu500/Hackerrank
|
e185ae9d3c7dc5cd661761142e436f5df6a3f0f1
|
[
"MIT"
] | null | null | null |
# https://www.hackerrank.com/challenges/compare-the-triplets/problem?h_r=internal-search
A = input().split()
B = input().split()
def compare(a, b):
alice = 0
bob = 0
x = len(a)
for i in range(x):
if int(a[i]) > int(b[i]):
alice += 1
elif int(a[i]) < int(b[i]):
bob += 1
elif a[i] == b[i]:
alice += 0
bob += 0
pass
return [alice, bob]
total = compare(A, B)
print(total)
"""
Examples
17 28 30
99 16 8
output => 2, 1
5 6 7
3 6 10
output => 1, 1
"""
| 16.666667 | 88 | 0.494545 |
3b682ece4666002ac6b65489ef29b6afa0a80452
| 1,249 |
py
|
Python
|
official/cv/srcnn/src/srcnn.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 77 |
2021-10-15T08:32:37.000Z
|
2022-03-30T13:09:11.000Z
|
official/cv/srcnn/src/srcnn.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 3 |
2021-10-30T14:44:57.000Z
|
2022-02-14T06:57:57.000Z
|
official/cv/srcnn/src/srcnn.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 24 |
2021-10-15T08:32:45.000Z
|
2022-03-24T18:45:20.000Z
|
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 mindspore.nn as nn
class SRCNN(nn.Cell):
def __init__(self, num_channels=1):
super(SRCNN, self).__init__()
self.conv1 = nn.Conv2d(num_channels, 64, kernel_size=9, padding=9 // 2, pad_mode='pad')
self.conv2 = nn.Conv2d(64, 32, kernel_size=5, padding=5 // 2, pad_mode='pad')
self.conv3 = nn.Conv2d(32, num_channels, kernel_size=5, padding=5 // 2, pad_mode='pad')
self.relu = nn.ReLU()
def construct(self, x):
x = self.relu(self.conv1(x))
x = self.relu(self.conv2(x))
x = self.conv3(x)
return x
| 40.290323 | 95 | 0.644516 |
79483a18ade49b9e3a6aee2e2162b3123a115e42
| 536 |
py
|
Python
|
python/en/_numpy/1.Quickstart_tutorial-1.The_Basics-1.An_eample.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
python/en/_numpy/1.Quickstart_tutorial-1.The_Basics-1.An_eample.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
python/en/_numpy/1.Quickstart_tutorial-1.The_Basics-1.An_eample.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
# 1.Quickstart_tutorial-1.The_Basics-1.An_eample.py
#
# https://docs.scipy.org/doc/numpy/user/quickstart.html
# The Basics - An example
import numpy as np
a = np.arange(15).reshape(3,5)
#>>> a
#array([[ 0, 1, 2, 3, 4],
# [ 5, 6, 7, 8, 9],
# [10, 11, 12, 13, 14]])
print( a.shape )
#(3, 5)
print( a.ndim )
#2
print( a.dtype.name )
#int64
print( a.itemsize )
#8
print( a.size )
#15
print( type(a) )
#<class 'numpy.ndarray'>
b = np.array( [6,7,8] )
#array([6, 7, 8])
print( type(b) )
#<class 'numpy.ndarray'>
| 14.486486 | 55 | 0.576493 |
eb6710330cd4341750137e64a7f344d4f35e286e
| 402 |
py
|
Python
|
book/translation/por/book/website/scripts/clean.py
|
AndreaSanchezTapia/the-turing-way
|
fe3e1a8ad36f9086edb4f36ec8e398f253fd8e0f
|
[
"CC-BY-4.0"
] | 1 |
2021-11-09T20:43:06.000Z
|
2021-11-09T20:43:06.000Z
|
book/translation/por/book/website/scripts/clean.py
|
AndreaSanchezTapia/the-turing-way
|
fe3e1a8ad36f9086edb4f36ec8e398f253fd8e0f
|
[
"CC-BY-4.0"
] | null | null | null |
book/translation/por/book/website/scripts/clean.py
|
AndreaSanchezTapia/the-turing-way
|
fe3e1a8ad36f9086edb4f36ec8e398f253fd8e0f
|
[
"CC-BY-4.0"
] | 2 |
2021-12-21T17:35:45.000Z
|
2021-12-21T20:43:01.000Z
|
"""Um script auxiliar para "limpar" todos os seus arquivos markdown e HTML gerados."""
importação shutil como shutil
do caminho de importação do pathlib
path_root = Caminho(__file__).parent.parent
caminhos = [path_root.joinpath('_site'),
path_root.joinpath('_build')]
para o caminho nos caminhos:
print(f'Removendo {path}...')
sh.rmtree(caminho, ignore_errors=True)
print('Feito!')
| 28.714286 | 86 | 0.731343 |
d685a61f85861f34b540d6df1cf6b6654c800d50
| 4,559 |
py
|
Python
|
LDA/LDA_notebook_example.py
|
Wurmloch/TopicModeling
|
e8c0b933a0e7dc9e668f6ad3ab371c7f2b84becc
|
[
"MIT"
] | 1 |
2018-05-14T10:02:54.000Z
|
2018-05-14T10:02:54.000Z
|
LDA/LDA_notebook_example.py
|
Wurmloch/TopicModeling
|
e8c0b933a0e7dc9e668f6ad3ab371c7f2b84becc
|
[
"MIT"
] | null | null | null |
LDA/LDA_notebook_example.py
|
Wurmloch/TopicModeling
|
e8c0b933a0e7dc9e668f6ad3ab371c7f2b84becc
|
[
"MIT"
] | null | null | null |
# coding: utf-8
# # Latent Dirichlet Allocation LDA
# #### Wikifetcher
# Raw Text von Wikipedia mittels Suchbegriffen
# #### LDAbuilder
# Ausführen der LDA mit der gegebenen Dokumentliste (Rohtext-Liste von Wikifetcher)
# ## Ausführung
# Zusätzlich für jeden Ausführungsblock wird die Ausführungszeit gemessen.
# ### Konfiguration
# - Wir benötigen Zugriff auf Wikipedia für den Rohtext
# - Natural Language Toolkit NLTK für die Tokenisierung und Stemming
# - Stop_words, um nichtssagende Wörter zu entfernen
# - Gensim für die Implementierung der Latent Dirichlet Allocation LDA
# In[1]:
import wikipedia
import time
from nltk.tokenize import RegexpTokenizer
from stop_words import get_stop_words
from nltk.stem.porter import PorterStemmer
import re
import warnings
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
from gensim import corpora, models
start = time.time()
sentence_pat = re.compile(r'([A-Z][^\.!?]*[\.!?])', re.M)
tokenizer = RegexpTokenizer(r'\w+')
# Erzeuge englische stop words Liste
en_stop = get_stop_words('en')
# Erzeuge p_stemmer der Klasse PorterStemmer
p_stemmer = PorterStemmer()
doc_list = []
wikipedia.set_lang('en')
end = time.time()
print('Ausführungszeit: %f' %(end-start) + ' s')
# ### Wikipedia Content
# Mittels Suchbegriffen holen wir den Rohen Inhalt aus Wikipedia.
# Danach wird der Inhalt in Sätze getrennt, welche zur Dokumentliste hinzugefügt werden.
# In[2]:
def get_page(name):
first_found = wikipedia.search(name)[0]
try:
return(wikipedia.page(first_found).content)
except wikipedia.exceptions.DisambiguationError as e:
return(wikipedia.page(e.options[0]).content)
start = time.time()
search_terms = ['Nature', 'Volcano', 'Ocean', 'Landscape', 'Earth', 'Animals']
separator = '== References =='
for term in search_terms:
full_content = get_page(term).split(separator, 1)[0]
# sentence_list = sentence_pat.findall(full_content)
#for sentence in sentence_list:
doc_list.append(full_content)
print(full_content[0:1000] + '...')
print('---')
end = time.time()
print('Ausführungszeit: %f' %(end-start) + ' s')
# ### Vorverarbeitung
# Der Text wird nun Tokenisiert, gestemt, nutzlose Wörter werden entfernt
# In[3]:
num_topics = 5
num_words_per_topic = 20
texts = []
# In[4]:
import pandas as pd
start = time.time()
for doc in doc_list:
raw = doc.lower()
# Erzeuge tokens
tokens = tokenizer.tokenize(raw)
# Entferne unnütze Information
stopped_tokens = [i for i in tokens if not i in en_stop]
# Stemme tokens - Entfernung von Duplikaten und Transformation zu Grundform (Optional)
# stemmed_tokens = [p_stemmer.stem(i) for i in stopped_tokens]
texts.append(stopped_tokens)
output_preprocessed = pd.Series(texts)
print(output_preprocessed)
end = time.time()
print('Ausführungszeit: %f' %(end-start) + ' s')
# ### Dictionary und Vektoren
# In diesem Abschnitt wird nun der Bag-of-words Korpus erstellt. Die Vektoren werden später für das LDA-Modell benötigt
# In[5]:
start = time.time()
# Erzeuge ein dictionary
dictionary = corpora.Dictionary(texts)
# Konvertiere dictionary in Bag-of-Words
# corpus ist eine Liste von Vektoren - Jeder Dokument-Vektor ist eine Serie von Tupeln
corpus = [dictionary.doc2bow(text) for text in texts]
output_vectors = pd.Series(corpus)
print(dictionary)
print('---')
print(output_vectors)
end = time.time()
print('Ausführungszeit: %f' %(end-start) + ' s')
# ### LDA-Modell
# Schließlich kann das LDA-Modell angewandt werden. Die Übergabeparameter dafür sind die Liste der Vektoren, die Anzahl der Themen, das Dictionary, sowie die Aktualisierungsrate.
# In der Trainingsphase sollte eine höhere Aktualisierungsrate >= 20 gewählt werden.
# In[6]:
start = time.time()
# Wende LDA-Modell an
ldamodel = models.ldamodel.LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=50)
lda = ldamodel.print_topics(num_topics=num_topics, num_words=num_words_per_topic)
for topic in lda:
for entry in topic:
print(entry)
print('---')
end = time.time()
print('Ausführungszeit: %f' %(end-start) + ' s')
# ## Visualisierung
# Mit pyLDAvis
# In[7]:
import pyLDAvis.gensim
# dprecation warnings bei pyLDAvis vermeiden
warnings.simplefilter("ignore", DeprecationWarning)
start = time.time()
pyLDAvis.enable_notebook()
vis_data = pyLDAvis.gensim.prepare(ldamodel, corpus, dictionary)
end = time.time()
print('Ausführungszeit: %f' %(end-start) + ' s')
# In[8]:
pyLDAvis.display(vis_data)
| 24.643243 | 178 | 0.726914 |
3013e789d8e350f15fae33ec3a3383b4a6026453
| 2,875 |
py
|
Python
|
Crashkurs Python/15_Klassen.py
|
slogslog/Kurzgeschichten-in-CSharp
|
3918c4174220e558cdeeada0edac941811418b93
|
[
"Unlicense"
] | 2 |
2019-03-15T20:48:34.000Z
|
2019-04-22T15:24:09.000Z
|
Crashkurs Python/15_Klassen.py
|
slogslog/Coding-Kurzgeschichten
|
9b08237038147c6c348d4cf4c69567178e07dd1d
|
[
"Unlicense"
] | null | null | null |
Crashkurs Python/15_Klassen.py
|
slogslog/Coding-Kurzgeschichten
|
9b08237038147c6c348d4cf4c69567178e07dd1d
|
[
"Unlicense"
] | null | null | null |
# Übungsaufgabe: Auto mit Booster in Python
class Booster:
powerOn = False # erzeugt und initialisiert eine Instanzvariable
def __init__(self, stufe): # Konstruktor
self.stufe = stufe # self ist 'this' in Java/C# -> erzeugt eine Instanzvariable
def getPower(self): # Methoden ohne self sind static
return self.powerOn
def setPower(self, powerOn):
self.powerOn = powerOn
def getStufe(self):
return self.stufe
def setStufe(self, stufe):
self.stufe = stufe
def __str__(self): # toString() in Java/ToString() in C#
return "Power OFF" if not self.powerOn else \
"Power ON - Stufe {0}".format(self.stufe)
class Auto:
def __init__(self, marke, vmax):
self.marke = marke
self.vmax = vmax
self.booster = None # ist 'null' in Java/C#
def getBooster(self):
return self.booster
def setBooster(self, booster):
self.booster = booster
def getVMax(self):
v = self.vmax
if self.booster is not None: # None = null
if self.booster.getPower():
acc = { 1: 15, 2: 30 } # in percent
percent = acc.get(self.booster.getStufe(), 0)
v *= 1+percent/100
return v
def getFahrzeit(self, wegstrecke):
return wegstrecke/self.getVMax()
def __str__(self):
text = "Kein Booster" if self.booster is None else self.booster
return "{0}: vmax = {1} Booster: {2}".\
format(self.marke, self.getVMax(), text)
# 1. Erstelle einen Booster mit Stufe 1
booster = Booster(1) # Erstellen einer Instanz/eines Objekts
# 2. Erstelle das Auto Ferrari SP3JC mit Höchstgeschwindigkeit 320 km/h
ferrari = Auto('Ferrari SP3JC', 320)
# 3. Erstelle das Auto BMW Z1 mit Höchstgeschwindigkeit 260 km/h
bmw = Auto('BMW Z1', 260)
# 4. Führe die 400 km-Fahrt mit dem Ferrari SP3JC aus und gibt die Fahrzeit aus
# Gib den Ferrari auf der Console aus.
tferrari = ferrari.getFahrzeit(400)
print('Der Ferrari benötigt {0:.3f} Stunden.'.format(tferrari))
print(ferrari)
tbmw = []
# Führe die Fahrt mit dem BMW Z1 aus.
# Gib nach jedem Streckenabschnitt die Statuswerte des Fahrzeugs aus.
# 1. Strecke: 20 km - ohne Booster
tbmw.append(bmw.getFahrzeit(20))
print(bmw)
# 2. Strecke: 140 km - mit eingeschaltenen Booster auf Stufe 1
bmw.setBooster(booster)
booster.setPower(True)
booster.setStufe(1)
tbmw.append(bmw.getFahrzeit(140))
print(bmw)
# 3. Strecke: 180 km - mit eingeschaltenen Booster auf Stufe 2
booster.setStufe(2)
tbmw.append(bmw.getFahrzeit(180))
print(bmw)
# 4. Strecke: 60 km - mit abgeschaltetem Booster
booster.setPower(False)
tbmw.append(bmw.getFahrzeit(60))
print(bmw)
for t in tbmw:
print("Fahrzeit {0:.3f}".format(t))
print('Der BMW benötigt {0:.3f} Stunden.'.format(sum(tbmw)))
| 28.75 | 92 | 0.654261 |
001cb3e6ae1e004358513b4e6dc15fc1d9d2807e
| 1,957 |
py
|
Python
|
src/main/main/exceptions.py
|
Nouvellie/django-tflite
|
1d08fdc8a2ec58886d7d2b8d40e7b3598613caca
|
[
"MIT"
] | 2 |
2021-08-23T21:56:07.000Z
|
2022-01-20T13:52:19.000Z
|
src/main/main/exceptions.py
|
Nouvellie/django-tflite
|
1d08fdc8a2ec58886d7d2b8d40e7b3598613caca
|
[
"MIT"
] | null | null | null |
src/main/main/exceptions.py
|
Nouvellie/django-tflite
|
1d08fdc8a2ec58886d7d2b8d40e7b3598613caca
|
[
"MIT"
] | null | null | null |
from django.http import (
JsonResponse,
response,
)
from rest_framework.authentication import TokenAuthentication
from rest_framework.exceptions import APIException
from rest_framework import status
from typing import (
Generic,
TypeVar,
)
SELFCLASS = TypeVar('SELFCLASS')
DEFAULT_DETAIL = {"error": "An error has ocurred."}
DEFAULT_CODE = status.HTTP_400_BAD_REQUEST
class CustomError(APIException):
"""Custom exception for any type of error generated in the applications."""
def __new__(cls, detail: str = DEFAULT_DETAIL, code: status = DEFAULT_CODE, *args, **kwargs) -> Generic[SELFCLASS]:
return super(CustomError, cls).__new__(cls, *args, **kwargs)
def __init__(self, detail: dict = DEFAULT_DETAIL, code: status = DEFAULT_CODE) -> response:
self.detail = detail
self.status_code = code
class CustomTokenAuthentication(TokenAuthentication):
"""Exception is rewritten, for a custom error."""
def authenticate_credentials(self, key: str) -> tuple:
model = self.get_model()
try:
token = model.objects.select_related('user').get(key=key)
except model.DoesNotExist:
raise CustomError(
detail={'error': 'Invalid token.'}, code=401)
if not token.user.is_active:
raise CustomError(
detail={'error': 'This account has been deactivated by an administrator.'}, code=401)
return (token.user, token)
def http_404_not_found(request: any, exception: APIException) -> JsonResponse:
message = ("The endpoint is not found.")
response = JsonResponse(data={'error': message, 'status_code': 404})
response.status_code = 404
return response
def http_500_internal_server_error(request: any) -> JsonResponse:
message = ("An error ocurred, it's on us.")
response = JsonResponse(data={'error': message, 'status_code': 500})
response.status_code = 500
return response
| 34.333333 | 119 | 0.690342 |
4e398e7861d9b6eb98f8610acc894a67fe987e59
| 259 |
py
|
Python
|
Python/Courses/Crash-Course-on-Python.Google/week-2-Basic-Python-Syntax/08-Branching-with-if-Statements.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
Python/Courses/Crash-Course-on-Python.Google/week-2-Basic-Python-Syntax/08-Branching-with-if-Statements.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
Python/Courses/Crash-Course-on-Python.Google/week-2-Basic-Python-Syntax/08-Branching-with-if-Statements.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
def hint_username(username: str) -> bool:
if len(username) < 3:
return False
elif len(username) > 15:
return False
else:
return True
def is_even(number: int):
if number % 2 == 0:
return True
return False
| 17.266667 | 41 | 0.571429 |
9def106ffeb8eff87b70f1efbd79bb7f9294bfc2
| 3,324 |
py
|
Python
|
pyntcloud/utils/array.py
|
bernssolg/pyntcloud-master
|
84cf000b7a7f69a2c1b36f9624f05f65160bf992
|
[
"MIT"
] | 1,142 |
2016-10-10T08:55:30.000Z
|
2022-03-30T04:46:16.000Z
|
pyntcloud/utils/array.py
|
bernssolg/pyntcloud-master
|
84cf000b7a7f69a2c1b36f9624f05f65160bf992
|
[
"MIT"
] | 195 |
2016-10-10T08:30:37.000Z
|
2022-02-17T12:51:17.000Z
|
pyntcloud/utils/array.py
|
bernssolg/pyntcloud-master
|
84cf000b7a7f69a2c1b36f9624f05f65160bf992
|
[
"MIT"
] | 215 |
2017-02-28T00:50:29.000Z
|
2022-03-22T17:01:31.000Z
|
import numpy as np
def cartesian(arrays, out=None):
"""Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
2-D array of shape (M, len(arrays)) containing cartesian products
formed of input arrays.
Examples
--------
>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
[1, 4, 7],
[1, 5, 6],
[1, 5, 7],
[2, 4, 6],
[2, 4, 7],
[2, 5, 6],
[2, 5, 7],
[3, 4, 6],
[3, 4, 7],
[3, 5, 6],
[3, 5, 7]])
"""
arrays = [np.asarray(x) for x in arrays]
shape = (len(x) for x in arrays)
dtype = arrays[0].dtype
ix = np.indices(shape)
ix = ix.reshape(len(arrays), -1).T
if out is None:
out = np.empty_like(ix, dtype=dtype)
for n, arr in enumerate(arrays):
out[:, n] = arrays[n][ix[:, n]]
return out
def PCA(data, correlation=False, sort=True):
""" Applies Principal Component Analysis to the data
Parameters
----------
data: array
The array containing the data. The array must have NxM dimensions, where each
of the N rows represents a different individual record and each of the M columns
represents a different variable recorded for that individual record.
array([
[V11, ... , V1m],
...,
[Vn1, ... , Vnm]])
correlation(Optional) : bool
Set the type of matrix to be computed (see Notes):
If True compute the correlation matrix.
If False(Default) compute the covariance matrix.
sort(Optional) : bool
Set the order that the eigenvalues/vectors will have
If True(Default) they will be sorted (from higher value to less).
If False they won't.
Returns
-------
eigenvalues: (1,M) array
The eigenvalues of the corresponding matrix.
eigenvector: (M,M) array
The eigenvectors of the corresponding matrix.
Notes
-----
The correlation matrix is a better choice when there are different magnitudes
representing the M variables. Use covariance matrix in other cases.
"""
mean = np.mean(data, axis=0)
data_adjust = data - mean
#: the data is transposed due to np.cov/corrcoef syntax
if correlation:
matrix = np.corrcoef(data_adjust.T)
else:
matrix = np.cov(data_adjust.T)
eigenvalues, eigenvectors = np.linalg.eig(matrix)
if sort:
#: sort eigenvalues and eigenvectors
sort = eigenvalues.argsort()[::-1]
eigenvalues = eigenvalues[sort]
eigenvectors = eigenvectors[:, sort]
return eigenvalues, eigenvectors
def point_in_array_2D(point, array_2D):
point = np.array(point, dtype=array_2D.dtype)
for other_point in array_2D:
if np.all(point == other_point):
return True
def cov3D(k_neighbors):
""" (N,K,3)
"""
diffs = k_neighbors - k_neighbors.mean(1, keepdims=True)
return np.einsum('ijk,ijl->ikl', diffs, diffs) / k_neighbors.shape[1]
| 26.380952 | 88 | 0.573406 |
c9dc21179d0d444d32b461996eff7c31632ea278
| 636 |
py
|
Python
|
src/onegov/agency/forms/__init__.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
src/onegov/agency/forms/__init__.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
src/onegov/agency/forms/__init__.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
from onegov.agency.forms.agency import ExtendedAgencyForm
from onegov.agency.forms.agency import MoveAgencyForm
from onegov.agency.forms.membership import MembershipForm
from onegov.agency.forms.mutation import AgencyMutationForm
from onegov.agency.forms.mutation import ApplyMutationForm
from onegov.agency.forms.mutation import PersonMutationForm
from onegov.agency.forms.user_group import UserGroupForm
__all__ = (
'AgencyMutationForm',
'ApplyMutationForm',
'ExtendedAgencyForm',
'ExtendedPersonForm',
'MembershipForm',
'MoveAgencyForm',
'MutationForm',
'PersonMutationForm',
'UserGroupForm',
)
| 30.285714 | 59 | 0.795597 |
4ec330620040a5e122a8ffc3010495618f3d8492
| 1,487 |
py
|
Python
|
Python/Buch_ATBS/Teil_2/Kapitel_13_Arbeiten_mit_Word_und_PDF_Dokumenten/02_pdf_zusammen_verbinden_und_seitenrotation/02_pdf_zusammen_verbinden_und_seitenrotation.py
|
Apop85/Scripts
|
e71e1c18539e67543e3509c424c7f2d6528da654
|
[
"MIT"
] | null | null | null |
Python/Buch_ATBS/Teil_2/Kapitel_13_Arbeiten_mit_Word_und_PDF_Dokumenten/02_pdf_zusammen_verbinden_und_seitenrotation/02_pdf_zusammen_verbinden_und_seitenrotation.py
|
Apop85/Scripts
|
e71e1c18539e67543e3509c424c7f2d6528da654
|
[
"MIT"
] | 6 |
2020-12-24T15:15:09.000Z
|
2022-01-13T01:58:35.000Z
|
Python/Buch_ATBS/Teil_2/Kapitel_13_Arbeiten_mit_Word_und_PDF_Dokumenten/02_pdf_zusammen_verbinden_und_seitenrotation/02_pdf_zusammen_verbinden_und_seitenrotation.py
|
Apop85/Scripts
|
1d8dad316c55e1f1343526eac9e4b3d0909e4873
|
[
"MIT"
] | null | null | null |
# 02_pdf_zusammen_verbinden.py
# In diesem Beispiel geht es Darum zwei PDF's miteinander zu verschmelzen
import os, PyPDF2
os.chdir(os.path.dirname(__file__))
source_file_1='.\\meetingminutes.pdf'
source_file_2='.\\meetingminutes2.pdf'
output_file='.\\meetingminutes_merged.pdf'
output_file_2='.\\meetingminutes_rotated.pdf'
if os.path.exists(output_file):
os.remove(output_file)
# Bereite Files zum Lesen vor und lese Seitenzahlen aus.
file_1_open=open(source_file_1, 'rb')
file_2_open=open(source_file_2, 'rb')
file_1_content=PyPDF2.PdfFileReader(file_1_open)
file_2_content=PyPDF2.PdfFileReader(file_2_open)
pages_file_1_length=file_1_content.numPages
pages_file_2_length=file_2_content.numPages
# Aktiviere PfdFileWriter()
pdf_writer=PyPDF2.PdfFileWriter()
pdf_writer_2=PyPDF2.PdfFileWriter()
# Schreibe Inhalt von PDF 1 in Zwischenspeicher
for page in range(pages_file_1_length):
page_content=file_1_content.getPage(page)
pdf_writer.addPage(page_content)
# Drehe Seite um 90°
page_content.rotateClockwise(180)
pdf_writer_2.addPage(page_content)
# Schreibe Inhalt von PDF 2 in Zwischenspeicher
for page in range(pages_file_2_length):
page_content=file_2_content.getPage(page)
pdf_writer.addPage(page_content)
# Schreibe neues PDF
output_file_open=open(output_file, 'wb')
pdf_writer.write(output_file_open)
output_file_open.close()
output_file_2_open=open(output_file_2, 'wb')
pdf_writer_2.write(output_file_2_open)
output_file_2_open.close()
| 31.638298 | 73 | 0.814391 |
1129e8fa7316d1f0da2a3d417d7d5488c380b97d
| 549 |
py
|
Python
|
python/en/archive/dropbox/python-python_speech_features/test_python_speech_features.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
python/en/archive/dropbox/python-python_speech_features/test_python_speech_features.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
python/en/archive/dropbox/python-python_speech_features/test_python_speech_features.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
# test_python_speech_features.py
from python_speech_features import mfcc
from python_speech_features import delta
from python_speech_features import logfbank
import scipy.io.wavfile as wav
( rate, sig ) = wav.read( 'english.wav' )
mfcc_feat = mfcc( sig, rate )
d_mfcc_feat = delta( mfcc_feat, 2)
fbank_feat = logfbank( sig, rate )
#print( fbank_feat[1:3,:] )
print('mfcc_feat')
print( mfcc_feat[1:2,:] )
print('d_mfcc_feat')
print( d_mfcc_feat[1:2,:] )
print('fbank_feat')
print( fbank_feat[1:2,:] )
| 24.954545 | 44 | 0.701275 |
11613d7d1f347f8409051bc2b8ea2b1322ec4d30
| 2,078 |
py
|
Python
|
deprecated/benchmark/ps/ctr/network_conf.py
|
hutuxian/FleetX
|
843c7aa33f5a14680becf058a3aaf0327eefafd4
|
[
"Apache-2.0"
] | 170 |
2020-08-12T12:07:01.000Z
|
2022-03-07T02:38:26.000Z
|
deprecated/benchmark/ps/ctr/network_conf.py
|
hutuxian/FleetX
|
843c7aa33f5a14680becf058a3aaf0327eefafd4
|
[
"Apache-2.0"
] | 195 |
2020-08-13T03:22:15.000Z
|
2022-03-30T07:40:25.000Z
|
deprecated/benchmark/ps/ctr/network_conf.py
|
hutuxian/FleetX
|
843c7aa33f5a14680becf058a3aaf0327eefafd4
|
[
"Apache-2.0"
] | 67 |
2020-08-14T02:07:46.000Z
|
2022-03-28T10:05:33.000Z
|
import paddle.fluid as fluid
import math
dense_feature_dim = 13
def ctr_dnn_model_dataset(dense_input, sparse_inputs, label,
embedding_size, sparse_feature_dim):
def embedding_layer(input):
return fluid.layers.embedding(
input=input,
is_sparse=True,
# you need to patch https://github.com/PaddlePaddle/Paddle/pull/14190
# if you want to set is_distributed to True
is_distributed=False,
size=[sparse_feature_dim, embedding_size],
param_attr=fluid.ParamAttr(name="SparseFeatFactors",
initializer=fluid.initializer.Uniform()))
sparse_embed_seq = list(map(embedding_layer, sparse_inputs))
concated = fluid.layers.concat(sparse_embed_seq + [dense_input], axis=1)
fc1 = fluid.layers.fc(input=concated, size=400, act='relu',
param_attr=fluid.ParamAttr(initializer=fluid.initializer.Normal(
scale=1 / math.sqrt(concated.shape[1]))))
fc2 = fluid.layers.fc(input=fc1, size=400, act='relu',
param_attr=fluid.ParamAttr(initializer=fluid.initializer.Normal(
scale=1 / math.sqrt(fc1.shape[1]))))
fc3 = fluid.layers.fc(input=fc2, size=400, act='relu',
param_attr=fluid.ParamAttr(initializer=fluid.initializer.Normal(
scale=1 / math.sqrt(fc2.shape[1]))))
predict = fluid.layers.fc(input=fc3, size=2, act='softmax',
param_attr=fluid.ParamAttr(initializer=fluid.initializer.Normal(
scale=1 / math.sqrt(fc3.shape[1]))))
cost = fluid.layers.cross_entropy(input=predict, label=label)
avg_cost = fluid.layers.reduce_sum(cost)
accuracy = fluid.layers.accuracy(input=predict, label=label)
auc_var, batch_auc_var, auc_states = \
fluid.layers.auc(input=predict, label=label, num_thresholds=2 ** 12, slide_steps=20)
return avg_cost, auc_var, batch_auc_var
| 51.95 | 94 | 0.620789 |
fed1dead0c7d17ab5895340b0d529a8c229b99e9
| 9,841 |
py
|
Python
|
research/cvtmodel/vgg/src/vgg19_bn.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 77 |
2021-10-15T08:32:37.000Z
|
2022-03-30T13:09:11.000Z
|
research/cvtmodel/vgg/src/vgg19_bn.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 3 |
2021-10-30T14:44:57.000Z
|
2022-02-14T06:57:57.000Z
|
research/cvtmodel/vgg/src/vgg19_bn.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 24 |
2021-10-15T08:32:45.000Z
|
2022-03-24T18:45:20.000Z
|
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 mindspore import nn
class Module3(nn.Cell):
def __init__(self, conv2d_0_in_channels, conv2d_0_out_channels):
super(Module3, self).__init__()
self.conv2d_0 = nn.Conv2d(in_channels=conv2d_0_in_channels,
out_channels=conv2d_0_out_channels,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1, 1, 1),
pad_mode="pad",
dilation=(1, 1),
group=1,
has_bias=True)
self.relu_1 = nn.ReLU()
def construct(self, x):
opt_conv2d_0 = self.conv2d_0(x)
opt_relu_1 = self.relu_1(opt_conv2d_0)
return opt_relu_1
class Module5(nn.Cell):
def __init__(self, module3_0_conv2d_0_in_channels, module3_0_conv2d_0_out_channels):
super(Module5, self).__init__()
self.module3_0 = Module3(conv2d_0_in_channels=module3_0_conv2d_0_in_channels,
conv2d_0_out_channels=module3_0_conv2d_0_out_channels)
self.pad_maxpool2d_0 = nn.Pad(paddings=((0, 0), (0, 0), (0, 0), (0, 0)))
self.maxpool2d_0 = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
def construct(self, x):
module3_0_opt = self.module3_0(x)
opt_maxpool2d_0 = self.pad_maxpool2d_0(module3_0_opt)
opt_maxpool2d_0 = self.maxpool2d_0(opt_maxpool2d_0)
return opt_maxpool2d_0
class Module2(nn.Cell):
def __init__(self, conv2d_1_in_channels, conv2d_1_out_channels, conv2d_3_in_channels, conv2d_3_out_channels,
conv2d_5_in_channels, conv2d_5_out_channels):
super(Module2, self).__init__()
self.pad_maxpool2d_0 = nn.Pad(paddings=((0, 0), (0, 0), (0, 0), (0, 0)))
self.maxpool2d_0 = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
self.conv2d_1 = nn.Conv2d(in_channels=conv2d_1_in_channels,
out_channels=conv2d_1_out_channels,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1, 1, 1),
pad_mode="pad",
dilation=(1, 1),
group=1,
has_bias=True)
self.relu_2 = nn.ReLU()
self.conv2d_3 = nn.Conv2d(in_channels=conv2d_3_in_channels,
out_channels=conv2d_3_out_channels,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1, 1, 1),
pad_mode="pad",
dilation=(1, 1),
group=1,
has_bias=True)
self.relu_4 = nn.ReLU()
self.conv2d_5 = nn.Conv2d(in_channels=conv2d_5_in_channels,
out_channels=conv2d_5_out_channels,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1, 1, 1),
pad_mode="pad",
dilation=(1, 1),
group=1,
has_bias=True)
self.relu_6 = nn.ReLU()
def construct(self, x):
opt_maxpool2d_0 = self.pad_maxpool2d_0(x)
opt_maxpool2d_0 = self.maxpool2d_0(opt_maxpool2d_0)
opt_conv2d_1 = self.conv2d_1(opt_maxpool2d_0)
opt_relu_2 = self.relu_2(opt_conv2d_1)
opt_conv2d_3 = self.conv2d_3(opt_relu_2)
opt_relu_4 = self.relu_4(opt_conv2d_3)
opt_conv2d_5 = self.conv2d_5(opt_relu_4)
opt_relu_6 = self.relu_6(opt_conv2d_5)
return opt_relu_6
class Module8(nn.Cell):
def __init__(self, module3_0_conv2d_0_in_channels, module3_0_conv2d_0_out_channels, module2_0_conv2d_1_in_channels,
module2_0_conv2d_1_out_channels, module2_0_conv2d_3_in_channels, module2_0_conv2d_3_out_channels,
module2_0_conv2d_5_in_channels, module2_0_conv2d_5_out_channels):
super(Module8, self).__init__()
self.module3_0 = Module3(conv2d_0_in_channels=module3_0_conv2d_0_in_channels,
conv2d_0_out_channels=module3_0_conv2d_0_out_channels)
self.module2_0 = Module2(conv2d_1_in_channels=module2_0_conv2d_1_in_channels,
conv2d_1_out_channels=module2_0_conv2d_1_out_channels,
conv2d_3_in_channels=module2_0_conv2d_3_in_channels,
conv2d_3_out_channels=module2_0_conv2d_3_out_channels,
conv2d_5_in_channels=module2_0_conv2d_5_in_channels,
conv2d_5_out_channels=module2_0_conv2d_5_out_channels)
def construct(self, x):
module3_0_opt = self.module3_0(x)
module2_0_opt = self.module2_0(module3_0_opt)
return module2_0_opt
class MindSporeModel(nn.Cell):
def __init__(self):
super(MindSporeModel, self).__init__()
self.conv2d_0 = nn.Conv2d(in_channels=3,
out_channels=64,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1, 1, 1),
pad_mode="pad",
dilation=(1, 1),
group=1,
has_bias=True)
self.relu_1 = nn.ReLU()
self.module5_0 = Module5(module3_0_conv2d_0_in_channels=64, module3_0_conv2d_0_out_channels=64)
self.module3_0 = Module3(conv2d_0_in_channels=64, conv2d_0_out_channels=128)
self.module8_0 = Module8(module3_0_conv2d_0_in_channels=128,
module3_0_conv2d_0_out_channels=128,
module2_0_conv2d_1_in_channels=128,
module2_0_conv2d_1_out_channels=256,
module2_0_conv2d_3_in_channels=256,
module2_0_conv2d_3_out_channels=256,
module2_0_conv2d_5_in_channels=256,
module2_0_conv2d_5_out_channels=256)
self.module8_1 = Module8(module3_0_conv2d_0_in_channels=256,
module3_0_conv2d_0_out_channels=256,
module2_0_conv2d_1_in_channels=256,
module2_0_conv2d_1_out_channels=512,
module2_0_conv2d_3_in_channels=512,
module2_0_conv2d_3_out_channels=512,
module2_0_conv2d_5_in_channels=512,
module2_0_conv2d_5_out_channels=512)
self.module8_2 = Module8(module3_0_conv2d_0_in_channels=512,
module3_0_conv2d_0_out_channels=512,
module2_0_conv2d_1_in_channels=512,
module2_0_conv2d_1_out_channels=512,
module2_0_conv2d_3_in_channels=512,
module2_0_conv2d_3_out_channels=512,
module2_0_conv2d_5_in_channels=512,
module2_0_conv2d_5_out_channels=512)
self.module5_1 = Module5(module3_0_conv2d_0_in_channels=512, module3_0_conv2d_0_out_channels=512)
self.pad_avgpool2d_37 = nn.Pad(paddings=((0, 0), (0, 0), (0, 0), (0, 0)))
self.avgpool2d_37 = nn.AvgPool2d(kernel_size=(1, 1), stride=(1, 1))
self.flatten_38 = nn.Flatten()
self.dense_39 = nn.Dense(in_channels=25088, out_channels=4096, has_bias=True)
self.relu_40 = nn.ReLU()
self.dense_41 = nn.Dense(in_channels=4096, out_channels=4096, has_bias=True)
self.relu_42 = nn.ReLU()
self.dense_43 = nn.Dense(in_channels=4096, out_channels=1000, has_bias=True)
def construct(self, input_1):
opt_conv2d_0 = self.conv2d_0(input_1)
opt_relu_1 = self.relu_1(opt_conv2d_0)
module5_0_opt = self.module5_0(opt_relu_1)
module3_0_opt = self.module3_0(module5_0_opt)
module8_0_opt = self.module8_0(module3_0_opt)
module8_1_opt = self.module8_1(module8_0_opt)
module8_2_opt = self.module8_2(module8_1_opt)
module5_1_opt = self.module5_1(module8_2_opt)
opt_avgpool2d_37 = self.pad_avgpool2d_37(module5_1_opt)
opt_avgpool2d_37 = self.avgpool2d_37(opt_avgpool2d_37)
opt_flatten_38 = self.flatten_38(opt_avgpool2d_37)
opt_dense_39 = self.dense_39(opt_flatten_38)
opt_relu_40 = self.relu_40(opt_dense_39)
opt_dense_41 = self.dense_41(opt_relu_40)
opt_relu_42 = self.relu_42(opt_dense_41)
opt_dense_43 = self.dense_43(opt_relu_42)
return opt_dense_43
| 51.794737 | 119 | 0.564374 |
3a74fd2b881927d6d0c7fa67cc96cf2a465c88ca
| 93 |
py
|
Python
|
year_3/numanalysis_2/lab23/djapp/integrals/apps.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | null | null | null |
year_3/numanalysis_2/lab23/djapp/integrals/apps.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | 21 |
2020-03-24T16:26:04.000Z
|
2022-02-18T15:56:16.000Z
|
year_3/numanalysis_2/lab23/djapp/integrals/apps.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | null | null | null |
from django.apps import AppConfig
class IntegralsConfig(AppConfig):
name = 'integrals'
| 15.5 | 33 | 0.763441 |
6c07ec7595443293ec46761c1ea10a43bebc964e
| 968 |
py
|
Python
|
BIZa/2014/Zyabko_A_A/Task_9_45.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
BIZa/2014/Zyabko_A_A/Task_9_45.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
BIZa/2014/Zyabko_A_A/Task_9_45.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
#Задача 9
#Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен попробовать отгадать слово.
# Зябко Антон
#21.05.2016
import random
WORDS=("питон","угадайка","простая","сложная","ответ","подстаканик")
word=random.choice(WORDS)
live=5
letter=""
wordz=""
(numbers)=len(word)
print("Я загадал случайное слово. Попробуй его отгадать. В этом слове",str(numbers)," букв.) У тебя будет 5 попыток угадать буквы. ПОЕХАЛИ!")
while live>0:
letter=input("Введите букву: ")
if letter in list(word):
print("да")
live=live-1
else:
print("нет")
live=live-1
if live==0:
wordz=input("Теперь введите слово: ")
if wordz==word:
print=("Поздравляю, вы отгадали")
else:
print("К сожалению, вы ошиблись")
input("Нажмите Enter для выхода.")
| 33.37931 | 309 | 0.727273 |
6c14e30dc5a97bddb46d87c5b01b3e8db4734ace
| 2,407 |
py
|
Python
|
Cat/Cat/urls.py
|
qq453388937/drf
|
63ef7c5f89cf8f597fd09828f8ce94ce809ce287
|
[
"MIT"
] | null | null | null |
Cat/Cat/urls.py
|
qq453388937/drf
|
63ef7c5f89cf8f597fd09828f8ce94ce809ce287
|
[
"MIT"
] | null | null | null |
Cat/Cat/urls.py
|
qq453388937/drf
|
63ef7c5f89cf8f597fd09828f8ce94ce809ce287
|
[
"MIT"
] | null | null | null |
# -*- coding:utf-8 -*-
"""Cat URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.contrib import admin
# from drf_project.views import GoodListView
from django.conf.urls import include, url
# 文档生成需要的命名空间
from rest_framework.documentation import include_docs_urls
from drf_project.views import *
# viewset 配置方法 基础版本不带 Route!!!!
good_list = GoodListViewSet.as_view({
'get': 'list', # get 请求绑定到list
# 'post': 'create' # post 请求绑定create
})
# Routers 引入
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
# ------------> r'^goodsroute/
router.register(r'goodsrt', GoodListViewSet, base_name='goods') # 自动默认 get -> list create -> post
router.register(r'goodscategory', GoodsCategoryViewSet, base_name='category')
urlpatterns = [
# url('', include(router.urls)),
url(r'^', include(router.urls), name='base'), # inlude router 注册的路由
url(r'^admin/', admin.site.urls),
url(r'^goods2/', GoodListViewPre2.as_view(), name='goods_list'),
url(r'^goods/', GoodListViewPre.as_view(), name='goods_list'),
# viewset 单纯版
url(r'^goodsvs/', good_list, name='goods_list'),
url(r'^docs/', include_docs_urls(title='ttt')), # 不可加$
url(r'^api-auth/', include('rest_framework.urls'))
]
# class base view 入手 Tutorial 3: Class-based Views
from rest_framework.authtoken import views
urlpatterns += [
url(r'^api-token-auth/', views.obtain_auth_token)
]
# jwt 认证模式 需要加的urls
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns += [
# url(r'^api-token-auth-mmd/', obtain_jwt_token),
url(r'^login/', obtain_jwt_token), # 看jwt原理
]
"""
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImNhdCIsImV4cCI6MTU0MzA3OTMxMiwiZW1haWwiOiI0NTMzODg5MzdAcXEuY29tIn0.GtyvqZkM4g_Y5M9SL4CVeX3ISJ7wVHNSm3ua0VCODRs"
}
"""
| 33.901408 | 195 | 0.714582 |
dd7e672fca09348d4a35306bb9a2c144a2bd85cd
| 511 |
py
|
Python
|
scripts/component_graph/server/util/logging.py
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | 3 |
2020-08-02T04:46:18.000Z
|
2020-08-07T10:10:53.000Z
|
scripts/component_graph/server/util/logging.py
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | null | null | null |
scripts/component_graph/server/util/logging.py
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | 1 |
2020-08-07T10:11:49.000Z
|
2020-08-07T10:11:49.000Z
|
#!/usr/bin/env python3
# Copyright 2019 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides default logging configuration for the project. """
import logging
def get_logger(name):
""" Returns a default logger configured a generic format """
logging.basicConfig(
level=logging.DEBUG, format='[%(levelname)s][%(name)s] - %(message)s')
logger = logging.getLogger(name)
return logger
| 31.9375 | 78 | 0.714286 |
b0b1a59689922a1227ddf195a549354688474e22
| 1,336 |
py
|
Python
|
Beginner/03. Python/pyLdapBind.py
|
ankita080208/Hacktoberfest
|
2be849e89285260e7b6672f42979943ad6bbec78
|
[
"MIT"
] | 1 |
2021-10-04T05:41:43.000Z
|
2021-10-04T05:41:43.000Z
|
Beginner/03. Python/pyLdapBind.py
|
ankita080208/Hacktoberfest
|
2be849e89285260e7b6672f42979943ad6bbec78
|
[
"MIT"
] | null | null | null |
Beginner/03. Python/pyLdapBind.py
|
ankita080208/Hacktoberfest
|
2be849e89285260e7b6672f42979943ad6bbec78
|
[
"MIT"
] | null | null | null |
import os
from pyad import pyad
import pyad.adquery
def prRed(msg):
print("\033[91m{}\033[00m" .format(msg))
def prGreen(msg):
print("\033[92m{}\033[00m" .format(msg))
def prYellow(msg):
print("\033[93m{}\033[00m" .format(msg))
def getGroups(userName):
''' Query for logged in user AD group membership '''
q = pyad.adquery.ADQuery()
q.execute_query(
attributes = ['memberof'],
where_clause = "samaccountname = '" + userName + "'",
base_dn = "DC=yourDomain,DC=local"
)
for r in q.get_results():
grps = r['memberof']
return grps
def checkGroupMembership(grps,adminGrps):
for adGrp in adminGrps:
if adGrp in grps:
prYellow(adGrp)
return True
def main():
''' [Update with AD approved groups] '''
adminGroups = [
"CN=Admin_Group1,OU=Administrators,DC=yourDomain,DC=local",
"CN=Admin_Group2,OU=Administrators,DC=yourDomain,DC=local",
"CN=Admin_Group3,OU=Administrators,DC=yourDomain,DC=local"
]
adGroups = getGroups(os.getlogin())
print("Checking Groups:")
print(*adminGroups,sep = "\n")
if checkGroupMembership(adGroups,adminGroups) is True:
prGreen("Access Granted")
else:
prRed("Access Denied")
main()
| 26.72 | 79 | 0.60479 |
b0b9c8d2b28bd680221f6d4817efe9b99d0b4e36
| 1,021 |
py
|
Python
|
index-renamer.py
|
wille430/index-renamer
|
95b925a26d7db2b4dc4365107368c7ea8e9b24f7
|
[
"MIT"
] | null | null | null |
index-renamer.py
|
wille430/index-renamer
|
95b925a26d7db2b4dc4365107368c7ea8e9b24f7
|
[
"MIT"
] | null | null | null |
index-renamer.py
|
wille430/index-renamer
|
95b925a26d7db2b4dc4365107368c7ea8e9b24f7
|
[
"MIT"
] | null | null | null |
import os
import re
import click
def get_abs_path(path: str) -> str:
if os.path.isabs(path):
return path
else:
return os.path.realpath(path)
def rename_in_dirs(dir_path: str):
# rename recursively in folders
for dir in os.listdir(dir_path):
full_dir = os.path.join(dir_path, dir)
if os.path.isfile(full_dir):
file_ext = re.search('(?<=index).*[\w+]', dir)
parent_dir = dir_path.split('\\')[-1]
if (file_ext):
# rename index to folder name
new_filename = f'{parent_dir}{file_ext[0]}'
print(f'Renaming {dir} to {new_filename}')
os.rename(full_dir, os.path.join(dir_path, new_filename))
else:
rename_in_dirs(full_dir)
@click.command()
@click.option('--dir', default=os.path.join(__file__), help='Which directory to recursively rename files named index')
def main(dir):
rename_in_dirs(dir)
print('DONE')
if (__name__ == '__main__'):
main()
| 29.171429 | 118 | 0.602351 |
bbbb5e8746774878e15b8d7ed5339916741149cd
| 1,537 |
py
|
Python
|
src/visuanalytics/tests/analytics/transform/types/test_transform_most_common.py
|
mxsph/Data-Analytics
|
c82ff54b78f50b6660d7640bfee96ea68bef598f
|
[
"MIT"
] | 3 |
2020-08-24T19:02:09.000Z
|
2021-05-27T20:22:41.000Z
|
src/visuanalytics/tests/analytics/transform/types/test_transform_most_common.py
|
mxsph/Data-Analytics
|
c82ff54b78f50b6660d7640bfee96ea68bef598f
|
[
"MIT"
] | 342 |
2020-08-13T10:24:23.000Z
|
2021-08-12T14:01:52.000Z
|
src/visuanalytics/tests/analytics/transform/types/test_transform_most_common.py
|
visuanalytics/visuanalytics
|
f9cce7bc9e3227568939648ddd1dd6df02eac752
|
[
"MIT"
] | 8 |
2020-09-01T07:11:18.000Z
|
2021-04-09T09:02:11.000Z
|
import unittest
from visuanalytics.tests.analytics.transform.transform_test_helper import prepare_test
class TestTransformMostCommon(unittest.TestCase):
def setUp(self):
self.data = {
"test": ["Canada", "Schweden", "Canada", "Schweden", "Canada", "Canada", "Schweden", "Canada"]
}
def test_most_common(self):
values = [
{
"type": "most_common",
"keys": ["_req|test"],
"new_keys": ["_req|test1"]
}
]
expected_data = {
"_req": {
"test": ["Canada", "Schweden", "Canada", "Schweden", "Canada", "Canada", "Schweden", "Canada"],
"test1": ["Canada", "Schweden"]
}
}
exp, out = prepare_test(values, self.data, expected_data)
self.assertDictEqual(exp, out, "most_common failed")
def test_most_common_include_count(self):
values = [
{
"type": "most_common",
"keys": ["_req|test"],
"new_keys": ["_req|test1"],
"include_count": True
}
]
expected_data = {
"_req": {
"test": ["Canada", "Schweden", "Canada", "Schweden", "Canada", "Canada", "Schweden", "Canada"],
"test1": [("Canada", 5), ("Schweden", 3)]
}
}
exp, out = prepare_test(values, self.data, expected_data)
self.assertDictEqual(exp, out, "most_common_include_count failed")
| 30.74 | 111 | 0.500976 |
b1f04c1327483626a64870b3f216f65924db7ac3
| 92 |
py
|
Python
|
2014/04/table-subminimum-wages/graphic_config.py
|
nprapps/graphics-archive
|
97b0ef326b46a959df930f5522d325e537f7a655
|
[
"FSFAP"
] | 14 |
2015-05-08T13:41:51.000Z
|
2021-02-24T12:34:55.000Z
|
2014/04/table-subminimum-wages/graphic_config.py
|
nprapps/graphics-archive
|
97b0ef326b46a959df930f5522d325e537f7a655
|
[
"FSFAP"
] | null | null | null |
2014/04/table-subminimum-wages/graphic_config.py
|
nprapps/graphics-archive
|
97b0ef326b46a959df930f5522d325e537f7a655
|
[
"FSFAP"
] | 7 |
2015-04-04T04:45:54.000Z
|
2021-02-18T11:12:48.000Z
|
#!/usr/bin/env python
COPY_GOOGLE_DOC_KEY = '1DTjU8IM4rryCHOKXHAzz06egQV7jVVCJgpKoCXJyB18'
| 23 | 68 | 0.847826 |
ab9c21ce16d3fb724e9e05713c4b540c61c06b29
| 233 |
py
|
Python
|
webapp/hackers_and_slack/first_flask_application/app.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
webapp/hackers_and_slack/first_flask_application/app.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
webapp/hackers_and_slack/first_flask_application/app.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
from flask import Flask
app = Flask(__name__,
instance_relative_config=False,
template_folder='templates',
static_folder='static')
@app.route('/')
def hello():
return 'Hello World'
| 21.181818 | 44 | 0.600858 |
e62d947304c084f7f41c0893ba19e00e5773d7dd
| 598 |
py
|
Python
|
code/products/mysql/connect.py
|
cutinha/devportal
|
fc564c7f0f779bba6a9713c27470d40a96fbc37a
|
[
"CC-BY-4.0"
] | 13 |
2021-05-04T07:46:38.000Z
|
2022-03-31T15:46:59.000Z
|
code/products/mysql/connect.py
|
cutinha/devportal
|
fc564c7f0f779bba6a9713c27470d40a96fbc37a
|
[
"CC-BY-4.0"
] | 656 |
2021-04-16T12:05:11.000Z
|
2022-03-31T19:33:26.000Z
|
code/products/mysql/connect.py
|
cutinha/devportal
|
fc564c7f0f779bba6a9713c27470d40a96fbc37a
|
[
"CC-BY-4.0"
] | 24 |
2021-04-21T04:17:13.000Z
|
2022-03-31T19:14:39.000Z
|
import pymysql
timeout = 10
connection = pymysql.connect(
charset="utf8mb4",
connect_timeout=timeout,
cursorclass=pymysql.cursors.DictCursor,
db="defaultdb",
host=MYSQL_HOST,
password=MYSQL_PASSWORD,
read_timeout=timeout,
port=MYSQL_PORT,
user=MYSQL_USERNAME,
write_timeout=timeout,
)
try:
cursor = connection.cursor()
cursor.execute("CREATE TABLE mytest (id INTEGER PRIMARY KEY)")
cursor.execute("INSERT INTO mytest (id) VALUES (1), (2)")
cursor.execute("SELECT * FROM mytest")
print(cursor.fetchall())
finally:
connection.close()
| 23.92 | 66 | 0.698997 |
058004e8706a67f59ebb0175bbcd94a1a74813d3
| 346 |
py
|
Python
|
backend/api/urls.py
|
giacomooo/CASFEE_Project2
|
420ff488d6b9deefe6623a45ecfed299f97a4639
|
[
"MIT"
] | null | null | null |
backend/api/urls.py
|
giacomooo/CASFEE_Project2
|
420ff488d6b9deefe6623a45ecfed299f97a4639
|
[
"MIT"
] | null | null | null |
backend/api/urls.py
|
giacomooo/CASFEE_Project2
|
420ff488d6b9deefe6623a45ecfed299f97a4639
|
[
"MIT"
] | null | null | null |
from django.conf.urls import url, include
from rest_framework import routers
from . import views
# pylint: disable=invalid-name
app_name = 'api'
router = routers.DefaultRouter()
router.register(r'parking', views.ParkingViewSet)
router.register(r'reservation', views.ReservationViewSet)
urlpatterns = [
url( r'^', include(router.urls)),
]
| 21.625 | 57 | 0.760116 |
55b8e9f88211d42abeb05e16feab4d8e2d7b4e9a
| 627 |
py
|
Python
|
python/en/archive/books/udemy-AutomateTheBoringStuffWithPythonProgramming/Ch02-FlowControl-while_break_continue_statements.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
python/en/archive/books/udemy-AutomateTheBoringStuffWithPythonProgramming/Ch02-FlowControl-while_break_continue_statements.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
python/en/archive/books/udemy-AutomateTheBoringStuffWithPythonProgramming/Ch02-FlowControl-while_break_continue_statements.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
# Ch02-FlowControl-while_break_continue_statements.py
# This is an example for while, break, continue statements.
#
# https://automatetheboringstuff.com/chapter2/
# Flow Control Statements: Lesson 6 - while Loops, break, and continue
#
# I changed the original code slightly.
count = 0
while True:
print('What is your name?')
name = input()
if name != 'Joe':
if count > 2:
print('Hint: The name should be Joe.')
count = count + 1
continue
print('Hi, Joe. What is the password?')
password = input()
if password == 'swordfish':
break
print('Access granted')
| 26.125 | 70 | 0.645933 |
e95c521ec7e01dec6f378813e28026de64964c1c
| 6,378 |
py
|
Python
|
projects/controllers/projects.py
|
Matheus158257/projects
|
26a6148046533476e625a872a2950c383aa975a8
|
[
"Apache-2.0"
] | null | null | null |
projects/controllers/projects.py
|
Matheus158257/projects
|
26a6148046533476e625a872a2950c383aa975a8
|
[
"Apache-2.0"
] | null | null | null |
projects/controllers/projects.py
|
Matheus158257/projects
|
26a6148046533476e625a872a2950c383aa975a8
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
"""Projects controller."""
import re
from datetime import datetime
from os.path import join
from sqlalchemy import func
from sqlalchemy.exc import InvalidRequestError, ProgrammingError
from werkzeug.exceptions import BadRequest, NotFound
from .experiments import create_experiment
from ..database import db_session
from ..models import Dependency, Experiment, Operator, Project
from ..object_storage import remove_objects
from .utils import uuid_alpha, list_objects, objects_uuid
def list_projects():
"""Lists all projects from our database.
Returns:
A list of all projects sorted by name in natural sort order.
"""
projects = db_session.query(Project).all()
# sort the list in place, using natural sort
projects.sort(key=lambda o: [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", o.name)])
return [project.as_dict() for project in projects]
def create_project(name=None, **kwargs):
"""Creates a new project in our database.
Args:
name (str): the project name.
Returns:
The project info.
"""
if not isinstance(name, str):
raise BadRequest("name is required")
check_project_name = db_session.query(Project).filter_by(name=name).first()
if check_project_name:
raise BadRequest("a project with that name already exists")
project = Project(uuid=uuid_alpha(), name=name, description=kwargs.get("description"))
db_session.add(project)
db_session.commit()
create_experiment(name="Novo experimento", project_id=project.uuid)
return project.as_dict()
def get_project(uuid):
"""Details a project from our database.
Args:
uuid (str): the project uuid to look for in our database.
Returns:
The project info.
"""
project = Project.query.get(uuid)
if project is None:
raise NotFound("The specified project does not exist")
return project.as_dict()
def update_project(uuid, **kwargs):
"""Updates a project in our database.
Args:
uuid (str): the project uuid to look for in our database.
**kwargs: arbitrary keyword arguments.
Returns:
The project info.
"""
project = Project.query.get(uuid)
if project is None:
raise NotFound("The specified project does not exist")
if "name" in kwargs:
name = kwargs["name"]
if name != project.name:
check_project_name = db_session.query(Project).filter_by(name=name).first()
if check_project_name:
raise BadRequest("a project with that name already exists")
data = {"updated_at": datetime.utcnow()}
data.update(kwargs)
try:
db_session.query(Project).filter_by(uuid=uuid).update(data)
db_session.commit()
except (InvalidRequestError, ProgrammingError) as e:
raise BadRequest(str(e))
return project.as_dict()
def delete_project(uuid):
"""Delete a project in our database and in the object storage.
Args:
uuid (str): the project uuid to look for in our database.
Returns:
The deletion result.
"""
project = Project.query.get(uuid)
if project is None:
raise NotFound("The specified project does not exist")
experiments = Experiment.query.filter(Experiment.project_id == uuid).all()
for experiment in experiments:
# remove dependencies
operators = db_session.query(Operator).filter(Operator.experiment_id == experiment.uuid).all()
for operator in operators:
Dependency.query.filter(Dependency.operator_id == operator.uuid).delete()
# remove operators
Operator.query.filter(Operator.experiment_id == experiment.uuid).delete()
Experiment.query.filter(Experiment.project_id == uuid).delete()
db_session.delete(project)
db_session.commit()
prefix = join("experiments", uuid)
remove_objects(prefix=prefix)
return {"message": "Project deleted"}
def pagination_projects(name, page, page_size):
"""The numbers of items to return maximum 100 """
if page_size > 100:
page_size = 100
query = db_session.query(Project)
if name:
query = query.filter(Project.name.ilike(func.lower(f"%{name}%")))
if page != 0:
query = query.order_by(Project.name).limit(page_size).offset((page - 1) * page_size)
projects = query.all()
projects.sort(key=lambda o: [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", o.name)])
return [project.as_dict() for project in projects]
def total_rows_projects(name):
query = db_session.query(func.count(Project.uuid))
if name:
query = query.filter(Project.name.ilike(func.lower(f"%{name}%")))
rows = query.scalar()
return rows
def delete_projects(project_ids):
total_elements = len(project_ids)
all_projects_ids = list_objects(project_ids)
if total_elements < 1:
return {"message": "please inform the uuid of the project"}
projects = db_session.query(Project).filter(Project.uuid.in_(all_projects_ids)).all()
experiments = db_session.query(Experiment).filter(Experiment.project_id.in_(objects_uuid(projects))).all()
operators = db_session.query(Operator).filter(Operator.experiment_id.in_(objects_uuid(experiments))) \
.all()
if len(projects) != total_elements:
raise NotFound("The specified project does not exist")
if len(operators) != 0:
# remove dependencies
for operator in operators:
Dependency.query.filter(Dependency.operator_id == operator.uuid).delete()
# remove operators
operators = Operator.__table__.delete().where(Operator.experiment_id.in_(objects_uuid(experiments)))
db_session.execute(operators)
if len(experiments) != 0:
deleted_experiments = Experiment.__table__.delete().where(Experiment.uuid.in_(objects_uuid(experiments)))
db_session.execute(deleted_experiments)
deleted_projects = Project.__table__.delete().where(Project.uuid.in_(all_projects_ids))
db_session.execute(deleted_projects)
for experiment in experiments:
prefix = join("experiments", experiment.uuid)
try:
remove_objects(prefix=prefix)
except Exception:
pass
db_session.commit()
return {"message": "Successfully removed projects"}
| 32.876289 | 113 | 0.68313 |
e983e7ba4f6a877ebd6df9433aca6044125791c8
| 774 |
py
|
Python
|
BITs/2014/Abdrahmanova_G_I/task_6_1.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
BITs/2014/Abdrahmanova_G_I/task_6_1.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
BITs/2014/Abdrahmanova_G_I/task_6_1.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
#Задача 6. Вариант 1.
#Создайте игру, в которой компьютер загадывает имя одного из трех мушкетеров - товарищей д'Артаньяна, а игрок должен его угадать.
import random
guessesTaken=0
print('Компьютер загадал имя одного из трех мушкетеров - товарищей д`Артаньяна. \nТвоя цель отгадать имя загаданного мушкетера.')
musketry=random.choice(["Атос", "Партос", "Арамис"])
while guessesTaken < 2:
print('Загаданное имя мушкетера: ')
guess=input()
guessesTaken=guessesTaken+1
if guess!=musketry:
print('Неверно!')
if guess==musketry:
break
if guess==musketry:
print('Верно! Число использованных попыток: ', guessesTaken)
if guess!=musketry:
print('Попытки кончились')
input('Нажмите Enter')
#Abdrahmanova G. I.
#28.03.2016
| 36.857143 | 129 | 0.711886 |
75a7677c1708739d2100642d686c9f578c44055d
| 1,500 |
py
|
Python
|
Aufgaben/abgabe5/main.py
|
JoshuaJoost/GNN_SS20
|
6b905319f2e51b71569354c347805abce9df3cb1
|
[
"MIT"
] | null | null | null |
Aufgaben/abgabe5/main.py
|
JoshuaJoost/GNN_SS20
|
6b905319f2e51b71569354c347805abce9df3cb1
|
[
"MIT"
] | null | null | null |
Aufgaben/abgabe5/main.py
|
JoshuaJoost/GNN_SS20
|
6b905319f2e51b71569354c347805abce9df3cb1
|
[
"MIT"
] | null | null | null |
__authors__ = "Rosario Allegro (1813064), Sedat Cakici (1713179), Joshua Joost (1626034)"
# maintainer = who fixes buggs?
__maintainer = __authors__
__date__ = "2020-06-24"
__version__ = "1.0"
__status__ = "Ready"
# kernel import
import numpy as np
import math
from matplotlib import pyplot as plt
# constants
## functions
tanh_func = lambda netInput: (2 / (1 + math.e ** (-2.0 * float(netInput))) -1)
## net constants
numBias = 1
numNeurons = 2
## weightMatrix
# [[W11, W21],[W12, W22]]
weightMatrix = np.array([[-4, -1.5], [1.5, 0]])
# [WBias1, WBias2]
weightMatrixBias = np.array([-3.37, 0.125])
# [Neuron1, Neuron2]
neuronValues = np.array([0.0,0.0])
# Implements reccurent Hopfield-Net
# main
iterations = 10
plotValuesN1 = np.zeros([iterations + 1])
plotValuesN1[0] = neuronValues[0]
plotValuesN2 = np.zeros([iterations + 1])
plotValuesN2[0] = neuronValues[1]
for i in range(iterations):
# synchron activation
synchNeuron1Value = neuronValues[0] * weightMatrix[0][0] + neuronValues[1] * weightMatrix[1][0] + weightMatrixBias[0]
synchNeuron2Value = neuronValues[0] * weightMatrix[0][1] + neuronValues[1] * weightMatrix[1][1] + weightMatrixBias[1]
neuronValues[0] = tanh_func(synchNeuron1Value)
neuronValues[1] = tanh_func(synchNeuron2Value)
plotValuesN1[i+1] = neuronValues[0]
plotValuesN2[i+1] = neuronValues[1]
pass
plt.plot(plotValuesN1, 's-', markersize=6, color='red')
plt.plot(plotValuesN2, 's-', markersize=6, color='blue')
plt.show()
| 26.315789 | 121 | 0.696 |
f96d35234a53cd83f18ac3c80b689cbdba19f166
| 18,746 |
py
|
Python
|
examples/nowcoder/SQL7/tests.py
|
zhengtong0898/django-decode
|
69680853a4a5b07f6a9c4b65c7d86b2d401a92b1
|
[
"MIT"
] | 5 |
2020-07-14T07:48:10.000Z
|
2021-12-20T21:20:10.000Z
|
examples/nowcoder/SQL7/tests.py
|
zhengtong0898/django-decode
|
69680853a4a5b07f6a9c4b65c7d86b2d401a92b1
|
[
"MIT"
] | 7 |
2021-03-26T03:13:38.000Z
|
2022-03-12T00:42:03.000Z
|
examples/nowcoder/SQL7/tests.py
|
zhengtong0898/django-decode
|
69680853a4a5b07f6a9c4b65c7d86b2d401a92b1
|
[
"MIT"
] | 1 |
2021-02-16T07:04:25.000Z
|
2021-02-16T07:04:25.000Z
|
from datetime import date
from django.db import connections
from django.test import TestCase, TransactionTestCase
from .models import salaries
from django.db.models.aggregates import Count
# Create your tests here.
class SimpleTest(TransactionTestCase):
reset_sequences = True
def prepare_data(self):
# 建表语句
# CREATE TABLE `sql7_salaries` (
# `emp_no` INT ( 11 ) NOT NULL AUTO_INCREMENT,
# `salary` INT ( 11 ) NOT NULL,
# `from_date` date NOT NULL,
# `to_date` date NOT NULL,
# PRIMARY KEY ( `emp_no` )
# ) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
# 一次只能插入一条数据,
# 如果想要插入多条数据, 需要采用 executemany 配合 insert into sql1_employees values (xxx), (xxx), (xxx);
cursor = connections['default'].cursor()
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,60117,'1986-06-26','1987-06-26');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,62102,'1987-06-26','1988-06-25');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,66074,'1988-06-25','1989-06-25');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,66596,'1989-06-25','1990-06-25');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,66961,'1990-06-25','1991-06-25');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,71046,'1991-06-25','1992-06-24');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,74333,'1992-06-24','1993-06-24');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,75286,'1993-06-24','1994-06-24');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,75994,'1994-06-24','1995-06-24');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,76884,'1995-06-24','1996-06-23');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,80013,'1996-06-23','1997-06-23');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,81025,'1997-06-23','1998-06-23');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,81097,'1998-06-23','1999-06-23');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,84917,'1999-06-23','2000-06-22');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,85112,'2000-06-22','2001-06-22');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,85097,'2001-06-22','2002-06-22');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10001,88958,'2002-06-22','9999-01-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10002,72527,'1996-08-03','1997-08-03');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10002,72527,'1997-08-03','1998-08-03');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10002,72527,'1998-08-03','1999-08-03');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10002,72527,'1999-08-03','2000-08-02');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10002,72527,'2000-08-02','2001-08-02');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10002,72527,'2001-08-02','9999-01-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10003,40006,'1995-12-03','1996-12-02');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10003,43616,'1996-12-02','1997-12-02');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10003,43466,'1997-12-02','1998-12-02');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10003,43636,'1998-12-02','1999-12-02');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10003,43478,'1999-12-02','2000-12-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10003,43699,'2000-12-01','2001-12-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10003,43311,'2001-12-01','9999-01-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,40054,'1986-12-01','1987-12-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,42283,'1987-12-01','1988-11-30');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,42542,'1988-11-30','1989-11-30');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,46065,'1989-11-30','1990-11-30');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,48271,'1990-11-30','1991-11-30');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,50594,'1991-11-30','1992-11-29');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,52119,'1992-11-29','1993-11-29');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,54693,'1993-11-29','1994-11-29');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,58326,'1994-11-29','1995-11-29');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,60770,'1995-11-29','1996-11-28');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,62566,'1996-11-28','1997-11-28');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,64340,'1997-11-28','1998-11-28');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,67096,'1998-11-28','1999-11-28');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,69722,'1999-11-28','2000-11-27');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,70698,'2000-11-27','2001-11-27');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10004,74057,'2001-11-27','9999-01-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,78228,'1989-09-12','1990-09-12');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,82621,'1990-09-12','1991-09-12');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,83735,'1991-09-12','1992-09-11');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,85572,'1992-09-11','1993-09-11');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,85076,'1993-09-11','1994-09-11');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,86050,'1994-09-11','1995-09-11');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,88448,'1995-09-11','1996-09-10');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,88063,'1996-09-10','1997-09-10');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,89724,'1997-09-10','1998-09-10');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,90392,'1998-09-10','1999-09-10');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,90531,'1999-09-10','2000-09-09');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,91453,'2000-09-09','2001-09-09');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10005,94692,'2001-09-09','9999-01-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1990-08-05','1991-08-05');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1991-08-05','1992-08-04');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1992-08-04','1993-08-04');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1993-08-04','1994-08-04');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1994-08-04','1995-08-04');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1995-08-04','1996-08-03');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1996-08-03','1997-08-03');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1997-08-03','1998-08-03');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1998-08-03','1999-08-03');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1999-08-03','2000-08-02');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'2000-08-02','2001-08-02');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'2001-08-02','9999-01-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,56724,'1989-02-10','1990-02-10');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,60740,'1990-02-10','1991-02-10');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,62745,'1991-02-10','1992-02-10');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,63475,'1992-02-10','1993-02-09');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,63208,'1993-02-09','1994-02-09');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,64563,'1994-02-09','1995-02-09');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,68833,'1995-02-09','1996-02-09');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,70220,'1996-02-09','1997-02-08');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,73362,'1997-02-08','1998-02-08');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,75582,'1998-02-08','1999-02-08');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,79513,'1999-02-08','2000-02-08');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,80083,'2000-02-08','2001-02-07');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,84456,'2001-02-07','2002-02-07');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10007,88070,'2002-02-07','9999-01-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10008,46671,'1998-03-11','1999-03-11');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10008,48584,'1999-03-11','2000-03-10');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10008,52668,'2000-03-10','2000-07-31');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,60929,'1985-02-18','1986-02-18');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,64604,'1986-02-18','1987-02-18');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,64780,'1987-02-18','1988-02-18');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,66302,'1988-02-18','1989-02-17');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,69042,'1989-02-17','1990-02-17');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,70889,'1990-02-17','1991-02-17');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,71434,'1991-02-17','1992-02-17');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,74612,'1992-02-17','1993-02-16');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,76518,'1993-02-16','1994-02-16');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,78335,'1994-02-16','1995-02-16');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,80944,'1995-02-16','1996-02-16');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,82507,'1996-02-16','1997-02-15');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,85875,'1997-02-15','1998-02-15');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,89324,'1998-02-15','1999-02-15');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,90668,'1999-02-15','2000-02-15');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,93507,'2000-02-15','2001-02-14');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,94443,'2001-02-14','2002-02-14');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10009,95409,'2002-02-14','9999-01-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10010,94409,'1996-11-24','1997-11-24');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10010,94409,'1997-11-24','1998-11-24');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10010,94409,'1998-11-24','1999-11-24');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10010,94409,'1999-11-24','2000-11-23');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10010,94409,'2000-11-23','2001-11-23');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10010,94409,'2001-11-23','9999-01-01');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10002,72527,'1985-11-21','1996-08-03');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10003,15828,'1986-08-28','1995-12-03');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1989-06-02','1990-08-05');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10006,43311,'1994-09-15','1998-03-11');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10010,94409,'1989-08-24','1996-11-24');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10008,25828,'1994-09-15','1998-03-11');""")
cursor.execute("""INSERT INTO sql7_salaries (emp_no, salary, from_date, to_date) VALUES(10011,25828,'1990-01-22','9999-01-01');""")
def clear_data(self):
cursor = connections['default'].cursor()
cursor.execute('delete from sql7_salaries;')
def pre_assert(self, qs):
# 断言:
# 10001|17
# 10004|16
# 10009|18
self.assertEqual(len(qs), 3)
self.assertEqual(qs[0].get('emp_no'), 10001)
self.assertEqual(qs[0].get('t'), 17)
self.assertEqual(qs[1].get('emp_no'), 10004)
self.assertEqual(qs[1].get('t'), 16)
self.assertEqual(qs[2].get('emp_no'), 10009)
self.assertEqual(qs[2].get('t'), 18)
def test_sql_7_1(self):
# 准备数据
self.prepare_data()
# 期望SQL
# select emp_no, count(to_date) as t
# from salaries
# group by emp_no
# having t > 4;
#
# 生成SQL
# SELECT `SQL7_salaries`.`emp_no`,
# COUNT(`SQL7_salaries`.`emp_no`) AS `t`
# FROM `SQL7_salaries`
# GROUP BY `SQL7_salaries`.`emp_no`
# HAVING COUNT(`SQL7_salaries`.`emp_no`) > 15
# ORDER BY NULL
qs = (salaries.objects.values('emp_no')
.annotate(t=Count('emp_no'))
.filter(t__gt=15))
# 断言
self.pre_assert(qs)
# 清空
self.clear_data()
| 99.712766 | 139 | 0.672357 |
ddf0226893e4da0579d3c058e212abac52d2cbce
| 1,042 |
py
|
Python
|
web/MicroservicesAsAservice/MAAS1.py
|
NoXLaw/RaRCTF2021-Challenges-Public
|
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
|
[
"MIT"
] | null | null | null |
web/MicroservicesAsAservice/MAAS1.py
|
NoXLaw/RaRCTF2021-Challenges-Public
|
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
|
[
"MIT"
] | null | null | null |
web/MicroservicesAsAservice/MAAS1.py
|
NoXLaw/RaRCTF2021-Challenges-Public
|
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
|
[
"MIT"
] | null | null | null |
#!/usr/bin/python3
import string
import aiohttp
import asyncio
import sys
if len(sys.argv) < 2:
print("Usage: solve.py http://host:port/")
exit()
url = sys.argv[1]
w = string.ascii_lowercase + ''.join([str(x) for x in range(0, 10)]) + '{}_'
check = "1 if open('/flag.txt', 'r').read()[{}] == '{}' else None"
async def try_char(sess, pos, char):
async with sess.post(url + "calculator", data={'mode': 'arithmetic', 'n1': check.format(pos, char), 'add': '+', 'n2': ' '}) as r:
text = await r.text()
if 'flag.txt' in text:
return True, char
return False, char
async def main():
flag = ""
async with aiohttp.ClientSession() as session:
while '}' not in flag:
futures = []
for c in w:
futures.append(try_char(session, len(flag), c))
for coro in asyncio.as_completed(futures):
res = await coro
if res[0] is True:
flag += res[1]
print(flag)
asyncio.run(main())
| 26.717949 | 133 | 0.540307 |
3490ae6d764ad80342a7e630d4bd02ec30a74a92
| 8,522 |
py
|
Python
|
haas_lib_bundles/python/docs/examples/smart_panel/esp32/code/hvac.py
|
wstong999/AliOS-Things
|
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
|
[
"Apache-2.0"
] | null | null | null |
haas_lib_bundles/python/docs/examples/smart_panel/esp32/code/hvac.py
|
wstong999/AliOS-Things
|
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
|
[
"Apache-2.0"
] | null | null | null |
haas_lib_bundles/python/docs/examples/smart_panel/esp32/code/hvac.py
|
wstong999/AliOS-Things
|
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
|
[
"Apache-2.0"
] | null | null | null |
import lvgl as lv
# RESOURCES_ROOT = "S:/Users/liujuncheng/workspace/iot/esp32/solution/MicroPython/smart_panel/smart_panel/"
RESOURCES_ROOT = "S:/data/pyamp/"
environment_alive = False
functionImage = [
RESOURCES_ROOT + "images/refrigeration.png",
RESOURCES_ROOT + "images/heating.png",
RESOURCES_ROOT + "images/dehumidification.png",
RESOURCES_ROOT + "images/ventilation.png"]
functionImageSelected = [
RESOURCES_ROOT + "images/refrigeration_selected.png",
RESOURCES_ROOT + "images/heating_selected.png",
RESOURCES_ROOT + "images/dehumidification_selected.png",
RESOURCES_ROOT + "images/ventilation_selected.png"]
currentFunc = 0
currentSelected = None
hvac_alive = False
def hvac_back_click_callback(e, win):
global hvac_alive
if (hvac_alive):
from smart_panel import load_smart_panel
load_smart_panel()
hvac_alive = False
def hvac_back_press_callback(e, image):
image.set_zoom(280)
def hvac_back_release_callback(e, image):
image.set_zoom(250)
def sub_pressed_cb(e, self):
print("sub")
if (self.value > 16):
self.value -= 1
print("value %d" % (self.value))
self.label.set_text(str(self.value))
def add_pressed_cb(e, self):
print("add")
if (self.value < 30):
self.value += 1
print("value %d" % (self.value))
self.label.set_text(str(self.value))
def func_pressed_cb(e, index):
global currentFunc
global currentSelected
print(index)
if (index != currentFunc):
currentSelected.set_src(functionImage[currentFunc])
selectedImage = e.get_target()
currentFunc = index
selectedImage.set_src(functionImageSelected[currentFunc])
currentSelected = selectedImage
class Hvac:
value = 25
def createPage(self):
global currentFunc
global currentSelected
global hvac_alive
print("Enter Hvac")
# init scr
scr = lv.obj()
win = lv.obj(scr)
win.set_size(scr.get_width(), scr.get_height())
win.set_style_border_opa(0, 0)
win.set_style_radius(0, 0)
win.set_style_bg_color(lv.color_black(), 0)
win.clear_flag(lv.obj.FLAG.SCROLLABLE)
# --------- value container ---------
col_dsc = [60, 65, 40, 60, lv.GRID_TEMPLATE.LAST]
row_dsc = [48, lv.GRID_TEMPLATE.LAST]
valueLayout = lv.obj(win)
valueLayout.set_layout(lv.LAYOUT_GRID.value)
valueLayout.set_style_bg_opa(0, 0)
valueLayout.set_style_border_opa(0, 0)
valueLayout.set_size(lv.SIZE.CONTENT, lv.SIZE.CONTENT)
valueLayout.set_grid_align(lv.GRID_ALIGN.SPACE_BETWEEN, lv.GRID_ALIGN.SPACE_BETWEEN)
valueLayout.set_style_grid_column_dsc_array(col_dsc, 0)
valueLayout.set_style_grid_row_dsc_array(row_dsc, 0)
valueLayout.set_style_pad_top(20, 0)
valueLayout.set_style_align(lv.ALIGN.TOP_MID, 0)
# ----------- - --------------
subImage = lv.img(valueLayout)
subImage.set_src(RESOURCES_ROOT + "images/subtraction.png")
subImage.set_grid_cell(lv.GRID_ALIGN.START, 0, 1, lv.GRID_ALIGN.CENTER, 0, 1)
subImage.add_flag(lv.obj.FLAG.CLICKABLE)
subImage.add_event_cb(lambda e: sub_pressed_cb(e, self), lv.EVENT.PRESSED, None)
# subImage.add_event_cb(lambda e: hvac_back_press_callback(e, subImage), lv.EVENT.PRESSED, None)
# subImage.add_event_cb(lambda e: hvac_back_release_callback(e, subImage), lv.EVENT.RELEASED, None)
subImage.set_ext_click_area(40)
# ----------- value -----------
self.label = lv.label(valueLayout)
self.label.set_text(str(self.value))
self.label.set_style_text_color(lv.color_white(), 0)
self.label.set_style_text_font(lv.font_montserrat_48, 0)
self.label.set_grid_cell(lv.GRID_ALIGN.CENTER, 1, 1, lv.GRID_ALIGN.CENTER, 0, 1)
# ----------- ºC ------------
centigradeImage = lv.img(valueLayout)
centigradeImage.set_src(RESOURCES_ROOT + "images/centigrade_s.png")
centigradeImage.set_style_pad_bottom(8, 0)
centigradeImage.set_grid_cell(lv.GRID_ALIGN.START, 2, 1, lv.GRID_ALIGN.END, 0, 1)
# ----------- + ----------------
addImage = lv.img(valueLayout)
addImage.set_src(RESOURCES_ROOT + "images/addition.png")
addImage.set_grid_cell(lv.GRID_ALIGN.CENTER, 3, 1, lv.GRID_ALIGN.CENTER, 0, 1)
addImage.add_flag(lv.obj.FLAG.CLICKABLE)
addImage.add_event_cb(lambda e: add_pressed_cb(e, self), lv.EVENT.PRESSED, None)
# addImage.add_event_cb(lambda e: hvac_back_press_callback(e, addImage), lv.EVENT.PRESSED, None)
# addImage.add_event_cb(lambda e: hvac_back_release_callback(e, addImage), lv.EVENT.RELEASED, None)
addImage.set_ext_click_area(40)
# ----------- tips ----------
tips = lv.label(win)
tips.set_text("Temperature")
tips.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
tips.set_style_pad_bottom(20, 0)
tips.set_align(lv.ALIGN.CENTER)
# ----------- function ----------
func_col_dsc = [70, 70, 70, 70, lv.GRID_TEMPLATE.LAST]
func_row_dsc = [40, lv.GRID_TEMPLATE.LAST]
funcContainer = lv.obj(win)
funcContainer.set_style_bg_opa(0, 0)
funcContainer.set_style_border_opa(0, 0)
funcContainer.set_grid_dsc_array(func_col_dsc, func_row_dsc)
funcContainer.set_width(300)
funcContainer.set_height(90)
funcContainer.set_layout(lv.LAYOUT_GRID.value)
funcContainer.set_align(lv.ALIGN.BOTTOM_MID)
funcContainer.set_grid_align(lv.GRID_ALIGN.SPACE_BETWEEN, lv.GRID_ALIGN.SPACE_BETWEEN)
image = lv.img(funcContainer)
image.set_src(functionImage[0])
image.add_flag(lv.obj.FLAG.CLICKABLE)
image.set_ext_click_area(20)
image.add_event_cb(lambda e: func_pressed_cb(e, 0), lv.EVENT.PRESSED, None)
image.set_grid_cell(lv.GRID_ALIGN.CENTER, 0, 1, lv.GRID_ALIGN.CENTER, 0, 1)
currentSelected = image
currentSelected.set_src(functionImageSelected[0])
image1 = lv.img(funcContainer)
image1.set_src(functionImage[1])
image1.add_flag(lv.obj.FLAG.CLICKABLE)
image1.set_ext_click_area(20)
image1.add_event_cb(lambda e: func_pressed_cb(e, 1), lv.EVENT.PRESSED, None)
image1.set_grid_cell(lv.GRID_ALIGN.CENTER, 1, 1, lv.GRID_ALIGN.CENTER, 0, 1)
image2 = lv.img(funcContainer)
image2.set_src(functionImage[2])
image2.add_flag(lv.obj.FLAG.CLICKABLE)
image2.set_ext_click_area(20)
image2.add_event_cb(lambda e: func_pressed_cb(e, 2), lv.EVENT.PRESSED, None)
image2.set_grid_cell(lv.GRID_ALIGN.CENTER, 2, 1, lv.GRID_ALIGN.CENTER, 0, 1)
image3 = lv.img(funcContainer)
image3.set_src(functionImage[3])
image3.add_flag(lv.obj.FLAG.CLICKABLE)
image3.set_ext_click_area(20)
image3.add_event_cb(lambda e: func_pressed_cb(e, 3), lv.EVENT.PRESSED, None)
image3.set_grid_cell(lv.GRID_ALIGN.CENTER, 3, 1, lv.GRID_ALIGN.CENTER, 0, 1)
# for i in range(4):
# image = lv.img(funcContainer)
# image.set_src(functionImage[i])
# image.add_flag(lv.obj.FLAG.CLICKABLE)
# image.set_ext_click_area(20)
# image.add_event_cb(lambda e: func_pressed_cb(e, i), lv.EVENT.PRESSED, None)
# image.set_grid_cell(lv.GRID_ALIGN.CENTER, i, 1, lv.GRID_ALIGN.CENTER, 0, 1)
# if (currentFunc == i):
# currentSelected = image
# currentSelected.set_src(functionImageSelected[i])
backImg=lv.img(win)
backImg.set_src(RESOURCES_ROOT + "images/back.png")
backImg.set_style_align(lv.ALIGN.LEFT_MID, 0)
backImg.add_flag(lv.obj.FLAG.CLICKABLE)
backImg.add_event_cb(lambda e: hvac_back_click_callback(e, win), lv.EVENT.CLICKED, None)
backImg.add_event_cb(lambda e: hvac_back_press_callback(e, backImg), lv.EVENT.PRESSED, None)
backImg.add_event_cb(lambda e: hvac_back_release_callback(e, backImg), lv.EVENT.RELEASED, None)
backImg.set_ext_click_area(20)
from smart_panel import needAnimation
if (needAnimation):
lv.scr_load_anim(scr, lv.SCR_LOAD_ANIM.MOVE_LEFT, 500, 0, True)
else:
lv.scr_load_anim(scr, lv.SCR_LOAD_ANIM.NONE, 0, 0, True)
hvac_alive = True
| 40.00939 | 107 | 0.660174 |
9b701f85472e679985df8373a66454121e2cdc7a
| 18,960 |
py
|
Python
|
tests/test_krotov.py
|
guruvamsi-policharla/noisy-krotov
|
c5397d9dbde68d06f17e88620d6a6b2c74664841
|
[
"BSD-3-Clause"
] | 49 |
2018-11-07T06:43:33.000Z
|
2022-03-18T20:53:06.000Z
|
tests/test_krotov.py
|
guruvamsi-policharla/noisy-krotov
|
c5397d9dbde68d06f17e88620d6a6b2c74664841
|
[
"BSD-3-Clause"
] | 94 |
2018-11-06T20:15:04.000Z
|
2022-01-06T09:06:15.000Z
|
tests/test_krotov.py
|
qucontrol/krotov
|
9f9a22336c433dc3a37637ce8cc8324df4290b46
|
[
"BSD-3-Clause"
] | 20 |
2018-11-06T20:03:11.000Z
|
2022-03-12T05:29:21.000Z
|
"""High-level tests for `krotov` package."""
import io
import logging
import os
from copy import deepcopy
from shutil import copyfile
import numpy as np
import pytest
import qutip
from pkg_resources import parse_version
import krotov
def test_valid_version():
"""Check that the package defines a valid __version__"""
assert parse_version(krotov.__version__) >= parse_version("0.1.0")
def test_complex_control_rejection():
"""Test that complex controls are rejected"""
H0 = qutip.Qobj(0.5 * np.diag([-1, 1]))
H1 = qutip.Qobj(np.mat([[1, 2], [3, 4]]))
psi0 = qutip.Qobj(np.array([1, 0]))
psi1 = qutip.Qobj(np.array([0, 1]))
def eps0(t, args):
return 0.2 * np.exp(1j * t)
def S(t):
"""Shape function for the field update"""
return krotov.shapes.flattop(
t, t_start=0, t_stop=5, t_rise=0.3, t_fall=0.3, func='sinsq'
)
H = [H0, [H1, eps0]]
objectives = [krotov.Objective(initial_state=psi0, target=psi1, H=H)]
pulse_options = {H[1][1]: dict(lambda_a=5, update_shape=S)}
tlist = np.linspace(0, 5, 500)
with pytest.raises(ValueError) as exc_info:
krotov.optimize_pulses(
objectives,
pulse_options,
tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
iter_stop=0,
)
assert 'all controls must be real-valued' in str(exc_info.value)
def S2(t):
"""Shape function for the field update"""
return 2.0 * krotov.shapes.flattop(
t, t_start=0, t_stop=5, t_rise=0.3, t_fall=0.3, func='sinsq'
)
def test_reject_invalid_shapes():
"""Test that invalid control shapes are rejected"""
H0 = qutip.Qobj(0.5 * np.diag([-1, 1]))
H1 = qutip.Qobj(np.mat([[1, 2], [3, 4]]))
psi0 = qutip.Qobj(np.array([1, 0]))
psi1 = qutip.Qobj(np.array([0, 1]))
def eps0(t, args):
return 0.2
H = [H0, [H1, eps0]]
objectives = [krotov.Objective(initial_state=psi0, target=psi1, H=H)]
tlist = np.linspace(0, 5, 500)
def S_complex(t):
"""Shape function for the field update"""
return 1j * krotov.shapes.flattop(
t, t_start=0, t_stop=5, t_rise=0.3, t_fall=0.3, func='sinsq'
)
def S_negative(t):
"""Shape function for the field update"""
return -1 * krotov.shapes.flattop(
t, t_start=0, t_stop=5, t_rise=0.3, t_fall=0.3, func='sinsq'
)
def S_large(t):
"""Shape function for the field update"""
return 2 * krotov.shapes.flattop(
t, t_start=0, t_stop=5, t_rise=0.3, t_fall=0.3, func='sinsq'
)
with pytest.raises(ValueError) as exc_info:
pulse_options = {H[1][1]: dict(lambda_a=5, update_shape=S_complex)}
krotov.optimize_pulses(
objectives,
pulse_options,
tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
iter_stop=0,
)
assert 'must be real-valued' in str(exc_info.value)
with pytest.raises(ValueError) as exc_info:
pulse_options = {H[1][1]: dict(lambda_a=5, update_shape=S_negative)}
krotov.optimize_pulses(
objectives,
pulse_options,
tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
iter_stop=0,
)
assert 'must have values in the range [0, 1]' in str(exc_info.value)
with pytest.raises(ValueError) as exc_info:
pulse_options = {H[1][1]: dict(lambda_a=5, update_shape=S_large)}
krotov.optimize_pulses(
objectives,
pulse_options,
tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
iter_stop=0,
)
assert 'must have values in the range [0, 1]' in str(exc_info.value)
@pytest.fixture
def simple_state_to_state_system():
"""System from 01_example_simple_state_to_state.ipynb"""
omega = 1.0
ampl0 = 0.2
H0 = -0.5 * omega * qutip.operators.sigmaz()
H1 = qutip.operators.sigmax()
eps0 = lambda t, args: ampl0
H = [H0, [H1, eps0]]
psi0 = qutip.ket('0')
psi1 = qutip.ket('1')
objectives = [krotov.Objective(initial_state=psi0, target=psi1, H=H)]
def S(t):
"""Shape function for the field update"""
return krotov.shapes.flattop(
t, t_start=0, t_stop=5, t_rise=0.3, t_fall=0.3, func='sinsq'
)
pulse_options = {H[1][1]: dict(lambda_a=5, update_shape=S)}
tlist = np.linspace(0, 5, 500)
return objectives, pulse_options, tlist
@pytest.mark.parametrize('iter_stop', [0, -1])
def test_zero_iterations(iter_stop, simple_state_to_state_system):
objectives, pulse_options, tlist = simple_state_to_state_system
with io.StringIO() as log_fh:
result = krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
store_all_pulses=True,
info_hook=krotov.info_hooks.print_table(
J_T=krotov.functionals.J_T_re, out=log_fh
),
iter_stop=iter_stop,
skip_initial_forward_propagation=True,
)
log = log_fh.getvalue()
assert len(log.splitlines()) == 2
assert result.message == 'Reached 0 iterations'
assert len(result.guess_controls) == 1 # one control field
assert len(result.guess_controls) == len(result.optimized_controls)
assert len(result.guess_controls[0]) == len(result.tlist)
assert len(result.optimized_controls[0]) == len(result.tlist)
for (c1, c2) in zip(result.guess_controls, result.optimized_controls):
assert np.all(c1 == c2)
for pulses_for_iteration in result.all_pulses:
for pulse in pulses_for_iteration:
# the pulses are defined on the *intervals* of tlist
assert len(pulse) == len(result.tlist) - 1
def test_continue_optimization(
simple_state_to_state_system, request, tmpdir, caplog
):
"""Big integration test for a simple optimization, with various
uses of `continue_from`. This covers a lot of edge cases not covered by the
example notebooks.
"""
objectives, pulse_options, tlist = simple_state_to_state_system
dumpfile = str(tmpdir.join("oct_result_{iter:03d}.dump"))
logfile = str(tmpdir.join("oct.log"))
testdir = os.path.splitext(request.module.__file__)[0]
logfile_expected = os.path.join(testdir, 'oct.log')
with open(logfile, 'w', encoding='utf8') as log_fh:
# initial optimization
with caplog.at_level(logging.WARNING):
oct_result1 = krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
store_all_pulses=True,
info_hook=krotov.info_hooks.print_table(
J_T=krotov.functionals.J_T_re, out=log_fh
),
check_convergence=krotov.convergence.Or(
krotov.convergence.check_monotonic_error,
krotov.convergence.dump_result(dumpfile, every=2),
),
iter_stop=3,
skip_initial_forward_propagation=True,
# not officially supported, but should work in this case
)
assert (
"You should not use `skip_initial_forward_propagation`"
in caplog.text
)
# fmt: off
assert len(oct_result1.iters) == 4 # 0 ... 3
assert len(oct_result1.iter_seconds) == 4
assert len(oct_result1.info_vals) == 4
assert len(oct_result1.all_pulses) == 4
assert len(oct_result1.states) == 1
assert len(oct_result1.guess_controls) == 1 # one control field
assert len(oct_result1.guess_controls) == len(oct_result1.optimized_controls)
assert len(oct_result1.guess_controls[0]) == len(oct_result1.tlist)
assert len(oct_result1.optimized_controls[0]) == len(oct_result1.tlist)
for pulses_for_iteration in oct_result1.all_pulses:
for pulse in pulses_for_iteration:
# the pulses are defined on the *intervals* of tlist
assert len(pulse) == len(oct_result1.tlist) - 1
assert "3 iterations" in oct_result1.message
# fmt: on
# repeating the same optimization only propagates the guess pulse
# (we'll check this later while verifying the output of the log file)
krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
store_all_pulses=True,
info_hook=krotov.info_hooks.print_table(
J_T=krotov.functionals.J_T_re, out=log_fh
),
check_convergence=krotov.convergence.Or(
krotov.convergence.check_monotonic_error,
krotov.convergence.dump_result(dumpfile, every=2),
),
continue_from=oct_result1,
iter_stop=3,
)
# another 2 iterations
oct_result2 = krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
store_all_pulses=True,
info_hook=krotov.info_hooks.print_table(
J_T=krotov.functionals.J_T_re, out=log_fh
),
check_convergence=krotov.convergence.Or(
krotov.convergence.check_monotonic_error,
krotov.convergence.dump_result(dumpfile, every=2),
),
continue_from=oct_result1,
iter_stop=5,
)
assert len(oct_result2.iters) == 6 # 0 ... 5
assert len(oct_result2.iter_seconds) == 6
assert len(oct_result2.info_vals) == 6
assert len(oct_result2.all_pulses) == 6
assert len(oct_result2.states) == 1
assert "5 iterations" in oct_result2.message
# and 2 more (skipping initial propagation)
oct_result3 = krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
store_all_pulses=True,
info_hook=krotov.info_hooks.print_table(
J_T=krotov.functionals.J_T_re, out=log_fh
),
check_convergence=krotov.convergence.Or(
krotov.convergence.check_monotonic_error,
krotov.convergence.dump_result(dumpfile, every=2),
),
continue_from=oct_result2,
iter_stop=7,
skip_initial_forward_propagation=True,
)
assert len(oct_result3.iters) == 8 # 0 ... 7
assert len(oct_result3.iter_seconds) == 8
assert len(oct_result3.info_vals) == 8
assert len(oct_result3.all_pulses) == 8
assert len(oct_result3.states) == 1
assert "7 iterations" in oct_result3.message
# no-op: already anough iterations
oct_result4 = krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
store_all_pulses=True,
info_hook=krotov.info_hooks.print_table(
J_T=krotov.functionals.J_T_re, out=log_fh
),
check_convergence=krotov.convergence.Or(
krotov.convergence.check_monotonic_error,
krotov.convergence.dump_result(dumpfile, every=2),
),
continue_from=oct_result3,
iter_stop=5, # < 7 in oct_result3
skip_initial_forward_propagation=True,
)
assert len(oct_result4.iters) == 8 # 0 ... 7
assert len(oct_result4.iter_seconds) == 8
assert len(oct_result4.info_vals) == 8
assert len(oct_result4.all_pulses) == 8
assert len(oct_result4.states) == 1
assert "7 iterations" in oct_result4.message
assert (
oct_result4.start_local_time_str
== oct_result3.start_local_time_str
)
assert oct_result4.iters == oct_result3.iters
assert oct_result4.message == oct_result3.message
# fmt: off
# check the combined log file
if not os.path.isfile(logfile_expected):
copyfile(logfile, logfile_expected)
with open(logfile, encoding='utf8') as fh1, open(logfile_expected, encoding='utf8') as fh2:
for line1 in fh1:
line2 = next(fh2)
assert line1[:63] == line2[:63]
# fmt: on
# continue from an incomplete dump file
with caplog.at_level(logging.WARNING):
result = krotov.result.Result.load(
str(tmpdir.join("oct_result_004.dump"))
)
assert 'Result.objectives contains control placeholders' in caplog.text
with pytest.raises(ValueError) as exc_info:
oct_result5 = krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
store_all_pulses=True,
check_convergence=krotov.convergence.Or(
krotov.convergence.check_monotonic_error,
krotov.convergence.dump_result(dumpfile, every=2),
),
continue_from=result,
iter_stop=7,
skip_initial_forward_propagation=True,
)
assert "objectives must remain unchanged" in str(exc_info.value)
result = krotov.result.Result.load(
str(tmpdir.join("oct_result_004.dump")), objectives=objectives
)
assert result.iters[-1] == 4
oct_result5 = krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
store_all_pulses=True,
info_hook=krotov.functionals.J_T_re,
check_convergence=krotov.convergence.Or(
krotov.convergence.check_monotonic_error,
krotov.convergence.dump_result(dumpfile, every=2),
),
continue_from=result,
iter_stop=7,
skip_initial_forward_propagation=True,
)
assert oct_result5.iters == oct_result3.iters
assert len(oct_result5.iter_seconds) == 8
assert len(oct_result5.info_vals) == 8
assert len(oct_result5.all_pulses) == 8
assert "7 iterations" in oct_result5.message
Δ = np.max(
np.abs(
oct_result5.optimized_controls[-1]
- oct_result3.optimized_controls[-1]
)
)
assert Δ < 1e-10
# broken continuation: different number of objectives
result_with_extra_objective = deepcopy(result)
result_with_extra_objective.objectives.append(
deepcopy(result.objectives[0])
)
with pytest.raises(ValueError) as exc_info:
krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
continue_from=result_with_extra_objective,
)
assert "number of objectives must be the same" in str(exc_info.value)
# broken continuation: different value for store_all_pulses
with pytest.raises(ValueError) as exc_info:
krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
continue_from=result,
store_all_pulses=False,
)
assert "store_all_pulses parameter cannot be changed" in str(
exc_info.value
)
# broken continuation: different time units
result_with_scaled_tlist = deepcopy(result)
result_with_scaled_tlist.objectives = result.objectives
result_with_scaled_tlist.tlist *= 2
with pytest.raises(ValueError) as exc_info:
krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
continue_from=result_with_scaled_tlist,
store_all_pulses=True,
)
assert "same time grid" in str(exc_info.value)
# broken continuation: changed nt
result_with_changed_nt = deepcopy(result)
result_with_changed_nt.objectives = result.objectives
result_with_changed_nt.tlist = np.linspace(0, 5, 1000)
with pytest.raises(ValueError) as exc_info:
krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
continue_from=result_with_changed_nt,
store_all_pulses=True,
)
assert "same time grid" in str(exc_info.value)
# incongruent controls
result_with_incongruent_pulse = deepcopy(result)
result_with_incongruent_pulse.objectives = result.objectives
result_with_incongruent_pulse.optimized_controls[0] = np.stack(
[result.optimized_controls[0], result.optimized_controls[0]]
).flatten()
with pytest.raises(ValueError) as exc_info:
krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
continue_from=result_with_incongruent_pulse,
store_all_pulses=True,
)
assert "optimized_controls and tlist are incongruent" in str(
exc_info.value
)
# passing complete garbage to `continue_from`
with pytest.raises(ValueError) as exc_info:
krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
chi_constructor=krotov.functionals.chis_re,
continue_from=result.objectives[0],
store_all_pulses=True,
)
assert "only possible from a Result object" in str(exc_info.value)
| 35.84121 | 95 | 0.627795 |
32f3277ed1a1a78217cb5298788ebeb15eb0af09
| 561 |
py
|
Python
|
common/models/pay/OauthAccessToken.py
|
yao6891/FlaskOrdering
|
cbd24bd8d95afaba91ce4d6b1b3548c4e82e3807
|
[
"Apache-2.0"
] | 2 |
2019-06-10T08:57:47.000Z
|
2021-06-12T16:22:15.000Z
|
common/models/pay/OauthAccessToken.py
|
yao6891/FlaskOrdering
|
cbd24bd8d95afaba91ce4d6b1b3548c4e82e3807
|
[
"Apache-2.0"
] | null | null | null |
common/models/pay/OauthAccessToken.py
|
yao6891/FlaskOrdering
|
cbd24bd8d95afaba91ce4d6b1b3548c4e82e3807
|
[
"Apache-2.0"
] | null | null | null |
# coding: utf-8
from sqlalchemy import Column, DateTime, Integer, String
from sqlalchemy.schema import FetchedValue
from application import db
class OauthAccessToken(db.Model):
__tablename__ = 'oauth_access_token'
id = db.Column(db.Integer, primary_key=True)
access_token = db.Column(db.String(600), nullable=False, server_default=db.FetchedValue())
expired_time = db.Column(db.DateTime, nullable=False, index=True, server_default=db.FetchedValue())
created_time = db.Column(db.DateTime, nullable=False, server_default=db.FetchedValue())
| 40.071429 | 103 | 0.773619 |
bd39e7b7bbb4ac75868e2d24926af6d23e341c10
| 191 |
py
|
Python
|
Hackergame_2020/火星文/index.py
|
Wycers/Codelib
|
86d83787aa577b8f2d66b5410e73102411c45e46
|
[
"MIT"
] | 22 |
2018-08-07T06:55:10.000Z
|
2021-06-12T02:12:19.000Z
|
Hackergame_2020/火星文/index.py
|
Wycers/Codelib
|
86d83787aa577b8f2d66b5410e73102411c45e46
|
[
"MIT"
] | 28 |
2020-03-04T23:47:22.000Z
|
2022-02-26T18:50:00.000Z
|
Hackergame_2020/火星文/index.py
|
Wycers/Codelib
|
86d83787aa577b8f2d66b5410e73102411c45e46
|
[
"MIT"
] | 4 |
2019-11-09T15:41:26.000Z
|
2021-10-10T08:56:57.000Z
|
from pathlib import Path
p = Path("gibberish_message.txt")
with p.open(encoding="utf-8") as f:
txt = f.read()
print(txt.encode("gbk").decode("utf-8").encode("latin1").decode("gbk"))
| 27.285714 | 75 | 0.659686 |
c845950c51ed0377e95fb45cba502f3afea7b193
| 486 |
py
|
Python
|
7-assets/past-student-repos/_DS-Python/Algorithms-master/recipe_batches/recipe_batches.py
|
eengineergz/Lambda
|
1fe511f7ef550aed998b75c18a432abf6ab41c5f
|
[
"MIT"
] | null | null | null |
7-assets/past-student-repos/_DS-Python/Algorithms-master/recipe_batches/recipe_batches.py
|
eengineergz/Lambda
|
1fe511f7ef550aed998b75c18a432abf6ab41c5f
|
[
"MIT"
] | 8 |
2020-03-24T17:47:23.000Z
|
2022-03-12T00:33:21.000Z
|
cs/lambda_cs/02_algorithms/Algorithms/recipe_batches/recipe_batches.py
|
tobias-fyi/vela
|
b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82
|
[
"MIT"
] | null | null | null |
#!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
pass
if __name__ == '__main__':
# Change the entries of these dictionaries to test
# your implementation with different inputs
recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }
ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }
print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
| 34.714286 | 164 | 0.716049 |
23deb3c099e189ac7a14ca2459782869915a6728
| 909 |
py
|
Python
|
src/makedata_classification.py
|
B1T0/DeUs
|
392f3bd3a97190cc2bc5dda9385b9728252cb975
|
[
"MIT"
] | 2 |
2018-03-13T06:49:32.000Z
|
2018-03-16T16:04:06.000Z
|
src/makedata_classification.py
|
B1T0/DeUs
|
392f3bd3a97190cc2bc5dda9385b9728252cb975
|
[
"MIT"
] | null | null | null |
src/makedata_classification.py
|
B1T0/DeUs
|
392f3bd3a97190cc2bc5dda9385b9728252cb975
|
[
"MIT"
] | null | null | null |
import os
import tensorflow as tf
def sliding(string, wnSize, step):
list = []
start = 0
while start + wnSize < len(string):
list.append(string[start:start+wnSize])
start = start + step
return list
def make(filename):
path = "../resources/texts"
author_ctr = 1
allAuthors = []
for infile in os.listdir(path):
allAuthors.append(open(path + "/" + infile, 'r', encoding="utf-8"))
author_ctr = author_ctr + 1
if author_ctr > tf.flags.FLAGS.num_authors and not tf.flags.FLAGS.use_all_available_texts:
break
output = open(filename, 'w', encoding="utf-8")
for a in range(len(allAuthors)):
wholeAuthor = ' '.join(allAuthors[a].readlines()).replace("\n", " ")
texts = sliding(wholeAuthor, tf.flags.FLAGS.text_length, 1)
for t in texts:
output.write(str(a+1) + "|SEPERATOR|" + t + "\n")
| 31.344828 | 98 | 0.606161 |
9b22e2adf66de77669946f1fd21c3e0cfe6c5f03
| 2,750 |
py
|
Python
|
packages/watchmen-storage/src/watchmen_storage/snowflake.py
|
Indexical-Metrics-Measure-Advisory/watchmen
|
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
|
[
"MIT"
] | null | null | null |
packages/watchmen-storage/src/watchmen_storage/snowflake.py
|
Indexical-Metrics-Measure-Advisory/watchmen
|
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
|
[
"MIT"
] | null | null | null |
packages/watchmen-storage/src/watchmen_storage/snowflake.py
|
Indexical-Metrics-Measure-Advisory/watchmen
|
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
|
[
"MIT"
] | null | null | null |
from time import time
from .snowflake_worker_id_generator import WorkerIdGenerator
# noinspection SpellCheckingInspection
TWEPOCH = 1420041600000
# 0 - 3, 4 data centers maximum
DATACENTER_ID_BITS = 2
# 0 - 1023, 1024 workers maximum per data center
WORKER_ID_BITS = 10
# 0 - 1023, 1024 sequence numbers per millisecond
SEQUENCE_BITS = 10
MAX_WORKER_ID = -1 ^ (-1 << WORKER_ID_BITS) # 2**10-1 0b1111111111
MAX_DATACENTER_ID = -1 ^ (-1 << DATACENTER_ID_BITS)
MAX_SEQUENCE = -1 ^ (-1 << SEQUENCE_BITS)
WORKER_ID_SHIFT = SEQUENCE_BITS
DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS
TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS
class InvalidSystemClockException(Exception):
pass
def generate_timestamp() -> int:
return int(time() * 1000)
def acquire_next_millisecond(last_timestamp):
timestamp = generate_timestamp()
while timestamp <= last_timestamp:
timestamp = generate_timestamp()
return timestamp
class SnowflakeGenerator:
"""
snowflake id generator
"""
def __init__(self, data_center_id: int = 0, generate_worker_id: WorkerIdGenerator = None):
"""
:param data_center_id: data center id, [0, 3]
:param generate_worker_id: a function returns worker id, [0, 1023]
"""
# sanity check
if data_center_id > MAX_DATACENTER_ID or data_center_id < 0:
raise ValueError(
f'Data center id invalid, it must be between [0, {MAX_DATACENTER_ID}] and passed by [{data_center_id}] .')
# compute worker id
assert generate_worker_id is not None, 'Worker id generator cannot be none.'
worker_id = generate_worker_id()
# sanity check
if worker_id > MAX_WORKER_ID or worker_id < 0:
raise ValueError(
f'Worker id invalid, it must be between [0, {MAX_WORKER_ID}] and passed by [{worker_id}] .')
# initialize
self.dataCenterId = data_center_id
self.workerId = worker_id
self.sequence = 0
self.lastTimestamp = -1
def next_id(self) -> int:
timestamp = generate_timestamp()
if timestamp < self.lastTimestamp:
# incorrect timestamp
# raise InvalidSystemClockException
# use current time stamp
timestamp = self.lastTimestamp
if timestamp == self.lastTimestamp:
# exactly in same timestamp, increase sequence
# and increase timestamp when sequence reaches the max value
self.sequence = (self.sequence + 1) & MAX_SEQUENCE
if self.sequence == 0:
timestamp = acquire_next_millisecond(self.lastTimestamp)
self.lastTimestamp = timestamp
else:
# already beyonds in-memory timestamp, reset in-memory
self.sequence = 0
self.lastTimestamp = timestamp
return \
((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | \
(self.dataCenterId << DATACENTER_ID_SHIFT) | \
(self.workerId << WORKER_ID_SHIFT) | \
self.sequence
| 29.255319 | 110 | 0.740727 |
b5a96df15f559edfc6903f6e1ea80362f6e3476c
| 1,384 |
py
|
Python
|
Problems/Breadth-FirstSearch/01Matrix/01_matrix.py
|
dolong2110/Algorithm-By-Problems-Python
|
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
|
[
"MIT"
] | null | null | null |
Problems/Breadth-FirstSearch/01Matrix/01_matrix.py
|
dolong2110/Algorithm-By-Problems-Python
|
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
|
[
"MIT"
] | null | null | null |
Problems/Breadth-FirstSearch/01Matrix/01_matrix.py
|
dolong2110/Algorithm-By-Problems-Python
|
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
|
[
"MIT"
] | null | null | null |
from collections import deque
from typing import List
# DP - Bottom up
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0])
for r in range(m):
for c in range(n):
if mat[r][c] > 0:
top = mat[r - 1][c] if r > 0 else float('inf')
left = mat[r][c - 1] if c > 0 else float('inf')
mat[r][c] = min(top, left) + 1
for r in range(m - 1, -1, -1):
for c in range(n - 1, -1, -1):
if mat[r][c] > 0:
bottom = mat[r + 1][c] if r < m - 1 else float('inf')
right = mat[r][c + 1] if c < n - 1 else float('inf')
mat[r][c] = min(mat[r][c], bottom + 1, right + 1)
return mat
# BFS
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
m, n = len(mat), len(mat[0])
DIR = [0, 1, 0, -1, 0]
q = deque([])
for r in range(m):
for c in range(n):
if mat[r][c] == 0:
q.append((r, c))
else:
mat[r][c] = -1 # Marked as not processed yet!
while q:
r, c = q.popleft()
for i in range(4):
nr, nc = r + DIR[i], c + DIR[i + 1]
if nr < 0 or nr == m or nc < 0 or nc == n or mat[nr][nc] != -1: continue
mat[nr][nc] = mat[r][c] + 1
q.append((nr, nc))
return mat
| 30.755556 | 84 | 0.439306 |
a5e1f585ebf83b076e2b7ea2748341db624fa2e1
| 198 |
py
|
Python
|
vorl7.py
|
haenno/FOM-BSc-WI-Semster3-Skriptsprachen-Python
|
bb34b6b1ba7e8fe7b22ce598a80d5011122c2d4a
|
[
"MIT"
] | null | null | null |
vorl7.py
|
haenno/FOM-BSc-WI-Semster3-Skriptsprachen-Python
|
bb34b6b1ba7e8fe7b22ce598a80d5011122c2d4a
|
[
"MIT"
] | null | null | null |
vorl7.py
|
haenno/FOM-BSc-WI-Semster3-Skriptsprachen-Python
|
bb34b6b1ba7e8fe7b22ce598a80d5011122c2d4a
|
[
"MIT"
] | null | null | null |
# 7. Vorlesung 20.11.2020, Skript Python 5 (07_Python_05.pdf)
#
import cv2
img = cv2.imread("belarus.jpg", cv2.IMREAD_COLOR)
cv2.imshow("myimage",img)
cv2.waitKey(0)
cv2.destroyWindow("myimage")
| 19.8 | 61 | 0.732323 |
8b5aad11059c2defe0d2fef8207f90569c163521
| 410 |
py
|
Python
|
Python1/aula9.py
|
Belaschich/SoulON
|
9f908b025b34fc79187b4efd5ea93a78dca0ef7e
|
[
"MIT"
] | null | null | null |
Python1/aula9.py
|
Belaschich/SoulON
|
9f908b025b34fc79187b4efd5ea93a78dca0ef7e
|
[
"MIT"
] | null | null | null |
Python1/aula9.py
|
Belaschich/SoulON
|
9f908b025b34fc79187b4efd5ea93a78dca0ef7e
|
[
"MIT"
] | null | null | null |
'''
1-Crie uma função que receba dois parâmetros e realize sua soma, subtração, adição e multiplicação.
2-Informe esses resultados através de um print ao usuário dentro da função.
'''
def operacoes(a,b):
soma = a + b
sub = a - b
mult = a * b
div = a / b
print("Soma: ", soma)
print("Subtração: ", sub)
print("Multiplicação: ", mult)
print("Divisão: ", div)
operacoes(4,3)
| 24.117647 | 99 | 0.626829 |
7be8b83b3a19ebde1540633334bed60cd49e93ba
| 741 |
py
|
Python
|
beispielanwendungen/sound/main.py
|
pbouda/pyqt-und-pyside-buch
|
a4ec10663ccc8aeda075c9a06b9707ded52382c8
|
[
"CC-BY-4.0"
] | 5 |
2017-03-11T13:27:27.000Z
|
2022-01-09T10:52:05.000Z
|
beispielanwendungen/sound/main.py
|
pbouda/pyqt-und-pyside-buch
|
a4ec10663ccc8aeda075c9a06b9707ded52382c8
|
[
"CC-BY-4.0"
] | 2 |
2021-02-14T10:59:59.000Z
|
2021-10-30T21:46:32.000Z
|
beispielanwendungen/sound/main.py
|
pbouda/pyqt-und-pyside-buch
|
a4ec10663ccc8aeda075c9a06b9707ded52382c8
|
[
"CC-BY-4.0"
] | 1 |
2019-08-07T03:08:18.000Z
|
2019-08-07T03:08:18.000Z
|
# -*- coding: utf-8 -*-
#!/usr/bin/env python
from PyQt4 import QtMultimedia
device = QtMultimedia.QAudioDeviceInfo.defaultOutputDevice()
info = QtMultimedia.QAudioDeviceInfo(device)
codecs = info.supportedCodecs()
print u"Device {0} unterstützt folgende Codecs:".format(device.deviceName())
for c in codecs:
print unicode(c)
format = QtMultimedia.QAudioFormat()
format.setChannels(2)
format.setFrequency(44100)
format.setSampleSize(16)
format.setCodec("audio/pcm")
format.setByteOrder(QtMultimedia.QAudioFormat.LittleEndian)
format.setSampleType(QtMultimedia.QAudioFormat.SignedInt)
if device.isFormatSupported(format):
print u"Format wird unterstützt."
else:
print u"Format wird nicht unterstützt."
| 29.64 | 77 | 0.765182 |
d0e2c1d06caecd5fb736078844ff93ac352ba206
| 892 |
py
|
Python
|
kts/core/lists.py
|
konodyuk/kts
|
3af5ccbf1d2089cb41d171626fcde4b0ba5aa8a7
|
[
"MIT"
] | 18 |
2019-02-14T13:10:07.000Z
|
2021-11-26T07:10:13.000Z
|
kts/core/lists.py
|
konodyuk/kts
|
3af5ccbf1d2089cb41d171626fcde4b0ba5aa8a7
|
[
"MIT"
] | 2 |
2019-02-17T14:06:42.000Z
|
2019-09-15T18:05:54.000Z
|
kts/core/lists.py
|
konodyuk/kts
|
3af5ccbf1d2089cb41d171626fcde4b0ba5aa8a7
|
[
"MIT"
] | 2 |
2019-09-15T13:12:42.000Z
|
2020-04-15T14:05:54.000Z
|
from kts.core.cache import CachedMapping
from kts.settings import cfg
class SyncedList(CachedMapping):
def sync(self, scope=None):
if scope is None:
scope = cfg.scope
for name, value in self.items():
scope[name] = value
class FeatureList(SyncedList):
def __init__(self):
super().__init__('features')
def register(self, feature_constructor):
if feature_constructor.name in self:
if feature_constructor.source != self[feature_constructor.name].source:
raise UserWarning(f"Source code mismatch. ")
return
self[feature_constructor.name] = feature_constructor
class HelperList(SyncedList):
def __init__(self):
super().__init__('helpers')
def register(self, helper):
self[helper.name] = helper
feature_list = FeatureList()
helper_list = HelperList()
| 27.030303 | 83 | 0.660314 |
d0ee636661fbe13a616e7d53650dd18b0a46098c
| 3,917 |
py
|
Python
|
Packs/ExpanseV2/Scripts/ExpanseAggregateAttributionCI/ExpanseAggregateAttributionCI.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 799 |
2016-08-02T06:43:14.000Z
|
2022-03-31T11:10:11.000Z
|
Packs/ExpanseV2/Scripts/ExpanseAggregateAttributionCI/ExpanseAggregateAttributionCI.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 9,317 |
2016-08-07T19:00:51.000Z
|
2022-03-31T21:56:04.000Z
|
Packs/ExpanseV2/Scripts/ExpanseAggregateAttributionCI/ExpanseAggregateAttributionCI.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 1,297 |
2016-08-04T13:59:00.000Z
|
2022-03-31T23:43:06.000Z
|
"""ExpanseAggregateAttributionCI
"""
import demistomock as demisto
from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
from CommonServerUserPython import * # noqa
from typing import Dict, Any, Tuple, Optional
import traceback
''' STANDALONE FUNCTION '''
def deconstruct_entry(ServiceNowCMDBContext: Dict[str, Any]) -> Tuple[str,
Optional[str],
Optional[str],
Optional[str],
Optional[str],
Optional[str]]:
"""
deconstruct_entry
Extracts device relevant fields from a log entry.
:type ServiceNowCMDBContext: ``Dict[str, Any]``
:param ServiceNowCMDBContext: ServiceNowCMDB.Record
:return: Tuple where the first element is the name or None, the second element is the
sys class name or None, the third element is the sys_id or None, the fourth element is the
asset display value or None, the fifth element is the asset link or None, and the final element
is the asset value or None.
:rtype: ``Tuple[Optional[str], Optional[str], Optional[str], Optional[int], Optional[str], Optional[str]]``
"""
name = ServiceNowCMDBContext.get("Attributes", {}).get("name")
sys_class_name = ServiceNowCMDBContext.get("Attributes", {}).get("sys_class_name")
sys_id = ServiceNowCMDBContext.get("Attributes", {}).get("sys_id", "Unknown")
asset_display_value = ServiceNowCMDBContext.get("Attributes", {}).get("asset", {}).get("display_value")
asset_link = ServiceNowCMDBContext.get("Attributes", {}).get("asset", {}).get("link")
asset_value = ServiceNowCMDBContext.get("Attributes", {}).get("asset", {}).get("value")
return sys_id, name, sys_class_name, asset_display_value, asset_link, asset_value
''' COMMAND FUNCTION '''
def aggregate_command(args: Dict[str, Any]) -> CommandResults:
input_list = argToList(args.get('input', []))
current_list = argToList(args.get('current', []))
current_sys_ids = {
f"{c.get('sys_id', 'Unknown')}": c
for c in current_list if c is not None
}
for entry in input_list:
if not isinstance(entry, dict):
continue
sys_id, name, sys_class_name, asset_display_value, asset_link, asset_value = deconstruct_entry(entry)
current_state = current_sys_ids.get(sys_id)
if current_state is None:
current_state = {
'name': name,
'sys_id': sys_id,
'sys_class_name': sys_class_name,
'asset_display_value': asset_display_value,
'asset_link': asset_link,
'asset_value': asset_value,
}
current_sys_ids[sys_id] = current_state
if current_sys_ids.get("Unknown") is not None:
del current_sys_ids["Unknown"]
human_readable = tableToMarkdown("## ExpanseAggregateAttributionCI", list(current_sys_ids.values()),
headers=["name", "sys_id", "asset_display_value"])
outputs = list(current_sys_ids.values())
return CommandResults(
readable_output=human_readable,
outputs=outputs or None,
outputs_prefix="Expanse.AttributionCI",
outputs_key_field=["sys_id"]
)
''' MAIN FUNCTION '''
def main():
try:
return_results(aggregate_command(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
return_error(f'Failed to execute ExpanseAggregateAttributionCI. Error: {str(ex)}')
''' ENTRY POINT '''
if __name__ in ('__main__', '__builtin__', 'builtins'):
main()
| 36.95283 | 111 | 0.606331 |
ef2846d1f59a95b5686d4c092b3179677fd5b4ed
| 796 |
pyde
|
Python
|
sketches/codingtrain_unicorn_rainbow_2/codingtrain_unicorn_rainbow_2.pyde
|
kantel/processingpy
|
74aae222e46f68d1c8f06307aaede3cdae65c8ec
|
[
"MIT"
] | 4 |
2018-06-03T02:11:46.000Z
|
2021-08-18T19:55:15.000Z
|
sketches/codingtrain_unicorn_rainbow_2/codingtrain_unicorn_rainbow_2.pyde
|
kantel/processingpy
|
74aae222e46f68d1c8f06307aaede3cdae65c8ec
|
[
"MIT"
] | null | null | null |
sketches/codingtrain_unicorn_rainbow_2/codingtrain_unicorn_rainbow_2.pyde
|
kantel/processingpy
|
74aae222e46f68d1c8f06307aaede3cdae65c8ec
|
[
"MIT"
] | 3 |
2019-12-23T19:12:51.000Z
|
2021-04-30T14:00:31.000Z
|
from unicornrainbow import UnicornRainbow
from codingtrain import CodingTrain
trains = []
NO_TRAINS = 2
def setup():
global unicorn, trains
size(720, 360)
this.surface.setTitle("Coding Train Unicorn Rainbow Stage 2")
unicorn = UnicornRainbow()
for i in range(NO_TRAINS):
train = CodingTrain((i*400) + 200)
trains.append(train)
def draw():
global unicorn, trains
background(64)
for train in trains:
train.update()
if train.reset:
unicorn.score += 1
print(unicorn.score)
unicorn.add_rainbow_stripes()
unicorn.update()
for train in trains:
train.show()
unicorn.show()
def keyPressed():
if (key == " "):
unicorn.up()
def mousePressed():
noLoop() # Für Screenshot
| 22.111111 | 65 | 0.624372 |
325e3f33826f50bad6d2a194f7974ca30c952619
| 1,728 |
py
|
Python
|
nz_crawl_demo/day7/demo1.py
|
gaohj/nzflask_bbs
|
36a94c380b78241ed5d1e07edab9618c3e8d477b
|
[
"Apache-2.0"
] | null | null | null |
nz_crawl_demo/day7/demo1.py
|
gaohj/nzflask_bbs
|
36a94c380b78241ed5d1e07edab9618c3e8d477b
|
[
"Apache-2.0"
] | 27 |
2020-02-12T07:55:58.000Z
|
2022-03-12T00:19:09.000Z
|
nz_crawl_demo/day7/demo1.py
|
gaohj/nzflask_bbs
|
36a94c380b78241ed5d1e07edab9618c3e8d477b
|
[
"Apache-2.0"
] | 2 |
2020-02-18T01:54:55.000Z
|
2020-02-21T11:36:28.000Z
|
import requests
import re
from urllib import request
from fontTools.ttLib import TTFont
def get_doutin():
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36",
}
url = "https://www.iesdouyin.com/share/user/88445518961"
res = requests.get(url,headers=headers,verify=False)
html = res.text
# font_url = "http://s3.pstatp.com/ies/resource/falcon/douyin_falcon/static/font/iconfont_9eb9a50.woff"
# # request.urlretrieve(font_url,'testt.woff')
return html
# def analysis_font():
# baseFont = TTFont('testt.woff')
# baseFont.saveXML('douyin.xml')
def get_real_word(content):
#网页上显示的 是  处理成 Oxe603
content = content.replace('&#','0').replace(';','')
print(content)
#预先定义好 它们的映射关系 name最终文字
name_word_list = [
{"name":['0xe603','0xe60d','0xe616'],'value':'0'},
{"name":['0xe602','0xe60e','0xe618'],'value':'1'},
{"name":['0xe605','0xe617','0xe610'],'value':'2'},
{"name":['0xe604','0xe611','0xe61a'],'value':'3'},
{"name":['0xe606','0xe60c','0xe619'],'value':'4'},
{"name":['0xe607','0xe60f','0xe61b'],'value':'5'},
{"name":['0xe612','0xe608','0xe61f'],'value':'6'},
{"name":['0xe613','0xe60a','0xe61c'],'value':'7'},
{"name":['0xe60b','0xe614','0xe61d'],'value':'8'},
{"name":['0xe609','0xe615','0xe61e'],'value':'9'},
]
for name_word in name_word_list:
for font_code in name_word['name']:
content = re.sub(font_code,name_word['value'],content)
print(content)
if __name__ == "__main__":
content = get_doutin()
info = get_real_word(content)
| 37.565217 | 139 | 0.604167 |
32afe23bfbc64666963c0e0dc4191162f991abf5
| 7,278 |
py
|
Python
|
event_detector/gttm/nlp/clean_text.py
|
MahdiFarnaghi/gtm
|
adbec372786262607291f901a444a0ebe9e98b48
|
[
"Apache-2.0"
] | null | null | null |
event_detector/gttm/nlp/clean_text.py
|
MahdiFarnaghi/gtm
|
adbec372786262607291f901a444a0ebe9e98b48
|
[
"Apache-2.0"
] | null | null | null |
event_detector/gttm/nlp/clean_text.py
|
MahdiFarnaghi/gtm
|
adbec372786262607291f901a444a0ebe9e98b48
|
[
"Apache-2.0"
] | null | null | null |
import re
import string
import pycountry
import spacy
from nltk.corpus import wordnet
from spacy.lang.xx import MultiLanguage
from spacy.lang.en import English
punct = list(string.punctuation)
extended_stop_words = ['rt', 'via', 'http', 'https', '...']
class TextCleaner:
def __init__(self):
pass
@staticmethod
def clean_text(text: str, lang: str = '', lang_full_name: str = ''):
if lang_full_name == '' and lang == '':
raise ValueError("Either lang or lang_full_name must be provided.")
try:
if lang_full_name == '':
lang_full_name = str.lower(pycountry.languages.get(alpha_2=lang).name)
if lang == '':
lang = str.lower(pycountry.languages.get(name=lang_full_name).name)
except:
print(lang)
# https://towardsdatascience.com/another-twitter-sentiment-analysis-bb5b01ebad90
text = TextCleaner.normalize_text(text)
lam_of_tweet = TextCleaner._tokenize_lemmatize(text=text, lang=lang)
lam_of_tweet_repeated_removed = TextCleaner._remove_repeated_characters(lam_of_tweet)
lam = " ".join(lam_of_tweet_repeated_removed)
num_of_words = len(lam_of_tweet_repeated_removed)
return lam, num_of_words, lang_full_name
# Excluded languages: ja, uk, th, 'vi', 'yo', 'zh', 'tl', 'ta', 'te, 'mr', 'si', 'kn', 'ko', 'id', 'eu'
supported_languages = ['de', 'el', 'en', 'es', 'fr', 'it', 'lt', 'nb', 'nl', 'pt', 'xx', 'af', 'ar', 'bg', 'bn',
'ca', 'cs', 'da', 'et', 'fa', 'fi', 'ga', 'he', 'hi', 'hr', 'hu', 'is', 'lb', 'lv',
'pl', 'ro', 'ru', 'sk', 'sl', 'sq', 'sr', 'sv', 'tr', 'tt', 'ur']
stopwords_for_languages = {}
nlp_for_languages = {}
@staticmethod
def is_lang_supported(lang):
return lang in TextCleaner.supported_languages
@staticmethod
def get_nlp_and_stopwords(lang):
if not lang in TextCleaner.nlp_for_languages:
if lang == 'en':
TextCleaner.nlp_for_languages['en'] = English() #spacy.load("en_core_web_sm")
TextCleaner.stopwords_for_languages['en'] = spacy.lang.en.stop_words.STOP_WORDS
elif lang in TextCleaner.supported_languages:
# In order to use languages that don’t yet come with a model, you have to import them directly, or use spacy.blank:
TextCleaner.nlp_for_languages[lang] = spacy.blank(lang)
TextCleaner.stopwords_for_languages[lang] = getattr(spacy.lang, lang).stop_words.STOP_WORDS
# if lang == 'sv':
# TextCleaner.stopwords_for_languages[lang] = spacy.lang.sv.stop_words.STOP_WORDS
# elif lang == 'ar':
# TextCleaner.stopwords_for_languages[lang] = spacy.lang.ar.stop_words.STOP_WORDS
return TextCleaner.nlp_for_languages[lang], TextCleaner.stopwords_for_languages[lang]
@staticmethod
def _tokenize_lemmatize(text, lang):
if not lang in TextCleaner.supported_languages:
return []
nlp, stop_words = TextCleaner.get_nlp_and_stopwords(lang)
doc = nlp(text)
# for word in doc:
# if not word.is_stop:
# print("{}\t:{}".format(word, word.lemma_))
res = [word.lemma_ for word in doc if not word.is_stop]
res = [word for word in res if word not in punct]
res = [word for word in res if word not in extended_stop_words]
return res
@staticmethod
def normalize_text(text):
text = text.replace('-', ' ')
# normalization 1: xxxThis is a --> xxx. This is a (missing delimiter)
text = re.sub(r'([a-z])([A-Z])', r'\1\. \2', text) # before lower case
# normalization 2: lower case
text = text.lower()
text = TextCleaner._remove_url(text)
text = TextCleaner._remove_usernames(text)
text = TextCleaner._remove_punct(text)
text = TextCleaner._replace_hashtag_by_text(text)
text = TextCleaner._remove_white_space(text)
text = TextCleaner._remove_utf8_bom(text)
# normalization 3: ">", "<"
text = re.sub(r'>|<', ' ', text)
# normalization 4: letter repetition (if more than 2)
text = re.sub(r'([a-z])\1{2,}', r'\1', text)
# normalization 5: non-word repetition (if more than 1)
text = re.sub(r'([\W+])\1{1,}', r'\1', text)
# normalization 6: string * as delimiter
text = re.sub(r'\*|\W\*|\*\W', '. ', text)
# normalization 7: stuff in parenthesis, assumed to be less informal
text = re.sub(r'\(.*?\)', '. ', text)
# normalization 8: xxx[?!]. -- > xxx.
text = re.sub(r'\W+?\.', '.', text)
# normalization 9: [.?!] --> [.?!] xxx
text = re.sub(r'(\.|\?|!)(\w)', r'\1 \2', text)
# normalization 10: ' ing ', noise text
# text = re.sub(r' ing ', ' ', text)
# normalization 11: noise text
text = re.sub(r'product received for free[.| ]', ' ', text)
# normalization 12: phrase repetition
text = re.sub(r'(.{2,}?)\1{1,}', r'\1', text)
return text
@staticmethod
def _remove_white_space(text):
# correct all multiple white spaces to a single white space
t1 = re.sub(r'[\s]+', ' ', text)
# Additional clean up : removing words less than 3 chars, and remove space at the beginning and teh end
t2 = re.sub(r'\W*\b\w{1,3}\b', '', t1)
return t2.strip()
@staticmethod
def _replace_hashtag_by_text(text):
return re.sub(r'#([^\s]+)', r'\1', text)
@staticmethod
def _remove_repeated_characters(tokens):
if tokens is None:
return None
repeat_pattern = re.compile(r'(\w*)(\w)\2(\w*)')
match_substitution = r'\1\2\3'
def replace(old_word):
if wordnet.synsets(old_word):
return old_word
new_word = repeat_pattern.sub(match_substitution, old_word)
return replace(new_word) if new_word != old_word else new_word
correct_tokens = [replace(word) for word in tokens]
return correct_tokens
@staticmethod
def _remove_punct(text):
text = "".join([char for char in text if char not in string.punctuation])
text = re.sub('[0-9]+', '', text)
return text
@staticmethod
def _remove_usernames(text):
return re.sub(r'@[^\s]+', '', text)
@staticmethod
def _remove_atsign(text):
return re.sub(r'@[A-Za-z0-9]+', '', text)
@staticmethod
def _remove_url(text):
return re.sub(r'((www\.[^\s]+)|(https?://[^\s]+))', '', text)
# return re.sub(r"http\S+", "", text)
# return re.sub('https?://[A-Za-z0-9./]+', '', text)
# convert url to string
# return re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', text)
@staticmethod
def _remove_utf8_bom(text: str):
# remove UTF-8 BOM (Byte Order Mark)
# https://towardsdatascience.com/another-twitter-sentiment-analysis-bb5b01ebad90
return text.replace(u"\ufffd", "?")
@staticmethod
def _remove_hashtag_numbers(text):
return re.sub("[^a-zA-Z]", " ", text)
| 40.659218 | 131 | 0.583952 |
32b0e73932f02bc98b8a41d8e70e7de88ef226e6
| 474 |
py
|
Python
|
posts/feeds.py
|
alien3211/lom-web
|
c7971238b0dd043854c911a0b9126b84d7deed4a
|
[
"MIT"
] | null | null | null |
posts/feeds.py
|
alien3211/lom-web
|
c7971238b0dd043854c911a0b9126b84d7deed4a
|
[
"MIT"
] | null | null | null |
posts/feeds.py
|
alien3211/lom-web
|
c7971238b0dd043854c911a0b9126b84d7deed4a
|
[
"MIT"
] | null | null | null |
from django.contrib.syndication.views import Feed
from django.template.defaultfilters import truncatewords_html
from .models import Post
class LatestPostFeed(Feed):
title_template = 'LOM'
link = '/post/'
description = 'Nowe posty na LOM'
def items(self):
return Post.objects.published()[:5]
def item_title(self, item):
return item.title
def item_description(self, item):
return truncatewords_html(item.get_markdown(), 30)
| 26.333333 | 61 | 0.708861 |
3e9c519c6b455545cec89cd412677cbb9d1ea94e
| 574 |
py
|
Python
|
413-arithmetic-slices/413-arithmetic-slices.py
|
hyeseonko/LeetCode
|
48dfc93f1638e13041d8ce1420517a886abbdc77
|
[
"MIT"
] | 2 |
2021-12-05T14:29:06.000Z
|
2022-01-01T05:46:13.000Z
|
413-arithmetic-slices/413-arithmetic-slices.py
|
hyeseonko/LeetCode
|
48dfc93f1638e13041d8ce1420517a886abbdc77
|
[
"MIT"
] | null | null | null |
413-arithmetic-slices/413-arithmetic-slices.py
|
hyeseonko/LeetCode
|
48dfc93f1638e13041d8ce1420517a886abbdc77
|
[
"MIT"
] | null | null | null |
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
if len(nums)<3:
return 0
output=[]
slices=[nums[0], nums[1]]
for num in nums[2:]:
if num-slices[-1]==slices[1]-slices[0]:
slices.append(num)
else:
if len(slices)>=3:
output.append(slices)
slices=[slices[-1], num]
output.append(slices)
result = 0
for o in output:
result+= int((len(o)-2)*(len(o)-1)/2)
return result
| 31.888889 | 63 | 0.470383 |
9d2635ca7956d2e8ad8a04be2b1407151757a1d7
| 4,798 |
py
|
Python
|
rpc.py
|
lihuiba/SoftSAN
|
1b8ab2cae92b7aac34211909b27d4ebe595275d7
|
[
"Apache-2.0"
] | 1 |
2015-08-02T09:53:18.000Z
|
2015-08-02T09:53:18.000Z
|
rpc.py
|
lihuiba/SoftSAN
|
1b8ab2cae92b7aac34211909b27d4ebe595275d7
|
[
"Apache-2.0"
] | null | null | null |
rpc.py
|
lihuiba/SoftSAN
|
1b8ab2cae92b7aac34211909b27d4ebe595275d7
|
[
"Apache-2.0"
] | 2 |
2018-03-21T04:59:50.000Z
|
2019-12-03T15:54:17.000Z
|
import logging, inspect, sys, traceback, pickle
import messages_pb2 as msg
import guid as Guid
# MethodInfo={
# "NewChunk": (msg.NewChunk_Request, msg.NewChunk_Response),
# "DeleteChunk": (msg.DeleteChunk_Request, msg.DeleteChunk_Response),
# "NewVolume": (msg.NewVolume_Request, msg.NewVolume_Response),
# "AssembleVolume": (msg.AssembleVolume_Request, msg.AssembleVolume_Response),
# "DisassembleVolume":(msg.DisassembleVolume_Request, msg.DisassembleVolume_Response),
# "RepairVolume": (msg.RepairVolume_Request, msg.RepairVolume_Response),
# "ReadVolume": (msg.ReadVolume_Request, msg.ReadVolume_Response),
# "WriteVolume": (msg.WriteVolume_Request, msg.WriteVolume_Response),
# "MoveVolume": (msg.MoveVolume_Request, msg.MoveVolume_Response),
# "ChMod": (msg.ChMod_Request, msg.ChMod_Response),
# "DeleteVolume": (msg.DeleteVolume_Request, msg.DeleteVolume_Response),
# "CreateLinK": (msg.CreateLink_Request, msg.CreateLink_Response),
#}
class ServiceTerminated:
pass
def BuildMethodInfo(theServer):
ret={}
for func in dir(theServer):
if func.startswith('_') or func.endswith('_'):
continue
target=getattr(theServer, func)
if not inspect.ismethod(target):
continue
req=getattr(msg, func+'_Request', None) or getattr(msg, func, type(None))
res=getattr(msg, func+'_Response', type(None))
ret[func]=(req, res)
return ret
def sendRpc(s, guid, token, name, body):
'''Guid token messageName bodySize\n'''
line="%s %u %s %u\n" % (Guid.toStr(guid), token, name, len(body))
s.sendall(line)
out = s.sendall(body)
def recvRpc(s):
fd=s.makefile()
parts=fd.readline().split()
if len(parts)==0:
raise ServiceTerminated()
guid=Guid.fromStr(parts[0])
token=int(parts[1])
name=parts[2]
size=int(parts[3])
body=fd.read(size)
fd.close()
if len(body)!=size:
raise IOError('Invalid rpc message')
return guid,token,name,body
class RpcService:
def __init__(self, Server, MethodInfo=None):
self.theServer=Server
self.peerguid=None
self.cursocket=None
Server.service=self
self.methodInfo=MethodInfo or BuildMethodInfo(Server)
logging.info(self.methodInfo.keys())
def peerGuid(self):
return self.peerguid
def currentSocket(self):
return self.cursocket
def doService(self, socket):
guid,token,name,body=recvRpc(socket)
self.peerguid=guid
self.cursocket=socket
try:
MI=self.methodInfo[name]
argument=MI[0].FromString(body)
method=getattr(self.theServer, name)
rettype=MI[1]
ret=method(argument)
assert type(ret)==rettype
if ret==None: return
body=ret.SerializeToString()
except:
name='Exception'
exception = sys.exc_info()[1]
body=pickle.dumps(exception)
logging.error("exception ", exc_info=1)
sendRpc(socket, guid, token, name, body)
def handler(self, socket, address):
guid=None
try:
while True:
self.doService(socket)
except ServiceTerminated:
pass
finally:
if guid==None: return
if hasattr(self.theServer, '_onConnectionClose_'):
self.theServer._onConnectionClose_()
class RpcStub:
def __init__(self, guid, socket=None, Interface=None, MethodInfo=None):
if Interface==None and MethodInfo==None:
raise ValueError("At least provide an Interface or a MethodInfo")
self.socket=socket
self.guid=guid
self.token=0
if isinstance(MethodInfo, dict): #if it's MethodInfo
self.methodInfo=MethodInfo
else:
self.methodInfo=BuildMethodInfo(Interface)
logging.info(self.methodInfo.keys())
def callMethod(self, name, argument, socket=None):
MI=self.methodInfo[name]
assert type(argument)==MI[0]
body=argument.SerializeToString()
socket = socket or self.socket
sendRpc(socket, self.guid, self.token, name, body)
if MI[1]==type(None): return
guid,token,name_,body_ = recvRpc(socket)
assert guid==self.guid
assert token==self.token
if name_=='Exception':
exception=pickle.loads(body_)
#print type(exception)
raise exception
assert name_==name
self.token=token+1
ret=MI[1].FromString(body_)
return ret
###################### Test ####################################
def test_BuildMethodInfo():
print(MethodInfo)
class mds:
def NewChunk(): pass
def DeleteChunk(): pass
def NewVolume(): pass
def AssembleVolume(): pass
def DisassembleVolume():pass
def RepairVolume(): pass
def ReadVolume(): pass
def WriteVolume(): pass
def MoveVolume(): pass
def ChMod(): pass
def DeleteVolume(): pass
def CreateLink(): pass
mi=BuildMethodInfo(mds)
print(mi)
def test_RpcService():
pass
if __name__=="__main__":
logging.basicConfig(level=logging.INFO)
test_BuildMethodInfo()
test_RpcService()
| 29.435583 | 86 | 0.693414 |
3e2821161c00ac74ae976524f3be83965ac6b0a7
| 128 |
py
|
Python
|
quantel/exceptions.py
|
RatherBland/Quantel-py
|
abb4ec3c1f72a7409aea3eb0a5e0f1ad5c6dbbe1
|
[
"MIT"
] | 37 |
2021-08-13T09:23:17.000Z
|
2021-12-15T17:25:05.000Z
|
quantel/exceptions.py
|
RatherBland/Quantel-py
|
abb4ec3c1f72a7409aea3eb0a5e0f1ad5c6dbbe1
|
[
"MIT"
] | 1 |
2021-08-24T05:51:08.000Z
|
2021-09-27T05:15:50.000Z
|
quantel/exceptions.py
|
RatherBland/Quantel-py
|
abb4ec3c1f72a7409aea3eb0a5e0f1ad5c6dbbe1
|
[
"MIT"
] | 2 |
2021-09-19T09:50:00.000Z
|
2021-10-31T18:21:09.000Z
|
class InvalidAPIKey(Exception):
pass
class GatewayError(Exception):
pass
class TooManyRequests(Exception):
pass
| 11.636364 | 33 | 0.734375 |
e41822a9aec32432039b1cba93278697689d361d
| 92 |
py
|
Python
|
2014/08/pork-beef-prices/graphic_config.py
|
nprapps/graphics-archive
|
97b0ef326b46a959df930f5522d325e537f7a655
|
[
"FSFAP"
] | 14 |
2015-05-08T13:41:51.000Z
|
2021-02-24T12:34:55.000Z
|
2014/08/pork-beef-prices/graphic_config.py
|
nprapps/graphics-archive
|
97b0ef326b46a959df930f5522d325e537f7a655
|
[
"FSFAP"
] | null | null | null |
2014/08/pork-beef-prices/graphic_config.py
|
nprapps/graphics-archive
|
97b0ef326b46a959df930f5522d325e537f7a655
|
[
"FSFAP"
] | 7 |
2015-04-04T04:45:54.000Z
|
2021-02-18T11:12:48.000Z
|
#!/usr/bin/env python
COPY_GOOGLE_DOC_KEY = '1agUUCq1UQbqO0djnWyUoeHbR9TKlYQkeuofdi8cKU5Y'
| 23 | 68 | 0.847826 |
e43b09d7f86bf2bb453d6f44fcfb1c37f9236473
| 267 |
py
|
Python
|
frds/mktstructure/__init__.py
|
mgao6767/wrds
|
7dca2651a181bf38c61ebde675c9f64d6c96f608
|
[
"MIT"
] | null | null | null |
frds/mktstructure/__init__.py
|
mgao6767/wrds
|
7dca2651a181bf38c61ebde675c9f64d6c96f608
|
[
"MIT"
] | null | null | null |
frds/mktstructure/__init__.py
|
mgao6767/wrds
|
7dca2651a181bf38c61ebde675c9f64d6c96f608
|
[
"MIT"
] | null | null | null |
__version__ = "0.2.0"
__description__ = "Download data from Refinitiv Tick History and compute some market microstructure measures."
__author__ = "Mingze Gao"
__author_email__ = "[email protected]"
# __github_url__ = "https://github.com/mgao6767/mktstructure"
| 44.5 | 110 | 0.786517 |
900cb60800d95660f5f1e3ce05f7e58d3e5daed4
| 2,835 |
py
|
Python
|
cryptoauthlib/python/cryptoauthlib/iface.py
|
PhillyNJ/SAMD21
|
0f123422ed0ad183d510add8f5d3472a16f1e8cb
|
[
"MIT"
] | 12 |
2017-11-15T08:29:03.000Z
|
2021-05-22T04:57:20.000Z
|
cryptoauthlib/python/cryptoauthlib/iface.py
|
PhillyNJ/SAMD21
|
0f123422ed0ad183d510add8f5d3472a16f1e8cb
|
[
"MIT"
] | 2 |
2019-09-22T12:02:07.000Z
|
2021-09-09T22:38:25.000Z
|
cryptoauthlib/python/cryptoauthlib/iface.py
|
PhillyNJ/SAMD21
|
0f123422ed0ad183d510add8f5d3472a16f1e8cb
|
[
"MIT"
] | 5 |
2019-04-05T13:46:44.000Z
|
2020-11-25T08:58:32.000Z
|
from ctypes import Structure, Union, c_uint16, c_int, c_uint8, c_uint32, c_void_p
from .atcab import get_cryptoauthlib
# The following must match atca_iface.h exactly
class _ATCAI2C(Structure):
_fields_ = [('slave_address', c_uint8),
('bus', c_uint8),
('baud', c_uint32)]
class _ATCASWI(Structure):
_fields_ = [('bus', c_uint8)]
class _ATCAUART(Structure):
_fields_ = [('port', c_int),
('baud', c_uint32),
('wordsize', c_uint8),
('parity', c_uint8),
('stopbits', c_uint8)]
class _ATCAHID(Structure):
_fields_ = [('idx', c_int),
('vid', c_uint32),
('pid', c_uint32),
('packetsize', c_uint32),
('guid', c_uint8*16)]
class _ATCACUSTOM(Structure):
_fields_ = [('halinit', c_void_p),
('halpostinit', c_void_p),
('halsend', c_void_p),
('halreceive', c_void_p),
('halwake', c_void_p),
('halidle', c_void_p),
('halsleep', c_void_p),
('halrelease', c_void_p)]
class _ATCAIfaceParams(Union):
_fields_ = [('atcai2c', _ATCAI2C),
('atcaswi', _ATCASWI),
('atcauart', _ATCAUART),
('atcahid', _ATCAHID),
('atcacustom', _ATCACUSTOM)]
class ATCAIfaceCfg(Structure):
_fields_ = [('iface_type', c_int),
('devtype', c_int),
('cfg', _ATCAIfaceParams),
('wake_delay', c_uint16),
('rx_retries', c_int),
('cfg_data', c_void_p)]
# Default configuration for an ECCx08A device on the first logical I2C bus
def cfg_ateccx08a_i2c_default():
return ATCAIfaceCfg.in_dll(get_cryptoauthlib(), 'cfg_ateccx08a_i2c_default')
# Default configuration for an ECCx08A device on the logical SWI bus over UART
def cfg_ateccx08a_swi_default():
return ATCAIfaceCfg.in_dll(get_cryptoauthlib(), 'cfg_ateccx08a_swi_default')
# Default configuration for Kit protocol over a HID interface
def cfg_ateccx08a_kithid_default():
return ATCAIfaceCfg.in_dll(get_cryptoauthlib(), 'cfg_ateccx08a_kithid_default')
# Default configuration for a SHA204A device on the first logical I2C bus
def cfg_atsha204a_i2c_default():
return ATCAIfaceCfg.in_dll(get_cryptoauthlib(), 'cfg_atsha204a_i2c_default')
# Default configuration for an SHA204A device on the logical SWI bus over UART*/
def cfg_atsha204a_swi_default():
return ATCAIfaceCfg.in_dll(get_cryptoauthlib(), 'cfg_atsha204a_swi_default')
# Default configuration for Kit protocol over a HID interface for SHA204
def cfg_atsha204a_kithid_default():
return ATCAIfaceCfg.in_dll(get_cryptoauthlib(), 'cfg_atsha204a_kithid_default')
| 32.215909 | 85 | 0.628219 |
5fc0019c7f91971a70e7e27182e7d804e5736e98
| 308 |
py
|
Python
|
Python/Courses/Python-Tutorials.Telusko/01.Object-Oriented-Programming/11.01-Constructor.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
Python/Courses/Python-Tutorials.Telusko/01.Object-Oriented-Programming/11.01-Constructor.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
Python/Courses/Python-Tutorials.Telusko/01.Object-Oriented-Programming/11.01-Constructor.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
class Computer:
def __init__(self):
self.name = "Shihab"
self.age = 18
def compare(self, other):
return self.age == other.age
c1 = Computer()
c1.age = 30
c2 = Computer()
c1.name = "Rashi"
if c1.compare(c2):
print("They are same")
else:
print("They are not same")
| 15.4 | 36 | 0.587662 |
841a80d5a0a85c6fb523f7bb2f0505a0bd84af24
| 1,068 |
py
|
Python
|
app/cardreader.py
|
openbikebox/websocket-client
|
50b61a70ffcff1acdc13ba69c017e671bd3f983f
|
[
"MIT"
] | null | null | null |
app/cardreader.py
|
openbikebox/websocket-client
|
50b61a70ffcff1acdc13ba69c017e671bd3f983f
|
[
"MIT"
] | null | null | null |
app/cardreader.py
|
openbikebox/websocket-client
|
50b61a70ffcff1acdc13ba69c017e671bd3f983f
|
[
"MIT"
] | null | null | null |
# encoding: utf-8
"""
openbikebox websocket-client
Copyright (c) 2021, binary butterfly GmbH
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
"""
import asyncio
from base64 import b64encode
from .config import Config
from .system import system
class Cardreader:
async def startup(self):
reader, writer = await asyncio.open_connection(Config.CARDREADER_SERVER, Config.CARDREADER_PORT)
socket_reader_task = asyncio.create_task(
self.socket_reader_task(reader)
)
done, pending = await asyncio.wait(
[socket_reader_task],
return_when=asyncio.ALL_COMPLETED,
)
async def socket_reader_task(self, reader):
while True:
try:
message = await reader.readuntil(b'\x90\x00\x00\x00')
except asyncio.IncompleteReadError:
return
if message[0] < 0x70:
continue
system.handle_card('emobility-card', message[0:-4])
cardreader = Cardreader()
| 27.384615 | 104 | 0.650749 |
29d3f788cc3a778223b65045045c05076f12627d
| 1,968 |
py
|
Python
|
showcase1/com/aaron/Hex2BytesExample.py
|
qsunny/python
|
ace8c3178a9a9619de2b60ca242c2079dd2f825e
|
[
"MIT"
] | null | null | null |
showcase1/com/aaron/Hex2BytesExample.py
|
qsunny/python
|
ace8c3178a9a9619de2b60ca242c2079dd2f825e
|
[
"MIT"
] | 2 |
2021-03-25T22:00:07.000Z
|
2022-01-20T15:51:48.000Z
|
showcase1/com/aaron/Hex2BytesExample.py
|
qsunny/python
|
ace8c3178a9a9619de2b60ca242c2079dd2f825e
|
[
"MIT"
] | null | null | null |
# -*- codiing:utf-8 -*-
"""regular expressions example
十进制
to
八进制: oct()
十进制
to
十六进制: hex()
"""
__author__="aaron.qiu"
import re
import binascii
import struct
import string
base = [str(x) for x in range(10)] + [ chr(x) for x in range(ord('A'),ord('A')+6)]
def hexStr2Byte(str):
"""从16进制字符串转byte"""
return bytes.fromhex(str)
def bin2dec(string_num):
"""二进制 to 十进制 : int(str,n=10)"""
return str(int(string_num, 2))
def hex2dec(string_num):
"""十六进制 to 十进制"""
return str(int(string_num.upper(), 16))
def dec2bin(string_num):
"""十进制 to 二进制: bin() """
num = int(string_num)
mid = []
while True:
if num == 0: break
num,rem = divmod(num, 2)
mid.append(base[rem])
return ''.join([str(x) for x in mid[::-1]])
def dec2hex(string_num):
num = int(string_num)
mid = []
while True:
if num == 0: break
num,rem = divmod(num, 16)
mid.append(base[rem])
return ''.join([str(x) for x in mid[::-1]])
def hex2bin(string_num):
return dec2bin(hex2dec(string_num.upper()))
def bin2hex(string_num):
return dec2hex(bin2dec(string_num))
if __name__=="__main__":
str1 = "4F390D0A"
print(bytearray(hex(ord('9')), 'utf-8'))
byte1 = bytearray([3, 4, 5]);
byte2 = bytearray(3)
print(byte1[0])
#a1 = bytes(bytearray(hex(ord('O')), 'utf-8'));
#a2 = bytes(bytearray(hex(ord('9')), 'utf-8'));
#a3 = bytes(bytearray(hex(ord('\r')), 'utf-8'));
#a4 = bytes(bytearray(hex(ord('\n')), 'utf-8'));
a1 = bytearray('4F','utf-8')
a2 = bytearray('39','utf-8')
a3 = bytearray('0D','utf-8')
a4 = bytearray('0A','utf-8')
print( bytes(a1+a2+a3+a4))
print(hexStr2Byte('0A'))
print(hex(int(hex2dec('4F'))).encode("utf-8"))
s = '0x4F'
b = int(s, 16)
print(b)
print('{:#x}'.format(int('0x0A',16)))
print('{:x}'.format(b))
print('{:#x}'.format(b))
print('{:#07x}'.format(b))
print(eval('0x4F'))
| 21.866667 | 82 | 0.567581 |
8a31982fca0c3348f4be5aec725f0de4af24e8ef
| 42,445 |
py
|
Python
|
myems-api/reports/equipmentsaving.py
|
guangyuzhang/myems
|
c88f0620d3e36154a500c755c805333b771d09c0
|
[
"MIT"
] | 82 |
2021-02-19T10:24:31.000Z
|
2022-03-28T06:30:18.000Z
|
myems-api/reports/equipmentsaving.py
|
guangyuzhang/myems
|
c88f0620d3e36154a500c755c805333b771d09c0
|
[
"MIT"
] | 188 |
2021-02-22T07:08:30.000Z
|
2022-03-02T04:11:03.000Z
|
myems-api/reports/equipmentsaving.py
|
guangyuzhang/myems
|
c88f0620d3e36154a500c755c805333b771d09c0
|
[
"MIT"
] | 54 |
2021-02-19T08:48:46.000Z
|
2022-03-30T06:21:34.000Z
|
import falcon
import simplejson as json
import mysql.connector
import config
from datetime import datetime, timedelta, timezone
from core import utilities
from decimal import Decimal
import excelexporters.equipmentsaving
class Reporting:
@staticmethod
def __init__():
""""Initializes Reporting"""
pass
@staticmethod
def on_options(req, resp):
resp.status = falcon.HTTP_200
####################################################################################################################
# PROCEDURES
# Step 1: valid parameters
# Step 2: query the equipment
# Step 3: query energy categories
# Step 4: query associated points
# Step 5: query base period energy saving
# Step 6: query reporting period energy saving
# Step 7: query tariff data
# Step 8: query associated points data
# Step 10: construct the report
####################################################################################################################
@staticmethod
def on_get(req, resp):
print(req.params)
equipment_id = req.params.get('equipmentid')
period_type = req.params.get('periodtype')
base_start_datetime_local = req.params.get('baseperiodstartdatetime')
base_end_datetime_local = req.params.get('baseperiodenddatetime')
reporting_start_datetime_local = req.params.get('reportingperiodstartdatetime')
reporting_end_datetime_local = req.params.get('reportingperiodenddatetime')
################################################################################################################
# Step 1: valid parameters
################################################################################################################
if equipment_id is None:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_EQUIPMENT_ID')
else:
equipment_id = str.strip(equipment_id)
if not equipment_id.isdigit() or int(equipment_id) <= 0:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_EQUIPMENT_ID')
if period_type is None:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
else:
period_type = str.strip(period_type)
if period_type not in ['hourly', 'daily', 'weekly', 'monthly', 'yearly']:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_PERIOD_TYPE')
timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
if config.utc_offset[0] == '-':
timezone_offset = -timezone_offset
base_start_datetime_utc = None
if base_start_datetime_local is not None and len(str.strip(base_start_datetime_local)) > 0:
base_start_datetime_local = str.strip(base_start_datetime_local)
try:
base_start_datetime_utc = datetime.strptime(base_start_datetime_local,
'%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
timedelta(minutes=timezone_offset)
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_BASE_PERIOD_START_DATETIME")
base_end_datetime_utc = None
if base_end_datetime_local is not None and len(str.strip(base_end_datetime_local)) > 0:
base_end_datetime_local = str.strip(base_end_datetime_local)
try:
base_end_datetime_utc = datetime.strptime(base_end_datetime_local,
'%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
timedelta(minutes=timezone_offset)
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_BASE_PERIOD_END_DATETIME")
if base_start_datetime_utc is not None and base_end_datetime_utc is not None and \
base_start_datetime_utc >= base_end_datetime_utc:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_BASE_PERIOD_END_DATETIME')
if reporting_start_datetime_local is None:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
else:
reporting_start_datetime_local = str.strip(reporting_start_datetime_local)
try:
reporting_start_datetime_utc = datetime.strptime(reporting_start_datetime_local,
'%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
timedelta(minutes=timezone_offset)
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_REPORTING_PERIOD_START_DATETIME")
if reporting_end_datetime_local is None:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
else:
reporting_end_datetime_local = str.strip(reporting_end_datetime_local)
try:
reporting_end_datetime_utc = datetime.strptime(reporting_end_datetime_local,
'%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
timedelta(minutes=timezone_offset)
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description="API.INVALID_REPORTING_PERIOD_END_DATETIME")
if reporting_start_datetime_utc >= reporting_end_datetime_utc:
raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
description='API.INVALID_REPORTING_PERIOD_END_DATETIME')
################################################################################################################
# Step 2: query the equipment
################################################################################################################
cnx_system = mysql.connector.connect(**config.myems_system_db)
cursor_system = cnx_system.cursor()
cnx_energy = mysql.connector.connect(**config.myems_energy_db)
cursor_energy = cnx_energy.cursor()
cnx_energy_baseline = mysql.connector.connect(**config.myems_energy_baseline_db)
cursor_energy_baseline = cnx_energy_baseline.cursor()
cnx_historical = mysql.connector.connect(**config.myems_historical_db)
cursor_historical = cnx_historical.cursor()
cursor_system.execute(" SELECT id, name, cost_center_id "
" FROM tbl_equipments "
" WHERE id = %s ", (equipment_id,))
row_equipment = cursor_system.fetchone()
if row_equipment is None:
if cursor_system:
cursor_system.close()
if cnx_system:
cnx_system.disconnect()
if cursor_energy:
cursor_energy.close()
if cnx_energy:
cnx_energy.disconnect()
if cursor_energy_baseline:
cursor_energy_baseline.close()
if cnx_energy_baseline:
cnx_energy_baseline.disconnect()
if cursor_historical:
cursor_historical.close()
if cnx_historical:
cnx_historical.disconnect()
raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', description='API.EQUIPMENT_NOT_FOUND')
equipment = dict()
equipment['id'] = row_equipment[0]
equipment['name'] = row_equipment[1]
equipment['cost_center_id'] = row_equipment[2]
################################################################################################################
# Step 3: query energy categories
################################################################################################################
energy_category_set = set()
# query energy categories in base period
cursor_energy.execute(" SELECT DISTINCT(energy_category_id) "
" FROM tbl_equipment_input_category_hourly "
" WHERE equipment_id = %s "
" AND start_datetime_utc >= %s "
" AND start_datetime_utc < %s ",
(equipment['id'], base_start_datetime_utc, base_end_datetime_utc))
rows_energy_categories = cursor_energy.fetchall()
if rows_energy_categories is not None or len(rows_energy_categories) > 0:
for row_energy_category in rows_energy_categories:
energy_category_set.add(row_energy_category[0])
# query energy categories in reporting period
cursor_energy.execute(" SELECT DISTINCT(energy_category_id) "
" FROM tbl_equipment_input_category_hourly "
" WHERE equipment_id = %s "
" AND start_datetime_utc >= %s "
" AND start_datetime_utc < %s ",
(equipment['id'], reporting_start_datetime_utc, reporting_end_datetime_utc))
rows_energy_categories = cursor_energy.fetchall()
if rows_energy_categories is not None or len(rows_energy_categories) > 0:
for row_energy_category in rows_energy_categories:
energy_category_set.add(row_energy_category[0])
# query all energy categories in base period and reporting period
cursor_system.execute(" SELECT id, name, unit_of_measure, kgce, kgco2e "
" FROM tbl_energy_categories "
" ORDER BY id ", )
rows_energy_categories = cursor_system.fetchall()
if rows_energy_categories is None or len(rows_energy_categories) == 0:
if cursor_system:
cursor_system.close()
if cnx_system:
cnx_system.disconnect()
if cursor_energy:
cursor_energy.close()
if cnx_energy:
cnx_energy.disconnect()
if cursor_energy_baseline:
cursor_energy_baseline.close()
if cnx_energy_baseline:
cnx_energy_baseline.disconnect()
if cursor_historical:
cursor_historical.close()
if cnx_historical:
cnx_historical.disconnect()
raise falcon.HTTPError(falcon.HTTP_404,
title='API.NOT_FOUND',
description='API.ENERGY_CATEGORY_NOT_FOUND')
energy_category_dict = dict()
for row_energy_category in rows_energy_categories:
if row_energy_category[0] in energy_category_set:
energy_category_dict[row_energy_category[0]] = {"name": row_energy_category[1],
"unit_of_measure": row_energy_category[2],
"kgce": row_energy_category[3],
"kgco2e": row_energy_category[4]}
################################################################################################################
# Step 4: query associated points
################################################################################################################
point_list = list()
cursor_system.execute(" SELECT p.id, ep.name, p.units, p.object_type "
" FROM tbl_equipments e, tbl_equipments_parameters ep, tbl_points p "
" WHERE e.id = %s AND e.id = ep.equipment_id AND ep.parameter_type = 'point' "
" AND ep.point_id = p.id "
" ORDER BY p.id ", (equipment['id'],))
rows_points = cursor_system.fetchall()
if rows_points is not None and len(rows_points) > 0:
for row in rows_points:
point_list.append({"id": row[0], "name": row[1], "units": row[2], "object_type": row[3]})
################################################################################################################
# Step 5: query base period energy saving
################################################################################################################
base = dict()
if energy_category_set is not None and len(energy_category_set) > 0:
for energy_category_id in energy_category_set:
kgce = energy_category_dict[energy_category_id]['kgce']
kgco2e = energy_category_dict[energy_category_id]['kgco2e']
base[energy_category_id] = dict()
base[energy_category_id]['timestamps'] = list()
base[energy_category_id]['values_baseline'] = list()
base[energy_category_id]['values_actual'] = list()
base[energy_category_id]['values_saving'] = list()
base[energy_category_id]['subtotal_baseline'] = Decimal(0.0)
base[energy_category_id]['subtotal_actual'] = Decimal(0.0)
base[energy_category_id]['subtotal_saving'] = Decimal(0.0)
base[energy_category_id]['subtotal_in_kgce_baseline'] = Decimal(0.0)
base[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0)
base[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0)
base[energy_category_id]['subtotal_in_kgco2e_baseline'] = Decimal(0.0)
base[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0)
base[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0)
# query base period's energy baseline
cursor_energy_baseline.execute(" SELECT start_datetime_utc, actual_value "
" FROM tbl_equipment_input_category_hourly "
" WHERE equipment_id = %s "
" AND energy_category_id = %s "
" AND start_datetime_utc >= %s "
" AND start_datetime_utc < %s "
" ORDER BY start_datetime_utc ",
(equipment['id'],
energy_category_id,
base_start_datetime_utc,
base_end_datetime_utc))
rows_equipment_hourly = cursor_energy_baseline.fetchall()
rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly,
base_start_datetime_utc,
base_end_datetime_utc,
period_type)
for row_equipment_periodically in rows_equipment_periodically:
current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \
timedelta(minutes=timezone_offset)
if period_type == 'hourly':
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
elif period_type == 'daily':
current_datetime = current_datetime_local.strftime('%Y-%m-%d')
elif period_type == 'weekly':
current_datetime = current_datetime_local.strftime('%Y-%m-%d')
elif period_type == 'monthly':
current_datetime = current_datetime_local.strftime('%Y-%m')
elif period_type == 'yearly':
current_datetime = current_datetime_local.strftime('%Y')
baseline_value = Decimal(0.0) if row_equipment_periodically[1] is None \
else row_equipment_periodically[1]
base[energy_category_id]['timestamps'].append(current_datetime)
base[energy_category_id]['values_baseline'].append(baseline_value)
base[energy_category_id]['subtotal_baseline'] += baseline_value
base[energy_category_id]['subtotal_in_kgce_baseline'] += baseline_value * kgce
base[energy_category_id]['subtotal_in_kgco2e_baseline'] += baseline_value * kgco2e
# query base period's energy actual
cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
" FROM tbl_equipment_input_category_hourly "
" WHERE equipment_id = %s "
" AND energy_category_id = %s "
" AND start_datetime_utc >= %s "
" AND start_datetime_utc < %s "
" ORDER BY start_datetime_utc ",
(equipment['id'],
energy_category_id,
base_start_datetime_utc,
base_end_datetime_utc))
rows_equipment_hourly = cursor_energy.fetchall()
rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly,
base_start_datetime_utc,
base_end_datetime_utc,
period_type)
for row_equipment_periodically in rows_equipment_periodically:
current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \
timedelta(minutes=timezone_offset)
if period_type == 'hourly':
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
elif period_type == 'daily':
current_datetime = current_datetime_local.strftime('%Y-%m-%d')
elif period_type == 'weekly':
current_datetime = current_datetime_local.strftime('%Y-%m-%d')
elif period_type == 'monthly':
current_datetime = current_datetime_local.strftime('%Y-%m')
elif period_type == 'yearly':
current_datetime = current_datetime_local.strftime('%Y')
actual_value = Decimal(0.0) if row_equipment_periodically[1] is None \
else row_equipment_periodically[1]
base[energy_category_id]['values_actual'].append(actual_value)
base[energy_category_id]['subtotal_actual'] += actual_value
base[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce
base[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e
# calculate base period's energy savings
for i in range(len(base[energy_category_id]['values_baseline'])):
base[energy_category_id]['values_saving'].append(
base[energy_category_id]['values_baseline'][i] -
base[energy_category_id]['values_actual'][i])
base[energy_category_id]['subtotal_saving'] = \
base[energy_category_id]['subtotal_baseline'] - \
base[energy_category_id]['subtotal_actual']
base[energy_category_id]['subtotal_in_kgce_saving'] = \
base[energy_category_id]['subtotal_in_kgce_baseline'] - \
base[energy_category_id]['subtotal_in_kgce_actual']
base[energy_category_id]['subtotal_in_kgco2e_saving'] = \
base[energy_category_id]['subtotal_in_kgco2e_baseline'] - \
base[energy_category_id]['subtotal_in_kgco2e_actual']
################################################################################################################
# Step 5: query reporting period energy saving
################################################################################################################
reporting = dict()
if energy_category_set is not None and len(energy_category_set) > 0:
for energy_category_id in energy_category_set:
kgce = energy_category_dict[energy_category_id]['kgce']
kgco2e = energy_category_dict[energy_category_id]['kgco2e']
reporting[energy_category_id] = dict()
reporting[energy_category_id]['timestamps'] = list()
reporting[energy_category_id]['values_baseline'] = list()
reporting[energy_category_id]['values_actual'] = list()
reporting[energy_category_id]['values_saving'] = list()
reporting[energy_category_id]['subtotal_baseline'] = Decimal(0.0)
reporting[energy_category_id]['subtotal_actual'] = Decimal(0.0)
reporting[energy_category_id]['subtotal_saving'] = Decimal(0.0)
reporting[energy_category_id]['subtotal_in_kgce_baseline'] = Decimal(0.0)
reporting[energy_category_id]['subtotal_in_kgce_actual'] = Decimal(0.0)
reporting[energy_category_id]['subtotal_in_kgce_saving'] = Decimal(0.0)
reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] = Decimal(0.0)
reporting[energy_category_id]['subtotal_in_kgco2e_actual'] = Decimal(0.0)
reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = Decimal(0.0)
# query reporting period's energy baseline
cursor_energy_baseline.execute(" SELECT start_datetime_utc, actual_value "
" FROM tbl_equipment_input_category_hourly "
" WHERE equipment_id = %s "
" AND energy_category_id = %s "
" AND start_datetime_utc >= %s "
" AND start_datetime_utc < %s "
" ORDER BY start_datetime_utc ",
(equipment['id'],
energy_category_id,
reporting_start_datetime_utc,
reporting_end_datetime_utc))
rows_equipment_hourly = cursor_energy_baseline.fetchall()
rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly,
reporting_start_datetime_utc,
reporting_end_datetime_utc,
period_type)
for row_equipment_periodically in rows_equipment_periodically:
current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \
timedelta(minutes=timezone_offset)
if period_type == 'hourly':
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
elif period_type == 'daily':
current_datetime = current_datetime_local.strftime('%Y-%m-%d')
elif period_type == 'weekly':
current_datetime = current_datetime_local.strftime('%Y-%m-%d')
elif period_type == 'monthly':
current_datetime = current_datetime_local.strftime('%Y-%m')
elif period_type == 'yearly':
current_datetime = current_datetime_local.strftime('%Y')
baseline_value = Decimal(0.0) if row_equipment_periodically[1] is None \
else row_equipment_periodically[1]
reporting[energy_category_id]['timestamps'].append(current_datetime)
reporting[energy_category_id]['values_baseline'].append(baseline_value)
reporting[energy_category_id]['subtotal_baseline'] += baseline_value
reporting[energy_category_id]['subtotal_in_kgce_baseline'] += baseline_value * kgce
reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] += baseline_value * kgco2e
# query reporting period's energy actual
cursor_energy.execute(" SELECT start_datetime_utc, actual_value "
" FROM tbl_equipment_input_category_hourly "
" WHERE equipment_id = %s "
" AND energy_category_id = %s "
" AND start_datetime_utc >= %s "
" AND start_datetime_utc < %s "
" ORDER BY start_datetime_utc ",
(equipment['id'],
energy_category_id,
reporting_start_datetime_utc,
reporting_end_datetime_utc))
rows_equipment_hourly = cursor_energy.fetchall()
rows_equipment_periodically = utilities.aggregate_hourly_data_by_period(rows_equipment_hourly,
reporting_start_datetime_utc,
reporting_end_datetime_utc,
period_type)
for row_equipment_periodically in rows_equipment_periodically:
current_datetime_local = row_equipment_periodically[0].replace(tzinfo=timezone.utc) + \
timedelta(minutes=timezone_offset)
if period_type == 'hourly':
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
elif period_type == 'daily':
current_datetime = current_datetime_local.strftime('%Y-%m-%d')
elif period_type == 'weekly':
current_datetime = current_datetime_local.strftime('%Y-%m-%d')
elif period_type == 'monthly':
current_datetime = current_datetime_local.strftime('%Y-%m')
elif period_type == 'yearly':
current_datetime = current_datetime_local.strftime('%Y')
actual_value = Decimal(0.0) if row_equipment_periodically[1] is None \
else row_equipment_periodically[1]
reporting[energy_category_id]['values_actual'].append(actual_value)
reporting[energy_category_id]['subtotal_actual'] += actual_value
reporting[energy_category_id]['subtotal_in_kgce_actual'] += actual_value * kgce
reporting[energy_category_id]['subtotal_in_kgco2e_actual'] += actual_value * kgco2e
# calculate reporting period's energy savings
for i in range(len(reporting[energy_category_id]['values_baseline'])):
reporting[energy_category_id]['values_saving'].append(
reporting[energy_category_id]['values_baseline'][i] -
reporting[energy_category_id]['values_actual'][i])
reporting[energy_category_id]['subtotal_saving'] = \
reporting[energy_category_id]['subtotal_baseline'] - \
reporting[energy_category_id]['subtotal_actual']
reporting[energy_category_id]['subtotal_in_kgce_saving'] = \
reporting[energy_category_id]['subtotal_in_kgce_baseline'] - \
reporting[energy_category_id]['subtotal_in_kgce_actual']
reporting[energy_category_id]['subtotal_in_kgco2e_saving'] = \
reporting[energy_category_id]['subtotal_in_kgco2e_baseline'] - \
reporting[energy_category_id]['subtotal_in_kgco2e_actual']
################################################################################################################
# Step 6: query tariff data
################################################################################################################
parameters_data = dict()
parameters_data['names'] = list()
parameters_data['timestamps'] = list()
parameters_data['values'] = list()
if energy_category_set is not None and len(energy_category_set) > 0:
for energy_category_id in energy_category_set:
energy_category_tariff_dict = utilities.get_energy_category_tariffs(equipment['cost_center_id'],
energy_category_id,
reporting_start_datetime_utc,
reporting_end_datetime_utc)
tariff_timestamp_list = list()
tariff_value_list = list()
for k, v in energy_category_tariff_dict.items():
# convert k from utc to local
k = k + timedelta(minutes=timezone_offset)
tariff_timestamp_list.append(k.isoformat()[0:19][0:19])
tariff_value_list.append(v)
parameters_data['names'].append('TARIFF-' + energy_category_dict[energy_category_id]['name'])
parameters_data['timestamps'].append(tariff_timestamp_list)
parameters_data['values'].append(tariff_value_list)
################################################################################################################
# Step 7: query associated points data
################################################################################################################
for point in point_list:
point_values = []
point_timestamps = []
if point['object_type'] == 'ANALOG_VALUE':
query = (" SELECT utc_date_time, actual_value "
" FROM tbl_analog_value "
" WHERE point_id = %s "
" AND utc_date_time BETWEEN %s AND %s "
" ORDER BY utc_date_time ")
cursor_historical.execute(query, (point['id'],
reporting_start_datetime_utc,
reporting_end_datetime_utc))
rows = cursor_historical.fetchall()
if rows is not None and len(rows) > 0:
for row in rows:
current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
timedelta(minutes=timezone_offset)
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
point_timestamps.append(current_datetime)
point_values.append(row[1])
elif point['object_type'] == 'ENERGY_VALUE':
query = (" SELECT utc_date_time, actual_value "
" FROM tbl_energy_value "
" WHERE point_id = %s "
" AND utc_date_time BETWEEN %s AND %s "
" ORDER BY utc_date_time ")
cursor_historical.execute(query, (point['id'],
reporting_start_datetime_utc,
reporting_end_datetime_utc))
rows = cursor_historical.fetchall()
if rows is not None and len(rows) > 0:
for row in rows:
current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
timedelta(minutes=timezone_offset)
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
point_timestamps.append(current_datetime)
point_values.append(row[1])
elif point['object_type'] == 'DIGITAL_VALUE':
query = (" SELECT utc_date_time, actual_value "
" FROM tbl_digital_value "
" WHERE point_id = %s "
" AND utc_date_time BETWEEN %s AND %s "
" ORDER BY utc_date_time ")
cursor_historical.execute(query, (point['id'],
reporting_start_datetime_utc,
reporting_end_datetime_utc))
rows = cursor_historical.fetchall()
if rows is not None and len(rows) > 0:
for row in rows:
current_datetime_local = row[0].replace(tzinfo=timezone.utc) + \
timedelta(minutes=timezone_offset)
current_datetime = current_datetime_local.strftime('%Y-%m-%dT%H:%M:%S')
point_timestamps.append(current_datetime)
point_values.append(row[1])
parameters_data['names'].append(point['name'] + ' (' + point['units'] + ')')
parameters_data['timestamps'].append(point_timestamps)
parameters_data['values'].append(point_values)
################################################################################################################
# Step 8: construct the report
################################################################################################################
if cursor_system:
cursor_system.close()
if cnx_system:
cnx_system.disconnect()
if cursor_energy:
cursor_energy.close()
if cnx_energy:
cnx_energy.disconnect()
if cursor_energy_baseline:
cursor_energy_baseline.close()
if cnx_energy_baseline:
cnx_energy_baseline.disconnect()
if cursor_historical:
cursor_historical.close()
if cnx_historical:
cnx_historical.disconnect()
result = dict()
result['equipment'] = dict()
result['equipment']['name'] = equipment['name']
result['base_period'] = dict()
result['base_period']['names'] = list()
result['base_period']['units'] = list()
result['base_period']['timestamps'] = list()
result['base_period']['values_saving'] = list()
result['base_period']['subtotals_saving'] = list()
result['base_period']['subtotals_in_kgce_saving'] = list()
result['base_period']['subtotals_in_kgco2e_saving'] = list()
result['base_period']['total_in_kgce_saving'] = Decimal(0.0)
result['base_period']['total_in_kgco2e_saving'] = Decimal(0.0)
if energy_category_set is not None and len(energy_category_set) > 0:
for energy_category_id in energy_category_set:
result['base_period']['names'].append(energy_category_dict[energy_category_id]['name'])
result['base_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure'])
result['base_period']['timestamps'].append(base[energy_category_id]['timestamps'])
result['base_period']['values_saving'].append(base[energy_category_id]['values_saving'])
result['base_period']['subtotals_saving'].append(base[energy_category_id]['subtotal_saving'])
result['base_period']['subtotals_in_kgce_saving'].append(
base[energy_category_id]['subtotal_in_kgce_saving'])
result['base_period']['subtotals_in_kgco2e_saving'].append(
base[energy_category_id]['subtotal_in_kgco2e_saving'])
result['base_period']['total_in_kgce_saving'] += base[energy_category_id]['subtotal_in_kgce_saving']
result['base_period']['total_in_kgco2e_saving'] += base[energy_category_id]['subtotal_in_kgco2e_saving']
result['reporting_period'] = dict()
result['reporting_period']['names'] = list()
result['reporting_period']['energy_category_ids'] = list()
result['reporting_period']['units'] = list()
result['reporting_period']['timestamps'] = list()
result['reporting_period']['values_saving'] = list()
result['reporting_period']['subtotals_saving'] = list()
result['reporting_period']['subtotals_in_kgce_saving'] = list()
result['reporting_period']['subtotals_in_kgco2e_saving'] = list()
result['reporting_period']['increment_rates_saving'] = list()
result['reporting_period']['total_in_kgce_saving'] = Decimal(0.0)
result['reporting_period']['total_in_kgco2e_saving'] = Decimal(0.0)
result['reporting_period']['increment_rate_in_kgce_saving'] = Decimal(0.0)
result['reporting_period']['increment_rate_in_kgco2e_saving'] = Decimal(0.0)
if energy_category_set is not None and len(energy_category_set) > 0:
for energy_category_id in energy_category_set:
result['reporting_period']['names'].append(energy_category_dict[energy_category_id]['name'])
result['reporting_period']['energy_category_ids'].append(energy_category_id)
result['reporting_period']['units'].append(energy_category_dict[energy_category_id]['unit_of_measure'])
result['reporting_period']['timestamps'].append(reporting[energy_category_id]['timestamps'])
result['reporting_period']['values_saving'].append(reporting[energy_category_id]['values_saving'])
result['reporting_period']['subtotals_saving'].append(reporting[energy_category_id]['subtotal_saving'])
result['reporting_period']['subtotals_in_kgce_saving'].append(
reporting[energy_category_id]['subtotal_in_kgce_saving'])
result['reporting_period']['subtotals_in_kgco2e_saving'].append(
reporting[energy_category_id]['subtotal_in_kgco2e_saving'])
result['reporting_period']['increment_rates_saving'].append(
(reporting[energy_category_id]['subtotal_saving'] - base[energy_category_id]['subtotal_saving']) /
base[energy_category_id]['subtotal_saving']
if base[energy_category_id]['subtotal_saving'] > 0.0 else None)
result['reporting_period']['total_in_kgce_saving'] += \
reporting[energy_category_id]['subtotal_in_kgce_saving']
result['reporting_period']['total_in_kgco2e_saving'] += \
reporting[energy_category_id]['subtotal_in_kgco2e_saving']
result['reporting_period']['increment_rate_in_kgce_saving'] = \
(result['reporting_period']['total_in_kgce_saving'] - result['base_period']['total_in_kgce_saving']) / \
result['base_period']['total_in_kgce_saving'] \
if result['base_period']['total_in_kgce_saving'] > Decimal(0.0) else None
result['reporting_period']['increment_rate_in_kgco2e_saving'] = \
(result['reporting_period']['total_in_kgco2e_saving'] - result['base_period']['total_in_kgco2e_saving']) / \
result['base_period']['total_in_kgco2e_saving'] \
if result['base_period']['total_in_kgco2e_saving'] > Decimal(0.0) else None
result['parameters'] = {
"names": parameters_data['names'],
"timestamps": parameters_data['timestamps'],
"values": parameters_data['values']
}
# export result to Excel file and then encode the file to base64 string
result['excel_bytes_base64'] = excelexporters.equipmentsaving.export(result,
equipment['name'],
reporting_start_datetime_local,
reporting_end_datetime_local,
period_type)
resp.text = json.dumps(result)
| 62.23607 | 120 | 0.523972 |
8a95719e5030328913d27fe4f88e2c358b35f8e6
| 3,426 |
py
|
Python
|
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/vultr_os_info.py
|
tr3ck3r/linklight
|
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
|
[
"MIT"
] | null | null | null |
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/vultr_os_info.py
|
tr3ck3r/linklight
|
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
|
[
"MIT"
] | null | null | null |
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/vultr_os_info.py
|
tr3ck3r/linklight
|
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
|
[
"MIT"
] | null | null | null |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018, Yanis Guenane <[email protected]>
# Copyright (c) 2019, René Moser <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: vultr_os_info
short_description: Get information about the Vultr OSes available.
description:
- Get infos about OSes available to boot servers.
author:
- "Yanis Guenane (@Spredzy)"
- "René Moser (@resmo)"
extends_documentation_fragment:
- community.general.vultr
'''
EXAMPLES = r'''
- name: Get Vultr OSes infos
vultr_os_info:
register: results
- name: Print the gathered infos
debug:
var: results.vultr_os_info
'''
RETURN = r'''
---
vultr_api:
description: Response from Vultr API with a few additions/modification
returned: success
type: complex
contains:
api_account:
description: Account used in the ini file to select the key
returned: success
type: str
sample: default
api_timeout:
description: Timeout used for the API requests
returned: success
type: int
sample: 60
api_retries:
description: Amount of max retries for the API requests
returned: success
type: int
sample: 5
api_retry_max_delay:
description: Exponential backoff delay in seconds between retries up to this max delay value.
returned: success
type: int
sample: 12
version_added: '2.9'
api_endpoint:
description: Endpoint used for the API requests
returned: success
type: str
sample: "https://api.vultr.com"
vultr_os_info:
description: Response from Vultr API as list
returned: available
type: complex
contains:
arch:
description: OS Architecture
returned: success
type: str
sample: x64
family:
description: OS family
returned: success
type: str
sample: openbsd
name:
description: OS name
returned: success
type: str
sample: OpenBSD 6 x64
windows:
description: OS is a MS Windows
returned: success
type: bool
'''
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.general.plugins.module_utils.vultr import (
Vultr,
vultr_argument_spec,
)
class AnsibleVultrOSInfo(Vultr):
def __init__(self, module):
super(AnsibleVultrOSInfo, self).__init__(module, "vultr_os_info")
self.returns = {
"OSID": dict(key='id', convert_to='int'),
"arch": dict(),
"family": dict(),
"name": dict(),
"windows": dict(convert_to='bool')
}
def get_oses(self):
return self.api_query(path="/v1/os/list")
def parse_oses_list(oses_list):
return [os for id, os in oses_list.items()]
def main():
argument_spec = vultr_argument_spec()
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
)
os_info = AnsibleVultrOSInfo(module)
result = os_info.get_result(parse_oses_list(os_info.get_oses()))
module.exit_json(**result)
if __name__ == '__main__':
main()
| 24.297872 | 99 | 0.659078 |
6adffe44dff1653fe7a821e33246e6d34f3ab867
| 7,762 |
py
|
Python
|
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/os_port_info.py
|
tr3ck3r/linklight
|
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
|
[
"MIT"
] | null | null | null |
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/os_port_info.py
|
tr3ck3r/linklight
|
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
|
[
"MIT"
] | null | null | null |
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/os_port_info.py
|
tr3ck3r/linklight
|
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
|
[
"MIT"
] | null | null | null |
#!/usr/bin/python
# Copyright (c) 2016 IBM
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: os_port_info
short_description: Retrieve information about ports within OpenStack.
author: "David Shrewsbury (@Shrews)"
description:
- Retrieve information about ports from OpenStack.
- This module was called C(os_port_facts) before Ansible 2.9, returning C(ansible_facts).
Note that the M(os_port_info) module no longer returns C(ansible_facts)!
requirements:
- "python >= 2.7"
- "openstacksdk"
options:
port:
description:
- Unique name or ID of a port.
filters:
description:
- A dictionary of meta data to use for further filtering. Elements
of this dictionary will be matched against the returned port
dictionaries. Matching is currently limited to strings within
the port dictionary, or strings within nested dictionaries.
availability_zone:
description:
- Ignored. Present for backwards compatibility
extends_documentation_fragment:
- openstack.cloud.openstack
'''
EXAMPLES = '''
# Gather information about all ports
- os_port_info:
cloud: mycloud
register: result
- debug:
msg: "{{ result.openstack_ports }}"
# Gather information about a single port
- os_port_info:
cloud: mycloud
port: 6140317d-e676-31e1-8a4a-b1913814a471
# Gather information about all ports that have device_id set to a specific value
# and with a status of ACTIVE.
- os_port_info:
cloud: mycloud
filters:
device_id: 1038a010-3a37-4a9d-82ea-652f1da36597
status: ACTIVE
'''
RETURN = '''
openstack_ports:
description: List of port dictionaries. A subset of the dictionary keys
listed below may be returned, depending on your cloud provider.
returned: always, but can be null
type: complex
contains:
admin_state_up:
description: The administrative state of the router, which is
up (true) or down (false).
returned: success
type: bool
sample: true
allowed_address_pairs:
description: A set of zero or more allowed address pairs. An
address pair consists of an IP address and MAC address.
returned: success
type: list
sample: []
"binding:host_id":
description: The UUID of the host where the port is allocated.
returned: success
type: str
sample: "b4bd682d-234a-4091-aa5b-4b025a6a7759"
"binding:profile":
description: A dictionary the enables the application running on
the host to pass and receive VIF port-specific
information to the plug-in.
returned: success
type: dict
sample: {}
"binding:vif_details":
description: A dictionary that enables the application to pass
information about functions that the Networking API
provides.
returned: success
type: dict
sample: {"port_filter": true}
"binding:vif_type":
description: The VIF type for the port.
returned: success
type: dict
sample: "ovs"
"binding:vnic_type":
description: The virtual network interface card (vNIC) type that is
bound to the neutron port.
returned: success
type: str
sample: "normal"
device_id:
description: The UUID of the device that uses this port.
returned: success
type: str
sample: "b4bd682d-234a-4091-aa5b-4b025a6a7759"
device_owner:
description: The UUID of the entity that uses this port.
returned: success
type: str
sample: "network:router_interface"
dns_assignment:
description: DNS assignment information.
returned: success
type: list
dns_name:
description: DNS name
returned: success
type: str
sample: ""
extra_dhcp_opts:
description: A set of zero or more extra DHCP option pairs.
An option pair consists of an option value and name.
returned: success
type: list
sample: []
fixed_ips:
description: The IP addresses for the port. Includes the IP address
and UUID of the subnet.
returned: success
type: list
id:
description: The UUID of the port.
returned: success
type: str
sample: "3ec25c97-7052-4ab8-a8ba-92faf84148de"
ip_address:
description: The IP address.
returned: success
type: str
sample: "127.0.0.1"
mac_address:
description: The MAC address.
returned: success
type: str
sample: "00:00:5E:00:53:42"
name:
description: The port name.
returned: success
type: str
sample: "port_name"
network_id:
description: The UUID of the attached network.
returned: success
type: str
sample: "dd1ede4f-3952-4131-aab6-3b8902268c7d"
port_security_enabled:
description: The port security status. The status is enabled (true) or disabled (false).
returned: success
type: bool
sample: false
security_groups:
description: The UUIDs of any attached security groups.
returned: success
type: list
status:
description: The port status.
returned: success
type: str
sample: "ACTIVE"
tenant_id:
description: The UUID of the tenant who owns the network.
returned: success
type: str
sample: "51fce036d7984ba6af4f6c849f65ef00"
'''
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.openstack.cloud.plugins.module_utils.openstack import openstack_full_argument_spec, openstack_module_kwargs, openstack_cloud_from_module
def main():
argument_spec = openstack_full_argument_spec(
port=dict(required=False),
filters=dict(type='dict', required=False),
)
module_kwargs = openstack_module_kwargs()
module = AnsibleModule(argument_spec, **module_kwargs)
is_old_facts = module._name == 'os_port_facts'
if is_old_facts:
module.deprecate("The 'os_port_facts' module has been renamed to 'os_port_info', "
"and the renamed one no longer returns ansible_facts", version='2.13')
port = module.params.get('port')
filters = module.params.get('filters')
sdk, cloud = openstack_cloud_from_module(module)
try:
ports = cloud.search_ports(port, filters)
if is_old_facts:
module.exit_json(changed=False, ansible_facts=dict(
openstack_ports=ports))
else:
module.exit_json(changed=False, openstack_ports=ports)
except sdk.exceptions.OpenStackCloudException as e:
module.fail_json(msg=str(e))
if __name__ == '__main__':
main()
| 34.345133 | 161 | 0.604097 |
6aee1f114938d88fc3386903948be863baf8fe4e
| 5,780 |
py
|
Python
|
tests/nlu/extractors/test_crf_entity_extractor.py
|
chaneyjd/rasa
|
104a9591fc10b96eaa7fe402b6d64ca652b7ebe2
|
[
"Apache-2.0"
] | 37 |
2019-06-07T07:39:00.000Z
|
2022-01-27T08:32:57.000Z
|
tests/nlu/extractors/test_crf_entity_extractor.py
|
chaneyjd/rasa
|
104a9591fc10b96eaa7fe402b6d64ca652b7ebe2
|
[
"Apache-2.0"
] | 209 |
2020-03-18T18:28:12.000Z
|
2022-03-01T13:42:29.000Z
|
tests/nlu/extractors/test_crf_entity_extractor.py
|
chaneyjd/rasa
|
104a9591fc10b96eaa7fe402b6d64ca652b7ebe2
|
[
"Apache-2.0"
] | 65 |
2019-05-21T12:16:53.000Z
|
2022-02-23T10:54:15.000Z
|
from pathlib import Path
from typing import Dict, Text, List, Any
import pytest
from rasa.nlu.components import ComponentBuilder
from rasa.nlu import train
from rasa.nlu.config import RasaNLUModelConfig
from rasa.nlu.model import Interpreter
from rasa.nlu.featurizers.dense_featurizer.spacy_featurizer import SpacyFeaturizer
from rasa.nlu.tokenizers.spacy_tokenizer import SpacyTokenizer
from rasa.nlu.constants import SPACY_DOCS
from rasa.shared.nlu.constants import TEXT, ENTITIES
from rasa.shared.nlu.training_data.message import Message
from rasa.nlu.extractors.crf_entity_extractor import CRFEntityExtractor
def pipeline_from_components(*components: Text) -> List[Dict[Text, Text]]:
return [{"name": c} for c in components]
async def test_train_persist_load_with_composite_entities(
component_builder: ComponentBuilder, tmp_path: Path
):
pipeline = pipeline_from_components("WhitespaceTokenizer", "CRFEntityExtractor")
_config = RasaNLUModelConfig({"pipeline": pipeline, "language": "en"})
(trainer, trained, persisted_path) = await train(
_config,
path=str(tmp_path),
data="data/test/demo-rasa-composite-entities.md",
component_builder=component_builder,
)
assert trainer.pipeline
assert trained.pipeline
loaded = Interpreter.load(persisted_path, component_builder)
assert loaded.pipeline
text = "I am looking for an italian restaurant"
assert loaded.parse(text) == trained.parse(text)
@pytest.mark.parametrize(
"config_params",
[
(
{
"features": [
["low", "title", "upper", "pos", "pos2"],
[
"low",
"suffix3",
"suffix2",
"upper",
"title",
"digit",
"pos",
"pos2",
],
["low", "title", "upper", "pos", "pos2"],
],
"BILOU_flag": False,
}
),
(
{
"features": [
["low", "title", "upper", "pos", "pos2"],
[
"low",
"suffix3",
"suffix2",
"upper",
"title",
"digit",
"pos",
"pos2",
],
["low", "title", "upper", "pos", "pos2"],
],
"BILOU_flag": True,
}
),
],
)
async def test_train_persist_with_different_configurations(
config_params: Dict[Text, Any], component_builder: ComponentBuilder, tmp_path: Path
):
pipeline = pipeline_from_components(
"SpacyNLP", "SpacyTokenizer", "CRFEntityExtractor"
)
assert pipeline[2]["name"] == "CRFEntityExtractor"
pipeline[2].update(config_params)
_config = RasaNLUModelConfig({"pipeline": pipeline, "language": "en"})
(trainer, trained, persisted_path) = await train(
_config,
path=str(tmp_path),
data="data/examples/rasa",
component_builder=component_builder,
)
assert trainer.pipeline
assert trained.pipeline
loaded = Interpreter.load(persisted_path, component_builder)
assert loaded.pipeline
text = "I am looking for an italian restaurant"
assert loaded.parse(text) == trained.parse(text)
detected_entities = loaded.parse(text).get(ENTITIES)
assert len(detected_entities) == 1
assert detected_entities[0]["entity"] == "cuisine"
assert detected_entities[0]["value"] == "italian"
def test_crf_use_dense_features(spacy_nlp: Any):
crf_extractor = CRFEntityExtractor(
component_config={
"features": [
["low", "title", "upper", "pos", "pos2"],
[
"low",
"suffix3",
"suffix2",
"upper",
"title",
"digit",
"pos",
"pos2",
"text_dense_features",
],
["low", "title", "upper", "pos", "pos2"],
]
}
)
spacy_featurizer = SpacyFeaturizer()
spacy_tokenizer = SpacyTokenizer()
text = "Rasa is a company in Berlin"
message = Message(data={TEXT: text})
message.set(SPACY_DOCS[TEXT], spacy_nlp(text))
spacy_tokenizer.process(message)
spacy_featurizer.process(message)
text_data = crf_extractor._convert_to_crf_tokens(message)
features = crf_extractor._crf_tokens_to_features(text_data)
assert "0:text_dense_features" in features[0]
dense_features, _ = message.get_dense_features(TEXT, [])
if dense_features:
dense_features = dense_features.features
for i in range(0, len(dense_features[0])):
assert (
features[0]["0:text_dense_features"]["text_dense_features"][str(i)]
== dense_features[0][i]
)
@pytest.mark.parametrize(
"entity_predictions, expected_label, expected_confidence",
[
([{"O": 0.34, "B-person": 0.03, "I-person": 0.85}], ["I-person"], [0.88]),
([{"O": 0.99, "person": 0.03}], ["O"], [0.99]),
],
)
def test_most_likely_entity(
entity_predictions: List[Dict[Text, float]],
expected_label: Text,
expected_confidence: float,
):
crf_extractor = CRFEntityExtractor({"BILOU_flag": True})
actual_label, actual_confidence = crf_extractor._most_likely_tag(entity_predictions)
assert actual_label == expected_label
assert actual_confidence == expected_confidence
| 30.744681 | 88 | 0.57301 |
7c376704850d31364a9e5a80b3c6ddd4d9278679
| 1,263 |
py
|
Python
|
completion of paratrom.py
|
aertoria/MiscCode
|
a2e94d0fe0890e6620972f84adcb7976ca9f1408
|
[
"Apache-2.0"
] | null | null | null |
completion of paratrom.py
|
aertoria/MiscCode
|
a2e94d0fe0890e6620972f84adcb7976ca9f1408
|
[
"Apache-2.0"
] | null | null | null |
completion of paratrom.py
|
aertoria/MiscCode
|
a2e94d0fe0890e6620972f84adcb7976ca9f1408
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/python
'''
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
'''
class Solution:
# @param {string} s
# @return {string}
def shortestPalindrome(self, s):
self.stringlist=list(s)
self.result=''
self.compare(self.stringlist)
return self.result
def compare(self,string):
if len(string)==0:
return
index = (len(string)+1)/2
indicator = (len(string)+1)%2
#print index,indicator
current=string[:]
if indicator == 1:
#current[:index],current[index:]
part=current[:index]
part.reverse()
if part==current[index:]:
remove = 2*len(current[:index])
completion = self.stringlist[remove:]
completion.reverse()
self.result=''.join(completion+self.stringlist)
return
else:
#print current[:index-1],current[index:]
part=current[:index-1]
part.reverse()
if part==current[index:]:
remove = 2*len(current[:index-1])+1
completion = self.stringlist[remove:]
completion.reverse()
self.result=''.join(completion+self.stringlist)
return
#This run didn't found any
self.compare(current[:-1])
s=Solution()
string='abababababaaaaabbbbbababababab'
print s.shortestPalindrome(string)
#print s.shortestPalindrome(st)#remvoed an a dcbabcd dcbabcd
| 22.157895 | 60 | 0.676168 |
86a77d0c6ae35ab97b77056b41654bec1444158c
| 56 |
py
|
Python
|
tests/test_arena.py
|
python-upskill/levelup
|
89655a560b83956e4d696914907158177ce47c1e
|
[
"BSD-3-Clause"
] | 1 |
2020-04-24T05:47:20.000Z
|
2020-04-24T05:47:20.000Z
|
tests/test_arena.py
|
radowit/levelup
|
89655a560b83956e4d696914907158177ce47c1e
|
[
"BSD-3-Clause"
] | 7 |
2020-04-27T16:16:05.000Z
|
2020-04-28T13:46:21.000Z
|
tests/test_arena.py
|
radowit/levelup
|
89655a560b83956e4d696914907158177ce47c1e
|
[
"BSD-3-Clause"
] | null | null | null |
import arena
def test_dummy():
assert arena.WORKS
| 9.333333 | 22 | 0.714286 |
71f918b790a450575acb17dd742b2aa179831105
| 203 |
py
|
Python
|
MainProject/MainApp/views.py
|
DarishkaAMS/Django_Projects-Django_Food_Delivery_App
|
2a1014c05ca628ba6bd9aefd2aae307e9d95c5c2
|
[
"MIT"
] | null | null | null |
MainProject/MainApp/views.py
|
DarishkaAMS/Django_Projects-Django_Food_Delivery_App
|
2a1014c05ca628ba6bd9aefd2aae307e9d95c5c2
|
[
"MIT"
] | null | null | null |
MainProject/MainApp/views.py
|
DarishkaAMS/Django_Projects-Django_Food_Delivery_App
|
2a1014c05ca628ba6bd9aefd2aae307e9d95c5c2
|
[
"MIT"
] | null | null | null |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home_page_view(request):
template = 'MainApp/index.html'
return render(request, template)
| 22.555556 | 36 | 0.773399 |
92ef405304c388a3551077edbd2a4a95179b5450
| 15,443 |
py
|
Python
|
Contrib-Inspur/openbmc/poky/bitbake/lib/bb/data.py
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 5 |
2019-11-11T07:57:26.000Z
|
2022-03-28T08:26:53.000Z
|
Contrib-Inspur/openbmc/poky/bitbake/lib/bb/data.py
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 3 |
2019-09-05T21:47:07.000Z
|
2019-09-17T18:10:45.000Z
|
Contrib-Inspur/openbmc/poky/bitbake/lib/bb/data.py
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 11 |
2019-07-20T00:16:32.000Z
|
2022-01-11T14:17:48.000Z
|
"""
BitBake 'Data' implementations
Functions for interacting with the data structure used by the
BitBake build tools.
The expandKeys and update_data are the most expensive
operations. At night the cookie monster came by and
suggested 'give me cookies on setting the variables and
things will work out'. Taking this suggestion into account
applying the skills from the not yet passed 'Entwurf und
Analyse von Algorithmen' lecture and the cookie
monster seems to be right. We will track setVar more carefully
to have faster update_data and expandKeys operations.
This is a trade-off between speed and memory again but
the speed is more critical here.
"""
# Copyright (C) 2003, 2004 Chris Larson
# Copyright (C) 2005 Holger Hans Peter Freyther
#
# SPDX-License-Identifier: GPL-2.0-only
#
# Based on functions from the base bb module, Copyright 2003 Holger Schurig
import sys, os, re
import hashlib
if sys.argv[0][-5:] == "pydoc":
path = os.path.dirname(os.path.dirname(sys.argv[1]))
else:
path = os.path.dirname(os.path.dirname(sys.argv[0]))
sys.path.insert(0, path)
from itertools import groupby
from bb import data_smart
from bb import codeparser
import bb
logger = data_smart.logger
_dict_type = data_smart.DataSmart
def init():
"""Return a new object representing the Bitbake data"""
return _dict_type()
def init_db(parent = None):
"""Return a new object representing the Bitbake data,
optionally based on an existing object"""
if parent is not None:
return parent.createCopy()
else:
return _dict_type()
def createCopy(source):
"""Link the source set to the destination
If one does not find the value in the destination set,
search will go on to the source set to get the value.
Value from source are copy-on-write. i.e. any try to
modify one of them will end up putting the modified value
in the destination set.
"""
return source.createCopy()
def initVar(var, d):
"""Non-destructive var init for data structure"""
d.initVar(var)
def keys(d):
"""Return a list of keys in d"""
return d.keys()
__expand_var_regexp__ = re.compile(r"\${[^{}]+}")
__expand_python_regexp__ = re.compile(r"\${@.+?}")
def expand(s, d, varname = None):
"""Variable expansion using the data store"""
return d.expand(s, varname)
def expandKeys(alterdata, readdata = None):
if readdata == None:
readdata = alterdata
todolist = {}
for key in alterdata:
if not '${' in key:
continue
ekey = expand(key, readdata)
if key == ekey:
continue
todolist[key] = ekey
# These two for loops are split for performance to maximise the
# usefulness of the expand cache
for key in sorted(todolist):
ekey = todolist[key]
newval = alterdata.getVar(ekey, False)
if newval is not None:
val = alterdata.getVar(key, False)
if val is not None:
bb.warn("Variable key %s (%s) replaces original key %s (%s)." % (key, val, ekey, newval))
alterdata.renameVar(key, ekey)
def inheritFromOS(d, savedenv, permitted):
"""Inherit variables from the initial environment."""
exportlist = bb.utils.preserved_envvars_exported()
for s in savedenv.keys():
if s in permitted:
try:
d.setVar(s, savedenv.getVar(s), op = 'from env')
if s in exportlist:
d.setVarFlag(s, "export", True, op = 'auto env export')
except TypeError:
pass
def emit_var(var, o=sys.__stdout__, d = init(), all=False):
"""Emit a variable to be sourced by a shell."""
func = d.getVarFlag(var, "func", False)
if d.getVarFlag(var, 'python', False) and func:
return False
export = d.getVarFlag(var, "export", False)
unexport = d.getVarFlag(var, "unexport", False)
if not all and not export and not unexport and not func:
return False
try:
if all:
oval = d.getVar(var, False)
val = d.getVar(var)
except (KeyboardInterrupt, bb.build.FuncFailed):
raise
except Exception as exc:
o.write('# expansion of %s threw %s: %s\n' % (var, exc.__class__.__name__, str(exc)))
return False
if all:
d.varhistory.emit(var, oval, val, o, d)
if (var.find("-") != -1 or var.find(".") != -1 or var.find('{') != -1 or var.find('}') != -1 or var.find('+') != -1) and not all:
return False
varExpanded = d.expand(var)
if unexport:
o.write('unset %s\n' % varExpanded)
return False
if val is None:
return False
val = str(val)
if varExpanded.startswith("BASH_FUNC_"):
varExpanded = varExpanded[10:-2]
val = val[3:] # Strip off "() "
o.write("%s() %s\n" % (varExpanded, val))
o.write("export -f %s\n" % (varExpanded))
return True
if func:
# NOTE: should probably check for unbalanced {} within the var
val = val.rstrip('\n')
o.write("%s() {\n%s\n}\n" % (varExpanded, val))
return 1
if export:
o.write('export ')
# if we're going to output this within doublequotes,
# to a shell, we need to escape the quotes in the var
alter = re.sub('"', '\\"', val)
alter = re.sub('\n', ' \\\n', alter)
alter = re.sub('\\$', '\\\\$', alter)
o.write('%s="%s"\n' % (varExpanded, alter))
return False
def emit_env(o=sys.__stdout__, d = init(), all=False):
"""Emits all items in the data store in a format such that it can be sourced by a shell."""
isfunc = lambda key: bool(d.getVarFlag(key, "func", False))
keys = sorted((key for key in d.keys() if not key.startswith("__")), key=isfunc)
grouped = groupby(keys, isfunc)
for isfunc, keys in grouped:
for key in sorted(keys):
emit_var(key, o, d, all and not isfunc) and o.write('\n')
def exported_keys(d):
return (key for key in d.keys() if not key.startswith('__') and
d.getVarFlag(key, 'export', False) and
not d.getVarFlag(key, 'unexport', False))
def exported_vars(d):
k = list(exported_keys(d))
for key in k:
try:
value = d.getVar(key)
except Exception as err:
bb.warn("%s: Unable to export ${%s}: %s" % (d.getVar("FILE"), key, err))
continue
if value is not None:
yield key, str(value)
def emit_func(func, o=sys.__stdout__, d = init()):
"""Emits all items in the data store in a format such that it can be sourced by a shell."""
keys = (key for key in d.keys() if not key.startswith("__") and not d.getVarFlag(key, "func", False))
for key in sorted(keys):
emit_var(key, o, d, False)
o.write('\n')
emit_var(func, o, d, False) and o.write('\n')
newdeps = bb.codeparser.ShellParser(func, logger).parse_shell(d.getVar(func))
newdeps |= set((d.getVarFlag(func, "vardeps") or "").split())
seen = set()
while newdeps:
deps = newdeps
seen |= deps
newdeps = set()
for dep in deps:
if d.getVarFlag(dep, "func", False) and not d.getVarFlag(dep, "python", False):
emit_var(dep, o, d, False) and o.write('\n')
newdeps |= bb.codeparser.ShellParser(dep, logger).parse_shell(d.getVar(dep))
newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split())
newdeps -= seen
_functionfmt = """
def {function}(d):
{body}"""
def emit_func_python(func, o=sys.__stdout__, d = init()):
"""Emits all items in the data store in a format such that it can be sourced by a shell."""
def write_func(func, o, call = False):
body = d.getVar(func, False)
if not body.startswith("def"):
body = _functionfmt.format(function=func, body=body)
o.write(body.strip() + "\n\n")
if call:
o.write(func + "(d)" + "\n\n")
write_func(func, o, True)
pp = bb.codeparser.PythonParser(func, logger)
pp.parse_python(d.getVar(func, False))
newdeps = pp.execs
newdeps |= set((d.getVarFlag(func, "vardeps") or "").split())
seen = set()
while newdeps:
deps = newdeps
seen |= deps
newdeps = set()
for dep in deps:
if d.getVarFlag(dep, "func", False) and d.getVarFlag(dep, "python", False):
write_func(dep, o)
pp = bb.codeparser.PythonParser(dep, logger)
pp.parse_python(d.getVar(dep, False))
newdeps |= pp.execs
newdeps |= set((d.getVarFlag(dep, "vardeps") or "").split())
newdeps -= seen
def update_data(d):
"""Performs final steps upon the datastore, including application of overrides"""
d.finalize(parent = True)
def build_dependencies(key, keys, shelldeps, varflagsexcl, d):
deps = set()
try:
if key[-1] == ']':
vf = key[:-1].split('[')
value, parser = d.getVarFlag(vf[0], vf[1], False, retparser=True)
deps |= parser.references
deps = deps | (keys & parser.execs)
return deps, value
varflags = d.getVarFlags(key, ["vardeps", "vardepvalue", "vardepsexclude", "exports", "postfuncs", "prefuncs", "lineno", "filename"]) or {}
vardeps = varflags.get("vardeps")
def handle_contains(value, contains, d):
newvalue = ""
for k in sorted(contains):
l = (d.getVar(k) or "").split()
for item in sorted(contains[k]):
for word in item.split():
if not word in l:
newvalue += "\n%s{%s} = Unset" % (k, item)
break
else:
newvalue += "\n%s{%s} = Set" % (k, item)
if not newvalue:
return value
if not value:
return newvalue
return value + newvalue
def handle_remove(value, deps, removes, d):
for r in sorted(removes):
r2 = d.expandWithRefs(r, None)
value += "\n_remove of %s" % r
deps |= r2.references
deps = deps | (keys & r2.execs)
return value
if "vardepvalue" in varflags:
value = varflags.get("vardepvalue")
elif varflags.get("func"):
if varflags.get("python"):
value = d.getVarFlag(key, "_content", False)
parser = bb.codeparser.PythonParser(key, logger)
parser.parse_python(value, filename=varflags.get("filename"), lineno=varflags.get("lineno"))
deps = deps | parser.references
deps = deps | (keys & parser.execs)
value = handle_contains(value, parser.contains, d)
else:
value, parsedvar = d.getVarFlag(key, "_content", False, retparser=True)
parser = bb.codeparser.ShellParser(key, logger)
parser.parse_shell(parsedvar.value)
deps = deps | shelldeps
deps = deps | parsedvar.references
deps = deps | (keys & parser.execs) | (keys & parsedvar.execs)
value = handle_contains(value, parsedvar.contains, d)
if hasattr(parsedvar, "removes"):
value = handle_remove(value, deps, parsedvar.removes, d)
if vardeps is None:
parser.log.flush()
if "prefuncs" in varflags:
deps = deps | set(varflags["prefuncs"].split())
if "postfuncs" in varflags:
deps = deps | set(varflags["postfuncs"].split())
if "exports" in varflags:
deps = deps | set(varflags["exports"].split())
else:
value, parser = d.getVarFlag(key, "_content", False, retparser=True)
deps |= parser.references
deps = deps | (keys & parser.execs)
value = handle_contains(value, parser.contains, d)
if hasattr(parser, "removes"):
value = handle_remove(value, deps, parser.removes, d)
if "vardepvalueexclude" in varflags:
exclude = varflags.get("vardepvalueexclude")
for excl in exclude.split('|'):
if excl:
value = value.replace(excl, '')
# Add varflags, assuming an exclusion list is set
if varflagsexcl:
varfdeps = []
for f in varflags:
if f not in varflagsexcl:
varfdeps.append('%s[%s]' % (key, f))
if varfdeps:
deps |= set(varfdeps)
deps |= set((vardeps or "").split())
deps -= set(varflags.get("vardepsexclude", "").split())
except bb.parse.SkipRecipe:
raise
except Exception as e:
bb.warn("Exception during build_dependencies for %s" % key)
raise
return deps, value
#bb.note("Variable %s references %s and calls %s" % (key, str(deps), str(execs)))
#d.setVarFlag(key, "vardeps", deps)
def generate_dependencies(d):
keys = set(key for key in d if not key.startswith("__"))
shelldeps = set(key for key in d.getVar("__exportlist", False) if d.getVarFlag(key, "export", False) and not d.getVarFlag(key, "unexport", False))
varflagsexcl = d.getVar('BB_SIGNATURE_EXCLUDE_FLAGS')
deps = {}
values = {}
tasklist = d.getVar('__BBTASKS', False) or []
for task in tasklist:
deps[task], values[task] = build_dependencies(task, keys, shelldeps, varflagsexcl, d)
newdeps = deps[task]
seen = set()
while newdeps:
nextdeps = newdeps
seen |= nextdeps
newdeps = set()
for dep in nextdeps:
if dep not in deps:
deps[dep], values[dep] = build_dependencies(dep, keys, shelldeps, varflagsexcl, d)
newdeps |= deps[dep]
newdeps -= seen
#print "For %s: %s" % (task, str(deps[task]))
return tasklist, deps, values
def generate_dependency_hash(tasklist, gendeps, lookupcache, whitelist, fn):
taskdeps = {}
basehash = {}
for task in tasklist:
data = lookupcache[task]
if data is None:
bb.error("Task %s from %s seems to be empty?!" % (task, fn))
data = ''
gendeps[task] -= whitelist
newdeps = gendeps[task]
seen = set()
while newdeps:
nextdeps = newdeps
seen |= nextdeps
newdeps = set()
for dep in nextdeps:
if dep in whitelist:
continue
gendeps[dep] -= whitelist
newdeps |= gendeps[dep]
newdeps -= seen
alldeps = sorted(seen)
for dep in alldeps:
data = data + dep
var = lookupcache[dep]
if var is not None:
data = data + str(var)
k = fn + "." + task
basehash[k] = hashlib.sha256(data.encode("utf-8")).hexdigest()
taskdeps[task] = alldeps
return taskdeps, basehash
def inherits_class(klass, d):
val = d.getVar('__inherit_cache', False) or []
needle = os.path.join('classes', '%s.bbclass' % klass)
for v in val:
if v.endswith(needle):
return True
return False
| 35.257991 | 150 | 0.572751 |
92f2bac8f861981f4072d1fce732e4c8272bed5b
| 154 |
py
|
Python
|
Contests/Ren Ashbell.py
|
MastaCoder/Projects
|
ebb0a3134522b12f052fec8d753005f384adf1b1
|
[
"MIT"
] | 5 |
2018-10-11T01:55:40.000Z
|
2021-12-25T23:38:22.000Z
|
Contests/Ren Ashbell.py
|
MastaCoder/mini_projects
|
ebb0a3134522b12f052fec8d753005f384adf1b1
|
[
"MIT"
] | null | null | null |
Contests/Ren Ashbell.py
|
MastaCoder/mini_projects
|
ebb0a3134522b12f052fec8d753005f384adf1b1
|
[
"MIT"
] | 1 |
2019-02-22T14:42:50.000Z
|
2019-02-22T14:42:50.000Z
|
a = int(input())
c = int(input())
s = True
for b in range(a - 1):
if int(input()) >= c:
s = False
if s:
print("YES")
else:
print("NO")
| 15.4 | 25 | 0.487013 |
135c5686ea5e76d06f234ff8e8a1c26cca052440
| 1,334 |
py
|
Python
|
src/tango_sdp_subarray/tests/conftest.py
|
rtobar/sdp-prototype
|
9f1527b884bf80daa509a7fe3722160c77260f4f
|
[
"BSD-3-Clause"
] | 2 |
2019-07-15T09:49:34.000Z
|
2019-10-14T16:04:17.000Z
|
src/tango_sdp_subarray/tests/conftest.py
|
rtobar/sdp-prototype
|
9f1527b884bf80daa509a7fe3722160c77260f4f
|
[
"BSD-3-Clause"
] | 17 |
2019-07-15T14:51:50.000Z
|
2021-06-02T00:29:43.000Z
|
src/tango_sdp_subarray/tests/conftest.py
|
ska-telescope/sdp-configuration-prototype
|
8c6cbda04a83b0e16987019406ed6ec7e1058a31
|
[
"BSD-3-Clause"
] | 1 |
2019-10-10T08:16:48.000Z
|
2019-10-10T08:16:48.000Z
|
# coding: utf-8
"""Pytest plugins."""
# from unittest.mock import MagicMock
import pytest
from tango.test_context import DeviceTestContext
from SDPSubarray import SDPSubarray
from SDPSubarray.release import VERSION
@pytest.fixture(scope='session', autouse=True)
def tango_context():
"""Fixture that creates SDPSubarray DeviceTestContext object."""
# pylint: disable=redefined-outer-name
# Set default feature toggle values for the test.
# Note: these are ignored if the env variables are already set. ie:
# TOGGLE_CONFIG_DB
# TOGGLE_CBF_OUTPUT_LINK
# Note: if these, or the env variables are not set, use the
# SDPSubarray device defaults.
SDPSubarray.set_feature_toggle_default('config_db', False)
SDPSubarray.set_feature_toggle_default('cbf_output_link', False)
device_name = 'mid_sdp/elt/subarray_1'
properties = dict(Version=VERSION)
tango_context = DeviceTestContext(SDPSubarray,
device_name=device_name,
properties=properties)
print()
print('Starting context...')
tango_context.start()
# SDPSubarray.get_name = MagicMock(
# side_effect=tango_context.get_device_access)
yield tango_context
print('Stopping context...')
tango_context.stop()
| 33.35 | 71 | 0.693403 |
6a37aaa5b88b4d3688165013b44e9a666b13d61a
| 1,520 |
py
|
Python
|
test/test_tag11.py
|
kopp/pyventskalender
|
6f6455f3c1db07f65a772b2716e4be95fbcd1804
|
[
"MIT"
] | null | null | null |
test/test_tag11.py
|
kopp/pyventskalender
|
6f6455f3c1db07f65a772b2716e4be95fbcd1804
|
[
"MIT"
] | null | null | null |
test/test_tag11.py
|
kopp/pyventskalender
|
6f6455f3c1db07f65a772b2716e4be95fbcd1804
|
[
"MIT"
] | null | null | null |
from unittest import TestCase
from unittest.mock import patch, mock_open
try:
from pyventskalender import tag11_loesung as heute
except ImportError:
from pyventskalender import tag11 as heute
class Tag11Tests(TestCase):
def test_10_adressbuch(self):
self.assertIn("Wolfgang", heute.adressbuch)
self.assertEqual(type(heute.adressbuch["Wolfgang"]), list)
self.assertEqual(
heute.adressbuch["Wolfgang"],
["0176 84927413", "07421 39495"],
)
def test_20_extrahiere_gewichte(self):
pseudo_file = mock_open(read_data="""1.11. Herrmann wiegt 72kg
1.11. Caro wiegt 62kg
1.11. Paul wiegt 32kg
2.11. Herrmann wiegt 73kg
2.11. Caro wiegt 60kg
3.11. Herrmann wiegt 71kg
3.11. Caro wiegt 59kg
3.11. Paul wiegt 32kg
4.11. Caro wiegt 60kg
6.11. Caro wiegt 60kg""")
with patch('builtins.open', pseudo_file):
gewichte = heute.extrahiere_gewichte("fake.txt")
self.assertEqual(type(gewichte), dict)
self.assertIn("Herrmann", gewichte)
self.assertIn("Paul", gewichte)
self.assertIn("Caro", gewichte)
for name in ["Herrmann", "Paul", "Caro"]:
self.assertEqual(type(gewichte[name]), list)
for gewicht in gewichte[name]:
self.assertEqual(type(gewicht), int)
self.assertEqual(len(gewichte["Herrmann"]), 3)
self.assertEqual(len(gewichte["Paul"]), 2)
self.assertEqual(len(gewichte["Caro"]), 5)
| 34.545455 | 70 | 0.642105 |
16532895b4779db943fea2886912f96584b515d3
| 1,631 |
py
|
Python
|
Contrib-Microsoft/Olympus_rack_manager/python-ocs/commonapi/controls/manage_logentry.py
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 5 |
2019-11-11T07:57:26.000Z
|
2022-03-28T08:26:53.000Z
|
Contrib-Microsoft/Olympus_rack_manager/python-ocs/commonapi/controls/manage_logentry.py
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 3 |
2019-09-05T21:47:07.000Z
|
2019-09-17T18:10:45.000Z
|
Contrib-Microsoft/Olympus_rack_manager/python-ocs/commonapi/controls/manage_logentry.py
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 11 |
2019-07-20T00:16:32.000Z
|
2022-01-11T14:17:48.000Z
|
# Copyright (C) Microsoft Corporation. All rights reserved.
# This program is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#!/usr/bin/python
# -*- coding: utf-8 -*-
from utils import *
from ocspaths import *
from controls.bladelog_lib import read_server_log
from controls.manage_rack_manager import get_rack_manager_log
def get_logentry(entry_id, log_id, type, device_id):
ret = {}
ret["members"] = {}
log_id = int(log_id)
if type == 'system' and log_id == 1:
output = read_server_log(int(device_id), False)
elif type == 'chassis' and log_id == 1:
if device_id == "rackmanager":
output = get_rack_manager_log(telemetry_log_path, False)
elif branch_id == "rowmanager":
return set_failure_dict("Rowmanager log is not available", completion_code.failure)
else:
return set_failure_dict("Requested log is not available", completion_code.failure)
else:
return set_failure_dict("Requested log is not available", completion_code.failure)
if entry_id == 0:
ret["members"] = output["members"]
elif entry_id in output["members"]:
ret["members"] = output["members"][entry_id]
ret["entry_type"] = "SEL"
ret["log_count"] = len(ret["members"])
ret["id"] = device_id
ret["type"] = type
return ret
| 32.62 | 95 | 0.632128 |
4c2adb6129284ad6763291505fd016b574d0fab5
| 1,075 |
py
|
Python
|
CodeChef_problems/uncle_jhony/solution.py
|
gbrls/CompetitiveCode
|
b6f1b817a655635c3c843d40bd05793406fea9c6
|
[
"MIT"
] | 165 |
2020-10-03T08:01:11.000Z
|
2022-03-31T02:42:08.000Z
|
CodeChef_problems/uncle_jhony/solution.py
|
gbrls/CompetitiveCode
|
b6f1b817a655635c3c843d40bd05793406fea9c6
|
[
"MIT"
] | 383 |
2020-10-03T07:39:11.000Z
|
2021-11-20T07:06:35.000Z
|
CodeChef_problems/uncle_jhony/solution.py
|
gbrls/CompetitiveCode
|
b6f1b817a655635c3c843d40bd05793406fea9c6
|
[
"MIT"
] | 380 |
2020-10-03T08:05:04.000Z
|
2022-03-19T06:56:59.000Z
|
# cook your dish here
t = int(input()) # Taking the Number of Test Cases
for i in range(t): # Looping over test cases
n = int(input()) # Taking the length of songs input
p = [int(i) for i in input().split()] # Taking the list of song length as input
k = int(input()) # Taking the position of the uncle jhony song(taking indexing from 1)
ele = p[k-1] # Storing that element in a variable (position was taken -1 as indexing of our list is from 0 and user entered according to indexing starting from 1)
for i in range(n): # Here for sorting the list we use bubble sort algorithm
j = 0 # bubble sorting program - line 10 to 14
for j in range(0, n-i-1):
if p[j] > p[j+1]:
p[j], p[j+1] = p[j+1], p[j]
ls = (p.index(ele)) # Now geeting the position of uncle jhony song in sorted list.
print(ls+1) # Printing the position + 1 as the indexing started from 0.
| 59.722222 | 177 | 0.552558 |
91333341e264ce6d8b49f97fb6dc226143c957e9
| 513 |
py
|
Python
|
PMIa/2015/Velyan_A_S/task_3_6.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
PMIa/2015/Velyan_A_S/task_3_6.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
PMIa/2015/Velyan_A_S/task_3_6.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
# Задача 3. Вариант 6.
# Напишите программу, которая выводит имя "Самюэл Ленгхорн Клеменс", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
# Velyan A. S.
# 27.05.2016
print("Герой нашей сегодняшней программы - Сэмюэл Ленгхорн Клеменс")
print("Под каким же именем мы знаем этого человека?")
input("\n\nВаш ответ: Марк Твен")
print("\nВсе верно: Самюэл Ленгхорн Клеменс - Марк Твен")
input("\nНажмите Enter для выхода")
| 46.636364 | 209 | 0.766082 |
e6ddd58a5d1bca3269797e210f69a6d17edf724e
| 551 |
py
|
Python
|
Contests/CCC/CCC '10 J5 - Knight Hop.py
|
MastaCoder/Projects
|
ebb0a3134522b12f052fec8d753005f384adf1b1
|
[
"MIT"
] | 5 |
2018-10-11T01:55:40.000Z
|
2021-12-25T23:38:22.000Z
|
Contests/CCC/CCC '10 J5 - Knight Hop.py
|
MastaCoder/mini_projects
|
ebb0a3134522b12f052fec8d753005f384adf1b1
|
[
"MIT"
] | null | null | null |
Contests/CCC/CCC '10 J5 - Knight Hop.py
|
MastaCoder/mini_projects
|
ebb0a3134522b12f052fec8d753005f384adf1b1
|
[
"MIT"
] | 1 |
2019-02-22T14:42:50.000Z
|
2019-02-22T14:42:50.000Z
|
y_a = [2, 2, -2, -2, -1, -1, 1, 1]
x_a = [1, -1, 1, -1, 2, -2, 2, -2]
s = []
start = list(map(int, input().split()))
stop = list(map(int, input().split()))
q = [start, None]
c = 0
def add_8_paths(p):
for a in range(8):
np = [p[0] + x_a[a], p[1] + y_a[a]]
if np not in q and np not in s and np[0] > 0 and np[1] > 0:
q.append(np)
while 1:
on = q.pop(0)
s.append(on)
if on == stop:
break
elif on == None:
c += 1
q.append(None)
else:
add_8_paths(on)
print(c)
| 19.678571 | 67 | 0.453721 |
fc59ea037d6526648755b25f4fb9aba7764b26c7
| 344 |
py
|
Python
|
src/network/bo/messages/connection_accepted.py
|
TimmMoetz/blockchain-lab
|
02bb55cc201586dbdc8fdc252a32381f525e83ff
|
[
"RSA-MD"
] | 2 |
2021-11-08T12:00:02.000Z
|
2021-11-12T18:37:52.000Z
|
src/network/bo/messages/connection_accepted.py
|
TimmMoetz/blockchain-lab
|
02bb55cc201586dbdc8fdc252a32381f525e83ff
|
[
"RSA-MD"
] | null | null | null |
src/network/bo/messages/connection_accepted.py
|
TimmMoetz/blockchain-lab
|
02bb55cc201586dbdc8fdc252a32381f525e83ff
|
[
"RSA-MD"
] | 1 |
2022-03-28T13:49:37.000Z
|
2022-03-28T13:49:37.000Z
|
from .message import Message
class Connection_accepted(Message):
def __init__(self) -> None:
super().__init__()
self._name = "connection-accepted"
def to_dict(self):
return {
"name": self.get_name()
}
@staticmethod
def from_dict(dict):
return Connection_accepted()
| 20.235294 | 42 | 0.590116 |
5d1831eb1ce2cc4139f684a7d70a97df2fd8824e
| 2,056 |
py
|
Python
|
tests/test_event.py
|
JeFaProductions/TextAdventure2
|
4ae690a1e41f30a564a77015f76346d55466c325
|
[
"MIT"
] | 2 |
2016-08-28T21:32:39.000Z
|
2016-09-02T05:56:53.000Z
|
tests/test_event.py
|
JeFaProductions/TextAdventure2
|
4ae690a1e41f30a564a77015f76346d55466c325
|
[
"MIT"
] | 7 |
2016-09-01T22:03:13.000Z
|
2019-06-13T21:38:05.000Z
|
tests/test_event.py
|
JeFaProductions/TextAdventure2
|
4ae690a1e41f30a564a77015f76346d55466c325
|
[
"MIT"
] | null | null | null |
import unittest
import tead.event as evt
class TestEventSystem(unittest.TestCase):
def myCallback(self, event):
self.called = self.called + 1
self.assertEqual('test', event.type)
self.assertIn('foo', event.userParam)
self.assertEqual('bar', event.userParam['foo'])
def setUp(self):
self.system = evt.EventSystem()
self.called = 0
def testRegisterEventHandler(self):
self.assertNotIn('test', self.system._eventHandlers)
self.system.registerEventHander('test', self.myCallback)
self.assertIn('test', self.system._eventHandlers, 'no list created')
self.assertEqual(1, len(self.system._eventHandlers['test']), 'no handler added')
def testUnregisterEventHandler(self):
self.assertNotIn('test', self.system._eventHandlers)
handlerID = self.system.registerEventHander('test', self.myCallback)
self.assertIn('test', self.system._eventHandlers)
self.assertEqual(1, len(self.system._eventHandlers['test']))
self.system.unregisterEventHandler('test', handlerID)
self.assertIn('test', self.system._eventHandlers, 'list was deleted')
self.assertEqual(0, len(self.system._eventHandlers['test']), 'handler was not removed')
def testCreateEvent(self):
self.assertEqual(0, self.system._eventQueue.qsize())
self.system.createEvent(evt.Event(eventType='test', userParam={'foo' : 'bar'}))
self.assertEqual(1, self.system._eventQueue.qsize(), 'queue has still no event')
def testProcessEvent(self):
self.system.registerEventHander('test', self.myCallback)
self.system.createEvent(evt.Event(eventType='test', userParam={'foo' : 'bar'}))
self.system.createEvent(evt.Event(eventType='test', userParam={'foo' : 'bar'}))
self.assertFalse(self.system._eventQueue.empty())
self.assertEqual(0, self.called)
self.system.processEvents()
self.assertTrue(self.system._eventQueue.empty())
self.assertEqual(2, self.called)
| 35.448276 | 95 | 0.678502 |
53fbb49791e6b36bafc57121006da7c1a2c869ad
| 7,875 |
py
|
Python
|
bearpi-hm_nano-oh_flower/00_src/bearpi-hm_nano_oh_fun/build/lite/hb/build/build_process.py
|
dawmlight/vendor_oh_fun
|
bc9fb50920f06cd4c27399f60076f5793043c77d
|
[
"Apache-2.0"
] | 1 |
2022-02-15T08:51:55.000Z
|
2022-02-15T08:51:55.000Z
|
hihope_neptune-oh_hid/00_src/v0.3/build/lite/hb/build/build_process.py
|
dawmlight/vendor_oh_fun
|
bc9fb50920f06cd4c27399f60076f5793043c77d
|
[
"Apache-2.0"
] | null | null | null |
hihope_neptune-oh_hid/00_src/v0.3/build/lite/hb/build/build_process.py
|
dawmlight/vendor_oh_fun
|
bc9fb50920f06cd4c27399f60076f5793043c77d
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 Huawei Device Co., Ltd.
# 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 os
from collections import defaultdict
from hb.common.utils import exec_command
from hb.common.utils import makedirs
from hb.common.utils import remove_path
from hb.common.utils import hb_info
from hb.common.utils import hb_warning
from hb.common.config import Config
from hb.cts.cts import CTS
from hb.common.device import Device
from hb.common.product import Product
class Build():
def __init__(self):
self.config = Config()
# Get gn args ready
self._args_list = []
self._target = None
self._compiler = None
self._test = None
@property
def target(self):
return self._target
@target.setter
def target(self, component):
cts = CTS()
cts.init_from_json()
for subsystem_cls in cts:
for cname, component_cls in subsystem_cls:
if cname == component:
if component_cls.adapted_board is None or\
self.config.board in component_cls.adapted_board:
if component_cls.adapted_kernel is None or\
self.config.kernel in component_cls.adapted_kernel:
self._target = component_cls.targets
self.register_args('ohos_build_target',
self._target)
return
raise Exception('Component {} not found'.format(component))
@property
def compiler(self):
return self._compiler
@compiler.setter
def compiler(self, value):
self._compiler = value
self.register_args('ohos_build_compiler_specified', self._compiler)
if self._compiler == 'clang':
self.register_args('ohos_build_compiler_dir',
self.config.clang_path)
@property
def test(self):
return self._test
@test.setter
def test(self, test_args):
cmd_list = ['xts']
if test_args[0] in cmd_list:
self._test = test_args[1]
if len(test_args) > 1:
self.register_args('ohos_xts_test_args', self._test)
else:
raise Exception('Error: wrong input of test')
def register_args(self, args_name, args_value, quota=True):
if quota:
if isinstance(args_value, list):
self._args_list += ['{}="{}"'.format(args_name,
"&&".join(args_value))]
else:
self._args_list += ['{}="{}"'.format(args_name, args_value)]
else:
self._args_list += ['{}={}'.format(args_name, args_value)]
def build(self, full_compile, ninja=True, cmd_args=None):
self.check_in_device()
cmd_list = self.get_cmd(full_compile, ninja)
if cmd_args is None:
cmd_args = defaultdict(list)
for exec_cmd in cmd_list:
exec_cmd(cmd_args)
return 0
def get_cmd(self, full_compile, ninja):
if not ninja:
self.register_args('ohos_full_compile', 'true', quota=False)
return [self.gn_build]
build_ninja = os.path.join(self.config.out_path, 'build.ninja')
if not os.path.isfile(build_ninja):
self.register_args('ohos_full_compile', 'true', quota=False)
makedirs(self.config.out_path)
return [self.gn_build, self.ninja_build]
if full_compile:
self.register_args('ohos_full_compile', 'true', quota=False)
remove_path(self.config.out_path)
makedirs(self.config.out_path)
return [self.gn_build, self.ninja_build]
self.register_args('ohos_full_compile', 'false', quota=False)
return [self.ninja_build]
def gn_build(self, cmd_args):
# Clean out path
remove_path(self.config.out_path)
makedirs(self.config.out_path)
# Gn cmd init and execute
gn_path = self.config.gn_path
gn_args = cmd_args.get('gn', [])
gn_cmd = [gn_path,
'gen',
self.config.out_path,
'--root={}'.format(self.config.root_path),
'--dotfile={}/.gn'.format(self.config.build_path),
'--script-executable=python3',
'--args={}'.format(" ".join(self._args_list))] + gn_args
exec_command(gn_cmd, log_path=self.config.log_path)
def gn_clean(self, out_path=None):
# Gn cmd init and execute
gn_path = self.config.gn_path
if out_path is not None:
self.config.out_path = os.path.abspath(out_path)
else:
self.config.out_path = os.path.join(self.config.root_path,
'out',
self.config.board,
self.config.product)
if not os.path.isdir(self.config.out_path):
hb_warning('{} not found'.format(self.config.out_path))
return
gn_cmd = [gn_path,
'--root={}'.format(self.config.root_path),
'--dotfile={}/.gn'.format(self.config.build_path),
'clean',
self.config.out_path]
exec_command(gn_cmd, log_path=self.config.log_path)
def ninja_build(self, cmd_args):
ninja_path = self.config.ninja_path
ninja_args = cmd_args.get('ninja', [])
ninja_cmd = [ninja_path,
'-w',
'dupbuild=warn',
'-C',
self.config.out_path] + ninja_args
exec_command(ninja_cmd, log_path=self.config.log_path, log_filter=True)
hb_info('{} build success'.format(
os.path.basename(self.config.out_path)))
def check_in_device(self):
if self._target is None and Device.is_in_device():
# Compile device board
device_path, kernel, board = Device.device_menuconfig()
self.config.out_path = os.path.join(self.config.root_path,
'out',
board)
gn_device_path = os.path.dirname(device_path)
gn_kernel_path = device_path
self.register_args('ohos_build_target', [gn_device_path])
self.register_args('device_path', gn_kernel_path)
self.register_args('ohos_kernel_type', kernel)
else:
# Compile product in "hb set"
self.register_args('product_path', self.config.product_path)
self.register_args('device_path', self.config.device_path)
self.register_args('ohos_kernel_type', self.config.kernel)
product_json = os.path.join(self.config.product_path,
'config.json')
self._args_list += Product.get_features(product_json)
self.config.out_path = os.path.join(self.config.root_path,
'out',
self.config.board,
self.config.product)
| 37.5 | 79 | 0.570286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.