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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dc9e80b17d900ec90393870f8906fe436c356ec1
| 1,488 |
py
|
Python
|
DataStructures/Tree/SwapNodes.py
|
baby5/HackerRank
|
1e68a85f40499adb9b52a4da16936f85ac231233
|
[
"MIT"
] | null | null | null |
DataStructures/Tree/SwapNodes.py
|
baby5/HackerRank
|
1e68a85f40499adb9b52a4da16936f85ac231233
|
[
"MIT"
] | null | null | null |
DataStructures/Tree/SwapNodes.py
|
baby5/HackerRank
|
1e68a85f40499adb9b52a4da16936f85ac231233
|
[
"MIT"
] | null | null | null |
#coding:utf-8
class Node(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
'''
def Inorder(root):
if root:
Inorder(root.left)
print root.data,
Inorder(root.right)
'''
def Inorder(root):
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
print root.data,
root = root.right
root = Node(1)
N = int(raw_input())
node_list = [root]
for i in range(1, N+1):
a, b = map(int, raw_input().split())
node = node_list.pop(0)
if a != -1:
node.left = Node(a)
node_list.append(node.left)
if b != -1:
node.right = Node(b)
node_list.append(node.right)
T = int(raw_input())
K_list = []
for j in range(T):
K_list.append(int(raw_input()))
for K in K_list:
prev_list = []
cur_list = [root]
swap_list = []
depth = 1
while 1:
if depth%K == 0:
swap_list.extend(cur_list)
for node in cur_list:
if node.left:
prev_list.append(node.left)
if node.right:
prev_list.append(node.right)
if not prev_list:
break
cur_list = prev_list
prev_list = []
depth += 1
for node in swap_list:
node.left, node.right = node.right, node.left
Inorder(root)
print
| 21.882353 | 57 | 0.531586 |
f492bed62e1882e3e6396c6cfee470471ba493a9
| 1,834 |
py
|
Python
|
Python/Buch_ATBS/Teil_1/Kapitel_06_Stringbearbeitung/02_string_manipulation.py
|
Apop85/Scripts
|
e71e1c18539e67543e3509c424c7f2d6528da654
|
[
"MIT"
] | null | null | null |
Python/Buch_ATBS/Teil_1/Kapitel_06_Stringbearbeitung/02_string_manipulation.py
|
Apop85/Scripts
|
e71e1c18539e67543e3509c424c7f2d6528da654
|
[
"MIT"
] | 6 |
2020-12-24T15:15:09.000Z
|
2022-01-13T01:58:35.000Z
|
Python/Buch_ATBS/Teil_1/Kapitel_06_Stringbearbeitung/02_string_manipulation.py
|
Apop85/Scripts
|
1d8dad316c55e1f1343526eac9e4b3d0909e4873
|
[
"MIT"
] | null | null | null |
# Manipulation von Strings
teststring='das ist EIN TEsTsTRInG'
low='lower'
upp='UPPER'
print('Stirings wie dieser:['+teststring+'] Können auch manipuliert werden')
print()
input()
print('Man kann z.b. mit upper() den kompletten Inhalt des Strings\nin Grossbuchstaben schreiben.')
print('Beispiel:', teststring.upper())
print()
input()
print('Man kann auch alles in Kleinbuchstaben ausgeben:')
print('Beispiel:', teststring.lower())
print()
input()
print('In diesem Beispiel geht es um join() und split(). Diese Funktionen\nDienen dazu mehrere Strings miteinander zu verbinden\noder einen String mit mehreren Wörter zu einzelnen Strings zu splitten.')
print('Gebe einen Satz mit mehreren Wörtern ein:')
sent=input()
spl=sent.split(' ')
print('Beispiel - Original:\t[', sent, ']')
print('Beispiel - Splitted:\t[', spl, ']')
print('Beispiel - Join mit "-":[', '-'.join(spl), ']')
print()
input()
msg='''Mit der split() und join()
Methode lassen sich auch
mehrzeilige Strings zu einer
Zeile zusammenfassen wie in
diesem Beispiel.'''
msgsplit=msg.split('\n')
print(' '.join(msgsplit))
print()
input()
print('Man Kann auch die Ausrichtung einer Stringausgabe mit \nrjust(), ljust und center() angeben')
print('Beispiel ljust():',teststring.ljust(50, '#'))
print('Beispiel rjust():',teststring.rjust(50, '#'))
print('Beispiel center():',teststring.center(49, '#'))
print()
input()
print('Die Optionen strip(), lstrip() und rstrip() ermöglichen es \nbestimmte Zeichen vom Anfang und dem Ende des Strings zu entfernen.')
teststring=' ==Hallo Welt== '
print('Teststring:\t\t['+teststring+']')
print('Beispiel lstrip():\t['+teststring.lstrip()+']')
print('Beispiel rstrip():\t['+teststring.rstrip()+']')
print('Beispiel strip():\t['+teststring.strip()+']')
print('Beispiel strip(\' =\'):\t['+teststring.strip(' =')+']')
| 33.962963 | 202 | 0.700109 |
f498818387aca8d1ffbc362c5834f282b3df40c7
| 1,979 |
py
|
Python
|
src/wrapped/spotify_access.py
|
willfurtado/SMAS
|
d094c9e021cd863e7f59ec171f0e46572aff4944
|
[
"MIT"
] | null | null | null |
src/wrapped/spotify_access.py
|
willfurtado/SMAS
|
d094c9e021cd863e7f59ec171f0e46572aff4944
|
[
"MIT"
] | null | null | null |
src/wrapped/spotify_access.py
|
willfurtado/SMAS
|
d094c9e021cd863e7f59ec171f0e46572aff4944
|
[
"MIT"
] | null | null | null |
import spotipy
from secrets import CLIENT_ID, CLIENT_SECRET, REDIRECT_URI
from spotipy.oauth2 import SpotifyOAuth
class SpotifyAccess:
"Spotify API abstraction"
def __init__(self, username, scope):
self.name = username
self.client_id = CLIENT_ID
self.client_secret = CLIENT_SECRET
self.redirect_uri = REDIRECT_URI
self.scope = scope
self.spotify = spotipy.Spotify(
auth_manager=SpotifyOAuth(
scope=scope,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
)
)
def top_songs(self, time_range, n=10):
songs = self.spotify.current_user_top_tracks(
limit=n,
time_range=time_range,
)
print(f"\n\n\n {n} top {time_range} songs for {self.name}")
for i in range(n):
try:
print("\n")
song = songs["items"][i - 1]
print(
f"{i+ 1}:",
song["name"],
f"-- {round(song['duration_ms'] / 3600)} minutes listened",
)
except IndexError:
print(f"Less than {n} topsongs; occured at number {i}")
break
def top_artists(self, time_range, n=10):
artists = self.spotify.current_user_top_artists(
limit=n,
time_range=time_range,
)
print(f"\n\n\n {n} top {time_range} artists for {self.name}")
for i in range(n):
try:
print("\n")
artist = artists["items"][i - 1]
print(
f"{i + 1}:",
artist["name"],
f"-- Genre: {artist['genre']}",
)
except IndexError:
print(f"Less than {n} topsongs; occured at number {i}")
break
| 30.446154 | 82 | 0.48762 |
87558778217907e7ad6e2757d46f7b63f196d6c0
| 614 |
py
|
Python
|
Python/zzz_training_challenge/Python_Challenge/solutions/ch03_recursion/solutions/ex03_gcd.py
|
Kreijeck/learning
|
eaffee08e61f2a34e01eb8f9f04519aac633f48c
|
[
"MIT"
] | null | null | null |
Python/zzz_training_challenge/Python_Challenge/solutions/ch03_recursion/solutions/ex03_gcd.py
|
Kreijeck/learning
|
eaffee08e61f2a34e01eb8f9f04519aac633f48c
|
[
"MIT"
] | null | null | null |
Python/zzz_training_challenge/Python_Challenge/solutions/ch03_recursion/solutions/ex03_gcd.py
|
Kreijeck/learning
|
eaffee08e61f2a34e01eb8f9f04519aac633f48c
|
[
"MIT"
] | null | null | null |
# Beispielprogramm für das Buch "Python Challenge"
#
# Copyright 2020 by Michael Inden
def gcd(a, b):
# rekursiver Abbruch
if b == 0:
return a
# rekursiver Abstieg
return gcd(b, a % b)
def gcd_iterative(a, b):
while b != 0:
remainder = a % b
a = b
b = remainder
# hier gilt b == 0
return a
def lcm(a, b):
return a * b // gcd(a, b)
def main():
print(gcd(2, 14))
print(gcd(42, 14))
print(gcd_iterative(2, 14))
print(gcd_iterative(42, 14))
print(lcm(2, 14))
print(lcm(42, 14))
if __name__ == "__main__":
main()
| 14.619048 | 50 | 0.54886 |
0d8798a4459cff7883b93d07ec3abd2396710c2a
| 3,301 |
py
|
Python
|
bin/oblique.py
|
username4gh/dotfiles
|
6ab3e6a7eecb82f01fadfa40a961164df34af091
|
[
"Unlicense"
] | 5 |
2017-04-18T20:21:06.000Z
|
2020-12-28T05:44:39.000Z
|
bin/oblique.py
|
username4gh/dotfiles
|
6ab3e6a7eecb82f01fadfa40a961164df34af091
|
[
"Unlicense"
] | 35 |
2016-09-21T18:04:51.000Z
|
2020-03-11T02:39:20.000Z
|
bin/oblique.py
|
username4gh/dotfiles
|
6ab3e6a7eecb82f01fadfa40a961164df34af091
|
[
"Unlicense"
] | 2 |
2018-12-17T03:16:35.000Z
|
2020-10-18T10:09:01.000Z
|
#! /usr/bin/env python
# coding=UTF-8
# https://en.wikipedia.org/wiki/Oblique_Strategies
# https://traviscj.com/blog/oblique_programming_strategies.html
import random
import sys
strategies = [
'Solve the easiest possible problem in the dumbest possible way.',
'Write a test for it.',
'Is there a better name for this thing?',
'Can we move work between query time (when we need the answer) and ingest time (when we see the data that eventually informs the answer)?',
'Is it easier in a relational data store? A KV Store? A column store? A document store? A graph store?',
'Can performance be improved by batching many small updates?',
'Can clarity be improved by transforming a single update to more smaller updates?',
'Can we more profitably apply a functional or declarative or imperative paradigm to the existing design?',
'Can we profitably apply a change from synchronous to asynchronous, or vice versa?',
'Can we profitably apply an inversion of control, moving logic between many individual call sites, a static central definition, and a reflectively defined description of the work to be done?',
'Is it faster with highly mutable or easier with completely immutable data structures?',
'Is it easier on the client side or the server side?',
'List the transitive closure of fields in a data model. Regroup them to make the most sense for your application. Do you have the same data model?',
'Is it better to estimate it quickly or compute it slowly?',
'What semantics do you need? Should it be ordered? Transactional? Blocking?',
'Can you do it with a regex? Do you need to bite the bullet and make a real parser? Can you avoid parsing by using a standardized format? (A few to get you started: s-expressions/XML/protobuf/JSON/yaml/msgpack/capn/avro/edn.)',
'What is the schema for this data? Is the schema holding you back?',
'Draw a state diagram according to the spec.',
'Draw a state diagram according to the data.',
'Draw a data flow (dX/dydX/dy)',
'Draw a timeline (dX/dtdX/dt)',
'How would you do it in Haskell? C? Javascript?',
'Instead of doing something, emit an object.',
'Instead of emitting an object, do something.',
'Store all of it.',
'Truncate the old stuff.',
'Write the API you wish existed.',
'Make an ugly version where all the things work.',
'Make a gorgeous version that doesn\'t do anything.',
'Can you codegen the boilerplate?',
'Enumerate all the cases.',
'What happens if you do it all offline / precompute everything? What happens if you recompute every time? Can you cache it?',
'Can you build an audit log?',
'Think like a tree: ignore the book-keeping details and find the cleanest representation.',
'Think like a stack: zoom in to the book-keeping details and ignore the structure.',
'Replace your implementation with an implementation that computes how much work the real implementation does for that problem.',
'What is the steady state?'
]
def main(argv=sys.argv):
print(strategies[int(round(random.random() * len(strategies)))])
sys.exit(main())
| 60.018182 | 235 | 0.690094 |
1d9f3242b01e5f1f01dbd28ac9421ff8c1a43857
| 3,805 |
py
|
Python
|
frappe-bench/apps/erpnext/erpnext/agriculture/doctype/crop_cycle/crop_cycle.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
frappe-bench/apps/erpnext/erpnext/agriculture/doctype/crop_cycle/crop_cycle.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
frappe-bench/apps/erpnext/erpnext/agriculture/doctype/crop_cycle/crop_cycle.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
import ast
class CropCycle(Document):
def validate(self):
if self.is_new():
crop = frappe.get_doc('Crop', self.crop)
self.create_project(crop.period, crop.agriculture_task)
if not self.crop_spacing_uom:
self.crop_spacing_uom = crop.crop_spacing_uom
if not self.row_spacing_uom:
self.row_spacing_uom = crop.row_spacing_uom
if not self.project:
self.project = self.name
disease = []
for detected_disease in self.detected_disease:
disease.append(detected_disease.name)
if disease != []:
self.update_disease(disease)
else:
old_disease, new_disease = [], []
for detected_disease in self.detected_disease:
new_disease.append(detected_disease.name)
for detected_disease in self.get_doc_before_save().get('detected_disease'):
old_disease.append(detected_disease.name)
if list(set(new_disease)-set(old_disease)) != []:
self.update_disease(list(set(new_disease)-set(old_disease)))
frappe.msgprint(_("All tasks for the detected diseases were imported"))
def update_disease(self, disease_hashes):
new_disease = []
for disease in self.detected_disease:
for disease_hash in disease_hashes:
if disease.name == disease_hash:
self.import_disease_tasks(disease.disease, disease.start_date)
def import_disease_tasks(self, disease, start_date):
disease_doc = frappe.get_doc('Disease', disease)
self.create_task(disease_doc.treatment_task, self.name, start_date)
def create_project(self, period, crop_tasks):
project = frappe.new_doc("Project")
project.project_name = self.title
project.expected_start_date = self.start_date
project.expected_end_date = frappe.utils.data.add_days(self.start_date, period-1)
project.insert()
self.create_task(crop_tasks, project.as_dict.im_self.name, self.start_date)
return project.as_dict.im_self.name
def create_task(self, crop_tasks, project_name, start_date):
for crop_task in crop_tasks:
task = frappe.new_doc("Task")
task.subject = crop_task.get("task_name")
task.priority = crop_task.get("priority")
task.project = project_name
task.exp_start_date = frappe.utils.data.add_days(start_date, crop_task.get("start_day")-1)
task.exp_end_date = frappe.utils.data.add_days(start_date, crop_task.get("end_day")-1)
task.insert()
def reload_linked_analysis(self):
linked_doctypes = ['Soil Texture', 'Soil Analysis', 'Plant Analysis']
required_fields = ['location', 'name', 'collection_datetime']
output = {}
for doctype in linked_doctypes:
output[doctype] = frappe.get_all(doctype, fields=required_fields)
output['Land Unit'] = []
for land in self.linked_land_unit:
output['Land Unit'].append(frappe.get_doc('Land Unit', land.land_unit))
frappe.publish_realtime("List of Linked Docs", output, user=frappe.session.user)
def append_to_child(self, obj_to_append):
for doctype in obj_to_append:
for doc_name in set(obj_to_append[doctype]):
self.append(doctype, {doctype: doc_name})
self.save()
def get_coordinates(self, doc):
return ast.literal_eval(doc.location).get('features')[0].get('geometry').get('coordinates')
def get_geometry_type(self, doc):
return ast.literal_eval(doc.location).get('features')[0].get('geometry').get('type')
def is_in_land_unit(self, point, vs):
x, y = point
inside = False
j = len(vs)-1
i = 0
while i < len(vs):
xi, yi = vs[i]
xj, yj = vs[j]
intersect = ((yi > y) != (yj > y)) and (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
if intersect:
inside = not inside
i = j
j += 1
return inside
| 36.586538 | 93 | 0.731143 |
d5226c97411f131e717abc22e12c0b3d226b34e1
| 3,446 |
py
|
Python
|
test/test_npu/test_network_ops/test_split_with_sizes.py
|
Ascend/pytorch
|
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
|
[
"BSD-3-Clause"
] | 1 |
2021-12-02T03:07:35.000Z
|
2021-12-02T03:07:35.000Z
|
test/test_npu/test_network_ops/test_split_with_sizes.py
|
Ascend/pytorch
|
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
|
[
"BSD-3-Clause"
] | 1 |
2021-11-12T07:23:03.000Z
|
2021-11-12T08:28:13.000Z
|
test/test_npu/test_network_ops/test_split_with_sizes.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 Test_split_with_sizes(TestCase):
def cpu_op_exec(self, input1, split_sizes, dim):
outputs = torch.split_with_sizes(input1, split_sizes, dim)
outputs_np = []
for output in outputs:
outputs_np.append(output.numpy())
return outputs_np
def npu_op_exec(self, input1, split_sizes, dim):
input1 = input1.to("npu")
outputs = torch.split_with_sizes(input1, split_sizes, dim)
outputs = list(outputs)
output_cpu = []
output_np = []
for i in outputs:
output_cpu.append(i.to("cpu"))
for i in output_cpu:
output_np.append(i.numpy())
return output_np
def test_add_common_shape_format1(self, device):
shape_format = [ # input, split_sizes, dim
[[np.int32, -1, (2, 3)], [1, 1], 0],
[[np.int32, -1, (2, 3)], [1, 1, 1], 1],
[[np.int32, -1, (2, 3, 10)], [2, 3, 5], 2],
[[np.int32, -1, (2, 3, 10, 4, 5)], [1, 1, 1, 1], 3],
[[np.int32, -1, (2, 3, 10, 4, 5)], [1, 1, 1, 1, 1], 4]
]
for item in shape_format:
cpu_input1, npu_input1 = create_common_tensor(item[0], 1, 100)
split_sizes = item[1]
dim = item[2]
cpu_outputs = self.cpu_op_exec(cpu_input1, split_sizes, dim)
npu_outputs = self.npu_op_exec(npu_input1, split_sizes, dim)
for i in range(0, len(cpu_outputs)):
self.assertRtolEqual(cpu_outputs[i], npu_outputs[i])
def test_add_common_shape_format2(self, device):
shape_format = [ # input, split_sizes, dim
[[np.float32, -1, (10, 31, 149, 2)], [2, 3, 5], 0],
[[np.float32, -1, (10, 31, 149, 2)], [2, 3, 5, 10, 11], 1],
[[np.float32, -1, (10, 31, 149, 2)], [50, 50, 20, 29], 2],
[[np.float32, -1, (10, 31, 149, 2)], [25, 25, 25, 25, 20, 29], 2],
[[np.float32, -1, (10, 31, 149, 2)], [1, 1], 3]
]
for item in shape_format:
cpu_input1, npu_input1 = create_common_tensor(item[0], -1.1754943508e-38, -1.1754943508e-38)
split_sizes = item[1]
dim = item[2]
cpu_outputs = self.cpu_op_exec(cpu_input1, split_sizes, dim)
npu_outputs = self.npu_op_exec(npu_input1, split_sizes, dim)
for i in range(0, len(cpu_outputs)):
self.assertRtolEqual(cpu_outputs[i], npu_outputs[i])
instantiate_device_type_tests(Test_split_with_sizes, globals(), except_for='cpu')
if __name__ == "__main__":
run_tests()
| 41.518072 | 104 | 0.600406 |
6357cce4d583c7224a83f27e093a4b38c493a752
| 2,772 |
py
|
Python
|
u1.py
|
watsondeservescredit/BIOINF101-Aufgabe-1
|
d366195be0ee663ec1b7aae50230f9d64e7c7a6a
|
[
"MIT"
] | null | null | null |
u1.py
|
watsondeservescredit/BIOINF101-Aufgabe-1
|
d366195be0ee663ec1b7aae50230f9d64e7c7a6a
|
[
"MIT"
] | null | null | null |
u1.py
|
watsondeservescredit/BIOINF101-Aufgabe-1
|
d366195be0ee663ec1b7aae50230f9d64e7c7a6a
|
[
"MIT"
] | null | null | null |
from itertools import product
#quick hack script. replace K in kmer function and DNA in check_mer_count function with your data.
#returns the most occured mers and their reverse also the maximum count these achieved in the line below
#this function reverses the sequence (c) bioinfo 101
def reverse(input_sequence):
reverse_complement = ''
n = len(input_sequence) - 1
while n >= 0:
if input_sequence[n] == 'A':
reverse_complement += 'T'
n = n-1
elif input_sequence[n] == 'T':
reverse_complement += 'A'
n = n-1
elif input_sequence[n] == 'C':
reverse_complement += 'G'
n = n-1
else:
reverse_complement += 'C'
n = n-1
return reverse_complement
#this function makes all possible kmers. replace k with your k.
def kmer():
k = 14
keywords = [''.join(i) for i in product("ATCG", repeat = k)]
return keywords
#this functions returns the numbers of counts the mer and its reverse appear in dna sequence. replace dna with your string.
def check_mer_count(mer,mer_reverse):
dna="GGTTGGCTGGTATCGAAATCACCGCAGCATTGAACGAGGTTGGCTGAACGATGGTATCGGCAGCATTGAACGAGCAGCATTGAACGAAAATCACCTGGTATCGGGTTGGCTGGTATCGTGAACGATGAACGAGCAGCATTGGTATCGTGGTATCGTGAACGAGCAGCATAAATCACCTGGTATCGAAATCACCAAATCACCGGTTGGCGCAGCATAAATCACCTGAACGATGGTATCGTGGTATCGTGGTATCGAAATCACCTGGTATCGTGGTATCGGGTTGGCAAATCACCGGTTGGCGCAGCATGCAGCATAAATCACCAAATCACCGCAGCATGGTTGGCGCAGCATGGTTGGCAAATCACCGCAGCATTGAACGAGGTTGGCGGTTGGCTGAACGATGAACGATGAACGAGCAGCATTGAACGATGAACGAAAATCACCAAATCACCGGTTGGCGCAGCATGGTTGGCTGAACGAGGTTGGCTGAACGAGGTTGGCTGGTATCGTGGTATCGTGGTATCGTGAACGATGGTATCGGGTTGGCGCAGCATTGGTATCGAAATCACCGCAGCATGGTTGGCAAATCACCTGGTATCGGGTTGGCGGTTGGCGGTTGGCGGTTGGCTGAACGAAAATCACCTGAACGAAAATCACCGGTTGGCTGGTATCGTGAACGAGGTTGGCAAATCACCTGGTATCGAAATCACCTGAACGAGGTTGGCAAATCACCAAATCACCGCAGCATGCAGCATAAATCACCGGTTGGCGCAGCATGGTTGGCTGAACGAAAATCACCTGGTATCGAAATCACCTGAACGATGGTATCGTGGTATCGTGGTATCGTGGTATCGTGGTATCG"
mer_count=dna.count(mer)
mer_reverse_count=dna.count(mer_reverse)
return mer_count + mer_reverse_count
#this is the actual function that returns the solution
max_mers = []
max_count = 0
for mer in kmer():
count = check_mer_count(mer,reverse(mer))
#edge case: all occurencies 0 useless
#if mer occurs as often as current max just append to max mer list
if max_count == count:
max_count = count
max_mers.append(mer)
max_mers.append(reverse(mer))
#if mer appears more often then current max replace current list with mer
elif max_count < count:
max_count = count
max_mers = [mer]
max_mers.append(reverse(mer))
ret_max_mers = ' '.join(max_mers)
print(ret_max_mers)
print(max_count)
| 47.793103 | 883 | 0.762987 |
8931bf1a634ff1fdeb557edf81ff16bd5adbb4e3
| 102 |
py
|
Python
|
packages/watchmen-pipeline-surface/src/watchmen_pipeline_surface/__init__.py
|
Indexical-Metrics-Measure-Advisory/watchmen
|
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
|
[
"MIT"
] | null | null | null |
packages/watchmen-pipeline-surface/src/watchmen_pipeline_surface/__init__.py
|
Indexical-Metrics-Measure-Advisory/watchmen
|
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
|
[
"MIT"
] | null | null | null |
packages/watchmen-pipeline-surface/src/watchmen_pipeline_surface/__init__.py
|
Indexical-Metrics-Measure-Advisory/watchmen
|
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
|
[
"MIT"
] | null | null | null |
from .main import get_pipeline_surface_routers
from .surface import pipeline_surface, PipelineSurface
| 34 | 54 | 0.882353 |
f6efa192a45c3642639edc2fbe191fe680a1e3ad
| 811 |
py
|
Python
|
utils/set_logger.py
|
UESTC-Liuxin/SkmtSeg
|
1251de57fae967aca395644d1c70a9ba0bb52271
|
[
"Apache-2.0"
] | 2 |
2020-12-22T08:40:05.000Z
|
2021-03-30T08:09:44.000Z
|
utils/set_logger.py
|
UESTC-Liuxin/SkmtSeg
|
1251de57fae967aca395644d1c70a9ba0bb52271
|
[
"Apache-2.0"
] | null | null | null |
utils/set_logger.py
|
UESTC-Liuxin/SkmtSeg
|
1251de57fae967aca395644d1c70a9ba0bb52271
|
[
"Apache-2.0"
] | null | null | null |
import os
import datetime
import logging
def get_logger(logdir):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ts = str(datetime.datetime.now()).split('.')[0].replace(' ', '_')
ts = ts.replace(':', '_').replace('-', '_')
file_path = os.path.join(logdir, 'run_{}.log'.format(ts))
hdlr = logging.FileHandler(file_path)
hdlr.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler() # 日志控制台输出
stream_handler.setLevel(logging.NOTSET)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
logger.addHandler(hdlr)
return logger
if __name__ =="__main__":
logger=get_logger(".././")
logger.info("aaa")
| 25.34375 | 74 | 0.678175 |
121808267cd88566be6d48f7e597d5d6a0929315
| 6,919 |
py
|
Python
|
test/test_projects.py
|
ekut-es/autojail
|
bc16e40e6df55c0a28a3059715851ffa59b14ba8
|
[
"MIT"
] | 6 |
2020-08-12T08:16:15.000Z
|
2022-03-05T02:25:53.000Z
|
test/test_projects.py
|
ekut-es/autojail
|
bc16e40e6df55c0a28a3059715851ffa59b14ba8
|
[
"MIT"
] | 1 |
2021-03-30T10:34:51.000Z
|
2021-06-09T11:24:00.000Z
|
test/test_projects.py
|
ekut-es/autojail
|
bc16e40e6df55c0a28a3059715851ffa59b14ba8
|
[
"MIT"
] | 1 |
2021-11-21T09:30:58.000Z
|
2021-11-21T09:30:58.000Z
|
import filecmp
import os
import shutil
import stat
import subprocess
from pathlib import Path
import pytest
from cleo import CommandTester
from ruamel.yaml import YAML
from autojail.main import AutojailApp
project_folder = os.path.join(os.path.dirname(__file__), "test_data")
autojail_root_folder = Path(__file__).parent.parent
qemu_scripts_folder = (autojail_root_folder / "scripts").resolve()
qemu_download_folder = (autojail_root_folder / "downloads" / "qemu").resolve()
def test_init(tmpdir):
os.chdir(tmpdir)
application = AutojailApp()
command = application.find("init")
tester = CommandTester(command)
yaml = YAML()
assert tester.execute(interactive=False) == 0
assert os.path.exists(os.path.join(tmpdir, "autojail.yml"))
with open("autojail.yml") as f:
data1 = yaml.load(f)
assert tester.execute(["-f"], interactive=False) == 0
assert os.path.exists(os.path.join(tmpdir, "autojail.yml"))
with open("autojail.yml") as f:
data2 = yaml.load(f)
assert (
tester.execute(["-f"], interactive=True, inputs="\n\n\n\n\n\n\n\n\n")
== 0
)
assert os.path.exists(os.path.join(tmpdir, "autojail.yml"))
with open("autojail.yml") as f:
data3 = yaml.load(f)
assert data1["name"] == data2["name"] == data3["name"]
assert data1["arch"] == data2["arch"] == data3["arch"]
assert (
data1["jailhouse_dir"]
== data2["jailhouse_dir"]
== data3["jailhouse_dir"]
)
assert (
data1["cross_compile"]
== data2["cross_compile"]
== data3["cross_compile"]
)
assert (
tester.execute(
"-f --arch arm --name jailhouse_test --uart /dev/ttyUSB0",
interactive=False,
)
== 0
)
assert os.path.exists(os.path.join(tmpdir, "autojail.yml"))
with open("autojail.yml") as f:
data_test = yaml.load(f)
assert data_test["name"] == "jailhouse_test"
assert data_test["arch"] == "ARM"
assert data_test["uart"] == "/dev/ttyUSB0"
try:
import automate # noqa
assert tester.execute("-f -a", interactive=False) == 0
assert os.path.exists(os.path.join(tmpdir, "autojail.yml"))
except ModuleNotFoundError:
pass
@pytest.mark.xfail
def test_simple(tmpdir):
"""tests a simple generation from cells.yml only"""
os.chdir(tmpdir)
application = AutojailApp()
command = application.find("init")
tester = CommandTester(command)
assert tester.execute(interactive=False) == 0
cells_path = Path(project_folder) / "test_cells.yml"
shutil.copy(cells_path, Path(tmpdir) / "cells.yml")
application = AutojailApp()
command = application.find("generate")
tester = CommandTester(command)
assert tester.execute(interactive=False, args="--generate-only") == 0
def test_config_rpi4_net(tmpdir):
""" Tests that rpi4_net creates the expected configuration for rpi4_net"""
os.chdir(tmpdir)
shutil.copytree(Path(project_folder) / "rpi4_net", "rpi4_net")
os.chdir("rpi4_net")
application = AutojailApp()
command = application.find("generate")
tester = CommandTester(command)
assert (
tester.execute(interactive=False, args="--skip-check --generate-only")
== 0
)
assert Path("rpi4-net.c").exists()
assert Path("rpi4-net-guest.c").exists()
assert filecmp.cmp("rpi4-net.c", "golden/rpi4-net.c")
assert filecmp.cmp("rpi4-net-guest.c", "golden/rpi4-net-guest.c")
def test_config_rpi4_default(tmpdir):
""" Tests that rpi4_default creates the expected configuration"""
os.chdir(tmpdir)
shutil.copytree(Path(project_folder) / "rpi4_default", "rpi4_default")
os.chdir("rpi4_default")
application = AutojailApp()
command = application.find("generate")
tester = CommandTester(command)
assert (
tester.execute(interactive=False, args="--skip-check --generate-only")
== 0
)
assert Path("raspberry-pi4.c").exists()
assert filecmp.cmp("raspberry-pi4.c", "golden/raspberry-pi4.c")
def test_config_rpi4_fixed_pci_mmconfig_base(tmpdir):
""" Tests that rpi4_fixed_pci_mmconfig_base creates the expected configuration"""
os.chdir(tmpdir)
shutil.copytree(
Path(project_folder) / "rpi4_fixed_pci_mmconfig_base",
"rpi4_fixed_pci_mmconfig_base",
)
os.chdir("rpi4_fixed_pci_mmconfig_base")
application = AutojailApp()
command = application.find("generate")
tester = CommandTester(command)
assert (
tester.execute(interactive=False, args="--skip-check --generate-only")
== 0
)
assert Path("raspberry-pi4.c").exists()
assert filecmp.cmp("raspberry-pi4.c", "golden/raspberry-pi4.c")
def prepare_qemu_scripts():
def ensure_executable(script_path: Path):
curr_mode = script_path.stat().st_mode
if not (curr_mode & stat.S_IXUSR):
script_path.chmod(curr_mode | stat.S_IXUSR)
ensure_executable(qemu_scripts_folder / "start_qemu.sh")
ensure_executable(qemu_scripts_folder / "stop_qemu.sh")
@pytest.mark.skipif(
not shutil.which("qemu-system-aarch64")
or not shutil.which("aarch64-linux-gnu-gcc"),
reason="Requires qemu-system-aarch64 and aarch64-linux-gnu-gcc",
)
def test_config_qemu(tmpdir):
""" Tests that rpi4_fixed_pci_mmconfig_base creates the expected configuration"""
os.chdir(tmpdir)
shutil.copytree(
Path(project_folder) / "qemu_net", "qemu_net",
)
os.chdir("qemu_net")
tmp_proj_dir = Path(tmpdir) / "qemu_net"
clone_command = [
"git",
"clone",
"--branch",
"next",
"https://github.com/siemens/jailhouse.git",
]
subprocess.run(clone_command, check=True)
os.symlink(
qemu_download_folder / "linux-jailhouse-images" / "build-full",
"kernel",
target_is_directory=True,
)
def generate_script(name):
script_path = tmp_proj_dir / name
assert not script_path.exists()
script_path.write_text(
f"""#!/bin/bash
{qemu_scripts_folder / name}
"""
)
script_path.chmod(stat.S_IRWXU)
generate_script("start_qemu.sh")
generate_script("stop_qemu.sh")
prepare_qemu_scripts()
application = AutojailApp()
extract = application.find("extract")
extract_tester = CommandTester(extract)
assert (
extract_tester.execute(args=f"--cwd {tmp_proj_dir}", interactive=False)
== 0
)
generate = application.find("generate")
generate_tester = CommandTester(generate)
assert generate_tester.execute(interactive=False) == 0
assert Path("root-cell.c").exists()
assert Path("guest.c").exists()
assert Path("guest1.c").exists()
test = application.find("generate")
test_tester = CommandTester(test)
assert test_tester.execute(interactive=False) == 0
| 28.356557 | 85 | 0.658043 |
f677f647ebf8811bcbaaad98110ca329e748efa8
| 214 |
py
|
Python
|
python/testlint/test/example.py
|
mpsonntag/snippets
|
fc3cc42ea49b885c1f29c0aef1379055a931a978
|
[
"BSD-3-Clause"
] | null | null | null |
python/testlint/test/example.py
|
mpsonntag/snippets
|
fc3cc42ea49b885c1f29c0aef1379055a931a978
|
[
"BSD-3-Clause"
] | null | null | null |
python/testlint/test/example.py
|
mpsonntag/snippets
|
fc3cc42ea49b885c1f29c0aef1379055a931a978
|
[
"BSD-3-Clause"
] | null | null | null |
def add_up(a, b):
return a + b
def test_add_up_succeed():
assert add_up(1, 2) == 3
def test_add_up_fail():
assert add_up(1, 2) == 4
def ignore_me():
assert "I will be" == "completely ignored"
| 14.266667 | 46 | 0.616822 |
2c2eaacdbe05595ce43fe9776180f59f5a25e7c8
| 3,279 |
py
|
Python
|
KnowledgeQuizTool/MillionHeroAssistant/core/baiduzhidao.py
|
JianmingXia/StudyTest
|
66d688ad41bbce619f44359ea126ff07a923f97b
|
[
"MIT"
] | null | null | null |
KnowledgeQuizTool/MillionHeroAssistant/core/baiduzhidao.py
|
JianmingXia/StudyTest
|
66d688ad41bbce619f44359ea126ff07a923f97b
|
[
"MIT"
] | 68 |
2020-09-05T04:22:49.000Z
|
2022-03-25T18:47:08.000Z
|
KnowledgeQuizTool/MillionHeroAssistant/core/baiduzhidao.py
|
JianmingXia/StudyTest
|
66d688ad41bbce619f44359ea126ff07a923f97b
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
Baidu zhidao searcher
"""
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import as_completed
import requests
from lxml import html
def zhidao_search(keyword, default_answer_select, timeout=2):
"""
Search BaiDu zhidao net
:param keyword:
:param timeout:
:return:
"""
answer_url_li = parse_search(
keyword=keyword,
default_answer_select=default_answer_select,
timeout=timeout)
return parse_answer(answer_url_li)
def get_general_number(result):
for item in ("百度", "为", "您", "找到", "相关", "结果", "约", "个", ","):
result = result.replace(item, "")
return result
def search_result_number(keyword, timeout=2):
"""
Search keyword and get search number
:param keyword:
:param timeout:
:return:
"""
url = "http://www.baidu.com/s"
params = {
"wd": keyword.encode("gbk")
}
resp = requests.get(url, params=params, timeout=timeout)
if not resp.ok:
print("baidu search error")
return 0
parser = html.fromstring(resp.text)
result = parser.xpath("//div[@class='nums']/text()")
if not result:
return 0
return int(get_general_number(result[0]))
def parse_search(keyword, default_answer_select=2, timeout=2):
"""
Parse BaiDu zhidao search
only return the first `default_answer_select`
:param keyword:
:param default_answer_select:
:return:
"""
params = {
"lm": "0",
"rn": "10",
"pn": "0",
"fr": "search",
"ie": "gbk",
"word": keyword.encode("gbk")
}
url = "https://zhidao.baidu.com/search"
resp = requests.get(url, params=params, timeout=timeout)
if not resp.ok:
print("baidu zhidao api error")
return ""
parser = html.fromstring(resp.text)
question_li = parser.xpath("//*[@id='page-main']//div[@class='list-inner']/*[@id='wgt-list']/dl/dt/a/@href")
return question_li[:default_answer_select]
def parse_answer(urls, timeout=2):
def fetch(url):
resp = requests.get(url, timeout=timeout)
if not resp.ok:
return ""
if resp.encoding == "ISO-8859-1" or not resp.encoding:
resp.encoding = requests.utils.get_encodings_from_content(resp.text)[0]
return resp.text
final = []
with ThreadPoolExecutor(5) as executor:
future_to_url = {
executor.submit(fetch, url): url
for url in urls
}
for future in as_completed(future_to_url):
url = future_to_url[future]
try:
text = future.result()
parser = html.fromstring(text)
parts = parser.xpath(
"//*[contains(@id, 'best-answer')]//*[@class='line content']/*[contains(@id, 'best-content')]/text()")
if not parts:
parts = parser.xpath(
"//*[@id='wgt-answers']//*[contains(@class, 'answer-first')]//*[contains(@id, 'answer-content')]//span[@class='con']/text()")
final.append(" ".join(parts))
except Exception as exc:
print("get url: {0} error: {1}".format(url, str(exc)))
return final
| 27.099174 | 149 | 0.57853 |
d39eef683e28c026412fcde0ec7a621230d23f23
| 373 |
py
|
Python
|
src/tango_sdp_subarray/SDPSubarray/release.py
|
ska-telescope/sdp-prototype
|
8c6cbda04a83b0e16987019406ed6ec7e1058a31
|
[
"BSD-3-Clause"
] | 2 |
2019-07-15T09:49:34.000Z
|
2019-10-14T16:04:17.000Z
|
src/tango_sdp_subarray/SDPSubarray/release.py
|
ska-telescope/sdp-prototype
|
8c6cbda04a83b0e16987019406ed6ec7e1058a31
|
[
"BSD-3-Clause"
] | 17 |
2019-07-15T14:51:50.000Z
|
2021-06-02T00:29:43.000Z
|
src/tango_sdp_subarray/SDPSubarray/release.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 -*-
"""Release information for Python Package."""
# Consider change to: ska-tangods-sdpsubarray ?
NAME = "ska-sdp-subarray"
# For version names see: https://www.python.org/dev/peps/pep-0440/
VERSION = "0.7.0"
VERSION_INFO = VERSION.split(".")
AUTHOR = "ORCA team, Sim Team"
LICENSE = 'License :: OSI Approved :: BSD License'
COPYRIGHT = "BSD-3-Clause"
| 31.083333 | 66 | 0.689008 |
e238eb32ae178f2903389d762bb3cfb34a7a3943
| 2,273 |
py
|
Python
|
LFA/class_factory.py
|
joao-frohlich/BCC
|
9ed74eb6d921d1280f48680677a2140c5383368d
|
[
"Apache-2.0"
] | 10 |
2020-12-08T20:18:15.000Z
|
2021-06-07T20:00:07.000Z
|
LFA/class_factory.py
|
joao-frohlich/BCC
|
9ed74eb6d921d1280f48680677a2140c5383368d
|
[
"Apache-2.0"
] | 2 |
2021-06-28T03:42:13.000Z
|
2021-06-28T16:53:13.000Z
|
LFA/class_factory.py
|
joao-frohlich/BCC
|
9ed74eb6d921d1280f48680677a2140c5383368d
|
[
"Apache-2.0"
] | 2 |
2021-01-14T19:59:20.000Z
|
2021-06-15T11:53:21.000Z
|
from class_assembly_line import Assembly_Line
class Factory:
errors = 0
closed = False
def __init__(self, assembly_type, max_errors):
self.line = Assembly_Line(assembly_type)
self.name = self.line.type
self.lines = [Assembly_Line(assembly_type) for lines in range(len(self.line))]
self.status = [0 for lines in range(len(self.line))]
self.produced = list()
self.fails = list()
self.serie_number = dict()
self.max_errors = max_errors
def __len__(self):
return len(self.lines)
def run(self, line, word, stop):
if self.errors < self.max_errors and not self.closed:
sucess, error = line.automaton.run_with_word(word, stop)
if sucess:
if error:
self.errors += 1
if self.errors == self.max_errors:
self.closed = True
self.serie_number[line.automaton.identifier] = 0
else:
self.errors += 1
self.serie_number[line.automaton.identifier] = 1
else:
self.closed = True
return
def find_available(self):
index = 0
for busy in self.status:
if busy == 0:
return index
index += 1
return -1
def set_busy(self, index):
if index >= 0:
self.status[index] = len(self.line.automaton)
return
return
def update_status(self):
for busy in range(len(self.status)):
if self.status[busy]:
self.status[busy] -= 1
self.produced.append(self.lines[busy].automaton.output)
self.lines[busy].automaton.output = ""
def count_busy(self):
count = 0
for busy in self.status:
if busy:
count += 1
return count
def count_produced(self):
sucess = list()
count = 0
for output in self.produced:
if output:
if "s" in output:
sucess.append(output)
count += 1
elif output:
self.fails.append(output)
self.produced = sucess
return count, self.errors
| 29.141026 | 86 | 0.529256 |
e287a0457d5207c6452dd8cebc2b4c0bb4c0e738
| 28,372 |
py
|
Python
|
multisensor.py
|
ClimberWue/greenhouse
|
e6ebcb1456cfb2727522925d83a66d105594526d
|
[
"Unlicense"
] | null | null | null |
multisensor.py
|
ClimberWue/greenhouse
|
e6ebcb1456cfb2727522925d83a66d105594526d
|
[
"Unlicense"
] | null | null | null |
multisensor.py
|
ClimberWue/greenhouse
|
e6ebcb1456cfb2727522925d83a66d105594526d
|
[
"Unlicense"
] | null | null | null |
#!/usr/bin/python
# -*- coding:utf-8 -*-
import paho.mqtt.client as mqtt
import os
import io
import glob
import time
import datetime
import sys
from ctypes import c_short
from ctypes import c_byte
from ctypes import c_ubyte
import tkinter
from tkinter import *
from tkinter import ttk
import board
import busio
import smbus
import adafruit_bmp280
from adafruit_bme280 import basic as adafruit_bme280 #has nearly a temperature shift of 2 degree Celsius
#import adafruit_bmp085
#import adafruit_bmp180
import adafruit_bmp3xx
from digitalio import DigitalInOut, Direction
import adafruit_bh1750
import adafruit_ccs811
import adafruit_sht31d
from adafruit_htu21d import HTU21D
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
#derzeit sind noch andere ads1x15 Bibliotheken installiert -
#referenziert wird die adafruit_circuitpython_ads1x15 ohne Großbuchstaben im Namen!
import math, struct, array, fcntl
import RPi.GPIO as GPIO
#Einrichten von autostart
#--> https://techgeeks.de/raspberry-pi-autostart-von-programmen/
#--> www.netzmafia.de/skripten/hardware/RaspPi/RasPi_Auto.html
#--> http://christian-brauweiler.de/autostart-unter-raspian/ So läuft es
# über /home/pi/.config/lxsession/LXDE-pi/autostart
#configuration
winOut = True
shellOut = True
MQTTout = True
useBMP280 = False
useBME280 = False
useBME280ext = False
useBMP3xx = True
useBMP3xx_SPI = False
useLightSensor = True
useHumiditySensor = True
useSoilHumiditySensor = True
useCO2Sensor = True
useCCS811Sensor = True
#seconds for measurement cycle
waitSeconds = 10#60 sec. or more
#initialize relais IO
relais_1_GPIO = 16 #O2 fres air
relais_2_GPIO = 6 #air cooling start temperature
GPIO.setmode(GPIO.BCM)
GPIO.setup(relais_1_GPIO, GPIO.OUT)
GPIO.setup(relais_2_GPIO, GPIO.OUT)
GPIO.output(relais_1_GPIO, GPIO.LOW)
GPIO.output(relais_2_GPIO, GPIO.LOW)
# fresh air == O2 intake parameters - in Teilen von 1.0!
O2concentration = 0.205 # nachzuführen bei nachlassender Sensor Leistung --> kleiner werdend
# Ausgangswert war wohl 0.21 zufälligerweise
O2minforFreshAir = 0.195 # dto. mit Differenz von 1-2% absolutem O² Gehalt
O2hysteresis = 0.1 #0.05 # dto. etwa die Hälfte der Differenz beider obiger O² Werte
relais_1_status = 1# Achtung konträre Logik!!!
ventFreshAir = False
GPIO.output(relais_1_GPIO, relais_1_status)
# maximaler CO2 Wert sollte dauerhaft 2.000 ppm nicht überschreiten?
# bis 5.000ppm =0,5% darf man noch arbeiten
# ab 40.000ppm wäre gesundheitsgefährdend (=Atemluft 4%) bis tödlich ~8%!!!
# der aktuelle Lüfter mit 150mm bietet etwa 250 m³/h Luftstrom abzüglich Leitungsverluste
# das GWH hat bei 10 m² Grundfläche und 2-2,5 m Höhe etwa 22 m³ Rauminhalt.
# eine Minute Lüften saugt 3(-4) m³ Innenluft ab.
# secondary inhouse fan parameters
airTemp = 20.0
airTempCooling = 20 #test only was 32.0
relais_2_status = 1
GPIO.output(relais_2_GPIO, relais_2_status)
DEVICE = 0x76 # Standard-Geräteaddresse am I2C
BUS = smbus.SMBus(1)
def get_short(data, index):
return c_short((data[index+1] << 8) + data[index]).value
def get_ushort(data, index):
return (data[index+1] << 8) + data[index]
def get_char(data, index):
result = data[index]
if result > 127:
result -= 256
return result
def get_uchar(data, index):
result = data[index] & 0xFF
return result
def read_bme280id(addr=DEVICE):
reg_id = 0xD0
(chip_id, chip_version) = BUS.read_i2c_block_data(addr, reg_id, 2)
return chip_id, chip_version
def read_bme280_all(addr=DEVICE):
reg_data = 0xF7
reg_control = 0xF4
reg_config = 0xF5
reg_control_hum = 0xF2
reg_hum_msb = 0xFD
reg_hum_lsb = 0xFE
oversample_temp = 2
oversample_pres = 2
mode = 1
oversample_hum = 2
BUS.write_byte_data(addr, reg_control_hum, oversample_hum)
control = oversample_temp << 5 | oversample_pres << 2 | mode
BUS.write_byte_data(addr, reg_control, control)
cal1 = BUS.read_i2c_block_data(addr, 0x88, 24)
cal2 = BUS.read_i2c_block_data(addr, 0xA1, 1)
cal3 = BUS.read_i2c_block_data(addr, 0xE1, 7)
dig_t1 = get_ushort(cal1, 0)
dig_t2 = get_short(cal1, 2)
dig_t3 = get_short(cal1, 4)
dig_p1 = get_ushort(cal1, 6)
dig_p2 = get_short(cal1, 8)
dig_p3 = get_short(cal1, 10)
dig_p4 = get_short(cal1, 12)
dig_p5 = get_short(cal1, 14)
dig_p6 = get_short(cal1, 16)
dig_p7 = get_short(cal1, 18)
dig_p8 = get_short(cal1, 20)
dig_p9 = get_short(cal1, 22)
dig_h1 = get_uchar(cal2, 0)
dig_h2 = get_short(cal3, 0)
dig_h3 = get_uchar(cal3, 2)
dig_h4 = get_char(cal3, 3)
dig_h4 = (dig_h4 << 24) >> 20
dig_h4 = dig_h4 | (get_char(cal3, 4) & 0x0F)
dig_h5 = get_char(cal3, 5)
dig_h5 = (dig_h5 << 24) >> 20
dig_h5 = dig_h5 | (get_uchar(cal3, 4) >> 4 & 0x0F)
dig_h6 = get_char(cal3, 6)
wait_time = 1.25 + (2.3 * oversample_temp) + ((2.3 * oversample_pres) + 0.575) + ((2.3 * oversample_hum)+0.575)
time.sleep(wait_time/1000)
data = BUS.read_i2c_block_data(addr, reg_data, 8)
pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4)
temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4)
hum_raw = (data[6] << 8) | data[7]
var1 = ((((temp_raw>>3)-(dig_t1<<1)))*(dig_t2)) >> 11
var2 = (((((temp_raw >> 4) - dig_t1) * ((temp_raw >> 4) - dig_t1)) >> 12) * dig_t3) >> 14
t_fine = var1+var2
temperature = float(((t_fine * 5) + 128) >> 8)
var1 = t_fine / 2.0 - 64000.0
var2 = var1 * var1 * dig_p6 / 32768.0
var2 = var2 + var1 * dig_p5 * 2.0
var2 = var2 / 4.0 + dig_p4 * 65536.0
var1 = (dig_p3 * var1 * var1 / 524288.0 + dig_p2 * var1) / 524288.0
var1 = (1.0 + var1 / 32768.0) * dig_p1
if var1 == 0:
pressure = 0
else:
pressure = 1048576.0 - pres_raw
pressure = ((pressure - var2 / 4096.0) * 6250.0) / var1
var1 = dig_p9 * pressure * pressure / 2147483648.0
var2 = pressure * dig_p8 / 32768.0
pressure = pressure + (var1 + var2 + dig_p7) / 16.0
humidity = t_fine - 76800.0
humidity = (hum_raw - (dig_h4 * 64.0 + dig_h5 / 16384.0 * humidity)) * \
(dig_h2 / 65536.0 * (1.0 + dig_h6 / 67108864.0 * humidity * (1.0 + dig_h3 / 67108864.0 * humidity)))
humidity = humidity * (1.0 - dig_h1 * humidity / 524288.0)
if humidity > 100:
humidity = 100
elif humidity < 0:
humidity = 0
return temperature/100.0, pressure/100.0, humidity
#grove ADC
from grove.adc import ADC
class GroveAirQualitySensor(object):
'''
Grove Air Quality Sensor class
Args:
pin(int): number of analog pin/channel the sensor connected.
'''
def __init__(self, channel):
self.channel = channel
self.adc = ADC()
@property
def value(self):
'''
Get the air quality strength value, badest value is 100.0%.
Returns:
(int): ratio, 0(0.0%) - 1000(100.0%)
'''
return self.adc.read(self.channel)
class GroveO2Sensor(object):
def __init__(self, channel):
self.channel = channel
self.adc = ADC()
@property
def value(self):
return self.adc.read(self.channel)
class GroveSoilHumiditySensor(object):
def __init__(self, channel):
self.channel = channel
self.adc = ADC()
@property
def value(self):
return self.adc.read(self.channel)
#CO2 sensor T6703
bus = 1
addressT6703 = 0x15
I2C_SLAVE = 0x0703
class i2c_(object):
def __init__(self, device, bus):
self.fr = io.open("/dev/i2c-"+str(bus), "rb", buffering=0)
self.fw = io.open("/dev/i2c-"+str(bus), "wb", buffering=0)
# set device address
fcntl.ioctl(self.fr, I2C_SLAVE, device)
fcntl.ioctl(self.fw, I2C_SLAVE, device)
def write(self, bytes):
self.fw.write(bytes)
def read(self, bytes):
return self.fr.read(bytes)
def close(self):
self.fw.close()
self.fr.close()
class T6703(object):
def __init__(self):
self.dev = i2c_(addressT6703, bus)
def status(self):
buffer = array.array('B', [0x04, 0x13, 0x8a, 0x00, 0x01])
self.dev.write(buffer)
time.sleep(0.1)
data = self.dev.read(4)
buffer = array.array('B', data)
return buffer[2]*256+buffer[3]
def gasPPM(self):
buffer = array.array('B', [0x04, 0x13, 0x8b, 0x00, 0x01])
self.dev.write(buffer)
time.sleep(0.1)
data = self.dev.read(4)
buffer = array.array('B', data)
return buffer[2]*256+buffer[3]
def checkABC(self):
buffer = array.array('B', [0x04, 0x03, 0xee, 0x00, 0x01])
self.dev.write(buffer)
time.sleep(0.1)
data = self.dev.read(4)
buffer = array.array('B', data)
return buffer[2]*256+buffer[3]
def calibrate(self):
buffer = array.array('B', [0x05, 0x03, 0xec, 0xff, 0x00])
self.dev.write(buffer)
time.sleep(0.1)
data = self.dev.read(5)
buffer = array.array('B', data)
return buffer[3]*256+buffer[3]
def shellPrint(st):
print(st)
def debugPrint(st):
print(st, file=sys.stderr)
def exceptionPrint(exc, st):
print(exc, st, file=sys.stderr)
def on_connect(client, userdata, flags, rc):
if rc == 0:
debugPrint("connected OK")
#MQTT endpoint
broker = "GWHpi4"
client = mqtt.Client("GWH")
client.on_connect = on_connect
#client.connect("Rotauge", 1883, 60)
client.connect(broker)
client.loop_start()
time.sleep(4)
#SPI setup
spi = board.SPI() #board.SCLK, board.MOSI, board.MISO)
cs = DigitalInOut(board.CE1) #??? was D5
#bmp_SPI = adafruit_bmp3xx.BMP3XX_SPI(spi, cs)
# Treiberinstallation
os.system('sudo modprobe w1-gpio')
#os.system('sudo modprobe w1-therm') # gives error os.system('modprobe w1-therm')
# Sensor als Objekt erstellen in Abhaengigkeit von I2C
i2c = busio.I2C(board.SCL, board.SDA)
#time.sleep(2)
#if useBMP3xx_SPI == True:
#sensorBMP3xx_SPI = adafruit_bmp3xx.BMP3XX_SPI(spi, cs=0)
if useLightSensor == True:
lightSensor = adafruit_bh1750.BH1750(i2c, address = 0x23)
#if useLightSensor == 0:
# debugPrint("BH1750 failed!")
if useHumiditySensor == True:
humiditySensor = HTU21D(i2c)
humiditymin = 100.0
humiditymax = 0.0
if useSoilHumiditySensor == True:
soilHumiditySensor = adafruit_sht31d.SHT31D(i2c)
soilHumiditymin = 100.0
soilHumiditymax = 0.0
if useBMP280 == True:
sensorBMP280 = adafruit_bmp280.Adafruit_BMP280_I2C(i2c, address=0x76)
if useBME280 == True:
sensorBME280 = adafruit_bme280.Adafruit_BME280_I2C(i2c, address=0x76)
if useBMP3xx == True:
sensorBMP3xx = adafruit_bmp3xx.BMP3XX_I2C(i2c, address=0x77)
ads = ADS.ADS1115(i2c, address=0x49)
# Create single-ended input on channel 0
chanSoilHum = AnalogIn(ads, ADS.P3) #humSoil
# Create single-ended input on channel 3
chanGas = AnalogIn(ads, ADS.P1) #Gas sensor
chan2 = AnalogIn(ads, ADS.P2)
chanO2 = AnalogIn(ads, ADS.P0) #O2 Sensor
if useCO2Sensor == True:
CO2sensor = T6703() # min read with this sensor 372ppm
CO2min = 10000
CO2max = 0
if useCCS811Sensor == True:
try:
ccs811 = adafruit_ccs811.CCS811(i2c)
while not ccs811.data_ready:
pass
temp = ccs811.temperature
ccs811.temp_offset = temp - 25.0
except Exception as exc:
exceptionPrint(exc, "CCS811 Exception Start")
#grove ADC
from grove.helper import SlotHelper
#SoilHumiditySensor2 = GroveSoilHumiditySensor(4)
#SoilHumiditySensor = GroveSoilHumiditySensor(5)
#O2sensor = GroveO2Sensor(0)
#do it wituout grove
O2min = 30.0
O2max = 0.0
#Netzmafia BMP280
if useBMP280 == True:
sensorBMP280.sea_level_pressure = 1013.25
ALTITUDE = 210.0
if useBME280 == True:
sensorBME280.sea_level_pressure = 1013.25
ALTITUDE = 210.0
if useBME280ext == True:
#sensorBME280.sea_level_pressure = 1013.25
ALTITUDE = 210.0
if useBMP3xx == True:
sensorBMP3xx.sea_level_pressure = 1013.25
ALTITUDE = 210.0
#28-051692fef6ff #3m
#28-03168b2cf0ff #3m
#28-00000887cdd4 #Transistor
#28-0517a199f4ff #
#28-0417a228a7ff #
#28-00000ab5fa1a #
#28-3c01d60702cf #1.2m
proto = False
# Temperatursensor initialisieren
base_dir = '/sys/bus/w1/devices/'
def read_rom(device_folder):
name_file=device_folder+'/name'
f = open(name_file,'r')
return f.readline()
# Sensor Temperatur lesen lassen
def read_temp_raw(filedev):
f = open(filedev, 'r')
lines = f.readlines()
f.close()
if proto == True:
print('lines: ', lines)
return lines
# Temperatur auslesen
def read_temp(filename):
lines = read_temp_raw(filename)
while len(lines) < 2 or lines[0].strip()[-3:] != 'YES':
#hier könnte eine schärfere Überprüfung formuliert werden,
#z.B. Rückgabe eines NAN Werts nach 10 Durchgängen
time.sleep(0.2)
lines = read_temp_raw(filename)
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
return temp_c
return 85.0 #Überlaufwert NAN des Chips; bei Kontaktproblemen auftretend
startTime = datetime.datetime.now()
if winOut == True:
root = Tk()
root.title("Gewächshaus")
tW = Text(root, width = 50, height = 32)#, wrap = "none")
tW.pack()
#mainloop() # not appropriate
#quellen --> https://stackoverflow.com/questions/54237067/how-to-make-tkinter-gui-thread-safe
winLine = 0
def winPrint(tkWin, st):
global winLine
tkWin.insert(tkinter.END, st)
tkWin.insert(tkinter.END, "\n")
winLine += 1
def winClear(tkWin):
global winLine
winLine = 0
tkWin.delete('1.0', tkinter.END)
# Ausgabe
while True:
if winOut == True:
winClear(tW)
dt = datetime.datetime.now()
if winOut == True:
winPrint(tW, dt)
if shellOut == True:
shellPrint(dt)
# interne Systemtemperatur
try:
fsys = open("/sys/class/thermal/thermal_zone0/temp", "r")
cpu_temp = fsys.readline()
fsys.close()
ct = float(cpu_temp)
except:
ct = 0.0
st1 = "Temperatur CPU: {0:0.1f} °C".format((ct / 1000))
if winOut == True:
winPrint(tW, st1)
if shellOut == True:
shellPrint(st1)
if MQTTout:
client.publish("gwh/tempCPU", "{0:0.1f}".format(ct / 1000))
# Ausgabe der Messwerte BMP280
if useBMP280 == True:
try:
pressure = sensorBMP280.pressure
pressure_nn = pressure/pow(1 - ALTITUDE/44330.0, 5.255)
airTemp = temperature = sensorBMP280.temperature
altitude = sensorBMP280.altitude
st1 = "Temperatur: {0:0.1f} °C".format(temperature)
st2 = "Luftdruck: {0:0.1f} hPa".format(pressure)
st3 = "LuftdruckNN: {0:0.1f} hPa".format(pressure_nn)
st4 = "Höhe: {0:0.2f} m".format(altitude)
if winOut == True:
winPrint(tW, st1)
winPrint(tW, st2)
winPrint(tW, st3)
winPrint(tW, st4)
if shellOut == True:
shellPrint(st1)
shellPrint(st2)
shellPrint(st3)
shellPrint(st4)
if MQTTout:
client.publish("gwh/tempBoard", "{0:0.1f}".format(temperature))
client.publish("gwh/pressure", "{0:0.1f}".format(pressure))
client.publish("gwh/pressureNN", "{0:0.1f}".format(pressure_nn))
client.publish("gwh/altitude", "{0:0.2f}".format(altitude))
except Exception as exc:
exceptionPrint(exc, "BMP280 Exception")
# Ausgabe der Messwerte BMP280
if useBME280 == True:
try:
pressure = sensorBME280.pressure
pressure_nn = pressure/pow(1 - ALTITUDE/44330.0, 5.255)
airTemp = temperature = sensorBME280.temperature
altitude = sensorBME280.altitude
st1 = "Temperatur: {0:0.1f} °C".format(temperature)
st2 = "Luftdruck: {0:0.1f} hPa".format(pressure)
st3 = "LuftdruckNN: {0:0.1f} hPa".format(pressure_nn)
st4 = "Höhe: {0:0.2f} m".format(altitude)
if winOut == True:
winPrint(tW, st1)
winPrint(tW, st2)
winPrint(tW, st3)
winPrint(tW, st4)
if shellOut == True:
shellPrint(st1)
shellPrint(st2)
shellPrint(st3)
shellPrint(st4)
if MQTTout:
client.publish("gwh/tempBoard", "{0:0.1f}".format(temperature))
client.publish("gwh/pressure", "{0:0.1f}".format(pressure))
client.publish("gwh/pressureNN", "{0:0.1f}".format(pressure_nn))
client.publish("gwh/altitude", "{0:0.2f}".format(altitude))
except Exception as exc:
exceptionPrint(exc, "BME280 Exception")
# Ausgabe der Messwerte BMP280
if useBME280ext == True:
try:
temperature, pressure, humidity = read_bme280_all()
#pressure_nn = pressure/pow(1 - ALTITUDE/44330.0, 5.255)
airTemp = temperature
st1 = "Temperatur: {0:0.1f} °C".format(temperature)
st2 = "Luftdruck: {0:0.1f} hPa".format(pressure)
if winOut == True:
winPrint(tW, st1)
winPrint(tW, st2)
if shellOut == True:
shellPrint(st1)
shellPrint(st2)
if MQTTout:
client.publish("gwh/tempBoard", "{0:0.1f}".format(temperature))
client.publish("gwh/pressure", "{0:0.1f}".format(pressure))
except Exception as exc:
exceptionPrint(exc, "BME280ext Exception")
if useBMP3xx == True:
try:
pressure3 = sensorBMP3xx.pressure
pressure_nn3 = pressure3/pow(1 - ALTITUDE/44330.0, 5.255)
airTemp = temperature3 = sensorBMP3xx.temperature
altitude3 = sensorBMP3xx.altitude
st1 = "Temperatur 3: {0:0.1f} °C".format(temperature3)
st2 = "Luftdruck 3: {0:0.2f} hPa".format(pressure3)
st3 = "LuftdruckNN 3: {0:0.2f} hPa".format(pressure_nn3)
st4 = "Höhe 3: {0:0.2f} m".format(altitude3)
if winOut == True:
winPrint(tW, st1)
winPrint(tW, st2)
winPrint(tW, st3)
winPrint(tW, st4)
if shellOut == True:
shellPrint(st1)
shellPrint(st2)
shellPrint(st3)
shellPrint(st4)
if MQTTout:
client.publish("gwh/tempBoard3", "{0:0.1f}".format(temperature3))
client.publish("gwh/pressure3", "{0:0.2f}".format(pressure3))
client.publish("gwh/pressureNN3", "{0:0.2f}".format(pressure_nn3))
client.publish("gwh/altitude3", "{0:0.2f}".format(altitude3))
except Exception as exc:
exceptionPrint(exc, "BMP3xx Exception")
if useLightSensor == True:
try:
lux = lightSensor.lux
st1 = "Lux: {0:0.2f} lx".format(lux)
if winOut == True:
winPrint(tW, st1)
if shellOut == True:
shellPrint(st1)
if MQTTout:
client.publish("gwh/lux", "{0:0.2f}".format(lux))
except Exception as exc:
exceptionPrint(exc, "LightSensor Exception")
if useHumiditySensor == True:
try:
tempHum = humiditySensor.temperature
relHum = humiditySensor.relative_humidity
st1 = "Temperatur: {0:0.1f} °C".format(tempHum)
st2 = "Feuchte: {0:0.1f} %".format(relHum)
if winOut == True:
winPrint(tW, st1)
winPrint(tW, st2)
if shellOut == True:
shellPrint(st1)
shellPrint(st2)
if MQTTout:
client.publish("gwh/temp", "{0:0.1f}".format(tempHum))
client.publish("gwh/humidity", "{0:0.1f}".format(relHum))
except Exception as exc:
exceptionPrint(exc, "Humidity Exception")
if useSoilHumiditySensor == True:
try:
tempHum = soilHumiditySensor.temperature
relHum = soilHumiditySensor.relative_humidity
st1 = "Bodentemperatur: {0:0.1f} °C".format(tempHum)
st2 = "Bodenfeuchte: {0:0.1f} %".format(relHum)
if winOut == True:
winPrint(tW, st1)
winPrint(tW, st2)
if shellOut == True:
shellPrint(st1)
shellPrint(st2)
if MQTTout:
client.publish("gwh/soiltemp", "{0:0.1f}".format(tempHum))
client.publish("gwh/soilhumidity", "{0:0.1f}".format(relHum))
except Exception as exc:
exceptionPrint(exc, "Soil Humidity Exception")
# T6703 CO2 Daten
if useCO2Sensor == True:
try:
CO2value = CO2sensor.gasPPM()
if CO2value > 0:
if CO2value < CO2min:
CO2min = CO2value
if CO2value > CO2max:
CO2max = CO2value
st1 = "CO2 ppm: {0:5d} min: {1:5d} max: {2:5d}".format(CO2value, CO2min, CO2max)
if winOut == True:
winPrint(tW, st1)
if shellOut == True:
shellPrint(st1)
if MQTTout:
client.publish("gwh/CO2", "{0:6d}".format(CO2value))
except Exception as exc:
exceptionPrint(exc, "CO2Sensor Exception")
if useCCS811Sensor == True:
try:
eco2 = ccs811.eco2
tvoc = ccs811.tvoc
tempCCS = ccs811.temperature
st1 = "eCO2: {0:5d} ppm".format(eco2)
st2 = "TVOC: {0:5d} ppm".format(tvoc)
st3 = "tempCCS: {0:0.1f} °C".format(tempCCS)
if winOut == True:
winPrint(tW, st1)
winPrint(tW, st2)
winPrint(tW, st3)
if shellOut == True:
shellPrint(st1)
shellPrint(st2)
shellPrint(st3)
if MQTTout:
client.publish("gwh/eCO2", "{0:5d}".format(eco2))
client.publish("gwh/TVOC", "{0:5d}".format(tvoc))
client.publish("gwh/tempCCS", "{0:0.1f} °C".format(tempCCS))
except Exception as exc:
exceptionPrint(exc, "CCS811 Exception")
try:
# O2 sensor
vReference = 5.0 #3.3
#value = O2sensor.value
value = chanO2.value
vOut = chanO2.voltage
vOut = value * (vReference / (256.0*180))
O2concentration = vOut * 0.21 / 2.05 # was 2.0
if O2concentration < O2min:
O2min = O2concentration
if O2concentration > O2max:
O2max = O2concentration
st1 = "O2 value: {0:.4f}".format(vOut)
st2 = "O2 %: {0:.3f} min %: {1:.3f} max %: {2:.3f}".format(O2concentration*100, O2min*100, O2max*100)
if winOut == True:
winPrint(tW, st1)
winPrint(tW, st2)
if shellOut == True:
shellPrint(st1)
shellPrint(st2)
if MQTTout:
client.publish("gwh/O2", "{0:0.3f}".format(O2concentration*100))
except Exception as exc:
exceptionPrint(exc, "AD O2 Exception")
try:
# Bodenfeuchte per Grove hat
#value = SoilHumiditySensor.value
#print("Bodenfeuchte: {}".format(value))
#value = SoilHumiditySensor2.value
#print("Bodenfeuchte2: {}".format(value))
# soil humidity
voltGas = chanGas.voltage
valueGas = chanGas.value
voltSoilHum = chanSoilHum.voltage
valueSoilHum = chanSoilHum.value
st1 = "Gas MQ-2: {:>5}\t{:>5.3f}".format(valueGas, voltGas)
#print("soil2: ", "{:>5}\t{:>5.3f}".format(chan2.value, chan2.voltage))
st3 = "soil3: {:>5}\t{:>5.3f}".format(valueSoilHum, voltSoilHum)
if winOut == True:
winPrint(tW, st1)
winPrint(tW, st3)
if shellOut == True:
shellPrint(st1)
shellPrint(st3)
if MQTTout:
client.publish("gwh/gas", "{:>5.3f}".format(voltGas))
client.publish("gwh/soilHum", "{:>5.3f}".format(voltSoilHum))
except Exception as exc:
exceptionPrint(exc, "AD soil humidity Exception")
# 1-Wire Sensoren
try:
device_folders = glob.glob(base_dir + '28*')
for device in device_folders:
temp_s = "85.0"
device_name = device[len(base_dir):]
device_file = device + '/w1_slave'
temp_c = read_temp(device_file)
temp_s = "{0:3.3f}".format(temp_c)
st1 = device_name + " {0} °C".format(temp_s)
if winOut == True:
winPrint(tW, st1)
if shellOut == True:
shellPrint(st1)
if MQTTout:
client.publish("gwh/{0}".format(device_name), temp_s)
except Exception as exc:
exceptionPrint(exc, "1-Wire Exception")
#Trigger beachten - sollte low sein
if ventFreshAir == True:
if O2concentration > O2minforFreshAir + O2hysteresis:
# Beende Frischluftzufuhr
relais_1_status = 1
ventFreshAir = False
else:
relais_1_status = 0
ventFreshAir = True
else: #ventFreshAir == False
if O2concentration > O2minforFreshAir:
relais_1_status = 1
ventFreshAir = False
else:
# Starte Frischluftzufuhr
relais_1_status = 0
ventFreshAir = True
GPIO.output(relais_1_GPIO, relais_1_status)
st1 = "ventilateFreshAir: {0:1d}".format(ventFreshAir)
if winOut == True:
winPrint(tW, st1)
if shellOut == True:
print(st1)
if MQTTout:
if ventFreshAir:
client.publish("gwh/ventFreshAir", "1")
else:
client.publish("gwh/ventFreshAir", "0")
if airTemp > airTempCooling:
relais_2_status = 1
isCooling = False
else:
relais_2_status = 0
isCooling = True
GPIO.output(relais_2_GPIO, relais_2_status)
st1 = "isCooling: {0:1d}".format(isCooling)
if winOut == True:
winPrint(tW, st1)
if shellOut == True:
shellPrint(st1)
if MQTTout:
if isCooling:
client.publish("gwh/isCooling", "1")
else:
client.publish("gwh/isCooling", "0")
dtNow = datetime.datetime.now()
tDelta = dtNow - dt
secondsDiff = waitSeconds - tDelta.total_seconds()
if secondsDiff > waitSeconds:
secondsDiff = waitSeconds
if secondsDiff < 0:
secondsDiff = 0
tDelta = dtNow - startTime
tDeltaToReboot = datetime.timedelta(days=1)# 5; assert days > 0 to avoid endless reboot
# print("tDelta ", tDelta)
# print("tDeltaToReboot ", tDeltaToReboot)
# print("dtNow.hour ", dtNow.hour)
if tDelta > tDeltaToReboot:
if dtNow.hour > 18:
debugPrint("multisensor shutdown pending....")
#os.system('sudo reboot -h now') #at evening
st1 = "seconds2wait: {0:1f}".format(secondsDiff)
if winOut == True:
winPrint(tW, st1)
if shellOut == True:
shellPrint(st1)
shellPrint('---')
if winOut == True:
root.update()
#nada #mainloop()
time.sleep(secondsDiff) #was 20
root.quit()
debugPrint("multisensor unerwartetes Ende!!!")
client.loop_stop()
client.disconnect()
#--fin--
| 33.029104 | 527 | 0.587551 |
2c3e667abd99e930482c8e8cef703c288102caa7
| 1,914 |
py
|
Python
|
src/assets/experiences/sortierroboter/libs/berrytemplates.py
|
TU-Blueberry/bluestberry
|
fbde8dbcd730fe5c4e69ba15a1208a5c0903aa7d
|
[
"MIT"
] | 1 |
2022-03-28T17:23:03.000Z
|
2022-03-28T17:23:03.000Z
|
src/assets/experiences/sortierroboter/libs/berrytemplates.py
|
TU-Blueberry/bluestberry
|
fbde8dbcd730fe5c4e69ba15a1208a5c0903aa7d
|
[
"MIT"
] | null | null | null |
src/assets/experiences/sortierroboter/libs/berrytemplates.py
|
TU-Blueberry/bluestberry
|
fbde8dbcd730fe5c4e69ba15a1208a5c0903aa7d
|
[
"MIT"
] | null | null | null |
import os
import numpy as np
import pandas as pd
from skimage import io
from skimage import transform
from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
path = "BlueberryData/TrainingData/"
def load_images():
labels = []
samples = []
for file in os.listdir(path):
res = io.imread(path + file)
samples.append(res)
if 'good' in file:
labels.append(1)
else:
labels.append(0)
return samples, labels
def extract_features(images, img_size=28):
bins = 24
pre_images = []
for i in range(len(images)):
image = images[i].astype("float64")
mod_image = transform.resize(image, (img_size, img_size), anti_aliasing=True)
features = np.array(mod_image.flatten())
for channel in range(image.shape[2]):
histogram, _ = np.histogram(image[:, :, channel], bins=bins, range=(0, 256))
features = np.append(features, histogram.flatten())
pre_images.append(features)
return pd.DataFrame(np.array(pre_images))
def classifier():
model = RandomForestClassifier(n_estimators=550, min_samples_split=4,
min_samples_leaf=1, max_features="auto", max_depth=20, bootstrap=True)
return model
def print_prediction_metrics(prediction_function, test_data_loader):
accuracy = test_data_loader.evaluate_metric(prediction_function, metric=metrics.accuracy_score)
f1 = test_data_loader.evaluate_metric(prediction_function, metric=metrics.f1_score)
class_report = test_data_loader.evaluate_metric(prediction_function, metric=metrics.classification_report, digits=2)
print("Classifier performance on the test set")
print("-------------------------------------------------")
print("Accuracy: {:.3f}".format(accuracy))
print("F1 score: {:.3f}".format(f1))
print(class_report)
print("\n")
| 33 | 120 | 0.666144 |
2c5aaef3311d500de5b9190f6ad53c422b1093d0
| 83 |
py
|
Python
|
lanz/apps.py
|
linemax/lanz
|
c7f6eb150c260f088faa8255f0b15fcc9435c4af
|
[
"Apache-2.0"
] | null | null | null |
lanz/apps.py
|
linemax/lanz
|
c7f6eb150c260f088faa8255f0b15fcc9435c4af
|
[
"Apache-2.0"
] | null | null | null |
lanz/apps.py
|
linemax/lanz
|
c7f6eb150c260f088faa8255f0b15fcc9435c4af
|
[
"Apache-2.0"
] | null | null | null |
from django.apps import AppConfig
class LanzConfig(AppConfig):
name = 'lanz'
| 13.833333 | 33 | 0.73494 |
3944578d8286250ff00f6c926ac4e5a4339602bb
| 448 |
py
|
Python
|
BIZa/2014/Tskipu_a_k/task_1_28.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
BIZa/2014/Tskipu_a_k/task_1_28.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
BIZa/2014/Tskipu_a_k/task_1_28.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
# Задача 1. Вариант 0.
# Напишите программу, которая будет сообщать род деятельности и псевдоним под которым скрывается Эдсон Арантис ду Насименту. После вывода информации программа должна дожидаться пока пользователь нажмет Enter для выхода.
# Krasnikov A. S.
# Цкипуришвили Александр
# 01.02.2016
print("Норма Бейкер более известена, как Американская киноактриса, певица и секс-символ Мэрилин Монро.")
input("\n\nНажмите Enter для выхода.")
| 34.461538 | 219 | 0.792411 |
1a9bd64a56d2b4ec6de5f16589f26b1830724b61
| 183 |
py
|
Python
|
c++filt_perf.py
|
ligang945/pyMisc
|
3107c80f7f53ffc797b289ec73d1ef4db80f0b63
|
[
"MIT"
] | null | null | null |
c++filt_perf.py
|
ligang945/pyMisc
|
3107c80f7f53ffc797b289ec73d1ef4db80f0b63
|
[
"MIT"
] | null | null | null |
c++filt_perf.py
|
ligang945/pyMisc
|
3107c80f7f53ffc797b289ec73d1ef4db80f0b63
|
[
"MIT"
] | null | null | null |
import os
file = 'perf.log'
with open(file) as f:
for line in f:
if 'libdecode.so' in line:
cmd = 'c++filt %s' % line.split()[2]
os.system(cmd)
| 18.3 | 49 | 0.508197 |
64915ff5a35a2793d7aedc73dc95311668c1712e
| 827 |
py
|
Python
|
RedBook/ch2/parse_image.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
RedBook/ch2/parse_image.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
RedBook/ch2/parse_image.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
from urllib.request import urlopen
from html.parser import HTMLParser
class ImageParser(HTMLParser):
def handle_starttag(self, tag, attrs):
if tag != 'img':
return
if not hasattr(self, 'result'):
self.result = []
for name, value in attrs:
if name == 'src':
self.result.append(value)
def parse_image(data):
parser = ImageParser()
parser.feed(data)
dataSet = set(x for x in parser.result)
return dataSet
def main():
url = "http://www.google.co.kr"
with urlopen(url) as f:
charset = f.info().get_param('charset')
data = f.read().decode(charset)
dataSet = parse_image(data)
print("\n>>>>>>>>>> Fetch Images from", url)
print("\n".join(sorted(dataSet)))
if __name__ == '__main__':
main()
| 23.628571 | 48 | 0.588875 |
809beefea9164b42b3043627eddace8595d6c694
| 7,519 |
py
|
Python
|
src/balldetection/Ball.py
|
florianletsch/kinect-juggling
|
f320cc0b55adf65d338d25986a03106a7e3f46ef
|
[
"Unlicense",
"MIT"
] | 7 |
2015-11-27T09:53:32.000Z
|
2021-01-13T17:35:54.000Z
|
src/balldetection/Ball.py
|
florianletsch/kinect-juggling
|
f320cc0b55adf65d338d25986a03106a7e3f46ef
|
[
"Unlicense",
"MIT"
] | null | null | null |
src/balldetection/Ball.py
|
florianletsch/kinect-juggling
|
f320cc0b55adf65d338d25986a03106a7e3f46ef
|
[
"Unlicense",
"MIT"
] | null | null | null |
from src.Util import getcolour
class Ball(object):
def __init__(self, position, radius=10, meta=None, max_history=2):
"""Represents a single ball mid-air, with its positions being updated every frame."""
self.colour = getcolour()
self.position = position
self.radius = radius
self.meta = meta
self.positions = [] # collect older positions
self.max_history = max_history
def updatePosition(self, position):
self.positions = self.positions[:self.max_history] # keep positions list short
self.positions.append(self.position)
self.position = position
def futurePosition(self, trajectory=False):
# this one doesnt to future predction, return current position instead
return self.position
def __str__(self):
return "Ball at %d/%d" % self.position
class SimpleBall(Ball):
"""Represents a single ball mid-air, with its positions being updated every frame."""
def __init__(self, position, radius=10, meta=None, max_history=10):
super(SimpleBall, self).__init__(position, radius, meta, max_history)
self.closeThreshold = 40 # pixel distance for 2 balls to be considered "close"
def __str__(self):
return "Ball at %d/%d" % self.position
def directionVector(self):
n = 2
if len(self.positions) < n:
return (0, 0)
else:
last_pos = self.positions[-1]
x = self.position[0] - last_pos[0]
y = self.position[1] - last_pos[1]
return (x, y)
def trajectory(self, (x1, y1), (x2, y2), t=1):
"""Calculate the throw trajectory based of 2 points return any future
or past point on that trajectory"""
# gravity, positive because y is upside-down
g = 9.81 * 0.4
# speed in x and y direction
v_x = x2 - x1
v_y = y2 - y1
# distance in x and y direction
x = v_x * t + x2
y = v_y * t + g/2 * t**2 + y2
return int(x), int(y)
def isClose(self, otherBall, future=True):
otherPosition = otherBall['position']
myPosition = self.futurePosition(True) if future else self.position
return (self.distance(otherPosition, myPosition) < self.closeThreshold)
def futurePosition(self, trajectory=False):
if trajectory:
if len(self.positions) < 2:
return (0, 0)
last_pos = self.positions[-1]
next_pos = self.trajectory(last_pos, self.position, 0)
return next_pos
else:
direction = self.directionVector()
return (self.position[0]+direction[0], self.position[1]+direction[1])
def distance(self, otherPosition, position):
return ((position[0]-otherPosition[0])**2 + (position[1]-otherPosition[1])**2)**0.5
class PreciseTrajectoryBall(Ball):
def __init__(self, posOne, posTwo, posThree, meta=None, max_history=10):
super(SimpleBall, self).__init__(position, radius, meta, max_history)
# remember older positions
self.positions = []
# meta data (like rects that created this ball)
self.meta = meta
# for drawing
self.radius = 10
self.colour = getcolour()
# gravity, positive because y is upside-down
self.gravity = 9.81 * 0.5
self._initTrajectory(posOne, posTwo, posThree)
# initial position
self.position = None
self.step()
self.firstPosition = self.position
def _initTrajectory(self, posOne, posTwo, posThree):
xList = [pos[0] for pos in [posOne, posTwo, posThree]]
yList = [pos[1] for pos in [posOne, posTwo, posThree]]
# does x fit a linear function?
self.xMovement = np.polyfit([-2, -1, 0], xList, 1)
# does y fit a square function?
self.yMovement = np.polyfit([-2, -1, 0], yList, 2)
# progress of the trajectory
self.t = 0
def futurePosition(self):
return self._trajectory(self.t+1)
def directionVector(self):
return (0,0)
def _trajectory(self, t=1):
"""Calculate the throw trajectory"""
# distance in x and y direction
x = np.polyval(self.xMovement, t)
# y = self.v_y * t + self.gravity/2 * t**2 + self.yOffset
y = np.polyval(self.yMovement, t)
return int(x), int(y)
def matches(self, position):
"""determine whether the predicted position could match a
given data point"""
return False
def update(self, position_raw):
position = position_raw['position']
self._initTrajectory(self.position, position)
self.position = position
def step(self):
if self.position:
self.positions.append(self.position)
self.position = self._trajectory(self.t)
self.t += 1
class TrajectoryBall(object):
def __init__(self, lowerPoint, upperPoint, meta=None):
# remember older positions
self.positions = []
# meta data (like rects that created this ball)
self.meta = meta
# for drawing
self.radius = 10
self.colour = getcolour()
# gravity, positive because y is upside-down
self.gravity = 9.81 * 0.5
self._initTrajectory(lowerPoint, upperPoint)
# initial position
self.position = None
self.step()
self.firstPosition = self.position
def _initTrajectory(self, lowerPoint, upperPoint):
# unpack
(x1, y1), (x2, y2) = lowerPoint, upperPoint
# speed in x and y direction
self.v_x = x2 - x1
self.v_y = y2 - y1
# why is the calculated speed too fast? need to correct it here
# self.v_x *= 0.5
self.v_y *= 0.8
# start trajectory in center of the two points we are based on
self.xOffset = (x2 + x1) / 2
self.yOffset = (y2 + y1) / 2
self.xOffset = x1
self.yOffset = y1
# progress of the trajectory
self.t = 0
def futurePosition(self):
return self._trajectory(self.t+1)
def directionVector(self):
return (0,0)
def _trajectory(self, t=1):
"""Calculate the throw trajectory based on 2 points
to return any future or past point on that trajectory"""
# distance in x and y direction
x = self.v_x * t + self.xOffset
y = self.v_y * t + self.gravity/2 * t**2 + self.yOffset
return int(x), int(y)
def matches(self, position):
"""determine whether the predicted position could match a
given data point"""
position = position['position']
predictedPos = self._trajectory(self.t+1)
distance_x = abs(predictedPos[0] - position[0])
distance_y = abs(predictedPos[1] - position[1])
distance = (distance_x**2 + distance_y**2)**0.5
return distance < 20
def update(self, position_raw):
position = position_raw['position']
self._initTrajectory(self.position, position)
self.position = position
def step(self):
if self.position:
self.positions.append(self.position)
self.position = self._trajectory(self.t)
self.t += 1
| 32.409483 | 94 | 0.583322 |
205c4f5006de32509c2ebf5478f3b17df6e65c0a
| 3,409 |
py
|
Python
|
scripts/generate_tpcds_schema.py
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | 2,816 |
2018-06-26T18:52:52.000Z
|
2021-04-06T10:39:15.000Z
|
scripts/generate_tpcds_schema.py
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | 1,310 |
2021-04-06T16:04:52.000Z
|
2022-03-31T13:52:53.000Z
|
scripts/generate_tpcds_schema.py
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | 270 |
2021-04-09T06:18:28.000Z
|
2022-03-31T11:55:37.000Z
|
import os
import subprocess
duckdb_program = '/Users/myth/Programs/duckdb-bugfix/build/release/duckdb'
struct_def = '''struct $STRUCT_NAME {
static constexpr char *Name = "$NAME";
static const char *Columns[];
static constexpr idx_t ColumnCount = $COLUMN_COUNT;
static const LogicalType Types[];
static constexpr idx_t PrimaryKeyCount = $PK_COLUMN_COUNT;
static const char *PrimaryKeyColumns[];
};
'''
initcode = '''
call dsdgen(sf=0);
.mode csv
.header 0
'''
column_count_query = '''
select count(*) from pragma_table_info('$NAME');
'''
pk_column_count_query = '''
select count(*) from pragma_table_info('$NAME') where pk=true;
'''
gen_names = '''
select concat('const char *', '$STRUCT_NAME', '::Columns[] = {', STRING_AGG('"' || name || '"', ', ') || '};') from pragma_table_info('$NAME');
'''
gen_types = '''
select concat('const LogicalType ', '$STRUCT_NAME', '::Types[] = {', STRING_AGG('LogicalType::' || type, ', ') || '};') from pragma_table_info('$NAME');
'''
pk_columns = '''
select concat('const char *', '$STRUCT_NAME', '::PrimaryKeyColumns[] = {', STRING_AGG('"' || name || '"', ', ') || '};') from pragma_table_info('$NAME') where pk=true;
'''
def run_query(sql):
input_sql = initcode + '\n' + sql
res = subprocess.run(duckdb_program, input=input_sql.encode('utf8'), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = res.stdout.decode('utf8').strip()
stderr = res.stderr.decode('utf8').strip()
if res.returncode != 0:
print("FAILED TO RUN QUERY")
print(stderr)
exit(1)
return stdout
def prepare_query(sql, table_name, struct_name):
return sql.replace('$NAME', table_name).replace('$STRUCT_NAME', struct_name)
header = '''
#pragma once
#include "duckdb.hpp"
#ifndef DUCKDB_AMALGAMATION
#include "duckdb/common/exception.hpp"
#include "duckdb/common/types/date.hpp"
#include "duckdb/parser/column_definition.hpp"
#include "duckdb/storage/data_table.hpp"
#include "duckdb/catalog/catalog_entry/table_catalog_entry.hpp"
#include "duckdb/planner/parsed_data/bound_create_table_info.hpp"
#include "duckdb/parser/parsed_data/create_table_info.hpp"
#include "duckdb/parser/constraints/not_null_constraint.hpp"
#include "duckdb/catalog/catalog.hpp"
#include "duckdb/planner/binder.hpp"
#endif
namespace tpcds {
using duckdb::LogicalType;
using duckdb::idx_t;
'''
footer = '''
}
'''
print(header)
table_list = run_query('show tables')
for table_name in table_list.split('\n'):
table_name = table_name.strip()
print('''
//===--------------------------------------------------------------------===//
// $NAME
//===--------------------------------------------------------------------===//'''.replace('$NAME', table_name))
struct_name = str(table_name.title().replace('_', '')) + 'Info'
column_count = int(run_query(prepare_query(column_count_query, table_name, struct_name)).strip())
pk_column_count = int(run_query(prepare_query(pk_column_count_query, table_name, struct_name)).strip())
print(prepare_query(struct_def, table_name, struct_name).replace('$COLUMN_COUNT', str(column_count)).replace('$PK_COLUMN_COUNT', str(pk_column_count)))
print(run_query(prepare_query(gen_names, table_name, struct_name)).replace('""', '"').strip('"'))
print("")
print(run_query(prepare_query(gen_types, table_name, struct_name)).strip('"'))
print("")
print(run_query(prepare_query(pk_columns, table_name, struct_name)).replace('""', '"').strip('"'))
print(footer)
| 32.466667 | 167 | 0.683485 |
45665b29494df65951d81b30841b182a36eb842d
| 867 |
py
|
Python
|
reverse/HolyGrenade/HolyGrenade.py
|
killua4564/2019-AIS3-preexam
|
b13b5c9d3a2ec8beef7cca781154655bb51605e3
|
[
"MIT"
] | 1 |
2019-06-15T11:45:41.000Z
|
2019-06-15T11:45:41.000Z
|
reverse/HolyGrenade/HolyGrenade.py
|
killua4564/2019-AIS3-preexam
|
b13b5c9d3a2ec8beef7cca781154655bb51605e3
|
[
"MIT"
] | null | null | null |
reverse/HolyGrenade/HolyGrenade.py
|
killua4564/2019-AIS3-preexam
|
b13b5c9d3a2ec8beef7cca781154655bb51605e3
|
[
"MIT"
] | null | null | null |
# uncompyle6 version 3.3.3
# Python bytecode 3.7 (3394)
# Decompiled from: Python 2.7.16 (default, Mar 4 2019, 09:01:38)
# [GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.11.45.5)]
# Embedded file name: HolyGrenade.py
# Size of source mod 2**32: 829 bytes
from secret import flag
from hashlib import md5
def OO0o(arg):
arg = bytearray(arg, 'ascii')
for Oo0Ooo in range(0, len(arg), 4):
O0O0OO0O0O0 = arg[Oo0Ooo]
iiiii = arg[(Oo0Ooo + 1)]
ooo0OO = arg[(Oo0Ooo + 2)]
II1 = arg[(Oo0Ooo + 3)]
arg[Oo0Ooo + 2] = II1
arg[Oo0Ooo + 1] = O0O0OO0O0O0
arg[Oo0Ooo + 3] = iiiii
arg[Oo0Ooo] = ooo0OO
return arg.decode('ascii')
flag += '0' * (len(flag) % 4)
for Oo0Ooo in range(0, len(flag), 4):
print(OO0o(md5(bytes(flag[Oo0Ooo:Oo0Ooo + 4])).hexdigest()))
# okay decompiling HolyGrenade.pyc
| 29.896552 | 66 | 0.61707 |
45b1793519009229cd66f10c162d926a05e3b58b
| 1,799 |
py
|
Python
|
src/network/conversations/block_broadcasting.py
|
TimmMoetz/blockchain-lab
|
02bb55cc201586dbdc8fdc252a32381f525e83ff
|
[
"RSA-MD"
] | 2 |
2021-11-08T12:00:02.000Z
|
2021-11-12T18:37:52.000Z
|
src/network/conversations/block_broadcasting.py
|
TimmMoetz/blockchain-lab
|
02bb55cc201586dbdc8fdc252a32381f525e83ff
|
[
"RSA-MD"
] | null | null | null |
src/network/conversations/block_broadcasting.py
|
TimmMoetz/blockchain-lab
|
02bb55cc201586dbdc8fdc252a32381f525e83ff
|
[
"RSA-MD"
] | 1 |
2022-03-28T13:49:37.000Z
|
2022-03-28T13:49:37.000Z
|
from .block_download import Block_download
from ..bo.messages.get_blocks import Get_blocks
from ..bo.messages.block_message import Block_message
import os
import sys
sys.path.append("..")
from src.db.mapper import Mapper
from src.blockchain.block import Block
class Block_broadcasting():
def __init__(self, node) -> None:
self.node = node
# node that broadcasts the block
def broadcast_block(self, block: Block):
msg = Block_message(block)
self.node.send_to_nodes(msg.to_dict())
# node that receives the block
def block_received(self, sender_node_conn, message):
msg_in = Block_message.from_dict(message)
block = msg_in.get_block()
my_block_hashes = os.listdir(os.getcwd() + "/db/blocks/")
local_latest_block_hash = Mapper().read_latest_block_hash()
if block.validate() is False:
print("The block is not valid")
return
if block.saved_hash in my_block_hashes:
print("The local blockchain contains the block already")
return
if block.predecessor == local_latest_block_hash:
block.write_to_file()
Mapper().write_latest_block_hash(block.saved_hash)
print("block saved")
else:
print("the predecessor of the received block doesn't match the local latest block")
print("initiate block download")
block_download = Block_download(self.node)
block_download.get_blocks(sender_node_conn)
# relay block
for conn in self.node.all_nodes:
if conn.id != sender_node_conn.id:
print("relay block " + block.saved_hash + " from Node " + self.node.id + " to Node " + conn.id)
self.node.send_to_node(conn, message)
| 36.714286 | 111 | 0.654252 |
ff27b6f9ec2e89a4fdaa12005c4ca5d1c836ac12
| 47,692 |
py
|
Python
|
python/course/leetcode/53. Maximum Subarray.py
|
TimVan1596/ACM-ICPC
|
07f7d728db1ecd09c5a3d0f05521930b14eb9883
|
[
"Apache-2.0"
] | 1 |
2019-05-22T07:12:34.000Z
|
2019-05-22T07:12:34.000Z
|
python/course/leetcode/53. Maximum Subarray.py
|
TimVan1596/ACM-ICPC
|
07f7d728db1ecd09c5a3d0f05521930b14eb9883
|
[
"Apache-2.0"
] | 3 |
2021-12-10T01:13:54.000Z
|
2021-12-14T21:18:42.000Z
|
python/course/leetcode/53. Maximum Subarray.py
|
TimVan1596/ACM-ICPC
|
07f7d728db1ecd09c5a3d0f05521930b14eb9883
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding:utf-8 -*-
# @Time:2020/6/29 18:52
# @Author:TimVan
# @File:53. Maximum Subarray.py
# @Software:PyCharm
# 53. Maximum Subarray
# Given an integer array nums, find the contiguous subarray (containing at least one number)
# which has the largest sum and return its sum.
#
# Example:
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
# Follow up:
# If you have figured out the O(n) solution,
# try coding another solution using the divide and conquer approach, which is more subtle.
from typing import List
# # 状态:超出时间限制
# class Solution:
# def maxSubArray(self, nums: List[int]) -> int:
# maxSum = nums[0]
# lens = len(nums)
# for i in range(0, lens, 1):
# base = nums[i]
# if base > maxSum:
# maxSum = base
# for j in range(i + 1, lens, 1):
# # print("%d~%d" % (i, j))
# base += nums[j]
# if base > maxSum:
# maxSum = base
# return maxSum
# 动态规划(子问题)
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
lens = len(nums)
maxSum = nums[-1]
dpDict = {(lens - 1, lens - 1): nums[-1]}
for i in range(lens - 1, -1, -1):
for j in range(i, lens, 1):
if i == j:
dpDict[(i, j)] = nums[i]
else:
dpDict[(i, j)] = dpDict.get((i, i)) + dpDict.get((i + 1, j))
if dpDict.get((i, j)) > maxSum:
maxSum = dpDict.get((i, j))
return maxSum
solution = Solution()
inputArr = [
# [-2, 1, -3, 4, -1, 2, 1, -5, 4]s
# ,
# [100]
# ,
# [-1, 100]
# ,
# [-2, 1]
# ,
# [2, 1, -3, 4]
# ,
[-57, 9, -72, -72, -62, 45, -97, 24, -39, 35, -82, -4, -63, 1, -93, 42, 44, 1, -75, -25, -87, -16, 9, -59, 20, 5,
-95, -41, 4, -30, 47, 46, 78, 52, 74, 93, -3, 53, 17, 34, -34, 34, -69, -21, -87, -86, -79, 56, -9, -55, -69, 3, 5,
16, 21, -75, -79, 2, -39, 25, 72, 84, -52, 27, 36, 98, 20, -90, 52, -85, 44, 94, 25, 51, -27, 37, 41, -6, -30, -68,
15, -23, 11, -79, 93, -68, -78, 90, 11, -41, -8, -17, -56, 17, 86, 56, 15, 7, 66, -56, -2, -13, -62, -77, -62, -12,
37, 55, 81, -93, 86, -27, -39, -3, -30, -46, 6, -8, -79, -83, 50, -10, -24, 70, -93, -38, 27, -2, 45, -7, 42, -57,
79, 56, -57, 93, -56, 79, 48, -98, 62, 11, -48, -77, 84, 21, -47, -10, -87, -49, -17, 40, 40, 35, 10, 23, 97, -63,
-79, 19, 6, 39, 62, -38, -27, 81, -68, -7, 60, 79, -28, -1, -33, 23, 22, -48, -79, 51, 18, -66, -98, -98, 50, 41,
13, -63, -59, 10, -49, -38, -70, 56, 77, 68, 95, -73, 26, -73, 20, -14, 83, 91, 61, -50, -9, -40, 1, 11, -88, -80,
21, 89, 97, -29, 8, 10, -15, 48, 97, 35, 86, -96, -9, 64, 48, -37, 90, -26, -10, -13, 36, -27, -45, -3, -1, 45, 34,
77, -66, 22, 73, 54, 11, 70, -97, -81, -43, -13, 44, -69, -78, 30, -66, -11, -29, 58, 52, -61, -68, -81, 25, 44,
-32, 57, -81, 66, 2, 52, 43, 35, -26, 16, -33, 61, -37, -54, 80, -3, 32, 24, 27, 30, -69, 38, -81, 2, -4, 47, 17,
5, 42, -58, -51, -90, 98, -33, 76, -22, 95, -4, 89, -31, -87, -44, -69, -48, 1, 87, 48, -90, -12, -24, 39, 18, -86,
35, 96, -14, -41, 13, 90, -98, 32, -83, -89, 7, -17, 63, 84, -21, -40, 51, 24, -51, 83, 31, 0, -38, -5, -74, -29,
59, 1, 87, -22, -9, -1, -49, 76, 57, 41, 44, 35, -27, 60, 23, 56, -80, -14, 41, -2, 22, -31, 99, 47, -48, 7, -75,
13, -97, -50, 61, 61, 27, 48, -84, 94, -76, -56, 70, 57, 84, -9, -7, -66, -49, -84, 89, -29, -22, 7, 45, -99, 75,
21, 24, -95, -71, 48, 17, -92, 74, -22, 45, 1, -97, 61, -5, -74, 81, -57, 83, 42, 33, -47, 75, 61, -55, 41, -68,
22, -51, 53, -1, -99, -25, -76, -95, 3, 48, -1, -13, 23, 53, -68, -76, 33, 92, -4, 35, 50, 38, 18, -8, -52, 47,
-33, -91, 91, 85, -60, 14, -89, 93, 89, -89, -55, 89, 92, 47, 38, -9, -66, -39, -79, -58, -39, 53, -65, 56, -11,
61, -29, 83, -46, 19, 31, -3, 27, -1, -18, 67, -87, -8, 37, 79, -20, 58, 68, -28, -18, -17, 39, -8, 43, 59, 33, 81,
13, 44, 37, -98, 6, 85, 84, 59, 4, -8, -44, -69, 91, 15, 74, 80, 83, -12, 59, -37, -54, 5, 34, 27, 87, -50, -81, 8,
-90, 52, -11, -1, -4, -97, 0, 78, 87, -39, 37, -32, 30, 70, -1, 21, -38, -50, -22, -55, 15, -85, 8, 60, 19, -81,
-35, -17, -31, -40, 90, -45, -88, -44, 53, -15, -41, -70, -37, -77, -33, 77, -9, 96, 24, 66, -6, 85, 92, 72, -70,
7, 86, 14, -32, -18, 33, 9, 64, 78, 68, 32, -90, 57, 87, 62, -58, -77, 68, -19, -54, -65, -42, 13, -68, 58, -44,
25, 43, -52, -26, 73, 55, -63, -13, -77, 18, 96, 31, -40, 51, -1, 91, 60, -44, 55, 22, -26, 78, -10, 32, -99, 2,
66, 13, 33, 25, 68, -65, -32, -84, -14, -82, 70, 22, 5, 69, -59, -22, -23, 0, -70, 53, -32, 89, 85, -77, -11, -40,
77, 55, 68, 77, -43, 34, -33, 66, -41, -88, -98, 27, -72, -13, 21, 74, 85, -74, 21, -74, -19, 97, 2, 10, 50, 46,
-1, 13, 69, 87, 72, 23, 20, 40, 1, 76, -49, 67, 43, 10, 79, 21, -86, 83, 84, 34, 34, 69, 37, -45, 72, -82, -70,
-26, 27, 56, 97, -97, -31, 66, 67, -82, -11, -13, 57, 66, -37, 85, 11, 82, -5, -33, 3, -15, -50, -13, 95, 60, -66,
9, -84, -94, 26, -78, -44, -70, 77, -47, -90, -53, 95, 76, -36, -38, -60, 98, -72, -21, 83, 15, -38, -45, 81, 41,
16, -69, -94, 11, 91, -84, -79, 83, -79, 23, -95, -24, 30, 58, 6, 39, -95, 1, -8, -54, 62, 31, -56, 67, 86, -96,
-18, -75, -42, -36, 66, 73, -29, 48, -39, -61, 63, -42, 98, 60, 81, -97, -64, 11, 61, 18, -73, 42, -80, 18, 87, 58,
-51, -69, 2, -88, -66, 84, -63, -32, -75, 79, -82, -28, 27, -21, 11, -33, 13, 9, -73, -6, -11, -61, 81, -73, 57,
-92, 45, 53, 25, 33, 11, 50, 40, 90, 62, 51, 74, 75, -81, 75, 54, -86, -53, -42, -8, 34, 1, -95, -79, 27, -24, -14,
42, -66, 12, -24, -58, -66, -71, 43, 66, 17, -29, -16, 7, -90, -65, -42, 84, -70, -90, 15, -57, -67, 49, 11, 67,
-50, -7, 64, 53, 68, -50, -5, 78, 38, 71, 96, 71, 76, 40, 15, -7, 87, 98, 76, 96, -90, -66, 57, -61, -57, -51, -41,
-47, 97, 69, -80, -53, -61, 83, 76, 83, -90, -29, 62, 47, -81, 58, 18, 95, -2, -67, -12, -38, -92, -35, -65, -83,
-25, 91, -44, -5, -83, -9, 47, -86, -40, 43, -63, -1, 3, -87, -18, 12, -39, -79, -41, -21, 79, 53, -26, -46, 63,
39, 16, 70, 80, 50, 87, -45, 19, -80, 26, 35, 10, -27, 26, 46, 92, 62, -55, -5, 52, 4, -93, -87, 1, -58, -9, -20,
95, 42, 34, 58, -19, -73, 5, -39, 53, -31, -8, -28, -12, 95, 84, 97, -55, 10, 44, -62, -51, 65, 32, -99, -54, 16,
89, 47, 57, -42, -96, 52, 99, 14, -13, -43, 40, 69, -6, -6, -62, 85, 42, 26, 80, 26, 0, -74, -87, -79, -60, -38,
63, 71, -61, 85, -13, -71, 9, -78, -14, 13, 50, -38, -73, -85, 18, 44, 83, -88, -85, -79, 73, 56, 23, 31, -40, -99,
33, -51, 97, 72, -13, 60, 20, 26, 46, 84, 31, -45, -94, 93, 67, 55, -45, 71, 69, 49, 15, 52, 37, 29, 50, -13, -38,
-50, -82, -2, -73, 27, 47, -75, -24, -66, 84, 96, 36, 7, 80, -56, 62, 62, -63, 6, 17, -32, -46, -13, 93, 45, -84,
30, -26, 42, -82, 13, 92, -88, -89, -81, 16, 34, -57, 91, 45, -95, 87, -42, 11, 44, 2, -50, 6, 15, 33, -76, 83, 86,
-13, 76, 32, -21, -16, 82, -78, -22, -28, 90, -34, -40, -91, 81, 93, -71, 73, 15, -90, 37, 73, -3, -41, -48, 47,
64, 66, -43, 64, 49, -57, -72, 3, 51, 7, 63, 11, 28, -82, 82, 18, -17, -58, 3, -58, -87, 8, -85, 27, 17, 28, -23,
-85, 86, 28, 38, 28, -5, 94, -31, -79, -86, -3, 0, 65, 80, -60, -24, 8, -43, -65, -97, 40, -23, -18, 81, -11, 90,
72, 92, -16, 0, -30, -25, -36, 97, -87, 68, -31, 83, -63, -33, 97, 10, 66, 39, -10, -93, 91, 74, -37, -74, 53, 79,
-21, -64, 37, 67, -74, 9, 60, 9, 86, -70, 84, -73, -96, 73, 94, -50, 57, -69, 16, 31, 18, -18, -53, -92, -35, -62,
59, 5, -60, 12, -16, 19, 47, -78, -14, 49, 7, -77, -64, -7, -71, 96, 19, -67, 69, -10, -18, 3, -2, 97, -89, -84,
-44, -43, 99, -2, -6, 58, -97, 11, -29, -14, -70, 94, -16, -8, 44, 91, 15, 79, -39, 20, 75, 57, 52, 21, -53, -89,
-98, 44, 84, -88, 36, -82, -31, 36, 15, 39, -29, 17, -50, 41, 79, -21, 13, -36, 71, -66, -68, -37, 89, -8, 82, 41,
-74, 12, -38, -50, -1, -37, 70, -39, -48, 7, -22, 20, -57, 69, -41, 13, -14, -14, -68, -58, 64, 21, 5, 12, 54, 13,
51, 43, -94, 11, -16, -92, 99, 22, -43, -2, 62, -72, 58, -86, 11, -87, 33, 53, 81, 68, -57, -56, -46, -49, -14, 95,
71, 67, -16, 2, -19, -87, -78, -37, 0, -18, -30, -1, -95, 4, 96, 66, 31, 32, 79, -81, 44, -11, 48, 3, -66, 90, 46,
-12, -81, -91, -40, 66, 76, 20, -54, -43, 9, -33, 19, -91, 49, 88, 7, 30, -8, -19, -4, 99, -87, -48, -82, 33, 40,
65, -64, 73, 33, 59, -62, 28, 67, -26, -29, 43, 71, 16, 99, -20, 83, 18, -11, 9, -16, 72, -61, 52, -47, 34, 29,
-58, 85, 23, 75, 2, -34, 87, -48, 75, 46, -33, 3, -9, 40, 73, -66, -12, -10, -89, 68, -50, 5, -66, 58, 88, 82, 96,
18, -64, 7, -53, -23, -31, 69, -71, 47, -88, -83, 98, 86, 39, -35, -34, -70, 82, -60, -36, -30, 6, -26, -85, 55,
55, -75, -10, 44, 84, -37, -38, -80, 69, -15, -27, -85, -69, -21, 61, -57, -5, 59, -71, -66, -98, -5, -59, 60, 11,
4, -93, 93, 54, 98, 48, 9, 99, -85, -70, 83, -23, -32, 79, -77, 52, -47, -63, 60, 8, 97, -97, -97, 33, -92, -87,
11, -21, -47, -29, 66, 33, -45, 59, -36, -47, -16, 50, -48, -2, 79, -64, 51, -75, -85, 73, 76, -56, -90, 13, 51,
83, -8, 30, 17, -23, 20, -72, 55, 49, -24, -1, -17, 7, -42, 23, 59, 42, -27, 87, -83, -47, 99, 68, -46, 91, 18,
-93, -88, 28, 20, 40, -12, -88, -30, -95, -12, 66, -90, -79, 16, -38, 19, 75, 68, 76, -2, 27, -5, 71, -9, 12, -99,
-32, -43, -46, -41, 74, -40, -53, -21, 79, 86, 67, 68, -66, 48, -67, 99, 57, -47, 15, -81, 71, -33, 86, 25, 65,
-10, 96, 36, 58, -15, 13, -74, 41, 66, -39, -7, -97, 7, 71, 59, -6, 15, 27, 4, -36, 59, 3, -79, 89, 95, -83, 37,
-38, 79, -38, -96, -53, -41, 39, -95, 43, -71, -93, -38, 71, -33, 54, 74, 50, 2, 10, -79, -82, -86, 24, -19, 49,
-95, 1, 38, 99, -6, -24, -62, -26, 14, -58, 20, 49, 57, 1, -7, 63, -16, 31, 34, 50, -15, -15, -23, 86, 94, -2, -96,
-92, 98, -39, 34, -97, 62, -28, 78, -67, 24, 93, 6, -61, -65, -97, 87, 68, -20, -43, 31, 63, 87, -57, -10, -51, 27,
67, -87, -1, -35, -84, -17, -60, -23, -83, -57, -84, -34, -79, -52, 89, -86, 31, -95, -75, 10, 69, 70, 90, -97, 1,
53, 67, 43, -56, -84, -52, 87, -72, 46, -71, -79, -71, -32, -26, -77, 10, -34, -12, 8, -10, -46, -2, -79, -41, 0,
8, -95, -30, -2, 83, 47, -72, 50, -9, -29, 43, 15, -65, 70, -39, -37, 67, -34, 31, -59, -12, -82, 6, 75, 25, 96,
-70, -99, 93, -35, 0, 1, -54, 69, 75, -71, 16, -96, 56, 83, -49, -1, -2, -14, -31, 35, 48, -86, -98, -21, -46, -34,
-3, 37, -58, 98, 10, -52, 98, 3, -11, -2, 81, 11, -33, 56, 16, 60, 36, -28, 43, 87, 47, -81, -50, 93, 53, 97, -93,
31, -46, -40, 97, 27, 73, -84, 25, -17, -60, 1, 63, 5, 98, 44, -84, -57, -23, 8, 79, 90, 57, 22, 54, 4, 17, -96,
-3, -29, -99, 3, 78, -69, 40, 52, 57, 13, 67, -40, 73, 83, 60, 36, -12, 35, -43, -20, 54, 10, 88, 33, 0, 45, -67,
-46, -51, 49, -43, 23, 96, -65, -74, 52, -35, 42, 4, 99, -67, -28, -41, -94, -45, -81, 18, 43, 53, 74, 99, -15,
-39, 87, -82, 61, 9, -73, 91, 58, 76, -74, -19, 49, -63, -17, 1, 1, -97, -94, -23, -65, -46, 35, -83, 8, 53, 34,
-72, -16, -15, -95, 68, 45, 91, 62, -17, 1, 89, -48, -64, 42, -46, -7, -9, -10, 52, 69, 67, 54, 74, -55, 65, -72,
79, 58, 12, 10, -31, 17, 70, 53, 21, 38, -24, -11, -23, 35, 89, -34, 86, -98, -92, -60, -6, -24, 6, -53, -55, -26,
77, -81, 18, 20, -77, -26, -22, 11, 60, 47, -72, 30, -23, 25, -55, 52, -85, 22, -12, 80, 87, -49, 59, 72, -32, -47,
-52, 73, -24, -8, -76, -69, -13, 18, 50, 9, 92, -95, 96, 52, 51, -98, -40, -71, 26, 4, 57, 17, -74, -78, -25, 90,
-50, -66, 39, 17, -37, 86, -33, 39, -45, -9, 69, 41, -91, -4, -73, 77, 0, -77, 7, -48, -76, 66, -43, 50, -30, 90,
-56, -27, -87, -5, -37, -38, 28, -98, 55, 91, 64, -78, 7, -81, 12, -47, 36, -2, 48, 62, -25, -75, 84, 81, -47, -91,
24, -14, 35, 94, -23, 78, -56, -34, -49, -17, 27, 78, -16, -18, 46, -75, -20, -70, -80, 92, -18, 55, -10, -93, 17,
41, -68, 1, 0, -39, -14, -76, 47, -79, 94, -76, 76, -62, -11, -73, 20, 92, 81, 80, -49, 28, -95, 30, 34, -99, 22,
-83, 55, 88, 99, -28, 7, -69, 50, -93, -8, -64, -93, -61, -66, -98, -61, 86, -61, 27, -87, 59, -4, 70, 16, 46, -25,
-2, -24, -90, -2, 75, -74, -46, 40, -98, 2, -53, -67, -48, -70, 1, -35, -63, 16, -2, -62, 31, -39, -47, -65, -27,
88, 30, -80, 5, -24, -5, -97, 51, 4, 0, 26, 6, 30, -33, 7, -67, -10, 16, -39, 20, 93, 25, 56, -14, 99, 70, -83,
-40, -77, -49, 9, -88, 80, 29, 16, -67, -99, -5, 84, -19, 71, -13, 86, 2, 30, -30, 11, -79, 63, 71, 17, 33, -26,
-27, -80, -27, -57, -87, 10, -35, -36, 95, -47, -79, 1, 45, -69, 1, -60, -85, 81, -88, -22, 44, -10, 85, 91, -99,
-94, 31, 48, -1, -36, -78, 71, -40, -28, 90, -27, 58, -68, 13, 53, -15, 10, -45, -70, 40, 32, -30, 31, -9, -42, 86,
-65, 24, 71, -97, 24, 53, 33, -51, -48, 97, -29, 99, -66, 42, 89, 6, 0, -79, 95, -70, 5, 6, -39, 12, -54, 93, 58,
54, -16, 92, 40, -5, 16, 11, -25, -83, -59, -92, -35, -8, 81, 35, -9, -84, -46, -43, -2, 30, -23, -6, 60, 59, 99,
97, -29, -78, 90, -94, 52, -49, 97, -8, 23, 13, 79, 97, 6, -80, -95, 70, -12, 63, -17, 55, 55, 36, -88, -47, -56,
-34, 23, -96, -98, 22, -99, -28, 21, 68, -46, -50, 95, -49, 42, 18, 40, -2, 15, -54, -5, -3, -84, 82, -63, -25, 15,
91, -88, 3, -56, -68, 68, 67, -88, 69, -34, 88, -82, 63, 56, -29, -86, 52, -2, 32, -53, -62, -70, 62, -17, 1, -64,
-24, -39, -28, 50, 75, -37, 38, -22, -17, 69, -53, -73, 80, 92, -30, 69, -89, -67, 2, -42, -77, -69, 56, 31, -22,
93, 61, -83, -46, -61, -48, 6, -1, 23, -67, -26, 62, 48, 29, -55, 17, 52, -51, -25, 44, 18, -79, 31, 27, 22, 89,
50, 53, 22, -42, -92, -8, -81, -76, 22, -65, -25, -72, 33, 74, -62, 84, 13, 85, 13, 57, 2, -58, 82, 53, 62, 0, 73,
-6, -72, -27, -40, 54, -74, 58, -88, -90, -50, -92, -67, 72, -81, -16, 76, 51, -65, -86, 35, 47, 98, -75, -19, -22,
-57, -36, -69, -94, 40, -95, -24, 67, -46, 35, -2, -44, -7, -13, -35, 19, -29, -3, -9, -11, 57, -55, -83, 91, -42,
29, 38, -43, 53, 95, 34, 73, -41, 41, 78, 99, 22, -46, 43, 75, 65, -81, -69, -65, -18, -5, 53, 29, 68, -78, -82,
25, -34, -89, -7, 23, 39, -69, 56, -30, -96, -33, -57, -38, -91, 97, -39, 30, -49, 81, 6, 92, 99, 36, -73, -42,
-68, 56, 86, 76, 54, 80, 2, 96, 90, 94, 20, 7, -97, -47, 76, -94, 20, -81, -56, 28, -84, -18, -42, -57, -37, 40,
-88, -61, -23, -62, -4, -15, 70, -18, -39, 2, -61, 39, -2, -71, 34, 94, 35, 13, -52, -12, 18, 67, -17, 38, -28,
-25, -80, 6, 17, -18, -53, 5, -3, 0, 42, 92, 61, -10, -49, -78, 91, -11, 61, -11, -5, -28, -16, -93, 84, 8, -5,
-21, -48, 54, -83, 0, -70, -86, -94, 23, -5, -71, -71, 92, 5, 47, 61, -34, -63, 89, -35, -95, -22, -74, -29, 49,
-26, 31, 33, -42, -61, -95, 13, -10, 58, 6, 89, 87, 19, 71, -12, 91, 77, 16, 60, -18, -37, 21, 25, -23, 10, 89,
-42, 65, 91, 28, -9, -35, -41, -76, -1, -26, -72, 88, 40, 63, -6, 6, 50, 90, -45, -62, 81, -68, 30, 41, -10, 93,
-61, -85, -53, 26, 80, 4, -9, 71, -90, 58, -64, -55, 82, 11, 19, 86, -1, -64, 49, 70, 42, -23, 60, 96, -9, 18, -72,
-78, -41, -6, 91, -26, 9, -62, 99, -11, 41, -33, -62, 50, -74, -27, 95, 84, 61, -9, 70, -40, 26, -3, -93, -55, 73,
66, -59, -59, -16, -55, -38, 19, 39, -47, 93, -52, -10, 69, 13, -91, -63, 50, 35, -38, -99, 7, -54, 61, 74, 92, 97,
-22, -11, -95, 22, -61, 47, 63, -20, -91, -92, 18, 27, 23, 71, -3, 47, -62, -33, -39, -77, -20, 87, 35, 41, 87,
-81, 63, 25, 93, 32, 23, -29, 98, 4, 92, -63, -72, 32, -7, -64, 17, -88, 40, -60, 59, -86, 87, 73, -43, -75, 73,
36, -88, 8, -46, 99, 3, -83, 1, -4, 26, -99, 43, 24, -19, 13, 60, 9, -55, -69, 44, 61, -81, -39, 78, 54, -25, 65,
4, 31, 89, -23, -55, 77, 61, -2, 53, -35, -8, -45, 37, -82, -45, -19, 41, 36, 93, -22, -78, -85, 8, 65, 76, 3, -96,
54, -43, -45, -4, 61, 62, -38, -62, -93, -61, 76, -18, 69, -82, 73, -76, 54, 67, -45, -88, 8, 67, 81, 62, 88, 96,
-52, 54, 49, 50, 34, -20, 84, 88, 52, 45, 50, -86, 59, 57, -71, 35, -84, 97, 29, 88, 97, -16, 55, -47, -28, -60,
-80, -46, 78, -91, -73, -74, 39, 52, 53, -50, -68, 37, -62, 60, -18, 64, 73, -82, -2, 78, 30, 13, 53, -41, -22, 50,
19, -90, 79, 91, -51, 76, -78, -95, 61, -75, -70, -23, 76, 59, 26, 84, -4, 40, 44, 54, -19, -6, 72, 79, -51, 2, -8,
-98, 37, 47, 29, -43, 56, -15, -75, -94, -39, -77, 86, 98, -53, -84, -25, 99, 75, 77, 60, -52, -6, -19, -97, 75,
74, 74, 54, -77, -47, -77, -98, 66, 69, 30, -77, 26, -85, -76, 8, -47, -54, -6, -49, -31, -14, 3, -55, -62, -20,
-95, -14, 51, -15, -35, 26, -64, -84, -43, -41, -32, -44, -63, -89, -97, 66, -89, 28, 57, -66, -87, -90, -43, -17,
-39, 2, 45, 40, 47, 83, 96, 51, -54, 47, -86, 10, -50, -51, 2, 6, -16, 46, 62, 20, 56, 64, -14, 66, -31, -56, 77,
-42, -70, -66, 17, -33, 12, -38, -93, -41, -78, -96, 87, -56, 27, -99, 30, 77, -51, -68, -40, 33, 77, 98, -70, 34,
39, 16, 0, -92, 36, -23, -58, 65, -13, 35, -67, 99, 97, -84, -65, 95, -81, -78, -60, 23, 98, 69, 0, -52, -98, 59,
57, 78, 58, 86, -11, -3, -21, 89, -18, 91, -57, 0, 57, 7, -64, 66, -17, -90, 81, 17, -95, 77, 16, -79, 0, 14, 90,
99, 38, 68, 35, -28, 23, -30, -64, -87, 67, 14, -98, -74, 6, -79, 25, -60, 4, 37, 82, 86, 46, 63, -19, 28, 40, 96,
48, -60, -13, 15, -84, -74, -17, 28, -3, -93, 97, 9, 95, 41, -99, 96, 66, 6, 93, -31, 22, -2, 82, 4, -16, 29, -56,
41, -66, 84, 37, 58, -99, -75, -26, 93, -73, 33, 21, 0, 16, 18, -90, 11, -63, -90, -16, -97, -8, -45, -52, -86, 52,
-69, -6, -87, 36, 37, 54, 69, -2, -32, 27, -1, -8, 77, -31, -5, -12, 66, 95, 80, -39, -95, -31, -3, 90, 52, 0, -18,
-93, 47, -28, 35, 54, 65, 25, -10, -21, -21, -41, 77, 46, 63, -47, -84, 17, -2, 10, -95, -36, 5, 85, 24, -14, -46,
-78, -24, 82, -2, 34, 66, -78, -94, -22, 76, 47, -97, -34, -96, -42, 2, 57, 81, -58, -90, 96, 58, 7, -17, 40, 47,
65, 2, -29, -72, 55, -31, -19, 14, 66, -85, -43, 65, 97, 35, 41, 21, 14, 83, 24, 72, -38, -19, 53, 3, -33, 26, -61,
73, 85, 78, -3, 50, -20, 68, 78, -88, -63, -41, 2, 80, -50, 59, 45, -53, -6, -37, 68, 84, -77, -31, 56, -38, 27,
-14, 64, 93, 88, 79, 44, 74, 57, -59, 24, -86, -91, -21, -75, -77, 14, 4, 79, 41, -37, 24, 87, 33, 63, 32, 17, 62,
78, -49, -76, 5, 36, 65, -2, 25, 44, -58, -24, -21, -40, 76, -8, -32, -44, -6, -33, 46, 97, -54, -13, -63, 46, -48,
69, 9, 60, -37, -28, 38, 13, -5, -57, -73, -63, 18, 28, 81, 59, -96, -40, -81, 79, 28, -36, -88, 98, 7, 58, 72, 53,
-78, -91, -1, -27, 54, 85, -66, -82, -66, 48, 7, 5, 91, 33, 42, 9, -62, 0, -55, -59, 36, -59, -79, -36, -19, -68,
-60, 87, 66, -88, 17, 88, 97, 93, -62, 51, 55, -52, 45, 88, 96, -47, -7, 64, 62, -88, -50, -99, 11, -6, -82, -53,
11, -62, -12, 68, -53, 27, 33, -87, 38, -50, 77, 12, -80, 92, -36, 74, -60, -91, 39, -87, -62, -90, 76, 77, -79,
-74, 54, 9, -3, 71, 55, 84, 86, -57, 53, -67, 46, -14, -78, -38, 12, 76, 73, 9, 68, -86, -40, -92, -77, 99, 97,
-63, 85, 73, -86, -94, 76, 44, -9, -50, 16, -53, -89, 2, -34, 63, 34, 89, -74, 32, -49, 15, 8, -76, -99, -24, -62,
-40, -39, -63, -41, -42, -50, -56, -92, -59, -73, 60, 84, 17, -90, 0, 40, 97, 78, 83, 37, -11, 72, 40, -78, -77,
-45, 29, -77, -45, 82, -63, -9, -80, -50, 50, -46, 0, 70, -39, 17, 73, 98, 1, -32, -92, 78, 84, 81, 56, 67, 19,
-54, 39, -41, -33, 38, 13, 72, 38, 44, 31, 51, -65, 50, -98, 61, -96, -22, 9, -58, 94, -41, -60, -5, 26, -76, -27,
11, -94, -70, -45, 24, -48, 71, 82, 18, -14, -28, -33, -76, 92, 98, 75, -96, 48, 53, 42, 29, -69, -49, 47, -75,
-14, 86, -4, -87, 86, 69, 0, 68, 75, 54, -8, -73, 2, -49, 21, 88, -1, 87, -88, -9, 62, 63, -5, -12, 16, -63, -83,
46, -36, 40, 47, 49, 26, -56, 38, -11, 89, -85, -42, 41, 46, 26, 44, -52, 77, -58, -64, -24, -94, -52, 44, 68, 87,
-61, -44, 4, -48, -51, -73, -8, 65, 51, -82, -9, 71, 56, 56, 60, 70, -86, -22, -7, 40, -78, 41, -6, -60, 76, 46,
-55, -99, -10, -87, 65, 5, -55, -31, 33, -30, -28, -75, -65, 99, -57, 2, 70, 75, -64, 7, 22, -51, 84, -84, 65, 82,
56, -64, -78, 9, 82, -33, 10, -28, -44, -25, 54, -22, 20, -13, 24, 68, 12, 36, 68, 31, -62, 38, 6, -27, -54, -72,
-1, -93, -57, -59, 89, 75, -23, 87, -15, -64, -69, 71, 7, -36, -77, -62, 18, 19, 25, -58, -13, -63, 77, -68, 44,
92, 47, -50, -58, 69, -23, 17, 75, -3, 58, 41, -28, -88, 6, 33, -53, 36, 4, 30, 99, 3, 68, -6, -78, -7, 36, -14, 6,
-10, 17, -50, -18, -36, -24, 24, -67, 29, -59, 85, -74, 75, 26, -25, 86, -68, -92, -67, 45, -11, 63, 21, 91, 8,
-84, 90, 77, 51, -24, -17, -59, 92, 9, 0, -66, 84, -99, -34, -10, -82, -72, 16, 93, 31, 67, 56, 39, 51, 89, -16,
-60, 29, -94, -91, -86, 97, 98, 90, 25, -26, -50, 42, -57, 58, -58, -24, 19, -58, 19, -91, -63, 46, 1, -70, -23,
-32, 85, -83, -80, 51, 0, -64, -43, -18, -56, -30, -21, -58, -40, 80, -8, 9, 23, 35, -56, 64, -89, 39, 83, 29, 48,
-80, -24, -51, -74, 29, -6, 87, 45, 13, 39, -77, 48, 72, 4, 69, -80, 60, 87, -21, 40, -20, 65, -60, -85, 85, 81,
-98, 25, 64, 31, -50, 60, 83, -2, 62, 12, 68, 49, -42, -19, -35, -20, -93, -85, 60, 75, -66, -3, 62, -11, -85, -81,
-69, -46, -67, -83, -65, -65, 41, 75, 42, 67, 12, 25, -35, -26, -63, -66, -99, -29, -9, -58, 27, -26, -44, -12,
-74, -11, 61, 65, 78, 75, 83, -91, -93, 93, -98, -59, -95, 19, 93, 46, -14, 5, -52, 28, 56, -39, 38, 56, 32, -94,
97, -41, -20, -69, 23, 5, 19, -38, -30, -26, -63, -69, -40, -57, -76, -62, -39, -72, 57, -46, 50, -57, 58, 97, 47,
-9, -42, -15, -53, 66, -9, -78, -97, 70, -48, 2, -48, 47, 63, -1, -78, -99, 29, -42, -80, 52, -5, -20, 56, -48, 10,
6, -28, -31, -20, 95, 59, 37, -19, 83, -19, 71, -95, -17, 18, -67, 61, 46, 79, 25, -55, 77, 2, 50, -88, 21, 2, 7,
78, -65, 35, -12, 40, 83, 33, -80, 79, -30, 34, -63, -47, -85, 84, -66, -26, 2, -34, -65, -75, -78, 36, -30, 76,
-62, -80, 87, 59, -1, -29, 37, 33, 83, -75, -49, 66, 58, -53, 22, -72, 57, 58, -43, 48, 42, -10, -78, -79, 32, -66,
-54, 30, 69, -8, 6, -92, -12, -29, 43, 63, 41, -43, -3, 24, -19, 24, -32, -84, 70, 89, -80, 5, 48, -24, -47, -33,
42, -25, -12, -49, -15, 10, 81, -69, -98, -36, -85, -11, 34, 57, -47, -47, -86, 26, 76, -28, -73, -79, -36, 73,
-89, -16, -22, 35, 36, 31, 78, -44, 82, -34, 6, -33, 75, -36, -26, 53, 5, -11, -80, -84, -77, -28, -32, -63, 74,
-78, -15, -99, -58, 48, 73, -71, -91, -48, 40, 22, 59, 19, 77, 41, 61, -40, 84, 14, 1, -42, -33, -94, 46, -37, -79,
69, 34, -34, 82, -15, -13, -56, -15, 5, 68, -64, 11, 77, -36, -49, -24, -77, 46, -47, 63, 8, -11, 47, 98, 89, -95,
-58, 71, 28, 5, 69, -3, -61, -65, -44, 1, -2, -1, 85, -97, -56, 97, -10, -79, -39, 41, -4, -17, -13, 25, -54, 71,
91, 92, 69, 57, 97, 88, 29, 2, -7, -2, 98, 8, 9, -69, -91, 83, 6, 71, 62, 49, 68, -47, 47, -70, 93, -80, 12, -43,
22, 58, -94, 13, 50, 51, -30, 24, 39, 75, -74, -68, -50, -99, 17, 35, -92, 25, 18, -10, -4, -19, -60, -35, 33, 63,
-6, 3, 82, 82, 59, 4, 40, 41, 93, -32, -7, -59, 68, -91, -84, 71, -82, -57, 48, 34, 77, 56, -64, -4, -77, 32, 76,
-38, 73, 9, -75, -56, -88, 84, -74, 47, -12, 66, -34, -41, -89, 35, -1, 78, 43, -9, 49, 37, 33, -25, -29, 11, -92,
7, 83, -70, -84, 59, -8, 88, -55, -7, -91, -67, -23, -66, 79, 42, 76, -78, 77, 86, 56, -24, 65, -23, 43, -9, -86,
-23, 65, -38, 64, 49, 68, 47, 79, 60, 6, -29, 25, 27, 40, 33, 59, -82, 66, 15, 36, 20, 37, 13, 6, -30, 65, -52, 46,
8, 16, 60, 61, -42, -78, 25, -92, 66, -51, 86, 26, 54, -66, -49, -19, 73, 60, -83, 67, 3, 32, 3, -77, -31, 92, 29,
38, 34, 76, -38, -57, -31, -78, 80, 27, -80, 6, 34, 85, 54, 20, -12, -14, 53, 15, 43, 26, -25, 60, -29, 54, -31,
50, 77, 37, 43, 6, -48, -46, -41, 13, -4, 28, 11, -46, -68, 30, 36, 65, -8, -10, -15, 56, 52, -85, -52, -27, 17,
-1, -67, 87, -46, -22, 38, -69, -85, -19, 13, -57, 34, 48, 33, -92, -47, -56, -62, -16, 51, 73, -51, -80, -60, 10,
53, 92, 24, -99, -35, -58, 0, -26, -71, 30, 51, 66, 60, 42, -76, -50, 61, 35, 97, -6, 19, -49, 15, 56, 34, -57, 6,
60, -38, 45, -30, 91, 37, 71, 92, 78, -87, -31, -71, -82, 98, 79, 61, 35, -2, 61, 84, -63, -27, 81, 30, 68, -91,
-78, 24, 43, -36, -93, 3, 3, 52, 49, -6, -11, 20, -37, -55, 9, 31, -27, 4, 6, -70, -35, -59, 27, -97, -75, 40, -24,
-93, -29, -56, 91, -31, 45, 34, 10, 51, -86, 89, 3, 63, -17, 69, -40, 23, -86, 69, -46, -14, -27, 60, -8, 14, -99,
96, 16, -97, 36, 68, 85, -93, -87, 76, -47, 34, 11, 62, -38, 1, 51, 65, -59, -89, 11, 1, 33, 24, -53, 64, 86, -4,
1, -44, 86, -22, -48, -21, -20, 87, -52, -35, 71, -63, -58, -76, 47, 29, 62, -91, -93, 13, 73, -52, 0, -39, 25,
-66, 61, 48, 74, 48, -79, -25, -96, -93, 52, -68, -38, -67, -81, -14, -26, 89, 22, -8, -87, -31, -79, 74, -45, -95,
-36, -72, -71, 64, -34, 53, 74, -73, -22, 25, 51, -25, 99, 31, -19, 28, 62, 19, 37, 81, -94, -88, 70, 4, 3, 83, 50,
1, 34, -95, -18, 75, -91, 10, 39, -26, -60, -10, 1, 17, -85, -48, 91, 90, 83, -51, 18, 45, 44, -44, 3, 49, -56,
-26, -46, 46, -66, -96, -76, 67, -92, 5, 42, -84, -85, -42, -10, -46, 24, 67, 47, 38, -81, 15, 28, 78, 40, -76, 1,
-15, -21, -96, -66, 22, -23, -36, -55, 10, -33, -54, -45, -49, 50, 73, -33, 42, -91, 33, 95, 32, -23, 20, -52, -5,
-65, 52, -49, 52, 75, 51, -63, -69, 54, -30, 29, -91, 34, 51, -5, 77, 96, 26, -71, 46, -23, -28, -12, -15, 81, -39,
93, -42, 57, -82, 29, 68, 47, 79, 20, -1, 7, 56, 30, -61, -96, -64, -53, 14, 86, 18, -9, 82, -55, -4, 29, 21, 44,
93, 82, 2, -69, 52, 36, 87, 70, -34, 56, 17, -78, -24, 92, 6, -67, 22, 44, -87, 35, 90, 26, 21, -15, 93, 4, 29,
-10, -90, -73, -89, 79, 85, 13, -89, 38, -51, 74, -15, -9, 30, 78, -10, 83, 70, 95, 92, -30, 39, -95, -95, 6, 30,
2, 90, 0, -94, -3, 66, 91, 23, 77, 48, -14, -33, 35, -76, -8, 9, -15, 83, -83, -37, -27, 76, -90, -32, 68, -21,
-93, 49, -40, -11, -44, 62, -21, 55, 44, 52, 22, 13, -24, -24, -39, 61, 42, 72, 61, -66, -42, -54, -83, -26, -15,
-34, -73, -29, 10, 94, 27, -7, 20, 86, 81, 75, 48, -62, 8, -30, 89, -70, 82, -58, 5, -80, -97, -76, 91, 40, -43,
-51, 62, -49, 0, -53, 16, 26, -5, -73, -2, -78, 19, -82, -92, -22, 70, 33, 15, -22, -97, 4, -16, 61, 46, 65, 80,
25, 88, 48, -34, -55, 96, -95, -5, -27, -71, 88, 99, 23, 91, -26, 44, 10, -32, 28, 64, -62, -39, -21, -8, -60, 83,
75, 77, 6, 40, 57, -69, 28, -18, -27, 50, -21, -22, -78, 28, 6, -90, 4, -71, -99, 77, 49, -12, -54, -23, -48, -40,
15, 8, 29, 31, -32, -19, 9, 73, -78, -57, 80, 26, 25, -46, -24, 80, 8, -25, 8, 90, -16, -87, 95, -38, 66, 44, 26,
88, -79, 54, -51, 12, -38, 54, -56, 29, -65, 52, -21, -44, 71, -40, 59, -4, -10, -88, -47, 97, -14, 61, 87, 47, 50,
82, 85, 16, 3, -12, 5, 0, -58, 30, -87, -19, -16, -44, 86, 18, 84, -34, 51, 32, 2, -13, -71, 91, -2, -19, 65, 61,
-81, 52, 8, 45, 11, -30, -38, 90, 57, 43, -10, 98, -50, 2, -44, 33, 34, -57, -72, -5, -15, 55, -72, 86, -58, -67,
77, 17, -10, 42, -45, -14, -29, 39, -69, 58, -91, -31, 48, 65, -88, -85, 40, -39, -6, 96, 70, -95, -84, 75, 0, 0,
7, 4, -37, 26, 13, -60, -57, -97, 58, -3, -12, -94, -64, -4, 40, -79, 64, -35, 85, 53, -21, 2, 90, 72, -25, 38, 77,
-10, 13, -46, 66, 96, 34, -94, 22, -53, -55, 41, -51, 79, -85, 14, 61, -73, -90, 1, -53, 50, 65, -91, 3, -78, 11,
-6, 70, 85, -68, 47, -47, 21, 77, 95, 17, 11, -98, -83, 57, -77, 57, 83, 79, 72, -26, 40, 98, -40, -81, -54, -90,
60, -46, 13, 58, 41, 83, 29, 4, 91, -47, 56, 12, -69, 28, -94, 18, 6, -78, -24, 29, 56, -64, -15, 28, 9, -98, 3,
45, -80, 25, 54, 57, 79, -56, 15, -3, -73, -56, -99, -82, -3, 33, 6, 27, -38, 12, -78, 44, 10, -26, -27, -34, 9,
34, 93, 94, 36, -26, 39, 55, 98, -29, 12, 54, 14, -95, -48, 41, -52, -48, 35, 21, 62, -58, -75, -99, 30, -53, 44,
-83, 20, 94, -17, -70, 28, -47, -99, -36, 26, 17, 96, 25, 87, -15, -21, 1, -11, 7, -81, 37, 59, 54, -42, -2, 72,
-17, -2, -21, 6, -58, -5, -74, -64, 77, -68, 64, -92, -67, -72, 33, 49, -76, -65, 36, -14, -9, -86, 74, 97, -67,
-12, 33, 63, 23, -69, 12, -94, 28, 90, 11, 70, -38, 13, 82, -60, 45, 46, -76, 77, 51, 56, 3, 51, 68, -61, -63, -64,
-48, -88, -67, -39, -24, 43, -76, 98, 73, 35, 80, -21, 2, -32, -74, 64, 81, -92, 80, 26, 54, -96, -20, -18, 36, 82,
-67, -19, -79, -53, 16, -51, -65, 49, -13, 10, -8, -13, 9, -58, 99, -11, 20, 1, 57, 45, -35, 15, 30, -78, -59, -39,
-75, 20, 42, 38, 2, 51, -81, -1, 97, 35, 24, -91, -39, 87, 19, 29, -25, -95, 70, -26, -30, -32, 74, -96, 89, -83,
18, 19, -62, 58, 79, -60, -45, -2, 77, 33, -50, 72, -68, -76, 7, 33, -67, 44, 20, 51, -27, 94, 32, -56, -55, -98,
-12, -80, -94, -23, -87, 23, 73, -73, -41, 29, -34, 13, -72, -80, -76, -23, 69, -45, 0, -47, 64, 32, 97, -38, -40,
-30, -44, 91, -10, 1, 93, 54, -3, 75, -91, -14, -2, 81, 12, 33, 10, 55, -76, 37, 51, -53, 90, 20, -22, -32, 73,
-57, 99, 47, 4, -63, 93, 36, -95, -16, -86, 97, -62, -13, 49, -54, 72, -75, -96, -15, 57, -9, -83, 80, -72, 67,
-73, 95, -35, -18, -37, -85, 1, -61, 61, 81, -25, 54, -6, -20, -85, 8, -46, -70, 71, -96, -48, 21, -72, -44, 82,
61, 46, 98, 42, 50, 42, 45, 45, -93, -73, 84, 97, 4, -76, 58, -15, -2, -10, 79, 54, -19, -36, -91, 10, -65, 88, 62,
55, -84, 94, 37, 53, 40, 12, -5, -33, -45, -82, -87, -62, -79, 96, -64, 25, 96, 70, -90, -5, -40, 65, -74, 18, -71,
-66, -72, -59, 98, 66, 72, 90, 60, -13, 44, -23, 98, -61, 44, -70, -67, 33, -32, -46, 6, 3, 55, 3, -27, 64, 74, 10,
7, 76, -72, 35, -89, -68, 52, 85, 98, 25, 76, 35, -88, 20, 89, -90, 58, 10, -83, 68, -57, -16, -78, 25, 86, 76,
-95, -41, 17, 55, 45, -76, 32, 72, 36, 19, -95, -12, 4, 79, -87, -20, 14, -99, 99, -20, 87, 35, 89, -96, 3, -91,
-13, 1, 34, -50, -46, 15, -15, 70, -29, -69, 71, 79, -97, -16, -2, 83, 71, 78, 62, 61, -41, -46, 61, -65, 33, 48,
69, 0, 28, -51, 8, -85, 26, -81, -36, 79, 34, 49, 27, 81, 56, -25, 60, 58, 58, -42, 19, 29, -87, -19, -33, -29, 11,
-71, 6, -78, 53, -48, 21, -18, -22, -71, -27, -96, -75, 14, 60, 58, -60, -13, 39, 95, 38, -24, 30, -4, 33, -51,
-98, 22, 7, -31, 93, -82, -26, -24, -61, -96, 4, 36, -38, 58, 42, 35, 39, 66, -51, -1, 24, -35, 62, -60, -40, 0,
15, 89, 95, -75, -61, 73, 46, 45, -58, 16, 39, 15, 91, 78, 19, -27, -9, 80, -69, -67, -8, 69, 98, 17, -32, -1, 81,
-93, 15, -59, -17, -70, -92, -45, -69, -77, -71, 54, 67, -30, -30, 6, 62, -61, -39, -42, 11, 52, -85, 41, 61, 7,
11, 60, -99, 55, -64, 82, 39, 51, 99, -78, 57, 83, -23, 88, -94, -18, 42, 72, 51, 88, -44, -10, -73, -7, 47, 37,
-78, 62, -44, 83, -54, 43, 20, -54, -25, 55, -95, -86, -17, 81, -87, -59, 64, -34, -94, 70, 47, 47, 19, -25, 35,
51, 65, 39, -78, 12, -24, -80, -49, 8, 79, -27, -49, -1, -4, 26, -68, -23, 16, -9, -42, 28, 31, 99, 70, 36, 69, 17,
-40, -35, 92, 72, 93, 57, 11, -85, -54, 63, -89, -26, -28, 90, 46, -1, -11, -58, -98, -3, 19, 18, 88, 53, -77, -4,
52, 93, -67, -2, 10, -31, 40, -21, -59, 33, -64, 28, 24, -41, -8, 34, 32, 40, 24, -22, -84, 90, -3, -82, -36, 92,
12, -48, 45, 11, 25, -25, 4, 57, 49, 91, -74, -11, -53, -56, 98, -17, 71, -1, 41, -60, -89, -27, 56, 11, 27, 72, 1,
-76, 66, 42, 92, -22, 70, 38, 88, -5, 89, -30, -71, 38, -62, -68, -95, -16, -25, 79, 43, -77, -21, -16, -37, -34,
33, -81, 76, -62, 67, -45, -62, 33, 96, -69, 87, 66, 45, 76, -61, 11, -77, -33, -51, -40, -2, -70, 20, 72, 86, -36,
72, -35, 24, -65, 30, -42, -70, -17, -28, 74, 37, 9, 7, 10, 16, -5, -23, -39, -52, -8, 71, -53, 58, 97, -17, -43,
-96, -97, -94, 89, -34, 77, -69, 90, 88, 37, -75, -81, -79, -4, 69, 34, 81, -24, -55, -2, 47, -2, 35, 71, 89, -16,
94, 47, -19, -23, -96, -39, -20, 86, -49, 45, 63, -42, 35, 29, 95, 36, 24, 92, -68, -7, 26, 90, 45, 70, -12, -30,
-32, 99, -59, -43, -17, -87, 81, 40, -11, 84, -98, 68, 47, -71, -9, -12, -14, -97, -83, -42, 39, 40, -50, 47, -67,
53, 37, 77, 23, -98, -53, 68, -98, -35, -75, -39, -23, -94, -98, 65, 67, 79, 11, -9, 84, 78, 78, -53, 80, 94, -18,
-4, 34, 31, -56, 66, -16, 80, 21, 84, 59, 67, 52, 37, -68, 53, 97, -15, 36, 75, -72, -20, 31, 38, 70, 15, 16, 49,
39, -27, 20, -79, 69, -45, 51, -87, 97, -87, 69, 18, 96, 28, -37, 25, -35, -29, -22, -60, 56, -86, -85, 60, -30,
46, -2, -59, -62, 90, 66, 76, -37, -14, 96, -68, 17, 25, -79, 15, 14, 90, -90, -13, -5, -51, -88, 37, -3, -34, 53,
-47, -43, 67, 89, 26, -10, -13, 66, 28, -23, 9, -19, 16, 95, -22, 25, 12, 79, 45, -96, -7, 12, 90, 79, 84, -61, 67,
-2, 35, -67, -49, 64, -11, 94, 53, -84, -38, -83, 58, 89, -30, -32, -53, 86, -60, 1, -12, 51, -20, -90, 32, 49, 22,
22, 28, -17, 37, -5, 57, -50, 5, -92, -86, 93, 78, 44, -91, -60, 37, 67, -94, -92, -88, -47, 70, -49, 53, -42, 78,
-89, -33, 10, 59, 65, -91, -35, -75, 46, 36, 81, 95, -59, 65, 85, -65, 44, 6, -80, 83, -56, 63, 89, -72, 74, -81,
97, -75, 48, -68, 80, 58, -25, -10, -5, -59, -1, 36, -58, -78, -28, -76, 93, -10, 65, 55, 1, 9, -38, 20, -30, -18,
-39, -64, 9, -65, -46, -17, -63, -98, 14, -83, 37, 88, -17, -91, -94, 58, 44, -52, 79, 92, -52, 49, -18, -87, 5,
82, -1, 43, -20, 68, -98, 40, -96, -13, 74, -66, 69, 87, -88, -40, 80, 25, -52, -36, 33, -69, -78, -23, -22, 78,
-30, 2, 27, 51, 14, -91, 11, 89, 28, 90, 57, 29, 7, 37, -84, -19, 47, 61, -54, 36, -79, -74, -39, -54, -34, 94,
-24, -35, -29, 30, -57, 17, -68, 46, -54, 22, 32, 56, 12, -40, 23, -54, 66, -70, 60, 58, -13, -16, 20, 9, -80, 17,
35, -19, 62, 77, -25, -85, -58, 22, 21, -16, -83, 52, -92, -38, -48, 39, 94, 40, 98, 17, 62, 41, 23, -1, 0, 86, 83,
-80, -4, -97, 13, -92, -17, -47, 84, 34, -33, -73, -66, 88, -13, -73, 17, -6, -12, 45, -90, -41, -15, 85, 52, -75,
26, -25, 23, -74, -39, 6, -78, 33, 9, 35, 40, 68, 64, 2, -20, -69, 28, -10, 95, 91, 16, -10, -37, -96, -65, -28,
-38, -3, -66, -86, 21, 60, -35, -56, 62, 2, 50, 84, -64, -64, -4, 52, 80, -40, -46, -40, -33, 58, 49, -60, 50, -35,
29, -87, -55, 63, -39, -17, -40, -28, -27, 57, -68, 14, -98, 93, -83, 28, 54, -71, 63, -73, 57, 20, -37, -88, 80,
7, 69, 6, 46, -4, 48, -25, -15, 92, -85, 46, -47, -25, -82, 2, -91, -74, -83, -90, 95, -90, 37, 27, -85, -23, 53,
71, 97, 93, 82, 54, 0, 52, -40, -54, -52, -92, 20, 33, 77, 11, -44, -93, 62, -50, 8, 71, -48, 1, 80, -53, 10, -5,
73, 24, 48, 4, -4, 22, -3, -22, -24, 96, -93, 13, -81, -68, -3, 15, 41, -49, -74, 73, -43, 88, 99, 42, 59, -49,
-57, 16, -26, 53, 87, -52, -46, 36, 28, 49, -65, -98, -95, -12, 74, 87, -99, 92, 95, -26, 7, 13, 25, 9, -14, 58,
-3, -15, 0, -67, 12, 20, 26, 86, -27, 13, -89, 3, -74, 38, -70, -39, 39, -66, 48, -10, 97, 25, -18, 93, 98, 65, 6,
0, -49, 69, -41, 25, -69, 35, 57, 43, -45, -40, 6, 4, 73, 16, -92, 98, -46, -63, -64, 69, -53, 60, -64, -56, -15,
-6, -86, -39, -64, -3, 60, -14, -34, -81, -89, -27, 54, 45, -84, 85, -95, 21, -10, 54, -86, -3, 30, -56, 10, 65,
89, 56, 26, -75, 99, 87, 18, -86, -52, 53, 10, -91, -60, 52, -96, -73, -75, 34, 71, -82, 20, 53, 15, -90, 7, 29,
-17, -63, 72, 92, -97, 62, 48, 5, 86, 24, -8, -18, 37, 40, -65, -76, 48, -26, 52, 28, -22, 77, -37, -51, 71, 82,
-98, -14, 68, 9, -85, -49, 22, 64, -57, 24, 3, 67, -94, -11, -9, -2, 70, -94, -62, 82, -94, 62, -44, 58, -33, 10,
12, 29, 59, -17, 11, 37, 45, -44, -54, 37, 6, 45, 1, 25, -31, -96, -8, -25, -31, 83, 49, -83, 88, 63, 98, 93, 2,
-69, 28, 68, 41, -60, -2, 0, -1, 85, -63, -55, -58, -40, 81, 47, -95, -41, -50, -50, -38, 41, 1, 7, 24, -50, 23,
-11, -87, 21, -40, 14, 52, 87, -40, -7, -72, 57, 69, 3, 42, 82, 47, 60, -81, 5, -15, 99, 63, 34, -73, -98, -25, 27,
9, 76, 54, -68, -35, 43, 30, 1, -65, -41, -11, -6, 28, -7, -72, -26, 95, 69, -44, 20, 7, -48, -75, 91, -72, 88, 25,
-46, 66, 76, 58, -25, 29, 12, -16, 71, -68, 90, -28, -57, -51, 60, 36, 76, -70, 63, -73, -74, 10, -18, 22, -83, 10,
46, 84, 38, 11, -14, 91, -22, -38, 49, 29, 68, -62, 89, 39, -53, 79, -89, -11, -95, 48, -97, 57, 77, 42, 83, 79,
-48, -34, 1, -55, 52, -52, -94, -10, 35, -9, -41, -87, 30, 84, 42, -2, 99, 31, -63, -54, -12, -76, 11, -8, 71, 13,
-50, 26, -44, -67, 5, -16, -25, -93, 29, -72, -69, 34, 17, 65, -97, 75, 55, 32, 60, -26, -70, 59, 81, -57, 81, -31,
-34, -8, 61, -85, 82, 87, 40, -62, -80, -55, 21, -28, -72, -73, -1, -65, 38, 92, -99, 40, 45, 55, -51, -18, -94,
-45, -82, 86, -3, 98, -44, 39, -33, 93, 53, -51, 57, -7, -37, 53, 15, 61, -75, 42, 64, 0, 77, 2, -7, 54, -81, -85,
-14, -56, -4, -9, -2, -10, -23, 71, -12, 9, 11, 31, -21, -59, 57, -64, 11, -80, 89, -74, 80, -86, 44, 22, -9, -2,
-76, 83, -48, -80, 74, 14, -37, -30, -95, 38, 59, -41, 9, -76, 44, 96, 31, -76, -85, -12, -64, 25, -15, -75, 50,
-58, -84, -6, 63, 6, 92, 64, -34, -79, 83, -60, 35, -77, 9, 16, 37, -55, 51, -76, -55, -27, 96, 75, -27, -89, -59,
8, 35, 25, 33, -38, 66, 25, 33, 30, -69, 2, -6, -27, 22, -46, 12, -66, -47, 97, 27, 90, -81, -45, -86, -37, 27,
-90, -62, 99, 97, -22, -15, 32, -97, -82, 71, 46, 19, 4, -47, 26, -94, 46, 98, 4, 76, 10, 38, -71, -16, -58, 95, 2,
-4, -91, 64, -99, 95, 78, 76, 92, -66, -39, 1, -87, -45, -28, 58, 73, 75, -89, -1, 57, 33, -26, -38, 9, 83, 76, 15,
-56, -82, 10, 45, -10, -4, 9, -33, -9, -35, -56, -40, -2, 4, 37, 10, 59, -90, -31, 9, 61, -21, -91, 19, 89, -18,
80, -2, -57, 56, 89, -14, 50, 0, -91, -83, 95, -6, -16, -37, 58, 27, -1, -44, -92, -64, 66, 43, -55, -88, -47, -93,
-33, -39, 2, -44, 19, -18, 31, 38, -85, 20, -98, 41, -80, -90, 57, 91, 3, -82, -46, -38, 21, 29, -6, 29, 65, -63,
-28, -90, -52, 24, 92, 15, 61, -6, 47, -42, 52, -22, 95, 43, 98, 96, -39, 94, 82, -81, 86, -14, -87, -83, 24, 11,
46, -82, -60, -12, -45, -12, -26, -21, 89, -33, 93, 27, 37, 41, 84, -33, 95, 57, 86, 70, 30, -52, 65, 13, -57, 28,
98, -45, 44, -1, 65, -33, -7, 81, 54, 24, -53, -71, -96, -64, -28, 73, 39, 85, -9, 24, -71, -13, -42, -84, -43, 87,
-37, 98, 0, 5, 26, -25, 59, -52, 50, 2, -9, -56, -40, -54, 67, 6, -49, 47, 18, 22, 21, -42, -16, 88, 58, 13, -48,
-84, 28, 9, 79, 90, -16, -20, -28, -89, 31, -92, -42, -18, 9, 25, 25, 69, 70, -31, -48, 97, 93, 70, -4, -9, -95,
80, -21, 39, -30, 31, 31, 97, -83, 10, 64, 0, 89, -64, -13, 21, -57, 21, 79, 29, -53, 4, -25, 93, 49, 26, 91, 42,
-27, -13, -67, -46, -56, 12, 92, 13, -80, 23, -13, -64, -66, -49, 12, 99, -14, 99, -3, 6, -3, -24, -65, 43, 79, 9,
37, 29, -65, 5, -52, -15, 91, -19, 38, -87, 69, 31, 25, 88, -69, -87, -99, -36, -37, -11, -36, 26, -35, 60, -68,
62, -63, -57, 5, 92, 51, -81, -2, 62, 23, 46, -53, -8, -96, 85, 4, 72, -7, -71, 37, 23, -82, 14, 64, -42, -97, -95,
60, -55, 64, 68, -93, 77, -89, -12, 47, 61, -16, -78, 23, -93, 67, 47, -25, 47, 9, 78, -4, 78, 84, -90, -22, 78,
23, -58, -64, 3, -54, 95, 47, 87, 63, 30, 41, 50, 94, -12, 11, -22, 10, -88, -38, -46, 35, 13, 78, -56, -8, -26,
98, -47, -16, -24, -69, 83, 18, -56, -37, 40, -61, -90, 27, 79, 16, -54, 6, -12, 33, 94, 65, -80, 82, -96, -49, 17,
17, -71, 37, 85, -21, 35, -62, 39, 87, -55, 0, 5, -12, 62, -77, 4, 72, 49, -40, -35, 71, 65, 52, -18, 59, -5, 1,
41, -2, 28, -65, 91, 33, 71, 53, 89, -17, 90, 28, -29, -87, -72, 75, 0, 90, 74, -96, 39, 24, -60, 80, -28, -94, 33,
53, 41, -95, -68, -17, -21, 59, 17, -29, -30, -34, -76, -41, 48, 91, 63, -81, -96, 68, 71, -20, 35, 45, -39, -26,
-54, 0, -69, 18, -18, 40, -29, -76, 44, 2, -17, -76, -61, 99, -29, 8, -58, -29, 43, 90, -38, 6, 85, -58, -49, 56,
22, 85, -21, 59, -64, 24, -41, -33, -81, 41, -93, -33, 64, 28, 45, -76, 51, 83, -77, -78, -32, -58, -8, 87, -68,
31, -29, -83, 49, 21, 50, -52, 7, -71, -93, 19, 29, -34, 85, 25, 83, 69, 91, 47, -3, 36, 47, -75, -3, 69, -54, 41,
87, 14, 6, -81, -78, 76, -87, 71, -26, 62, -81, 57, 67, -74, -23, -27, -32, -61, 97, -49, -92, 65, 74, -19, 2, 21,
5, 75, -33, 27, -7, -45, -81, 98, -50, -60, 51, -38, 87, -74, -99, 83, 59, 44, 85, -64, -82, -47, -48, 91, -20,
-64, 57, -46, 17, -64, 74, -78, 87, -82, 26, -20, -28, 44, -44, 22, 83, -93, 60, 48, -91, 61, 31, 68, 5, 16, 80,
-1, 45, -68, -9, -75, -55, -75, -45, 61, -40, -94, 59, -53, -77, -15, 3, -28, -71, 58, 93, 89, 42, 53, 37, 27, -9,
-55, -5, 73, 37, -47, -28, -41, -39, 39, -17, 5, 40, 14, -34, 76, 19, -97, 99, 41, -13, 3, -87, -7, -62, 82, -18,
56, 13, 95, -16, -96, -83, 55, 53, 53, -92, -97, 88, -54, 18, -52, 50, -41, 61, 93, -65, -20, 95, -65, -79, -41,
14, -89, 51, 51, 92, -90, 8, -18, 81, 68, -14, 97, 23, -84, 27, 8, -82, 15, 53, 36, 62, 3, 94, 0, -27, -94, 79,
-32, -60, 77, 4, 53, 87, -45, -18, 56, -58, 66, -61, -77, 34, 24, 97, -66, 16, 24, 41, 34, -83, -6, -30, 55, 74,
-59, -44, -53, -54, -88, -8, -14, 88, 95, -84, 75, -73, -26, 32, -32, -60, 70, -32, 50, -29, -35, 84, 86, 65, 25,
20, 58, 96, 66, -9, 70, -93, 23, 93, -70, 34, -15, -8, 23, -20, 7, -2, -16, 58, -93, 51, 97, 76, 95, 48, -53, -63,
9, -89, -97, -66, 7, 37, -93, -26, -72, 76, -43, 50, 47, -14, -15, -68, 77, 84, -11, -38, -18, 72, -80, -11, 0,
-83, -58, -4, 41, -34, 32, -50, -24, 11, -39, 82, -51, -33, -67, -47, -79, -10, 80, 67, 75, -58, 75, 30, -74, -36,
91, -16, -87, -89, 49, 13, -96, 91, -91, 45, -43, 17, 71, 9, -71, -91, -32, -46, -47, 1, 6, -50, 67, -14, 93, 42,
4, 68, -28, 29, -90, -60, -86, -78, -50, 62, 11, -46, 30, 19, 75, 86, -86, 23, -28, -58, 32, 40, -28, 84, -82, 77,
-89, 84, -59, -96, 26, 44, 48, 75, -49, 57, -85, -59, 56, -58, -97, -33, -28, 33, 63, -53, -4, 76, 46, 45, 94, -22,
-15, -34, -61, 2, -80, -51, -14, -63, -71, 88, 81, 77, 40, -91, 11, 32, -51, -33, 73, -72, 34, -55, 37, -26, -32,
-89, -73, -86, 55, -79, -31, -60, -37, 7, 18, -41, 33, 80, -4, 61, 68, -46, 15, 9, -38, -73, -82, 10, -7, 90, 14,
-96, -88, -48, -23, -44, -38, -20, -31, -83, 0, 14, -67, 39, -78, 50, 98, 31, 30, -6, -31, -25, 47, 84, 60, 85,
-89, 77, -28, -20, 44, 85, -16, 55, -63, 37, -89, -25, -82, -43, -32, -6, 47, 0, -66, 45, -73, -91, -24, 33, -21,
45, 85, -74, 6, 45, 87, 16, 0, -41, 95, -56, -56, -44, 76, -42, 70, 63, 9, 87, -80, 77, -42, 67, -46, -32, 12, -19,
-24, 65, 90, 54, -13, 75, 56, 92, 21, 43, -15, -79, 78, -43, -59, 99, 13, -83, -43, -17, 80, 42, -53, 76, 19, -19,
20, 50, 49, -90, -69, -98, 74, 97, 33, -62, 73, -34, -70, -29, 86, 14, -32, 64, 70, 8, 63, -40, 2, 96, 19, -18, 39,
42, -42, -65, -76, 55, 84, 72, 64, 91, 50, 15, 89, -40, 52, 39, 26, 58, -90, 12, -28, -23, -24, -81, 61, -83, -44,
-37, -87, 74, 44, 28, 17, 79, 63, 40, 11, 24, -11, -25, 16, -84, 66, -18, -24, 18, -79, -98, -24, -70, -10, 24,
-17, 42, 19, -79, 58, 74, -16, 48, 49, -95, -47, -57, 60, -84, 82, -29, 17, -52, 22, -67, -37, -12, -9, 15, -94,
11, 16, -42, 17, 82, 81, 76, 25, 1, 96, -17, -25, -20, -92, -99, -38, -39, -57, -78, -47, -98, -30, 69, -51, 91,
78, -11, -20, -31, -96, -15, 56, -3, 20, -50, -21, 1, -74, -96, 78, -77, -36, -69, -21, -52, -92, 17, 8, -49, 39,
38, -71, 85, -16, -22, 76, -37, 43, -44, 8, 23, 18, -58, -80, -62, -9, -1, 15, 17, -21, -29, 16, 19, 1, 71, 67,
-15, -11, -48, 12, -95, 89, 41, 89, -26, 95, 65, 13, 38, 98, -79, -39, 16, -38, -42, 53, 53, 33, -32, -53, -88, 38,
39, 31, -84, 10, -25, 1, 75, 26, -87, 56, 16, 30, 45, 66, 25, -12, -21, -60, -14, -24, -22, -98, 38, 35, 31, -32,
-32, 75, -9, -44, -9, -70, 63, 6, 16, -62, 83, -31, 64, 73, -75, -43, 3, 70, -77, -94, -65, 1, -55, 20, 76, 22, -2,
-9, -43, -71, 35, 1, -96, -74, 57, -6, -68, -3, 77, 25, 35, 60, 93, -24, 10, -82, 32, 90, 64, 31, 95, 98, -91, -83,
-5, 61, 39, 92, -47, 72, -79, 64, -26, -75, 67, -92, -5, 98, -19, -28, 0, -84, -90, -7, -9, -4, -12, 99, -14, -48,
30, -42, -72, 38, -25, 22, 0, -86, 15, 29, 62, 35, -7, -87, 36, -40, 96, -68, -64, -22, -20, 35, -7, -34, -94, 61,
62, -7, 37, -52, 44, -32, -17, 71, 82, 57, -6, -41, 47, -91, 87, 9, 20, -42, 22, -66, -6, -5, -58, 29, 72, 21, -58,
-57, 87, -53, -96, 26, 39, 40, 73, -17, 84, -44, -68, 67, 89, 2, -97, 36, -13, 90, -77, -93, -52, 21, -83, 18, -84,
-42, -52, 88, 56, -11, -69, 20, 35, -89, -54, -49, 27, 95, 33, -11, -71, 41, -67, -82, -57, -65, 31, 29, -75, 53,
13, -51, -26, 6, 67, -34, 64, 91, -69, -3, -43, -62, -83, 68, -52, -61, -81, 52, -66, 28, -59, -38, -30, -27, -43,
-11, 7, 87, 95, 9, 40, 8, 34, 90, 90, -22, -67, 54, -31, -36, -72, 25, 1, -79, -7, 26, -41, 11, -22, -30, -83, -5,
31, -14, 67, 87, 74, -49, 51, 46, 36, -9, -46, -29, -42, -78, 48, -9, 75, 94, 54, 80, -4, -45, -99, 89, 57, -63,
-23, -65, 6, -7, 29, -86, 55, -27, 78, 7, 1, 29, -47, -63, 97, -16, -16, -45, 5, -67, 45, -43, -96, -24, -86, -1,
8, -85, -35, -35, -72, 42, 0, 33, -88, -94, 23, 44, -44, 1, -72, 56, -92, -43, 92, -95, 40, -23, -41, -78, -14, 81,
-44, -34, -43, -31, 64, 41, -40, -70, -93, -13, 48, -17, -80, 36, -12, 20, -20, 43, -79, 7, -24, -95, 64, -31, -91,
-19, 22, -55, -20, 84, -97, 35, -50, -64, -96, 90, 77, -36, -80, 83, 50, 44, -34, 47, -19, 30, -33, 60, -49, -36,
-55, 26, -54, 85, 71, -46, -57, -30, -25, 22, -46, -23, -66, -20, -10, -62, -52, -33, -22, -33, -73, -95, -88, -31,
28, -31, 75, 71, -71, -74, -64, -50, 29, -19, -88, 0, 11, -68, 70, 63, 53, -99, -83, 64, -42, 6, 78, 5, 49, -44,
48, 75, -63, 36, -79, 65, -95, 96, 36, -89, 98, 48, -63, 27, -94, -74, -95, -6, -43, 51, -43, 86, 51, -27, 50, 85,
56, 28, -33, 5, 60, 92, -42, 97, 28, -22, 39, 10, -26, -48, 20, -27, -99, 33, 76, 82, 58, 80, -24, -85, 31, 32,
-98, -40, 82, 28, -78, 38, -66, -11, -57, 93, -19, 0, 67, 85, 78, -17, -5, -71, 35, 91, -22, 12, 2, -45, -6, -40,
-88, 47, -48, 43, -21, -70, -97, -39, 57, -99, 98, 90, -11, -81, 61, 46, 18, 28, 9, -27, -88, 80, 2, 23, 49, 56,
-65, -49, -89, 5, 10, -77, -48, 61, 42, 8, 90, 21, 45, 25, 21, 44, 15, 87, 62, -47, 33, -43, 81, -81, 30, 69, 99,
-91, -31, 48, 64, -20, 98, 75, 84, -15, 74, -86, -76, -7, 21, 90, -86, -34, 15, 34, 86, -92, -2, 25, -40, -68, 82,
-82, -73, -11, 63, -74, -3, -68, 50, -39, 11, 25, -87, -27, -89, 63, -37, -89, -44, 83, -99, -54, -74, -7, 80, 89,
0, -22, 14, 36, -14, -27, 31, 13, 61, -29, 15, -65, 3, -34, -27, 90, 90, -38, -60, 77, -97, 2, 87, -42, -38, 65, 4,
-12, -42, -39, -23, 34, 15, 67, -30, 78, -82, 77, -32, 55, -51, 59, 90, 28, -98, -60, -5, 69, 1, 35, 46, -20, -63,
11, 38, -1, -24, -81, 63, 33, -44, -83, -33, 47, 83, 13, 2, 77, -32, 69, 33, 16, 6, 0, -79, 7, 39, 15, -24, -83,
-50, 99, -3, -13, 10, -88, 62, 62, -93, 25, -5, -61, 41, 38, 62, 1, -72, -35, -21, -5, -89, 88, -89, 16, -12, -92,
-76, -96, 23, -24, -80, 72, -25, -7, -64, 61, 4, 97, 23, -13, -1, -82, 25, -83, 32, -12, 18, 60, 29, 73, -45, 39,
61, -57, -67, -74, -73, -67, -71, 49, 8, -52, 22, 83, 18, 34, 21, -78, 9, -55, -14, -92, -61, -89, -98, 71, -25,
-4, 8, -96, -54, 39, 20, 83, 58, 52, -91, 85, 84, -63, 34, -31, -39, -67, -48, 78, 44, 50, 77, -47, 94, -37, -63,
-67, -50, -62, 80, 2, 10, -12, 5, 55, -95, -98, 38, 62, 30, 46, 47, 14, 59, -41, 83, -79, -32, -88, 75, -88, 61,
29, -36, 55, 91, -22, 65, -81, -8, 45, 20, -97, -89, -98, 57, -85, -96, -27, 76, 33, -81, 1, -75, 55, 36, -92, 52,
-96, 95, 27, -84, 34, -43, -44, -34, -75, 33, -69, -57, -74, 53, 62, -95, 40, 64, 38, 54, 44, -89, 7, -23, -93, 84,
1, 61, 20, -15, 13, 24, -42, -83, 39, 91, -27, 94, -43, -2, 5, -35, 17, 7, -82, -20, 11, 57, -79, -74, -12, 64,
-63, 71, -59, -57, 56, 19, 80, -24, -96, -7, 76, -39, 9, -8, -71, 59, -36, -14, -66, 68, 50, 50, -25, 44, -70, 62,
-22, -50, 64, 65, -86, -99, 13, -68, -80, -31, 50, 76, 22, 30, -31, -2, 68, 55, 90, 96, -9, -69, -41, 24, 98, 85,
-49, -50, 6, -42, 88, 83, -16, 52, 25, -25, 30, -61, 6, 49, -16, -67, 26, -94, 39, 71, -19, 7, 3, -52, -19, 93,
-22, 39, -6, -47, 2, 45, 2, -92, -97, -10, 91, -14, -81, -7, 60, 48, 8, -57, -25, 92, -25, 77, 97, -85, 25, -45,
-2, -71, 2, 78, 98, 56, -5, -30, -91, 73, -85, 10, 80, 93, 76, 48, -44, 72, -58, -83, 20, 49, -64, 94, 18, 11, 48,
16, 2, -26, 47, 99, -21, -50, 55, -23, -94, -73, 46, -85]
]
for one in inputArr:
print(solution.maxSubArray(one))
| 104.358862 | 120 | 0.417701 |
caac73a15a8be8420cc3018ebf3c70bf80421433
| 2,073 |
py
|
Python
|
tarefas-poo/lista-03/balde/view/paineis/painel_manipula_baldes.py
|
victoriaduarte/POO_UFSC
|
0c65b4f26383d1e3038d8469bd91fd2c0cb98c1a
|
[
"MIT"
] | null | null | null |
tarefas-poo/lista-03/balde/view/paineis/painel_manipula_baldes.py
|
victoriaduarte/POO_UFSC
|
0c65b4f26383d1e3038d8469bd91fd2c0cb98c1a
|
[
"MIT"
] | null | null | null |
tarefas-poo/lista-03/balde/view/paineis/painel_manipula_baldes.py
|
victoriaduarte/POO_UFSC
|
0c65b4f26383d1e3038d8469bd91fd2c0cb98c1a
|
[
"MIT"
] | null | null | null |
# --------------------------
# UFSC - CTC - INE - INE5663
# Exercício do Balde
# --------------------------
# Classe que permite manipular os baldes.
#
from view.menu import Menu
from model.balde import Balde
class PainelManipulaBaldes:
def __init__(self):
opcoes = {
0: 'Voltar',
1 : 'Encher balde A',
2 : 'Encher balde B',
3 : 'Esvaziar balde A',
4 : 'Esvaziar balde B',
5 : 'Derrame balde A em balde B',
6 : 'Derrame balde B em balde A',
7 : 'Balde A receba de balde B',
8 : 'Balde B receba de balde A'
}
self._menu = Menu('Opções de Manipulação', opcoes)
def manipule(self, baldeA, baldeB):
print('--- Manipula Baldes ---')
encerrar = False
while not encerrar:
self._mostre_baldes(baldeA, baldeB)
opcao = self._menu.pergunte()
if opcao == 0:
encerrar = True
elif opcao == 1:
baldeA.fique_cheio()
elif opcao == 2:
baldeB.fique_cheio()
elif opcao == 3:
baldeA.fique_vazio()
elif opcao == 4:
baldeB.fique_vazio()
elif opcao == 5:
baldeA.derrame_em(baldeB)
elif opcao == 6:
baldeB.derrame_em(baldeA)
elif opcao == 7:
baldeA.receba_de(baldeB)
elif opcao == 8:
baldeB.receba_de(baldeA)
def _mostre_baldes(self, baldeA, baldeB):
print('****** Situação Atual dos Baldes')
print('- Balde A')
self._mostre_balde(baldeA)
print('- Balde B')
self._mostre_balde(baldeB)
print('****************************\n')
def _mostre_balde(self, balde):
print('capacidade : {}'.format(balde.capacidade()))
print('quantidade : {}'.format(balde.quantidade()))
print('está cheio : {}'.format(balde.esta_cheio()))
print('está vazio : {}'.format(balde.esta_vazio()))
| 32.390625 | 59 | 0.4959 |
942e89a9a1c8ae591995de386de5dd738b0b5bd9
| 660 |
py
|
Python
|
Curso_Python/Secao3-Python-Intermediario-Programacao-Procedural/59_exercicio/exercicio.py
|
pedrohd21/Cursos-Feitos
|
b223aad83867bfa45ad161d133e33c2c200d42bd
|
[
"MIT"
] | null | null | null |
Curso_Python/Secao3-Python-Intermediario-Programacao-Procedural/59_exercicio/exercicio.py
|
pedrohd21/Cursos-Feitos
|
b223aad83867bfa45ad161d133e33c2c200d42bd
|
[
"MIT"
] | null | null | null |
Curso_Python/Secao3-Python-Intermediario-Programacao-Procedural/59_exercicio/exercicio.py
|
pedrohd21/Cursos-Feitos
|
b223aad83867bfa45ad161d133e33c2c200d42bd
|
[
"MIT"
] | null | null | null |
lista_inteiros = [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[9, 1, 8, 9, 9, 7, 2, 1, 6, 8],
[1, 3, 2, 2, 8, 6, 5, 9,6, 7],
[3, 8, 2, 8, 6, 7, 7, 3, 1, 9],
[4, 8, 8, 8, 5, 1, 10, 3, 1, 7],
[1, 3, 7, 2, 2, 1, 5, 1, 9, 9],
[10, 2, 2, 1, 3, 5, 1, 9, 9],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
]
def encontra_duplicado(parametro):
numeros_checados = set()
primeiro_duplicado = -1
for numero in parametro:
if numero in numeros_checados:
primeiro_duplicado = numero
break
numeros_checados.add(numero)
return primeiro_duplicado
for c in lista_inteiros:
print(c, encontra_duplicado(c))
| 23.571429 | 39 | 0.506061 |
ca52c9ae898ef39b3b29c0708676ba0da8e0937f
| 368 |
py
|
Python
|
012-C108-BellCurve/__main__.py
|
somePythonProgrammer/PythonCode
|
fb2b2245db631cefd916a960768f411969b0e78f
|
[
"MIT"
] | 2 |
2021-09-28T13:55:20.000Z
|
2021-11-15T10:08:49.000Z
|
012-C108-BellCurve/__main__.py
|
somePythonProgrammer/PythonCode
|
fb2b2245db631cefd916a960768f411969b0e78f
|
[
"MIT"
] | null | null | null |
012-C108-BellCurve/__main__.py
|
somePythonProgrammer/PythonCode
|
fb2b2245db631cefd916a960768f411969b0e78f
|
[
"MIT"
] | 1 |
2022-01-20T03:02:20.000Z
|
2022-01-20T03:02:20.000Z
|
# 012-C108-BellCurve
# This is a python script made by @somePythonProgrammer
# for a WhiteHat Junior project.
import pandas as pd
import plotly.figure_factory as ff
df = pd.read_csv('012-C108-BellCurve/csv/data.csv')
figure = ff.create_distplot([df['Rating'].tolist()],['Rating'], show_hist=False,)
figure.write_html('012-C108-BellCurve/index.html', auto_open=True)
| 33.454545 | 81 | 0.763587 |
f3fc8364ac9e9c09cc222faa4c67f6365e9be7b8
| 1,144 |
py
|
Python
|
Problems/Depth-First Search/medium/ArrayNesting/array_nesting.py
|
dolong2110/Algorithm-By-Problems-Python
|
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
|
[
"MIT"
] | 1 |
2021-08-16T14:52:05.000Z
|
2021-08-16T14:52:05.000Z
|
Problems/Depth-First Search/medium/ArrayNesting/array_nesting.py
|
dolong2110/Algorithm-By-Problems-Python
|
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
|
[
"MIT"
] | null | null | null |
Problems/Depth-First Search/medium/ArrayNesting/array_nesting.py
|
dolong2110/Algorithm-By-Problems-Python
|
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
|
[
"MIT"
] | null | null | null |
from typing import List
def arrayNesting(self, nums: List[int]) -> int:
res, seen = 0, set()
for i in nums:
j, l = i, 0
while j not in seen:
seen.add(j)
j = nums[j]
l += 1
if l > res:
res = l
if l > len(nums) - len(seen): # early exit
break
return res
# def arrayNesting(self, nums: List[int]) -> int:
# res = 0
#
# n = len(nums)
# for idx in range(n):
# if nums[idx] != -1:
# cur_pointer, cur_length = nums[idx], 0
# while nums[cur_pointer] != -1:
# temp = cur_pointer
# cur_pointer = nums[cur_pointer]
# cur_length += 1
# nums[temp] = -1
#
# res = max(res, cur_length)
#
# return res
# def arrayNesting(self, nums: List[int]) -> int:
# def dfs(idx: int):
# if nums[idx] == -1:
# return 0
#
# next = nums[idx]
# nums[idx] = -1
# return dfs(next) + 1
#
#
# n = len(nums)
# ans = 0
# for i in range(n):
# ans = max(ans, dfs(i))
# return ans
| 23.346939 | 52 | 0.444056 |
b6a5cabcd0af6dfd5329f5cfe8a6a89b5fb46a01
| 6,075 |
py
|
Python
|
biowardrobe_airflow_advanced/utils/initialize.py
|
Barski-lab/biowardrobe-airflow-advanced
|
e43aa268fd05635e8356788b8e814279b698263f
|
[
"Apache-2.0"
] | null | null | null |
biowardrobe_airflow_advanced/utils/initialize.py
|
Barski-lab/biowardrobe-airflow-advanced
|
e43aa268fd05635e8356788b8e814279b698263f
|
[
"Apache-2.0"
] | 1 |
2018-09-30T16:57:06.000Z
|
2018-09-30T16:57:06.000Z
|
biowardrobe_airflow_advanced/utils/initialize.py
|
Barski-lab/biowardrobe-airflow-advanced
|
e43aa268fd05635e8356788b8e814279b698263f
|
[
"Apache-2.0"
] | null | null | null |
import os
import logging
import subprocess
from json import dumps, loads
from airflow.settings import DAGS_FOLDER
from airflow.bin.cli import api_client
from biowardrobe_airflow_advanced.templates.outputs import TEMPLATES
from biowardrobe_airflow_advanced.utils.utilities import (validate_locations,
add_details_to_outputs,
fill_template,
run_command,
export_to_file,
norm_path,
get_files)
logger = logging.getLogger(__name__)
SCRIPTS_DIR = norm_path(os.path.join(os.path.dirname(os.path.abspath(os.path.join(__file__, "../"))), "scripts"))
SQL_DIR = norm_path(os.path.join(os.path.dirname(os.path.abspath(os.path.join(__file__, "../"))), "sql_patches"))
def create_dags():
deseq_template = u"""#!/usr/bin/env python3
from airflow import DAG
from biowardrobe_airflow_advanced import biowardrobe_advanced
from biowardrobe_airflow_advanced.operators import DeseqJobDispatcher, DeseqJobGatherer
dag = biowardrobe_advanced("deseq-advanced.cwl", DeseqJobDispatcher, DeseqJobGatherer, "biowardrobe_advanced")"""
export_to_file(deseq_template, os.path.join(DAGS_FOLDER, "deseq-advanced.py"))
heatmap_template = u"""#!/usr/bin/env python3
from airflow import DAG
from biowardrobe_airflow_advanced import biowardrobe_advanced
from biowardrobe_airflow_advanced.operators import HeatmapJobDispatcher, HeatmapJobGatherer
dag = biowardrobe_advanced("heatmap.cwl", HeatmapJobDispatcher, HeatmapJobGatherer, "biowardrobe_advanced")"""
export_to_file(heatmap_template, os.path.join(DAGS_FOLDER, "heatmap.py"))
pca_template = u"""#!/usr/bin/env python3
from airflow import DAG
from biowardrobe_airflow_advanced import biowardrobe_advanced
from biowardrobe_airflow_advanced.operators import PcaJobDispatcher, PcaJobGatherer
dag = biowardrobe_advanced("pca.cwl", PcaJobDispatcher, PcaJobGatherer, "biowardrobe_advanced")"""
export_to_file(pca_template, os.path.join(DAGS_FOLDER, "pca.py"))
def create_pools(pool, slots=10, description=""):
try:
pools = [api_client.get_pool(name=pool)]
except Exception:
api_client.create_pool(name=pool, slots=slots, description=description)
def validate_outputs(superset, subset):
try:
dummy = [superset[key] for key, val in subset.items()]
except KeyError:
raise OSError
def apply_patches(connect_db):
logger.debug(f"Applying SQL patches from {SQL_DIR}")
bw_patches = get_files(os.path.join(SQL_DIR, "biowardrobe"), ".*sql$")
for filename in bw_patches.values():
try:
connect_db.apply_patch(filename)
except Exception as ex:
logger.debug(f"Failed to apply patch {filename} due to\n {ex}")
def gen_outputs(connect_db):
setting_data = connect_db.get_settings_data()
sql_query = """SELECT
l.uid as uid,
l.params as outputs,
e.etype as exp_type,
e.id as exp_id
FROM labdata l
INNER JOIN (experimenttype e) ON (e.id=l.experimenttype_id)
WHERE (l.deleted=0) AND
(l.libstatus=12) AND
COALESCE(l.egroup_id,'')<>'' AND
COALESCE(l.name4browser,'')<>''"""
logger.debug(f"Run SQL query:\n{sql_query}")
for db_record in connect_db.fetchall(sql_query):
logger.info(f"LOAD: {db_record['uid']} - {db_record['exp_type']}")
get_to_update_stage = False
get_to_upload_stage = False
db_record.update(setting_data)
db_record.update({"prefix": SCRIPTS_DIR})
db_record.update({"outputs": loads(db_record["outputs"]) if db_record["outputs"] and db_record['outputs'] != "null" else {}})
for item_str in TEMPLATES.get(db_record["exp_id"], []):
try:
logger.debug(f"CHECK: if experiment's outputs require correction")
item_parsed = fill_template(item_str, db_record)
list(validate_locations(item_parsed["outputs"])) # TODO Use normal way to execute generator
validate_outputs(db_record["outputs"], item_parsed["outputs"])
except KeyError as ex:
logger.info(f"SKIP: couldn't find required experiment's output {ex}")
except OSError as ex:
get_to_update_stage = True
logger.debug(f"GENERATE: missing file or correpospondent data in DB: {ex}")
try:
commands = " ".join(item_parsed["commands"])
logger.debug(f"RUN: {commands}")
run_command(commands)
add_details_to_outputs(item_parsed["outputs"])
db_record["outputs"].update(item_parsed["outputs"])
get_to_upload_stage = True
except subprocess.CalledProcessError as ex:
logger.error(f"FAIL: got error while running the command {ex}")
except OSError as ex:
logger.error(f"FAIL: couldn't locate generated files {ex}")
if get_to_upload_stage:
connect_db.execute(f"""UPDATE labdata SET params='{dumps(db_record["outputs"])}' WHERE uid='{db_record["uid"]}'""")
logger.debug(f"UPDATE: new experiment's outputs\n{dumps(db_record['outputs'], indent=4)}")
logger.info(f"SUCCESS: experiment's outputs have been corrected")
elif get_to_update_stage:
logger.info(f"FAIL: experiment's outputs have not been corrected")
else:
logger.info(f"SUCCESS: experiment's outputs are not required or cannot be corrected")
| 46.730769 | 133 | 0.617613 |
94d7b47a20db36530cab4c2967c969681e17940a
| 2,224 |
py
|
Python
|
python/game-of-life/src/board.py
|
enolive/learning
|
075b714bd7bea6de58a8da16cf142fc6c8535e11
|
[
"MIT"
] | 8 |
2016-10-18T09:30:12.000Z
|
2021-12-08T13:28:28.000Z
|
python/game-of-life/src/board.py
|
enolive/learning
|
075b714bd7bea6de58a8da16cf142fc6c8535e11
|
[
"MIT"
] | 29 |
2019-12-28T06:09:07.000Z
|
2022-03-02T03:44:19.000Z
|
python/game-of-life/src/board.py
|
enolive/learning
|
075b714bd7bea6de58a8da16cf142fc6c8535e11
|
[
"MIT"
] | 4 |
2018-07-23T22:20:58.000Z
|
2020-09-19T09:46:41.000Z
|
from itertools import product
class Board(object):
def __init__(self, cell_array):
self.living_cells = set()
for p in self.__get_only_living_cells(cell_array):
self.set_alive_at(p)
def count_living_neighbours_of(self, position):
(x, y) = position
all_neighbours = [
(x - 1, y - 1), (x, y - 1), (x + 1, y - 1),
(x - 1, y), (x + 1, y),
(x - 1, y + 1), (x, y + 1), (x + 1, y + 1),
]
return self.__length_of(filter(
lambda p: self.is_alive_at(p),
all_neighbours))
def is_alive_at(self, position):
return position in self.living_cells
def set_alive_at(self, position):
self.living_cells.add(position)
def set_dead_at(self, position):
if self.is_alive_at(position):
self.living_cells.remove(position)
def transform_cell_at(self, position, next_state):
self.__get_transformation(next_state)(position)
def dimensions(self):
if len(self.living_cells) == 0:
return 0, 0
widest_living_cell = max(self.living_cells, key=lambda p: p[0])[0]
highest_living_cell = max(self.living_cells, key=lambda p: p[1])[1]
return widest_living_cell + 1, highest_living_cell + 1
@staticmethod
def __get_dimension(cell_array):
height = len(cell_array)
width = len(cell_array[0]) if height > 0 else 0
return width, height
def to_cell_array(self):
width, height = self.dimensions()
dump = [[self.__dump_value(x, y) for x in range(width)] for y in range(height)]
return dump
@staticmethod
def __length_of(filtered):
return len(list(filtered))
def __get_transformation(self, next_state):
return self.set_alive_at if next_state else self.set_dead_at
def __get_only_living_cells(self, cell_array):
width, height = self.__get_dimension(cell_array)
matrix = product(range(0, width), range(0, height))
alive_matrix = filter(lambda x_y: cell_array[x_y[1]][x_y[0]] == 'x', matrix)
return alive_matrix
def __dump_value(self, x, y):
return 'x' if self.is_alive_at((x, y)) else '.'
| 33.19403 | 87 | 0.617806 |
bfa7b094bd252f96cca44b38bd5cf048e4f776bc
| 11,769 |
py
|
Python
|
tests/test_experiments.py
|
Matheus158257/projects
|
26a6148046533476e625a872a2950c383aa975a8
|
[
"Apache-2.0"
] | null | null | null |
tests/test_experiments.py
|
Matheus158257/projects
|
26a6148046533476e625a872a2950c383aa975a8
|
[
"Apache-2.0"
] | null | null | null |
tests/test_experiments.py
|
Matheus158257/projects
|
26a6148046533476e625a872a2950c383aa975a8
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
from json import dumps
from unittest import TestCase
from projects.api.main import app
from projects.controllers.utils import uuid_alpha
from projects.database import engine
from projects.object_storage import BUCKET_NAME
EXPERIMENT_ID = str(uuid_alpha())
NAME = "foo"
PROJECT_ID = str(uuid_alpha())
TEMPLATE_ID = str(uuid_alpha())
COMPONENT_ID = str(uuid_alpha())
OPERATOR_ID = str(uuid_alpha())
POSITION = 0
IS_ACTIVE = True
PARAMETERS = {"coef": 0.1}
PARAMETERS_JSON = dumps(PARAMETERS)
DESCRIPTION = "long foo"
COMMANDS = ["CMD"]
COMMANDS_JSON = dumps(COMMANDS)
TAGS = ["PREDICTOR"]
TAGS_JSON = dumps(TAGS)
COMPONENTS_JSON = dumps([COMPONENT_ID])
EXPERIMENT_NOTEBOOK_PATH = f"minio://{BUCKET_NAME}/components/{COMPONENT_ID}/Experiment.ipynb"
DEPLOYMENT_NOTEBOOK_PATH = f"minio://{BUCKET_NAME}/components/{COMPONENT_ID}/Deployment.ipynb"
CREATED_AT = "2000-01-01 00:00:00"
CREATED_AT_ISO = "2000-01-01T00:00:00"
UPDATED_AT = "2000-01-01 00:00:00"
UPDATED_AT_ISO = "2000-01-01T00:00:00"
OPERATORS = [{"uuid": OPERATOR_ID, "componentId": COMPONENT_ID, "dependencies": [],"parameters": PARAMETERS, "experimentId": EXPERIMENT_ID, "createdAt": CREATED_AT_ISO, "updatedAt": UPDATED_AT_ISO}]
EXPERIMENT_ID_2 = str(uuid_alpha())
NAME_2 = "foo 2"
POSITION_2 = 1
class TestExperiments(TestCase):
def setUp(self):
self.maxDiff = None
conn = engine.connect()
text = (
f"INSERT INTO components (uuid, name, description, commands, tags, experiment_notebook_path, deployment_notebook_path, is_default, created_at, updated_at) "
f"VALUES ('{COMPONENT_ID}', '{NAME}', '{DESCRIPTION}', '{COMMANDS_JSON}', '{TAGS_JSON}', '{EXPERIMENT_NOTEBOOK_PATH}', '{DEPLOYMENT_NOTEBOOK_PATH}', 0, '{CREATED_AT}', '{UPDATED_AT}')"
)
conn.execute(text)
text = (
f"INSERT INTO projects (uuid, name, created_at, updated_at) "
f"VALUES ('{PROJECT_ID}', '{NAME}', '{CREATED_AT}', '{UPDATED_AT}')"
)
conn.execute(text)
text = (
f"INSERT INTO experiments (uuid, name, project_id, position, is_active, created_at, updated_at) "
f"VALUES ('{EXPERIMENT_ID}', '{NAME}', '{PROJECT_ID}', '{POSITION}', 1, '{CREATED_AT}', '{UPDATED_AT}')"
)
conn.execute(text)
text = (
f"INSERT INTO experiments (uuid, name, project_id, position, is_active, created_at, updated_at) "
f"VALUES ('{EXPERIMENT_ID_2}', '{NAME_2}', '{PROJECT_ID}', '{POSITION_2}', 1, '{CREATED_AT}', '{UPDATED_AT}')"
)
conn.execute(text)
text = (
f"INSERT INTO operators (uuid, experiment_id, component_id, parameters, created_at, updated_at) "
f"VALUES ('{OPERATOR_ID}', '{EXPERIMENT_ID}', '{COMPONENT_ID}', '{PARAMETERS_JSON}', '{CREATED_AT}', '{UPDATED_AT}')"
)
conn.execute(text)
text = (
f"INSERT INTO templates (uuid, name, components, created_at, updated_at) "
f"VALUES ('{TEMPLATE_ID}', '{NAME}', '{COMPONENTS_JSON}', '{CREATED_AT}', '{UPDATED_AT}')"
)
conn.execute(text)
conn.close()
def tearDown(self):
conn = engine.connect()
text = f"DELETE FROM templates WHERE uuid = '{TEMPLATE_ID}'"
conn.execute(text)
text = f"DELETE FROM operators WHERE experiment_id = '{EXPERIMENT_ID}'"
conn.execute(text)
text = f"DELETE FROM operators WHERE experiment_id = '{EXPERIMENT_ID_2}'"
conn.execute(text)
text = f"DELETE FROM experiments WHERE project_id = '{PROJECT_ID}'"
conn.execute(text)
text = f"DELETE FROM projects WHERE uuid = '{PROJECT_ID}'"
conn.execute(text)
text = f"DELETE FROM components WHERE uuid = '{COMPONENT_ID}'"
conn.execute(text)
conn.close()
def test_list_experiments(self):
with app.test_client() as c:
rv = c.get("/projects/unk/experiments")
result = rv.get_json()
expected = {"message": "The specified project does not exist"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 404)
rv = c.get(f"/projects/{PROJECT_ID}/experiments")
result = rv.get_json()
self.assertIsInstance(result, list)
def test_create_experiment(self):
with app.test_client() as c:
rv = c.post("/projects/unk/experiments", json={})
result = rv.get_json()
expected = {"message": "The specified project does not exist"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 404)
rv = c.post(f"/projects/{PROJECT_ID}/experiments", json={})
result = rv.get_json()
expected = {"message": "name is required"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 400)
rv = c.post(f"/projects/{PROJECT_ID}/experiments", json={
"name": NAME,
})
result = rv.get_json()
expected = {"message": "an experiment with that name already exists"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 400)
rv = c.post(f"/projects/{PROJECT_ID}/experiments", json={
"name": "test",
})
result = rv.get_json()
expected = {
"name": "test",
"projectId": PROJECT_ID,
"position": 2,
"isActive": IS_ACTIVE,
"operators": [],
}
# uuid, created_at, updated_at are machine-generated
# we assert they exist, but we don't assert their values
machine_generated = ["uuid", "createdAt", "updatedAt"]
for attr in machine_generated:
self.assertIn(attr, result)
del result[attr]
self.assertDictEqual(expected, result)
def test_get_experiment(self):
with app.test_client() as c:
rv = c.get(f"/projects/foo/experiments/{EXPERIMENT_ID}")
result = rv.get_json()
expected = {"message": "The specified project does not exist"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 404)
rv = c.get(f"/projects/{PROJECT_ID}/experiments/foo")
result = rv.get_json()
expected = {"message": "The specified experiment does not exist"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 404)
rv = c.get(f"/projects/{PROJECT_ID}/experiments/{EXPERIMENT_ID}")
result = rv.get_json()
expected = {
"uuid": EXPERIMENT_ID,
"name": NAME,
"projectId": PROJECT_ID,
"position": POSITION,
"isActive": IS_ACTIVE,
"operators": OPERATORS,
"createdAt": CREATED_AT_ISO,
"updatedAt": UPDATED_AT_ISO,
}
self.assertDictEqual(expected, result)
def test_update_experiment(self):
with app.test_client() as c:
rv = c.patch(f"/projects/foo/experiments/{EXPERIMENT_ID}", json={})
result = rv.get_json()
expected = {"message": "The specified project does not exist"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 404)
rv = c.patch(f"/projects/{PROJECT_ID}/experiments/foo", json={})
result = rv.get_json()
expected = {"message": "The specified experiment does not exist"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 404)
rv = c.patch(f"/projects/{PROJECT_ID}/experiments/{EXPERIMENT_ID}", json={
"name": NAME_2,
})
result = rv.get_json()
expected = {"message": "an experiment with that name already exists"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 400)
rv = c.patch(f"/projects/{PROJECT_ID}/experiments/{EXPERIMENT_ID}", json={
"templateId": "unk",
})
result = rv.get_json()
expected = {"message": "The specified template does not exist"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 400)
rv = c.patch(f"/projects/{PROJECT_ID}/experiments/{EXPERIMENT_ID}", json={
"unk": "bar",
})
self.assertEqual(rv.status_code, 400)
# update experiment using the same name
rv = c.patch(f"/projects/{PROJECT_ID}/experiments/{EXPERIMENT_ID}", json={
"name": NAME,
})
self.assertEqual(rv.status_code, 200)
rv = c.patch(f"/projects/{PROJECT_ID}/experiments/{EXPERIMENT_ID}", json={
"name": "bar",
})
result = rv.get_json()
expected = {
"uuid": EXPERIMENT_ID,
"name": "bar",
"projectId": PROJECT_ID,
"position": POSITION,
"isActive": IS_ACTIVE,
"operators": OPERATORS,
"createdAt": CREATED_AT_ISO,
}
machine_generated = ["updatedAt"]
for attr in machine_generated:
self.assertIn(attr, result)
del result[attr]
self.assertDictEqual(expected, result)
rv = c.patch(f"/projects/{PROJECT_ID}/experiments/{EXPERIMENT_ID}", json={
"templateId": TEMPLATE_ID,
})
result = rv.get_json()
expected = {
"uuid": EXPERIMENT_ID,
"name": "bar",
"projectId": PROJECT_ID,
"position": POSITION,
"isActive": IS_ACTIVE,
"createdAt": CREATED_AT_ISO,
}
result_operators = result["operators"]
machine_generated = ["updatedAt", "operators"]
for attr in machine_generated:
self.assertIn(attr, result)
del result[attr]
self.assertDictEqual(expected, result)
expected = [{
"componentId": COMPONENT_ID,
"experimentId": EXPERIMENT_ID,
"parameters": {},
"dependencies": []
}]
machine_generated = ["uuid", "createdAt", "updatedAt"]
for attr in machine_generated:
for operator in result_operators:
self.assertIn(attr, operator)
del operator[attr]
self.assertListEqual(expected, result_operators)
def test_delete_experiment(self):
with app.test_client() as c:
rv = c.delete(f"/projects/foo/experiments/{EXPERIMENT_ID}")
result = rv.get_json()
expected = {"message": "The specified project does not exist"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 404)
rv = c.delete(f"/projects/{PROJECT_ID}/experiments/unk")
result = rv.get_json()
expected = {"message": "The specified experiment does not exist"}
self.assertDictEqual(expected, result)
self.assertEqual(rv.status_code, 404)
rv = c.delete(f"/projects/{PROJECT_ID}/experiments/{EXPERIMENT_ID}")
result = rv.get_json()
expected = {"message": "Experiment deleted"}
self.assertDictEqual(expected, result)
| 40.582759 | 198 | 0.57592 |
1572ef7362f0874b11201d2353bf0efd88af5413
| 1,482 |
py
|
Python
|
Apps/Model Evaluation/corpus_stats.py
|
RGreinacher/bachelor-thesis
|
60dbc03ce40e3ec42f2538d67a6aabfea6fbbfc8
|
[
"MIT"
] | 1 |
2021-04-13T10:00:46.000Z
|
2021-04-13T10:00:46.000Z
|
Apps/Model Evaluation/corpus_stats.py
|
RGreinacher/bachelor-thesis
|
60dbc03ce40e3ec42f2538d67a6aabfea6fbbfc8
|
[
"MIT"
] | null | null | null |
Apps/Model Evaluation/corpus_stats.py
|
RGreinacher/bachelor-thesis
|
60dbc03ce40e3ec42f2538d67a6aabfea6fbbfc8
|
[
"MIT"
] | null | null | null |
from itertools import repeat
from nltk import Tree
from nltk.chunk.api import ChunkParserI
from os import listdir
from os.path import isfile, join
from pprint import pprint as pp
import csv
import json
import nltk
import pickle
import ner_pipeline
TEXT_SET = 'NER-de-train'
def read_germeval():
total_annotation_count = 0
total_sentence_count = 0
print('reading corpus...')
with open('training/germeval/' + TEXT_SET + '.tsv') as tsv:
tsvin = csv.reader(
tsv,
delimiter='\t',
quotechar='"',
doublequote = True,
quoting = csv.QUOTE_NONE
)
current_sentence = []
for row in tsvin:
if len(row) == 0:
continue
if row[0] == '#':
if current_sentence != []:
total_annotation_count += count_annotations(current_sentence)
total_sentence_count += 1
current_sentence = []
else:
current_sentence.append((row[1], row[2]))
return total_annotation_count, total_sentence_count
def count_annotations(sentence):
annotations = 0
for word in sentence:
if word[1][0] == 'B':
annotations += 1
return annotations
if __name__ == '__main__':
total_annotation_count, total_sentence_count = read_germeval()
print('%s: %s sentences and %s annotations' % (TEXT_SET, total_sentence_count, total_annotation_count))
| 27.444444 | 107 | 0.612011 |
159242fd716e8dfc6893e64d2936389428fbd757
| 210 |
py
|
Python
|
exercises/fr/solution_01_02_02.py
|
Jette16/spacy-course
|
32df0c8f6192de6c9daba89740a28c0537e4d6a0
|
[
"MIT"
] | 2,085 |
2019-04-17T13:10:40.000Z
|
2022-03-30T21:51:46.000Z
|
exercises/fr/solution_01_02_02.py
|
Jette16/spacy-course
|
32df0c8f6192de6c9daba89740a28c0537e4d6a0
|
[
"MIT"
] | 79 |
2019-04-18T14:42:55.000Z
|
2022-03-07T08:15:43.000Z
|
exercises/fr/solution_01_02_02.py
|
Jette16/spacy-course
|
32df0c8f6192de6c9daba89740a28c0537e4d6a0
|
[
"MIT"
] | 361 |
2019-04-17T13:34:32.000Z
|
2022-03-28T04:42:45.000Z
|
# Importe la classe de langue "English"
from spacy.lang.en import English
# Crée l'objet nlp
nlp = English()
# Traite un texte
doc = nlp("This is a sentence.")
# Affiche le texte du document
print(doc.text)
| 17.5 | 39 | 0.719048 |
172a78087505ee3ad01da87d77290f9d3a87e3dd
| 30,973 |
py
|
Python
|
labeldcm/module/app.py
|
hyh520/label-dcm
|
07f8257dcc52b827fcb6d1dec311b532c3ae8925
|
[
"MIT"
] | 1 |
2021-12-20T11:06:42.000Z
|
2021-12-20T11:06:42.000Z
|
labeldcm/module/app.py
|
hyh520/label-dcm
|
07f8257dcc52b827fcb6d1dec311b532c3ae8925
|
[
"MIT"
] | null | null | null |
labeldcm/module/app.py
|
hyh520/label-dcm
|
07f8257dcc52b827fcb6d1dec311b532c3ae8925
|
[
"MIT"
] | null | null | null |
from labeldcm.module import static
from labeldcm.module.config import config
from labeldcm.module.mode import LabelMode
from labeldcm.ui.form import Ui_Form
from PyQt5.QtCore import pyqtBoundSignal, QCoreApplication, QEvent, QObject, QPointF, QRectF, QSize, Qt
from PyQt5.QtGui import QColor, QCursor, QFont, QIcon, QMouseEvent, QPainter, QPen, QPixmap, QResizeEvent
from PyQt5.QtWidgets import QAction, QFileDialog, QGraphicsScene, QInputDialog, \
QMainWindow, QMenu, QMessageBox, QStatusBar
from typing import Dict, Optional, Set, Tuple
class LabelApp(QMainWindow, Ui_Form):
def __init__(self):
super(LabelApp, self).__init__()
self.setupUi(self)
self.retranslateUi(self)
# qss设置
with open('labeldcm/assets/style.qss', 'r', encoding='utf-8') as f:
self.setStyleSheet(f.read())
# 初始化颜色单选框
self.initColorBox()
self.color = QColor(config.defaultColor)
# 初始化操作单选框
self.initActionBox()
self.mode = LabelMode.DefaultMode
# 图片比例,初始100%
self.imgSize = 1
# 初始化画布,原图,现图,现图/原图,原图/现图
self.src: Optional[QPixmap] = None
self.img: Optional[QPixmap] = None
self.ratioFromOld = 1
self.ratioToSrc = 1
self.targetEventType = [QMouseEvent.MouseButtonPress, QMouseEvent.MouseMove, QMouseEvent.MouseButtonRelease]
self.initEventConnections()
# Init Index
self.indexA = -1
self.indexB = -1
self.indexC = -1
# A: IndexA - A, Color
self.points: Dict[int, Tuple[QPointF, QColor]] = {}
# AB: IndexA, IndexB - Color
self.lines: Dict[Tuple[int, int], QColor] = {}
# ∠ABC: IndexA, IndexB, IndexC - Color
self.angles: Dict[Tuple[int, int, int], QColor] = {}
# ⊙A, r = AB: IndexA, IndexB - Color
self.circles: Dict[Tuple[int, int], QColor] = {}
# Init Pivots
self.pivots: Set[int] = set()
# Init Highlight 选中的点
self.highlightMoveIndex = -1
self.highlightPoints: Set[int] = set()
# Init Right Button Menu
self.rightBtnMenu = QMenu(self)
# 状态栏
self.statusBar = QStatusBar()
self.setStatusBar(self.statusBar)
# 绑定事件
def initEventConnections(self):
self.imgView.viewport().installEventFilter(self)
self.loadImgBtn.triggered.connect(self.uploadImg)
self.storeImgBtn.triggered.connect(self.saveImg)
self.colorBox.currentIndexChanged.connect(self.changeColor)
self.actionBox.currentIndexChanged.connect(self.changeMode)
self.imgSizeSlider.valueChanged.connect(self.changeImgSizeSlider)
self.clearAllBtn.triggered.connect(self.initImgWithPoints)
self.deleteImgBtn.triggered.connect(self.clearImg)
self.addSizeBtn.triggered.connect(self.addImgSize)
self.subSizeBtn.triggered.connect(self.subImgSize)
self.originalSizeBtn.triggered.connect(self.originalImgSize)
self.quitAppBtn.triggered.connect(QCoreApplication.instance().quit)
self.aiBtn.triggered.connect(self.aiPoint)
# 更新关键点信息
def updatePivotsInfo(self):
if not self.img or not self.points or not self.pivots:
self.pivotsInfo.setMarkdown('')
return None
pivots = list(self.pivots)
pivots.sort()
mdInfo = ''
for index in pivots:
point = self.getSrcPoint(self.points[index][0])
mdInfo += '{}: ({}, {})\n\n'.format(index, round(point.x(), 2), round(point.y(), 2))
self.pivotsInfo.setMarkdown(mdInfo)
# 初始化画布
def initImg(self):
self.src = None
self.img = None
self.ratioFromOld = 1
self.ratioToSrc = 1
self.patientInfo.setMarkdown('')
# 更新图片,依据画布尺寸自动更新图片尺寸
def updateImg(self):
if not self.src:
self.initImg()
return None
old = self.img if self.img else self.src
size = QSize(
(self.imgView.width() - 2 * self.imgView.lineWidth()) * self.imgSize,
(self.imgView.height() - 2 * self.imgView.lineWidth()) * self.imgSize
)
self.img = self.src.scaled(size, Qt.KeepAspectRatio)
self.ratioFromOld = self.img.width() / old.width()
self.ratioToSrc = self.src.width() / self.img.width()
# 更新画布,添加图片到画布
def updateImgView(self):
scene = QGraphicsScene()
if self.img:
scene.addPixmap(self.img)
self.imgView.setScene(scene)
# DICOM (*.dcm),得到dicom文件的pixmap和内含信息
def loadDcmImg(self, imgDir: str):
if static.isImgAccess(imgDir):
self.src, mdInfo = static.getDcmImgAndMdInfo(imgDir)
self.patientInfo.setMarkdown(mdInfo)
self.updateAll()
else:
self.warning('The image file is not found or unreadable!')
# JPEG (*.jpg;*.jpeg;*.jpe), PNG (*.png)
def loadImg(self, imgDir: str):
if static.isImgAccess(imgDir):
self.src = QPixmap()
self.src.load(imgDir)
self.updateAll()
else:
self.warning('The image file is not found or unreadable!')
# 上传图片到画布
def uploadImg(self):
caption = 'Open Image File'
extFilter = 'DICOM (*.dcm);;JPEG (*.jpg;*.jpeg;*.jpe);;PNG (*.png)'
dcmFilter = 'DICOM (*.dcm)'
imgDir, imgExt = QFileDialog.getOpenFileName(self, caption, static.getHomeImgDir(), extFilter, dcmFilter)
if not imgDir:
return None
self.initAll()
if imgExt == dcmFilter:
self.loadDcmImg(imgDir)
else:
self.loadImg(imgDir)
# 保存结果
def saveImg(self):
if not self.src:
self.warning('Please upload an image file first!')
img = self.src.copy()
self.eraseHighlight()
self.updateLabels(img, True)
caption = 'Save Image File'
extFilter = 'JPEG (*.jpg;*.jpeg;*.jpe);;PNG (*.png)'
initFilter = 'JPEG (*.jpg;*.jpeg;*.jpe)'
imgDir, _ = QFileDialog.getSaveFileName(self, caption, static.getHomeImgDir(), extFilter, initFilter)
if imgDir:
img.save(imgDir)
# 初始化颜色单选框
def initColorBox(self):
size = self.colorBox.iconSize()
index = 0
defaultIndex = -1
for color in config.colorList:
if color == config.defaultColor:
defaultIndex = index
colorIcon = QPixmap(size)
colorIcon.fill(QColor(color))
self.colorBox.addItem(QIcon(colorIcon), f' {color.capitalize()}')
index += 1
self.colorBox.setCurrentIndex(defaultIndex)
# 初始化操作单选框
def initActionBox(self):
index = 0
defaultIndex = -1
for action in config.actionList:
if action == config.defaultAction:
defaultIndex = index
self.actionBox.addItem(f' {action}')
index += 1
self.actionBox.setCurrentIndex(defaultIndex)
# 改变滑块
def changeImgSizeSlider(self):
size = self.imgSizeSlider.value()
self.imgSize = size / 100
self.imgSizeLabel.setText(f'大小:{size}%')
self.updateAll()
def addImgSize(self):
size = min(int(self.imgSize * 100 + 10), 200)
self.imgSizeSlider.setValue(size)
self.imgSize = size / 100
self.imgSizeLabel.setText(f'大小:{size}%')
self.updateAll()
def subImgSize(self):
size = max(int(self.imgSize * 100 - 10), 50)
self.imgSizeSlider.setValue(size)
self.imgSize = size / 100
self.imgSizeLabel.setText(f'大小:{size}%')
self.updateAll()
def originalImgSize(self):
size = 100
self.imgSizeSlider.setValue(size)
self.imgSize = size / 100
self.imgSizeLabel.setText(f'大小:{size}%')
self.updateAll()
# 改变颜色
def changeColor(self):
self.color = QColor(config.colorList[self.colorBox.currentIndex()])
# 改变状态
def changeMode(self):
self.eraseHighlight()
text = config.actionList[self.actionBox.currentIndex()]
mode: LabelMode
if text == '点':
mode = LabelMode.PointMode
elif text == '线':
mode = LabelMode.LineMode
elif text == '角度':
mode = LabelMode.AngleMode
elif text == '圆':
mode = LabelMode.CircleMode
elif text == '中点':
mode = LabelMode.MidpointMode
elif text == '直角':
mode = LabelMode.VerticalMode
elif text == '移动点':
mode = LabelMode.MovePointMode
elif text == '删除点':
mode = LabelMode.ClearPointMode
else:
mode = LabelMode.DefaultMode
self.mode = mode
def initIndex(self):
self.indexA = -1
self.indexB = -1
self.indexC = -1
def initHighlight(self):
self.highlightMoveIndex = -1
self.highlightPoints.clear()
# 清除点,线,角度,圆,中点,高
def initExceptImg(self):
self.initIndex()
self.points.clear()
self.lines.clear()
self.angles.clear()
self.circles.clear()
self.pivots.clear()
self.initHighlight()
# 更新点位置
def updatePoints(self):
if not self.img or not self.points or self.ratioFromOld == 1:
return None
for point, _ in self.points.values():
point.setX(point.x() * self.ratioFromOld)
point.setY(point.y() * self.ratioFromOld)
self.ratioFromOld = 1
# 对应原图点位置
def getSrcPoint(self, point: QPointF):
return QPointF(point.x() * self.ratioToSrc, point.y() * self.ratioToSrc)
# 绘点
def labelPoints(self, img: Optional[QPixmap], toSrc: bool):
if not img or not self.points:
return None
painter = QPainter()
painter.begin(img)
painter.setRenderHint(QPainter.Antialiasing, True)
pen = QPen()
pen.setCapStyle(Qt.RoundCap)
font = QFont('Consolas')
if toSrc:
pen.setWidthF(config.pointWidth * self.ratioToSrc)
font.setPointSizeF(config.fontSize * self.ratioToSrc)
else:
pen.setWidthF(config.pointWidth)
font.setPointSizeF(config.fontSize)
painter.setFont(font)
for index, (point, color) in self.points.items():
labelPoint: QPointF
if toSrc:
pen.setColor(color)
labelPoint = self.getSrcPoint(point)
else:
pen.setColor(
color if index != self.highlightMoveIndex and index not in self.highlightPoints
else QColor.lighter(color)
)
labelPoint = point
painter.setPen(pen)
painter.drawPoint(labelPoint)
painter.drawText(static.getIndexShift(labelPoint), str(index))
painter.end()
# 绘线
def labelLines(self, img: Optional[QPixmap], toSrc: bool):
if not img or not self.lines:
return None
painter = QPainter()
painter.begin(img)
painter.setRenderHint(QPainter.Antialiasing, True)
pen = QPen()
pen.setCapStyle(Qt.RoundCap)
font = QFont('Consolas')
if toSrc:
pen.setWidthF(config.lineWidth * self.ratioToSrc)
font.setPointSizeF(config.fontSize * self.ratioToSrc)
else:
pen.setWidthF(config.lineWidth)
font.setPointSizeF(config.fontSize)
painter.setFont(font)
for (indexA, indexB), color in self.lines.items():
isHighlight = indexA in self.highlightPoints and indexB in self.highlightPoints \
and (self.mode == LabelMode.AngleMode or self.mode == LabelMode.VerticalMode)
pen.setColor(QColor.lighter(color) if isHighlight else color)
painter.setPen(pen)
A = self.points[indexA][0]
B = self.points[indexB][0]
srcA = self.getSrcPoint(A)
srcB = self.getSrcPoint(B)
labelPoint: QPointF
if toSrc:
painter.drawLine(srcA, srcB)
labelPoint = static.getMidpoint(srcA, srcB)
else:
painter.drawLine(A, B)
labelPoint = static.getMidpoint(A, B)
painter.drawText(static.getDistanceShift(A, B, labelPoint), str(round(static.getDistance(srcA, srcB), 2)))
painter.end()
# 绘角度
def labelAngles(self, img: Optional[QPixmap], toSrc: bool):
if not img or not self.angles:
return None
painter = QPainter()
painter.begin(img)
painter.setRenderHint(QPainter.Antialiasing, True)
pen = QPen()
pen.setCapStyle(Qt.RoundCap)
font = QFont('Consolas')
if toSrc:
pen.setWidthF(config.angleWidth * self.ratioToSrc)
font.setPointSizeF(config.fontSize * self.ratioToSrc)
else:
pen.setWidthF(config.angleWidth)
font.setPointSizeF(config.fontSize)
painter.setFont(font)
for (indexA, indexB, indexC), color in self.angles.items():
pen.setColor(color)
painter.setPen(pen)
A = self.points[indexA][0]
B = self.points[indexB][0]
C = self.points[indexC][0]
D, E = static.getDiagPoints(self.points[indexA][0], B, C)
F = static.getArcMidpoint(A, B, C)
labelRect: QRectF
labelPointA: QPointF
labelPointB: QPointF
if toSrc:
labelRect = QRectF(self.getSrcPoint(D), self.getSrcPoint(E))
labelPointA = self.getSrcPoint(B)
labelPointB = self.getSrcPoint(F)
else:
labelRect = QRectF(D, E)
labelPointA = B
labelPointB = F
deg = static.getDegree(A, B, C)
painter.drawArc(labelRect, int(static.getBeginDegree(A, B, C) * 16), int(deg * 16))
painter.drawText(static.getDegreeShift(labelPointA, labelPointB), str(round(deg, 2)) + '°')
painter.end()
# 绘圆
def labelCircles(self, img: Optional[QPixmap], toSrc: bool):
if not img or not self.circles:
return None
painter = QPainter()
painter.begin(img)
painter.setRenderHint(QPainter.Antialiasing, True)
pen = QPen()
pen.setCapStyle(Qt.RoundCap)
pen.setWidthF(config.lineWidth if not toSrc else config.lineWidth * self.ratioToSrc)
for (indexA, indexB), color in self.circles.items():
isHighlight = indexA in self.highlightPoints and indexB in self.highlightPoints \
and self.mode == LabelMode.CircleMode
pen.setColor(QColor.lighter(color) if isHighlight else color)
painter.setPen(pen)
A = self.points[indexA][0]
B = self.points[indexB][0]
painter.drawEllipse(
static.getMinBoundingRect(A, B) if not toSrc
else static.getMinBoundingRect(self.getSrcPoint(A), self.getSrcPoint(B))
)
painter.end()
def erasePoint(self, index):
if index not in self.points:
return None
del self.points[index]
for line in list(self.lines.keys()):
if index in line:
del self.lines[line]
for angle in list(self.angles.keys()):
if index in angle:
del self.angles[angle]
for circle in list(self.circles.keys()):
if index in circle:
del self.circles[circle]
self.pivots.discard(index)
def eraseHighlight(self):
if self.mode == LabelMode.CircleMode:
self.erasePoint(self.indexA)
self.erasePoint(self.indexB)
self.initIndex()
self.initHighlight()
self.updateAll()
def updateLabels(self, img: Optional[QPixmap], toSrc: bool):
self.labelPoints(img, toSrc)
self.labelLines(img, toSrc)
self.labelAngles(img, toSrc)
self.labelCircles(img, toSrc)
def getImgPoint(self, point: QPointF):
return QPointF(point.x() / self.ratioToSrc, point.y() / self.ratioToSrc)
# 更新标号
def getNewIndex(self):
return max(self.points.keys() if self.points else [0]) + 1
# 得到point位置标号
def getPointIndex(self, point: QPointF):
if not self.img or not self.points:
return -1
distance = config.pointWidth - config.eps
# Index -1 means the point does not exist
index = -1
for idx, (pt, _) in self.points.items():
dis = static.getDistance(point, pt)
if dis < distance:
distance = dis
index = idx
return index
def isPointOutOfBound(self, point: QPointF):
return point.x() < config.pointWidth / 2 or point.x() > self.img.width() - config.pointWidth / 2 \
or point.y() < config.pointWidth / 2 or point.y() > self.img.height() - config.pointWidth / 2
# 得到有效标号数量
def getIndexCnt(self):
return len([i for i in [self.indexA, self.indexB, self.indexC] if i != -1])
# 判断高亮
def triggerIndex(self, index: int):
if not self.img or not self.points or index == -1:
return None
if index in [self.indexA, self.indexB, self.indexC]:
indexs = [i for i in [self.indexA, self.indexB, self.indexC] if i != index]
self.indexA = indexs[0]
self.indexB = indexs[1]
self.indexC = -1
self.highlightPoints.remove(index)
else:
indexs = [i for i in [self.indexA, self.indexB, self.indexC] if i != -1]
indexs.append(index)
while len(indexs) < 3:
indexs.append(-1)
self.indexA = indexs[0]
self.indexB = indexs[1]
self.indexC = indexs[2]
self.highlightPoints.add(index)
def endTrigger(self):
self.initIndex()
self.initHighlight()
def endTriggerWith(self, index: int):
self.endTrigger()
self.highlightMoveIndex = index
# 添加到各个字典中
def addPoint(self, point: QPointF):
if self.img:
index = self.getNewIndex()
self.points[index] = point, self.color
return index
def addLine(self, indexA: int, indexB: int):
if self.img and indexA in self.points and indexB in self.points:
self.lines[static.getLineKey(indexA, indexB)] = self.color
def addAngle(self, indexA: int, indexB: int, indexC: int):
if self.img and static.getLineKey(indexA, indexB) in self.lines \
and static.getLineKey(indexB, indexC) in self.lines:
self.angles[static.getAngleKey(indexA, indexB, indexC)] = self.color
def addCircle(self, indexA: int, indexB: int):
if self.img and indexA in self.points and indexB in self.points:
self.circles[(indexA, indexB)] = self.color
# 点击事件
def handlePointMode(self, evt: QMouseEvent):
if evt.type() != QMouseEvent.MouseButtonPress:
return None
point = self.imgView.mapToScene(evt.pos())
index = self.getPointIndex(point)
if index != -1:
self.points[index] = self.points[index][0], self.color
else:
self.addPoint(point)
self.updateAll()
def handleLineMode(self, evt: QMouseEvent):
if evt.type() != QMouseEvent.MouseButtonPress:
return None
point = self.imgView.mapToScene(evt.pos())
index = self.getPointIndex(point)
if index == -1:
self.triggerIndex(self.addPoint(point))
else:
self.triggerIndex(index)
if self.getIndexCnt() == 2:
self.addLine(self.indexA, self.indexB)
self.endTriggerWith(self.indexB)
self.updateAll()
def handleAngleMode(self, evt: QMouseEvent):
if evt.type() != QMouseEvent.MouseButtonPress:
return None
self.triggerIndex(self.getPointIndex(self.imgView.mapToScene(evt.pos())))
if self.getIndexCnt() == 2 and static.getLineKey(self.indexA, self.indexB) not in self.lines:
self.triggerIndex(self.indexA)
elif self.getIndexCnt() == 3:
if static.getLineKey(self.indexB, self.indexC) in self.lines:
self.addAngle(self.indexA, self.indexB, self.indexC)
self.endTriggerWith(self.indexC)
else:
indexC = self.indexC
self.endTrigger()
self.triggerIndex(indexC)
self.updateAll()
def handleCircleMode(self, evt: QMouseEvent):
point = self.imgView.mapToScene(evt.pos())
if self.getPointIndex(point) == -1:
if evt.type() == QMouseEvent.MouseButtonPress:
if self.getIndexCnt() == 0:
self.triggerIndex(self.addPoint(point))
self.triggerIndex(
self.addPoint(QPointF(point.x() + 2 * config.eps, point.y() + 2 * config.eps))
)
self.addCircle(self.indexA, self.indexB)
elif self.getIndexCnt() == 2:
self.endTriggerWith(self.indexB)
elif evt.type() == QMouseEvent.MouseMove and self.getIndexCnt() == 2 and not self.isPointOutOfBound(point):
self.points[self.indexB][0].setX(point.x())
self.points[self.indexB][0].setY(point.y())
else:
if evt.type() == QMouseEvent.MouseButtonPress:
if self.getIndexCnt() == 0:
self.triggerIndex(self.getPointIndex(point))
self.triggerIndex(
self.addPoint(QPointF(point.x() + 2 * config.eps, point.y() + 2 * config.eps))
)
self.addCircle(self.indexA, self.indexB)
elif self.getIndexCnt() == 2:
self.endTriggerWith(self.indexB)
elif evt.type() == QMouseEvent.MouseMove and self.getIndexCnt() == 2 and not self.isPointOutOfBound(point):
self.points[self.indexB][0].setX(point.x())
self.points[self.indexB][0].setY(point.y())
self.updateAll()
def handleMidpointMode(self, evt: QMouseEvent):
if evt.type() != QMouseEvent.MouseButtonPress:
return None
self.triggerIndex(self.getPointIndex(self.imgView.mapToScene(evt.pos())))
if self.getIndexCnt() == 2:
if static.getLineKey(self.indexA, self.indexB) in self.lines:
A = self.points[self.indexA][0]
B = self.points[self.indexB][0]
indexC = self.addPoint(static.getMidpoint(A, B))
self.addLine(self.indexA, indexC)
self.addLine(self.indexB, indexC)
self.endTriggerWith(self.indexB)
else:
self.triggerIndex(self.indexA)
self.updateAll()
def handleVerticalMode(self, evt: QMouseEvent):
if evt.type() != QMouseEvent.MouseButtonPress:
return None
self.triggerIndex(self.getPointIndex(self.imgView.mapToScene(evt.pos())))
if self.getIndexCnt() == 2:
if static.getLineKey(self.indexA, self.indexB) not in self.lines:
self.triggerIndex(self.indexA)
elif self.getIndexCnt() == 3:
A = self.points[self.indexA][0]
B = self.points[self.indexB][0]
C = self.points[self.indexC][0]
if static.isOnALine(A, B, C):
if static.getLineKey(self.indexB, self.indexC) in self.lines:
self.triggerIndex(self.indexA)
else:
indexC = self.indexC
self.endTrigger()
self.triggerIndex(indexC)
else:
D = static.getFootPoint(A, B, C)
indexD = self.addPoint(D)
if not static.isOnSegment(A, B, D):
self.addLine(
(self.indexA if static.getDistance(A, D) < static.getDistance(B, D) else self.indexB), indexD
)
self.addLine(self.indexC, indexD)
self.endTriggerWith(self.indexC)
self.updateAll()
def handleDragMode(self, evt: QMouseEvent):
point = self.imgView.mapToScene(evt.pos())
if evt.type() == QMouseEvent.MouseButtonPress and self.getIndexCnt() == 0:
self.triggerIndex(self.getPointIndex(point))
elif evt.type() == QMouseEvent.MouseMove and self.getIndexCnt() == 1 and not self.isPointOutOfBound(point):
self.points[self.indexA][0].setX(point.x())
self.points[self.indexA][0].setY(point.y())
elif evt.type() == QMouseEvent.MouseButtonRelease and self.getIndexCnt() == 1:
self.triggerIndex(self.indexA)
self.updateAll()
def handleClearPointMode(self, evt: QMouseEvent):
index = self.getPointIndex(self.imgView.mapToScene(evt.pos()))
if evt.type() == QMouseEvent.MouseButtonPress and index != -1:
self.erasePoint(index)
self.updateAll()
def handleHighlightMove(self, evt: QMouseEvent):
point = self.imgView.mapToScene(evt.pos())
self.highlightMoveIndex = self.getPointIndex(point)
text = f'坐标:{round(point.x(), 2)}, {round(point.y(), 2)}'
self.statusBar.showMessage(text, 1000)
self.updateAll()
def initAll(self):
self.initImg()
self.initExceptImg()
def updateAll(self):
self.updateImg()
self.updatePoints()
self.updateLabels(self.img, False)
self.updateImgView()
self.updatePivotsInfo()
# 清除所有点,还原图片
def initImgWithPoints(self):
if not self.img:
return None
self.initExceptImg()
self.updateAll()
# 清除图片
def clearImg(self):
if not self.src:
return None
self.initAll()
self.updateAll()
# 自动适应窗口
def resizeEvent(self, _: QResizeEvent):
self.updateAll()
# 错误警告
def warning(self, text: str):
QMessageBox.warning(self, 'Warning', text)
# 更改标号
def modifyIndex(self, index: int):
newIndex, modify = QInputDialog.getInt(self, '更改标号', '请输入一个新的标号', index, 0, step=1)
if not modify or newIndex == index:
return None
if newIndex <= 0:
self.warning('标号不可小于或等于0!')
return None
if newIndex in self.points:
self.warning('此标号已存在!')
return None
self.points[newIndex] = self.points[index]
del self.points[index]
for line in list(self.lines.keys()):
if index in line:
fixedIndex = line[0] + line[1] - index
self.lines[static.getLineKey(newIndex, fixedIndex)] = self.lines[line]
del self.lines[line]
for angle in list(self.angles.keys()):
if index in angle:
if index == angle[1]:
self.angles[angle[0], newIndex, angle[2]] = self.angles[angle]
else:
fixedIndex = angle[0] + angle[2] - index
self.angles[static.getAngleKey(newIndex, angle[1], fixedIndex)] = self.angles[angle]
del self.angles[angle]
for circle in list(self.circles.keys()):
if index in circle:
if index == circle[0]:
self.circles[(newIndex, circle[1])] = self.circles[circle]
else:
self.circles[(circle[0], newIndex)] = self.circles[circle]
del self.circles[circle]
if index in self.pivots:
self.pivots.remove(index)
self.pivots.add(newIndex)
def addPivots(self, index: int):
if self.img and index in self.points:
self.pivots.add(index)
def removePivots(self, index: int):
if self.img and self.pivots:
self.pivots.discard(index)
def switchPivotState(self, index: int):
if index not in self.pivots:
self.addPivots(index)
else:
self.removePivots(index)
def createRightBtnMenu(self, index: int, point: QPointF):
self.rightBtnMenu = QMenu(self)
modifyIndex = QAction('更改标号', self.rightBtnMenu)
modifyIndexTriggered: pyqtBoundSignal = modifyIndex.triggered
modifyIndexTriggered.connect(lambda: self.modifyIndex(index))
switchPivotState = QAction('删除该点信息' if index in self.pivots else '查看该点信息', self.rightBtnMenu)
switchPivotStateTriggered: pyqtBoundSignal = switchPivotState.triggered
switchPivotStateTriggered.connect(lambda: self.switchPivotState(index))
erasePoint = QAction('清除该点', self.rightBtnMenu)
erasePointTriggered: pyqtBoundSignal = erasePoint.triggered
erasePointTriggered.connect(lambda: self.erasePoint(index))
self.rightBtnMenu.addAction(modifyIndex)
self.rightBtnMenu.addAction(switchPivotState)
self.rightBtnMenu.addAction(erasePoint)
self.rightBtnMenu.exec(point)
def handleRightBtnMenu(self, evt: QMouseEvent):
if (index := self.getPointIndex(self.imgView.mapToScene(evt.pos()))) != -1:
self.eraseHighlight()
self.highlightMoveIndex = index
self.updateAll()
self.createRightBtnMenu(index, evt.globalPos())
self.highlightMoveIndex = self.getPointIndex(
self.imgView.mapToScene(self.imgView.mapFromParent(self.mapFromParent(QCursor.pos())))
)
self.updateAll()
def eventFilter(self, obj: QObject, evt: QEvent):
if not self.img or obj is not self.imgView.viewport() or evt.type() not in self.targetEventType:
return super().eventFilter(obj, evt)
if self.mode == LabelMode.PointMode:
self.handlePointMode(evt)
elif self.mode == LabelMode.LineMode:
self.handleLineMode(evt)
elif self.mode == LabelMode.AngleMode:
self.handleAngleMode(evt)
elif self.mode == LabelMode.CircleMode:
self.handleCircleMode(evt)
elif self.mode == LabelMode.MidpointMode:
self.handleMidpointMode(evt)
elif self.mode == LabelMode.VerticalMode:
self.handleVerticalMode(evt)
elif self.mode == LabelMode.MovePointMode:
self.handleDragMode(evt)
elif self.mode == LabelMode.ClearPointMode:
self.handleClearPointMode(evt)
if evt.type() == QMouseEvent.MouseMove:
self.handleHighlightMove(evt)
elif evt.type() == QMouseEvent.MouseButtonPress and QMouseEvent(evt).button() == Qt.RightButton:
self.handleRightBtnMenu(evt)
return super().eventFilter(obj, evt)
# 自动出点
def aiPoint(self):
pass
| 38.285538 | 119 | 0.588383 |
bdfb629621674223dd543633dd0f525b0de89455
| 4,201 |
py
|
Python
|
tests/onegov/translator_directory/test_collections.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
tests/onegov/translator_directory/test_collections.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
tests/onegov/translator_directory/test_collections.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
from onegov.translator_directory.collections.language import LanguageCollection
from onegov.translator_directory.collections.translator import \
TranslatorCollection
from onegov.translator_directory.constants import INTERPRETING_TYPES, \
PROFESSIONAL_GUILDS
from tests.onegov.translator_directory.shared import create_languages, \
create_translator
def test_translator_search(session):
interpreting_types = list(INTERPRETING_TYPES.keys())
guild_types = list(PROFESSIONAL_GUILDS.keys())
seba = create_translator(
session,
email='[email protected]',
first_name='Sebastian Hans',
last_name='Meier Hugentobler',
expertise_interpreting_types=[],
expertise_professional_guilds=guild_types[0:3]
)
mary = create_translator(
session,
email='[email protected]',
first_name='Mary Astiana',
last_name='Sitkova Lavrova',
expertise_interpreting_types=interpreting_types[0:1],
expertise_professional_guilds=[]
)
translators = TranslatorCollection(session)
translators.search = 'Lavrov'
assert translators.query().one().last_name == 'Sitkova Lavrova'
translators.search = 'mari sitkova'
assert translators.query().one().last_name == 'Sitkova Lavrova'
translators.search = 'Sebastian astian'
assert translators.query().all() == [seba, mary]
translators.search = 'astian'
assert translators.query().all() == [seba, mary]
translators.interpret_types = [interpreting_types[0]]
assert translators.query().all() == [mary]
translators.interpret_types.append(interpreting_types[1])
assert translators.query().all() == []
translators.interpret_types = []
translators.guilds = guild_types[0:2]
assert translators.query().all() == [seba]
def test_translator_collection(session):
langs = create_languages(session)
collection = TranslatorCollection(session)
james = create_translator(session, email='[email protected]', last_name='Z')
translator = session.query(collection.model_class).one()
assert translator == collection.by_id(translator.id)
assert collection.query().all() == [translator]
# Adds second translator
bob = create_translator(session, email='[email protected]', last_name='X')
# Test filter spoken language
collection.spoken_langs = [langs[0].id]
assert not collection.query().first()
james.spoken_languages.append(langs[0])
assert collection.query().count() == 1
# Test filter with multiple spoken languages
collection.spoken_langs = [langs[0].id, langs[1].id]
assert not collection.query().first()
# Add second language for james and test filter with two languages
james.spoken_languages.append(langs[1])
collection.spoken_langs = [langs[0].id, langs[1].id]
assert collection.query().all() == [james]
# Test filter with two languages
bob.written_languages.append(langs[1])
bob.written_languages.append(langs[2])
bob.spoken_languages.append(langs[1])
bob.spoken_languages.append(langs[2])
collection.spoken_langs = [langs[2].id]
collection.written_langs = collection.spoken_langs
assert collection.query().all() == [bob]
# Test filter with two languages spoken and written
collection.written_langs = [langs[1].id, langs[2].id]
collection.spoken_langs = collection.written_langs
assert collection.query().all() == [bob]
# Test ordering
collection.spoken_langs = None
collection.written_langs = None
assert collection.order_by == 'last_name'
assert collection.order_desc is False
assert collection.query().all() == [bob, james]
collection.order_desc = True
assert collection.query().all() == [james, bob]
def test_collection_wrong_user_input(session):
# Prevent wrong user input from going to the db query
coll = TranslatorCollection(session, order_by='nothing', order_desc='hey')
assert coll.order_desc is False
assert coll.order_by == 'last_name'
def test_language_collection(session):
coll = LanguageCollection(session)
zulu = coll.add(name='Zulu')
arabic = coll.add(name='Arabic')
assert coll.query().all() == [arabic, zulu]
| 35.905983 | 79 | 0.712687 |
97c79deb52086a69f6295b76053c75a7863ee135
| 3,894 |
py
|
Python
|
examples/rasa_demo/actions/actions.py
|
ajay-cz/chatbot-engine
|
df58f3e7e899151feedb847e56d9fc699e66f60c
|
[
"MIT"
] | null | null | null |
examples/rasa_demo/actions/actions.py
|
ajay-cz/chatbot-engine
|
df58f3e7e899151feedb847e56d9fc699e66f60c
|
[
"MIT"
] | 1 |
2021-12-20T07:05:33.000Z
|
2021-12-29T01:35:37.000Z
|
examples/rasa_demo/actions/actions.py
|
ajay-cz/chatbot-engine
|
df58f3e7e899151feedb847e56d9fc699e66f60c
|
[
"MIT"
] | null | null | null |
import os
from mailchimp3 import MailChimp
from mailchimp3.mailchimpclient import MailChimpError
from rasa_sdk import Action
from typing import Text
class ActionAboutMe(Action):
def name(self):
return "action_about_me"
def run(self, dispatcher, tracker, domain):
message = {
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
"title":"Visit our website",
"buttons":[
{
"title":"Project GitLab",
"url": "https://gitlab.com/langnerd/chatbot-engine"
}
]
}
]
}
}
dispatcher.utter_message(attachment=message)
return []
class ActionCheerUp(Action):
def name(self):
return "action_cheer_up"
def run(self, dispatcher, tracker, domain):
dispatcher.utter_template("utter_cheer_up", tracker)
dispatcher.utter_template("utter_did_that_help", tracker)
return []
class ActionContribute(Action):
def name(self):
return "action_contribute"
def run(self, dispatcher, tracker, domain):
message = {
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
"title":"See how you can make a difference!",
"buttons":[
{
"title":"Become a contributor",
"url": "https://gitlab.com/langnerd/chatbot-engine"
}
]
}
]
}
}
dispatcher.utter_message(attachment=message)
return []
class ActionDefaultFallback(Action):
def name(self):
return "action_default_fallback"
def run(self, dispatcher, tracker, domain):
dispatcher.utter_template("utter_default_fallback", tracker)
return []
class ActionSubscribe(Action):
"""Asks for the user's email, calls the newsletter API and signs the user up"""
def name(self) -> Text:
return "action_subscribe"
def run(self, dispatcher, tracker, domain):
email = next(tracker.get_latest_entity_values("email"), None)
if email:
client = MailChimpClient(os.getenv('MAILCHIMP_API_KEY'), os.getenv('MAILCHIMP_USER'))
# if the email is already subscribed, this returns False
added_to_list = client.subscribe(os.getenv('MAILCHIMP_LIST_ID'), email)
# utter submit template
if added_to_list:
dispatcher.utter_message(template="utter_confirmation_email")
else:
dispatcher.utter_message(template="utter_already_subscribed")
else:
# no entity was picked up, we want to ask again
dispatcher.utter_message(template="utter_no_email")
return []
class MailChimpClient:
"""Sends emails through MailChimp"""
def __init__(self, api_key: Text, user: Text) -> None:
self.client = MailChimp(mc_api=api_key, mc_user=user)
def subscribe(self, newsletter_id: Text, email: Text) -> bool:
# Subscribe the user to the newsletter if they're not already
# User subscribed with the status pending
try:
self.client.lists.members.create(
newsletter_id, data={"email_address": email, "status": "pending"}
)
return True
except MailChimpError as e:
# TODO this can be any error log it!
print(e)
# The user is already subscribed
return False
| 32.181818 | 97 | 0.541089 |
c19d0cf43ece4171691192bd4d15debabda2a0a8
| 78 |
py
|
Python
|
open_archives.py
|
EmanuelDms/automation
|
25a0f370f40aa955225d7c3a1e28c2d8cc988689
|
[
"MIT"
] | null | null | null |
open_archives.py
|
EmanuelDms/automation
|
25a0f370f40aa955225d7c3a1e28c2d8cc988689
|
[
"MIT"
] | null | null | null |
open_archives.py
|
EmanuelDms/automation
|
25a0f370f40aa955225d7c3a1e28c2d8cc988689
|
[
"MIT"
] | null | null | null |
arquivo = open('argv.py', 'r')
for line in arquivo:
print(line.rstrip())
| 15.6 | 30 | 0.628205 |
a9e1c83b048b08de68f1fd0dda0a5a9caf861ea9
| 973 |
py
|
Python
|
PMIa/2014/KUCHERYAVENKO_A_I/task_6_38.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
PMIa/2014/KUCHERYAVENKO_A_I/task_6_38.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
PMIa/2014/KUCHERYAVENKO_A_I/task_6_38.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
# Задача 6. Вариант 38.
#Создайте игру, в которой компьютер загадывает имя одной из девяти муз в
#древнегреческой мифологии, а игрок должен его угадать.
# Kucheryavenko A. I.
# 14.04.2016
import random
muza = random.randint(1,9)
print("Программа случайным образом загадывает имя одной из девяти муз в древнегреческой мифологии, а игрок должен его угадать.")
if muza == 1 :
muza = ('Каллиопа')
elif muza == 2 :
muza = ('Клио')
elif muza == 3 :
muza = ('Мельпомена')
elif muza == 4 :
muza = ('Талия')
elif muza == 5 :
muza = ('Эвтерпа')
elif muza == 6 :
muza = ('Эрато')
elif muza == 7 :
muza = ('Терпсихора')
elif muza == 8 :
muza = ('Полигимния')
elif muza == 9 :
muza = ('Урания')
answer = input('\nНазовите одной из девяти муз древнегреческое мифологии: ')
if answer == muza :
print('\nВы угадали!')
else :
print('\nВы не угадали!!!')
print('Правильный ответ: ', muza)
input("\n\nНажмите Enter для выхода.")
| 22.113636 | 128 | 0.638232 |
e7cfa98d5137209be1a30c32430d74089b87cf0a
| 2,054 |
py
|
Python
|
homepage/pelicanconf.py
|
ecs-org/ecs-docs
|
0d685db17731a35c90852d7f75fbdf3791bd696c
|
[
"Apache-2.0"
] | 1 |
2020-01-04T05:51:39.000Z
|
2020-01-04T05:51:39.000Z
|
homepage/pelicanconf.py
|
ecs-org/ecs-docs
|
0d685db17731a35c90852d7f75fbdf3791bd696c
|
[
"Apache-2.0"
] | null | null | null |
homepage/pelicanconf.py
|
ecs-org/ecs-docs
|
0d685db17731a35c90852d7f75fbdf3791bd696c
|
[
"Apache-2.0"
] | 1 |
2021-11-23T15:41:01.000Z
|
2021-11-23T15:41:01.000Z
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
import os
from datetime import datetime
AUTHOR = (
datetime.now().strftime("%Y")
+ " Medizinische Universität Wien, Medizinische Universität Innsbruck, Medizinische Universität Graz, Johannes Kepler Universität Linz, Karl Landsteiner Privatuniversität für Gesundheitswissenschaften, Land Salzburg, Vinzenz Gruppe"
)
SITENAME = "ECS - Ethics Committee System"
SITEURL = ""
# THEME = 'simple'
THEME = "_themes/pelican-bootstrap3"
PLUGIN_PATHS = [
os.path.abspath(os.path.join(os.path.dirname(__file__), "_plugins")),
]
PLUGINS = [
"i18n_subsites",
]
JINJA_ENVIRONMENT = {"extensions": ["jinja2.ext.i18n"]}
OUTPUT_SOURCES = False
OUTPUT_PATH = "_build"
PATH = "."
PAGE_PATHS = ["pages"]
ARTICLE_PATHS = ["articles"]
STATIC_PATHS = ["static"]
DEFAULT_LANG = "en"
DEFAULT_DATE = "fs"
DEFAULT_PAGINATION = False
DEFAULT_DATE_FORMAT = "%a %d %B %Y"
TIMEZONE = "Europe/Paris"
TYPOGRIFY = False
PAGE_ORDER_BY = "order" # use meta tag order to define pages order
# Menu
DISPLAY_PAGES_ON_MENU = True # do not display, because we want to override all
DISPLAY_CATEGORIES_ON_MENU = False
# A list of tuples (Title, URL) for additional menu items to appear at the beginning of the main menu.
MENUITEMS = (
# ( 'Custom', '#'),
)
# Links
# A list of tuples (Title, URL) for links to appear on the header.
LINKS = (
# ( 'Test Header Link', '#'),
)
# A list of tuples (Title, URL) to appear in the “social” section.
SOCIAL = (
# ('Test Social Link', '#'),
)
# Tags are not needed
TAGS_SAVE_AS = ""
TAG_SAVE_AS = ""
# Feed generation is not needed
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Article info is not needed
SHOW_ARTICLE_AUTHOR = False
SHOW_ARTICLE_CATEGORY = False
SHOW_DATE_MODIFIED = False
# Add custom CSS
CUSTOM_CSS = "static/custom.css"
# Theme options
HIDE_SIDEBAR = True
BOOTSTRAP_NAVBAR_INVERSE = True
SITELOGO = "static/favicon.ico"
| 25.358025 | 236 | 0.72298 |
99f35a1b101c11e72ff82ce426bd6f75cd636f82
| 2,842 |
py
|
Python
|
Prototype/main prototype/TempWidget.py
|
fowado/BauphysikSE1
|
eb8805196c8fbf99a879c40c5e0725d740c5a0de
|
[
"CC-BY-4.0"
] | 4 |
2019-12-03T16:13:09.000Z
|
2019-12-11T23:22:58.000Z
|
Prototype/main prototype/TempWidget.py
|
fowado/BauphysikSE1
|
eb8805196c8fbf99a879c40c5e0725d740c5a0de
|
[
"CC-BY-4.0"
] | 65 |
2019-12-08T17:43:59.000Z
|
2020-08-14T15:26:21.000Z
|
Prototype/main prototype/TempWidget.py
|
fowado/BauphysikSE1
|
eb8805196c8fbf99a879c40c5e0725d740c5a0de
|
[
"CC-BY-4.0"
] | null | null | null |
# This Python file uses the following encoding: utf-8
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from CustomMiniWidgets import MyDoubleSpinBox
class TempWidget(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
#layout
tempLayout = QtWidgets.QGridLayout()
tempLayout.setContentsMargins(0,0,0,0)
tempLayout.setSpacing(20)
self.tempTitleLabel = QtWidgets.QLabel()
"""title of TempWidget"""
self.tempInsideLabel = QtWidgets.QLabel()
self.tempOutsideLabel = QtWidgets.QLabel()
#hard coded solution for spinbox size, could be done better?
self.tempOutsideDoubleSpinBox = MyDoubleSpinBox()
"""input/output for T_inside"""
self.tempOutsideDoubleSpinBox.setMaximum(1000)
self.tempOutsideDoubleSpinBox.setMinimum(-273.15)
self.tempOutsideDoubleSpinBox.setDecimals(2)
self.tempOutsideDoubleSpinBox.setSingleStep(0.1)
self.tempOutsideDoubleSpinBox.setMaximumWidth(100)
self.tempOutsideDoubleSpinBox.setMinimumWidth(100)
#hard coded solution for spinbox size, could be done better?
self.tempInsideDoubleSpinBox = MyDoubleSpinBox()
"""input/output for T_inside"""
self.tempInsideDoubleSpinBox.setMaximum(1000)
self.tempInsideDoubleSpinBox.setMinimum(-273.15)
self.tempInsideDoubleSpinBox.setDecimals(2)
self.tempInsideDoubleSpinBox.setSingleStep(0.1)
self.tempInsideDoubleSpinBox.setMaximumWidth(100)
self.tempInsideDoubleSpinBox.setMinimumWidth(100)
self.tempCelsiusLabel1 = QtWidgets.QLabel()
self.tempCelsiusLabel2 = QtWidgets.QLabel()
#assemble layout
tempLayout.addWidget(self.tempTitleLabel,0,0)
tempLayout.addWidget(self.tempInsideLabel,0,1)
tempLayout.addWidget(self.tempOutsideLabel,1,1)
tempLayout.addWidget(self.tempCelsiusLabel1,0,3)
tempLayout.addWidget(self.tempCelsiusLabel2,1,3)
tempLayout.addWidget(self.tempInsideDoubleSpinBox, 0,2)
tempLayout.addWidget(self.tempOutsideDoubleSpinBox, 1,2)
self.setLayout(tempLayout)
self.retranslateUi()
def retranslateUi(self):
_translate = QtCore.QCoreApplication.translate
self.tempTitleLabel.setText(_translate("TempWidget", "Temp"))
self.tempInsideLabel.setText(_translate("TempWidget", "innen:"))
self.tempOutsideLabel.setText(_translate("TempWidget", "außen:"))
self.tempCelsiusLabel1.setText(_translate("TempWidget", "°C"))
self.tempCelsiusLabel2.setText(_translate("TempWidget", "°C"))
def setData(self, tleft, tright):
"""sets spinboxes with given data"""
self.tempInsideDoubleSpinBox.setValue(tleft)
self.tempOutsideDoubleSpinBox.setValue(tright)
| 38.405405 | 73 | 0.711471 |
68d09f1a8cb5d48ac305b586bd15eed139cbf565
| 345 |
py
|
Python
|
Python/M01_ProgrammingBasics/L05_WhileLoop/Exercises/Solutions/P06_Cake.py
|
todorkrastev/softuni-software-engineering
|
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
|
[
"MIT"
] | null | null | null |
Python/M01_ProgrammingBasics/L05_WhileLoop/Exercises/Solutions/P06_Cake.py
|
todorkrastev/softuni-software-engineering
|
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
|
[
"MIT"
] | null | null | null |
Python/M01_ProgrammingBasics/L05_WhileLoop/Exercises/Solutions/P06_Cake.py
|
todorkrastev/softuni-software-engineering
|
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
|
[
"MIT"
] | 1 |
2022-02-23T13:03:14.000Z
|
2022-02-23T13:03:14.000Z
|
width = int(input())
lenght = int(input())
count = width * lenght
while count > 0:
line = input()
if line == "STOP":
break
else:
new_pieces = int(line)
count = count - new_pieces
if count > 0:
print(f"{count} pieces are left.")
else:
print(f"No more cake left! You need {abs(count)} pieces more.")
| 19.166667 | 67 | 0.57971 |
6bf8c3921bd21176630543d5abaa7bb8dead2c28
| 1,912 |
py
|
Python
|
experiments/Non_RL.py
|
june6723/sumo-rl-offset
|
775cddc8d168fb7c4959610a96a791d746fa0afd
|
[
"MIT"
] | 4 |
2020-10-11T01:30:13.000Z
|
2021-04-27T16:03:41.000Z
|
experiments/Non_RL.py
|
june6723/sumo-rl-offset
|
775cddc8d168fb7c4959610a96a791d746fa0afd
|
[
"MIT"
] | null | null | null |
experiments/Non_RL.py
|
june6723/sumo-rl-offset
|
775cddc8d168fb7c4959610a96a791d746fa0afd
|
[
"MIT"
] | null | null | null |
import argparse
import os
import sys
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
sys.path.append(tools)
else:
sys.exit("Please declare the environment variable 'SUMO_HOME'")
import pandas as pd
import ray
from ray.rllib.agents.dqn.dqn import DQNTrainer
from ray.rllib.agents.dqn.dqn import DQNTFPolicy
from ray.tune.registry import register_env
from ray.tune.logger import pretty_print
from gym import spaces
import numpy as np
from sumo_rl.environment.env_NonRL import SumoEnvironment
import traci
def policy_mapping(id):
if id == "left":
return "left"
else:
return "right"
if __name__ == '__main__':
ray.init()
register_env("2TLS", lambda _: SumoEnvironment(net_file='nets/Research/case03/intersection_NonRL.net.xml',
route_file='nets/Research/case03/test.rou.xml',
out_csv_path='outputs/grad/',
out_csv_name='nonrl',
use_gui=True,
num_seconds=22000,
time_to_load_vehicles=21600,
max_depart_delay=0)
)
trainer = DQNTrainer(env="2TLS", config={
"multiagent": {
"policy_graphs": {
'left': (DQNTFPolicy, spaces.Box(low=np.zeros(21), high=np.ones(21)), spaces.Discrete(2), {}),
'right': (DQNTFPolicy, spaces.Box(low=np.zeros(21), high=np.ones(21)), spaces.Discrete(2), {})
},
"policy_mapping_fn": policy_mapping # Traffic lights are always controlled by this policy
},
"lr": 0.0001,
})
while True:
result = trainer.train()
| 36.769231 | 110 | 0.544456 |
cf0f8c321f820512301141ab6ebc985c3606b464
| 1,078 |
py
|
Python
|
Python/Buch_Python3_Das_umfassende_Praxisbuch/Kapitel_06_Funktionen/12_chapter_06_repetition_task_5_turtle_figures.py
|
Apop85/Scripts
|
e71e1c18539e67543e3509c424c7f2d6528da654
|
[
"MIT"
] | null | null | null |
Python/Buch_Python3_Das_umfassende_Praxisbuch/Kapitel_06_Funktionen/12_chapter_06_repetition_task_5_turtle_figures.py
|
Apop85/Scripts
|
e71e1c18539e67543e3509c424c7f2d6528da654
|
[
"MIT"
] | 6 |
2020-12-24T15:15:09.000Z
|
2022-01-13T01:58:35.000Z
|
Python/Buch_Python3_Das_umfassende_Praxisbuch/Kapitel_06_Funktionen/12_chapter_06_repetition_task_5_turtle_figures.py
|
Apop85/Scripts
|
1d8dad316c55e1f1343526eac9e4b3d0909e4873
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
###
# File: 12_chapter_06_repetition_task_5_turtle_figures.py
# Project: Kapitel_06_Funktionen
# Created Date: Sunday 24.02.2019, 16:38
# Author: Apop85
# -----
# Last Modified: Tuesday 26.02.2019, 10:57
# -----
# Copyright (c) 2019 Apop85
# This software is published under the MIT license.
# Check http://www.opensource.org/licenses/MIT for further informations
# -----
# Description: Page 193. Task 5. This script will paint a asymmetric tree and a 90° tree
###
from turtle import *
from time import sleep
def move_to_start():
up()
left(90)
back(200)
down()
def asym_tree(x):
if x < 3:
return
forward(x)
left(30)
asym_tree(x*0.6)
right(90)
asym_tree(x*0.4)
left(60)
back(x)
return
def binary_tree(x):
if x < 3:
return
forward(x)
left(90)
binary_tree(x/2)
right(180)
binary_tree(x/2)
left(90)
back(x)
clear()
move_to_start()
try:
asym_tree(200)
sleep(5)
clear()
binary_tree(200)
sleep(5)
except:
pass
| 17.966667 | 88 | 0.628015 |
d8d2741472f0ce94802ba1d021af9c447fa28883
| 1,639 |
py
|
Python
|
lab2/argparser.py
|
B0mM3L6000/CI
|
3b55ef8e6017a596e7b22e20a16ca7659bc73204
|
[
"MIT"
] | 1 |
2018-04-18T19:55:42.000Z
|
2018-04-18T19:55:42.000Z
|
lab2/argparser.py
|
B0mM3L6000/CI
|
3b55ef8e6017a596e7b22e20a16ca7659bc73204
|
[
"MIT"
] | null | null | null |
lab2/argparser.py
|
B0mM3L6000/CI
|
3b55ef8e6017a596e7b22e20a16ca7659bc73204
|
[
"MIT"
] | null | null | null |
import argparse
parser = argparse.ArgumentParser(
description = "Parse TSP files and calculate paths using simple "
"algorithms.")
parser.add_argument (
"-n"
, "--nearest"
, action = "store_true"
, dest = "need_nearest_neighbor"
, default = False
, help = "calculate distance traveled by nearest neighbor heuristic"
)
parser.add_argument (
"-f"
, "--furthest"
, action = "store_true"
, dest = "need_furthest_neighbor"
, default = False
, help = "calculate distance traveled by furthest insertion heuristic"
)
parser.add_argument (
"-i"
, "--in-order"
, action = "store_true"
, dest = "need_in_order"
, default = False
, help = "calculate the distance traveled by the in-order-tour [1..n,1]"
)
parser.add_argument(
"-c"
, "--hill_climber"
, action="store_true"
, dest="need_HC"
, default=False
, help="calculate the distance traveled by hill climber"
)
parser.add_argument(
"-g"
, "--evolutionary-algorithm"
, action="store_true"
, dest="need_EA"
, default=False
, help="calculate the distance traveled by an evolutionary algorithm"
)
parser.add_argument (
"-p"
, "--print-tours"
, action = "store_true"
, dest = "need_tours_printed"
, default = False
, help = "print explicit tours"
)
parser.add_argument (
"tsp_queue"
, nargs = "+"
, metavar = "PATH"
, help = "Path to directory or .tsp file. If PATH is a directory, run "
"on all .tsp files in the directory."
)
| 23.414286 | 79 | 0.591214 |
998081c4931a275b5bbe547b62f81755c8b87241
| 3,130 |
py
|
Python
|
python/system/gen_algo_core.py
|
Nekel-Seyew/SRN
|
806384cd11aff044b02b36e820940036c2352798
|
[
"Apache-2.0"
] | 1 |
2016-08-30T18:25:08.000Z
|
2016-08-30T18:25:08.000Z
|
python/system/gen_algo_core.py
|
Nekel-Seyew/SRN
|
806384cd11aff044b02b36e820940036c2352798
|
[
"Apache-2.0"
] | null | null | null |
python/system/gen_algo_core.py
|
Nekel-Seyew/SRN
|
806384cd11aff044b02b36e820940036c2352798
|
[
"Apache-2.0"
] | null | null | null |
import pt_rand
def reproduce(a,b, mutate_func, numkids = 10, mutate_chance=0.001):
kids = []
agenes = a.get_genes()
bgenes = b.get_genes()
#half-and-half -> 2
a1 = agenes[:len(agenes)/2]
a2 = agenes[len(agenes)/2:]
b1 = bgenes[:len(bgenes)/2]
b2 = bgenes[len(bgenes)/2:]
kids.append(organism(a1+b2))
kids.append(organism(b1+a2))
#interleave -> 2
kida = []
kidb = []
for i in range(len(agenes)):
if i % 2 == 0:
a.append(agenes[i])
b.append(agenes[i])
else:
a.append(bgenes[i])
b.append(agenes[i])
kids.append(organism(kida))
kids.append(organism(kidb))
#if we have too many, mutate and return shuffled selection
if len(kids) > numkids:
for i in range(len(kids)):
k = kids[i]
if pt_rand.genrand()%(1/mutate_chance) == 1:
k = k.mutate(mutate_func, mutate_chance)
kids[i] = k
return pt_rand.shuffle(kids)[:numkids]
#if we don't have enough yet, start randomly breeding
numneeded = numkids - 4
for i in range(numneeded):
kid = []
for k in range(len(agenes)):
choice = pt_rand.genrand()%2
if choice == 0:
kid.append(agenes[k])
else:
kid.append(bgenes[k])
kids.append(organism(kid))
for i in range(len(kids)):
k = kids[i]
if pt_rand.genrand()%(1/mutate_chance) == 1:
k = k.mutate(mutate_func, mutate_chance)
kids[i] = k
return kids
class gene(object):
def __init__(self,data):
self._data = data
def get_data(self):
return self._data
class organism(object):
def __init__(self,genes):
self._genes = list(genes)
def get_genes(self):
return self._genes
def add_gene(self,gene,pos=-1):
self._genes.insert(pos,gene)
return self
def mutate(self,mutate_func, chance):
for i in range(len(self._genes)):
g = self._genes[i]
if pt_rand.genrand()%(1/chance) == 1:
g = mutate_func(g)
self._genes[i] = g
return self
class genetic_system(object):
def __init__(self, fitness_func, mutate_func, reproduction=reproduce, generation):
self._fitness_func = fitness_func
self._mutate_func = mutate_func
self._reproduction = reproduction
self._generation = generation
def iterate(self, times, numkids = 10, gensize = 100, mutate_chance=0.001):
for i in range(times):
allchild = []
for x in self._generation:
for y in self._generation:
if x == y:
continue
children = self._reproduction(x,y, self._mutate_func, fitness_cutoff, numkids, mutate_chance)
allchild = allchild + children
allchild.sort(key=lambda x: self._fitness_func(c),reverse=True)
retkids = allchild[:gensize]
self._generation = retkids
def get_generation(self):
return self._generation
def breed(self, numkids=10, gensize=100, mutate_chance=0.001):
allchild = []
for x in self._generation:
for y in self._generation:
if x == y:
continue
children = self._reproduction(x,y, self._mutate_func, fitness_cutoff, numkids, mutate_chance)
allchild = allchild + children
retkids = pt_rand.shuffle(allchild)[:gensize]
self._generation = retkids
def reap(self, cutoff):
keep = []
for k in self._generation:
if cutoff <= self._fitness_func(k):
keep.append(k)
self._generation = keep
| 28.198198 | 98 | 0.685304 |
5af3249a53fbc3a531538ae7c9ac5bd47c4436ca
| 3,524 |
py
|
Python
|
21-fs-ias-lec/FrontEnd/socialgraph/utils/jsonUtils.py
|
Kyrus1999/BACnet
|
5be8e1377252166041bcd0b066cce5b92b077d06
|
[
"MIT"
] | 8 |
2020-03-17T21:12:18.000Z
|
2021-12-12T15:55:54.000Z
|
21-fs-ias-lec/FrontEnd/socialgraph/utils/jsonUtils.py
|
Kyrus1999/BACnet
|
5be8e1377252166041bcd0b066cce5b92b077d06
|
[
"MIT"
] | 2 |
2021-07-19T06:18:43.000Z
|
2022-02-10T12:17:58.000Z
|
21-fs-ias-lec/FrontEnd/socialgraph/utils/jsonUtils.py
|
Kyrus1999/BACnet
|
5be8e1377252166041bcd0b066cce5b92b077d06
|
[
"MIT"
] | 25 |
2020-03-20T09:32:45.000Z
|
2021-07-18T18:12:59.000Z
|
import json
import os
def extract_connections(data, text):
index = text.index(" ")
id = text[0:index]
hops = int(text[index+1:])
nodes = data['nodes']
links = data['links']
connections = []
for x in range(len(links)):
s = links[x]['source']
t = links[x]['target']
if not any(s in q.values() for q in connections):
connections.append({"source": s, "target": [t]})
for y in range(len(connections)):
d = connections[y]
if d['source'] == s:
if t not in d['target']:
d['target'].append(t)
json = createJSONwHops(connections, nodes, id, hops)
return json
def createJSON(connections, nodes, id):
j = {}
n = []
l = []
found = False
for e in connections:
if e.get('source') == int(id):
found = True
for x in nodes:
if x.get('id') == e.get('source') and x not in n:
n.append(x)
break
for t in e.get('target'):
for x in nodes:
if x.get('id') == t and x not in n:
n.append(x)
break
l.append({'source': e.get('source'), 'target': t})
if not found:
for x in nodes:
if x.get('id') == int(id):
n.append(x)
break
j.update({'nodes': n})
j.update({'links': l})
return json.dumps(j)
def createJSONwHops(connections, nodes, id, hops):
j = {}
n = []
l = []
ids = [int(id)]
found = False
for i in range(hops):
for i2 in ids:
for e in connections:
if e.get('source') == i2:
found = True
for x in nodes:
if x.get('id') == e.get('source') and x not in n:
n.append(x)
break
for t in e.get('target'):
for x in nodes:
if x.get('id') == t and x not in n:
n.append(x)
break
if {'source': e.get('source'), 'target': t} not in l:
l.append({'source': e.get('source'), 'target': t})
for x in n:
ids.append(x.get('id'))
if not found:
for x in nodes:
if x.get('id') == int(id):
n.append(x)
break
j.update({'nodes': n})
j.update({'links': l})
return json.dumps(j)
def getRoot(nodes):
for n in nodes:
if n.get("hopLayer") == 0:
return n
def getRootFollowsSize(links, rootId):
f = 0
for l in links:
if l.get("source") == rootId:
f += 1
return f
def getRootFollowersSize(links, rootId):
f = 0
for l in links:
if l.get("target") == rootId:
f += 1
return f
def saveSettings(settings_data, settings, path):
s = settings.split(' ')
settings_data["nodeRadius"] = s[0]
settings_data["linkLength"] = s[1]
settings_data["textFontSize"] = s[2]
settings_data["maleColor"] = s[3]
settings_data["femaleColor"] = s[4]
settings_data["otherColor"] = s[5]
if os.path.exists(path):
os.remove(path)
with open(path, 'w') as json_file:
json.dump(settings_data, json_file, indent=2)
return json.dumps(settings_data)
| 23.337748 | 78 | 0.458002 |
5cce56d4b59061c632b5ce82ab74819bc6dada71
| 590 |
py
|
Python
|
Automate your Morning Routine/Play Youtube.py
|
Akshu-on-github/MLH-INIT-2022
|
cf3fbbc8abd3eae3b958d3d482ed1fa1467f559e
|
[
"MIT"
] | 1 |
2021-07-05T14:30:34.000Z
|
2021-07-05T14:30:34.000Z
|
Automate your Morning Routine/Play Youtube.py
|
Akshu-on-github/MLH-INIT-2022
|
cf3fbbc8abd3eae3b958d3d482ed1fa1467f559e
|
[
"MIT"
] | 1 |
2021-07-02T15:36:02.000Z
|
2021-07-02T15:37:25.000Z
|
Automate your Morning Routine/Play Youtube.py
|
Akshu-on-github/MLH-INIT-2022
|
cf3fbbc8abd3eae3b958d3d482ed1fa1467f559e
|
[
"MIT"
] | 1 |
2021-07-02T15:15:17.000Z
|
2021-07-02T15:15:17.000Z
|
from WakeyCore import youtubePlayList, playerVLC
from tkinter import *
# GlobalVars
filePath = "c:\\logs\\" # Windows Path
# MainWindow
root = Tk()
root.title("Youtube Player")
# Playlist Entry Box
v = StringVar()
e = Entry(root, textvariable=v, width=60)
e.pack()
# YouTube Callback(WakeyCore)
def youTube(event):
playList = filePath + "playList.txt"
youList = Entry.get(e)
print(youList)
youtubePlayList(youList)
playerVLC(playList)
# Buttons
button_1 = Button(root, text="Start Playlist")
button_1.bind("<Button-1>", youTube)
button_1.pack()
root.mainloop()
| 18.4375 | 48 | 0.708475 |
7a460777e0253ac93482a0df5e7ab9eb081be3b2
| 2,590 |
py
|
Python
|
listings/chapter05/naive_salesman.py
|
SaschaKersken/Daten-Prozessanalyse
|
370f07a75b9465329deb3671adbfbef8483f76f6
|
[
"Apache-2.0"
] | 2 |
2021-09-20T06:16:41.000Z
|
2022-01-17T14:24:43.000Z
|
listings/chapter05/naive_salesman.py
|
SaschaKersken/Daten-Prozessanalyse
|
370f07a75b9465329deb3671adbfbef8483f76f6
|
[
"Apache-2.0"
] | null | null | null |
listings/chapter05/naive_salesman.py
|
SaschaKersken/Daten-Prozessanalyse
|
370f07a75b9465329deb3671adbfbef8483f76f6
|
[
"Apache-2.0"
] | null | null | null |
from itertools import permutations
# Brute-Force-Ansatz für das Problem des Handlungsreisenden
def generate_distances():
source_distances = {
("Berlin", "Kopenhagen"): 355, ("Berlin", "Warschau"): 517,
("Berlin", "Prag"): 280, ("Berlin", "Wien"): 524,
("Berlin", "Bern"): 753, ("Berlin", "Paris"): 878,
("Berlin", "Luxembourg"): 592, ("Berlin", "Brüssel"): 652,
("Berlin", "Amsterdam"): 578, ("Kopenhagen", "Warschau"): 672,
("Kopenhagen", "Prag"): 634, ("Kopenhagen", "Wien"): 870,
("Kopenhagen", "Bern"): 1033, ("Kopenhagen", "Paris"): 1027,
("Kopenhagen", "Luxembourg"): 802, ("Kopenhagen", "Brüssel"): 765,
("Kopenhagen", "Amsterdam"): 621, ("Warschau", "Prag"): 517,
("Warschau", "Wien"): 556, ("Warschau", "Bern"): 1138,
("Warschau", "Paris"): 1367, ("Warschau", "Luxembourg"): 1981,
("Warschau", "Brüssel"): 1160, ("Warschau", "Amsterdam"): 1094,
("Prag", "Wien"): 253, ("Prag", "Bern"): 621,
("Prag", "Paris"): 1031, ("Prag", "Luxembourg"): 597,
("Prag", "Brüssel"): 718, ("Prag", "Amsterdam"): 710,
("Wien", "Bern"): 684, ("Wien", "Paris"): 1034,
("Wien", "Luxembourg"): 764, ("Wien", "Brüssel"): 915,
("Wien", "Amsterdam"): 937, ("Bern", "Paris"): 435,
("Bern", "Luxembourg"): 312, ("Bern", "Brüssel"): 490,
("Bern", "Amsterdam"): 631, ("Paris", "Luxembourg"): 287,
("Paris", "Brüssel"): 264, ("Paris", "Amsterdam"): 430,
("Luxembourg", "Brüssel"): 187, ("Luxembourg", "Amsterdam"): 319,
("Brüssel", "Amsterdam"): 174
}
distances = {}
for cities in source_distances:
distances[cities] = source_distances[cities]
distances[(cities[1], cities[0])] = source_distances[cities]
return distances
def get_distance(route, distances):
sum = 0
for index, city in enumerate(route):
if index < len(route) - 1:
next_city = route[index + 1]
else:
next_city = route[0]
sum += distances[(city, next_city)]
return sum
cities = ["Berlin", "Kopenhagen", "Warschau", "Prag", "Wien", "Bern", "Paris", "Luxembourg", "Brüssel", "Amsterdam"]
distances = generate_distances()
all_routes = permutations(cities)
shortest = 100000
result = []
round = 0
for route in all_routes:
round += 1
if round % 10000 == 0:
print(round)
current_distance = get_distance(route, distances)
if current_distance < shortest:
shortest = current_distance
result = route
print(result, shortest)
| 40.46875 | 116 | 0.568726 |
711f71885dae50ce9d4c7ad8e5845a836e13dd20
| 5,404 |
py
|
Python
|
tw_map.py
|
subkultur/teilwas_bot
|
dbdf5a65ce5056c6ffa159dd8fe3a96da1e8a074
|
[
"MIT"
] | null | null | null |
tw_map.py
|
subkultur/teilwas_bot
|
dbdf5a65ce5056c6ffa159dd8fe3a96da1e8a074
|
[
"MIT"
] | null | null | null |
tw_map.py
|
subkultur/teilwas_bot
|
dbdf5a65ce5056c6ffa159dd8fe3a96da1e8a074
|
[
"MIT"
] | null | null | null |
import staticmaps
import cairo
import s2sphere
import io
# https://github.com/flopp/py-staticmaps/blob/master/examples/custom_objects.py
class TextLabel(staticmaps.Object):
def __init__(self, latlng: s2sphere.LatLng, text: str) -> None:
staticmaps.Object.__init__(self)
self._latlng = latlng
self._text = text
self._margin = 4
self._arrow = 16
self._font_size = 12
def latlng(self) -> s2sphere.LatLng:
return self._latlng
def bounds(self) -> s2sphere.LatLngRect:
return s2sphere.LatLngRect.from_point(self._latlng)
def extra_pixel_bounds(self) -> staticmaps.PixelBoundsT:
# Guess text extents.
tw = len(self._text) * self._font_size * 0.5
th = self._font_size * 1.2
w = max(self._arrow, tw + 2.0 * self._margin)
return (int(w / 2.0), int(th + 2.0 * self._margin + self._arrow), int(w / 2), 0)
def render_pillow(self, renderer: staticmaps.PillowRenderer) -> None:
x, y = renderer.transformer().ll2pixel(self.latlng())
x = x + renderer.offset_x()
tw, th = renderer.draw().textsize(self._text)
w = max(self._arrow, tw + 2 * self._margin)
h = th + 2 * self._margin
path = [
(x, y),
(x + self._arrow / 2, y - self._arrow),
(x + w / 2, y - self._arrow),
(x + w / 2, y - self._arrow - h),
(x - w / 2, y - self._arrow - h),
(x - w / 2, y - self._arrow),
(x - self._arrow / 2, y - self._arrow),
]
renderer.draw().polygon(path, fill=(255, 255, 255, 255))
renderer.draw().line(path, fill=(255, 0, 0, 255))
renderer.draw().text((x - tw / 2, y - self._arrow - h / 2 - th / 2), self._text, fill=(0, 0, 0, 255))
def render_cairo(self, renderer: staticmaps.CairoRenderer) -> None:
x, y = renderer.transformer().ll2pixel(self.latlng())
ctx = renderer.context()
ctx.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
ctx.set_font_size(self._font_size)
x_bearing, y_bearing, tw, th, _, _ = ctx.text_extents(self._text)
w = max(self._arrow, tw + 2 * self._margin)
h = th + 2 * self._margin
path = [
(x, y),
(x + self._arrow / 2, y - self._arrow),
(x + w / 2, y - self._arrow),
(x + w / 2, y - self._arrow - h),
(x - w / 2, y - self._arrow - h),
(x - w / 2, y - self._arrow),
(x - self._arrow / 2, y - self._arrow),
]
ctx.set_source_rgb(1, 1, 1)
ctx.new_path()
for p in path:
ctx.line_to(*p)
ctx.close_path()
ctx.fill()
ctx.set_source_rgb(1, 0, 0)
ctx.set_line_width(1)
ctx.new_path()
for p in path:
ctx.line_to(*p)
ctx.close_path()
ctx.stroke()
ctx.set_source_rgb(0, 0, 0)
ctx.set_line_width(1)
ctx.move_to(x - tw / 2 - x_bearing, y - self._arrow - h / 2 - y_bearing - th / 2)
ctx.show_text(self._text)
ctx.stroke()
def render_svg(self, renderer: staticmaps.SvgRenderer) -> None:
x, y = renderer.transformer().ll2pixel(self.latlng())
# guess text extents
tw = len(self._text) * self._font_size * 0.5
th = self._font_size * 1.2
w = max(self._arrow, tw + 2 * self._margin)
h = th + 2 * self._margin
path = renderer.drawing().path(
fill="#ffffff",
stroke="#ff0000",
stroke_width=1,
opacity=1.0,
)
path.push(f"M {x} {y}")
path.push(f" l {self._arrow / 2} {-self._arrow}")
path.push(f" l {w / 2 - self._arrow / 2} 0")
path.push(f" l 0 {-h}")
path.push(f" l {-w} 0")
path.push(f" l 0 {h}")
path.push(f" l {w / 2 - self._arrow / 2} 0")
path.push("Z")
renderer.group().add(path)
renderer.group().add(
renderer.drawing().text(
self._text,
text_anchor="middle",
dominant_baseline="central",
insert=(x, y - self._arrow - h / 2),
font_family="sans-serif",
font_size=f"{self._font_size}px",
fill="#000000",
)
)
async def render_map(locations):
context = staticmaps.Context()
context.set_tile_provider(staticmaps.tile_provider_OSM)
# merge markers that would end up overlapping
# doing this "properly" would require a 2nd pass, so..
num = 1
markers = []
for loc in locations:
str_loc_lat = f'{loc[0]:.4f}'
str_loc_lng = f'{loc[1]:.4f}'
merged = False
for idx, m in enumerate(markers):
if not merged and m[0] == str_loc_lat and m[1] == str_loc_lng:
markers[idx] = (m[0], m[1], m[2] + " + " + str(num), m[3], m[4])
merged = True
if not merged:
markers.append((str_loc_lat, str_loc_lng, str(num), loc[0], loc[1]))
num += 1
for m in markers:
poi = staticmaps.create_latlng(m[3], m[4])
context.add_object(TextLabel(poi, m[2]))
image = context.render_cairo(800, 500)
png_bytes = io.BytesIO()
image.write_to_png(png_bytes)
png_bytes.flush()
png_bytes.seek(0)
return png_bytes
| 33.565217 | 109 | 0.536825 |
855ba6e229e44a9086582d6c4444528564430686
| 332 |
py
|
Python
|
tools/pythonpkg/tests/fast/api/test_dbapi04.py
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | 2,816 |
2018-06-26T18:52:52.000Z
|
2021-04-06T10:39:15.000Z
|
tools/pythonpkg/tests/fast/api/test_dbapi04.py
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | 1,310 |
2021-04-06T16:04:52.000Z
|
2022-03-31T13:52:53.000Z
|
tools/pythonpkg/tests/fast/api/test_dbapi04.py
|
AldoMyrtaj/duckdb
|
3aa4978a2ceab8df25e4b20c388bcd7629de73ed
|
[
"MIT"
] | 270 |
2021-04-09T06:18:28.000Z
|
2022-03-31T11:55:37.000Z
|
#simple DB API testcase
class TestSimpleDBAPI(object):
def test_regular_selection(self, duckdb_cursor):
duckdb_cursor.execute('SELECT * FROM integers')
result = duckdb_cursor.fetchall()
assert result == [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,), (None,)], "Incorrect result returned"
| 36.888889 | 123 | 0.605422 |
8581899fa611131e70c08071b3cdf9b73659dc5b
| 901 |
py
|
Python
|
opencv_tutorial/opencv_python_tutorials/Image_Processing/image_processing.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
opencv_tutorial/opencv_python_tutorials/Image_Processing/image_processing.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
opencv_tutorial/opencv_python_tutorials/Image_Processing/image_processing.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 16:10:12 2019
@author: jone
"""
import cv2
import numpy as np
# Camera 객체를 생성 후 사이즈로 320 x 240으로 조정
cap = cv2.VideoCapture(0)
cap.set(3, 320)
cap.set(4, 240)
while(1):
# camera에서 frame capture
ret, frame = cap.read()
if ret:
# BGR -> HSV로 변환
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# blue 영역의 from ~ to
lower_blue = np.array([110, 50, 50])
upper_blue = np.array([130, 255, 255])
# 이미지에서 blue 영역
mask = cv2.inRange(hsv, lower_blue, upper_blue)
# bit 연산자를 통해서 blue 영역만 남김
res = cv2.bitwise_and(frame, frame, mask=mask)
cv2.imshow('frame', frame)
cv2.imshow('mask', mask)
cv2.imshow('res', res)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()
| 21.452381 | 55 | 0.551609 |
859d1cd548c1779a34d8dee902b3966ef89b0db1
| 353 |
py
|
Python
|
python/en/archive/books/jump2python/j2p-05_2-module.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
python/en/archive/books/jump2python/j2p-05_2-module.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
python/en/archive/books/jump2python/j2p-05_2-module.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
p.212
05-2.모듈
@author: aimldl
"""
# mod1.py
def sum(a,b):
return a+b
def safe_sum(a,b):
if type(a) != type(b):
print("Different types!")
return
else:
result = sum(a,b)
return result
print( safe_sum('a',1) )
print( safe_sum(1,4) )
print( sum(10,10.4) )
| 15.347826 | 33 | 0.535411 |
2d1a1ce3dc32764d0032a039e350c60e1237d086
| 997 |
py
|
Python
|
GZP_GTO_QGIS/INSTALLATION/GeoTaskOrganizer/mActionGTOopenfile.py
|
msgis/swwat-gzp-template
|
080afbe9d49fb34ed60ba45654383d9cfca01e24
|
[
"MIT"
] | 3 |
2019-06-18T15:28:09.000Z
|
2019-07-11T07:31:45.000Z
|
GZP_GTO_QGIS/INSTALLATION/GeoTaskOrganizer/mActionGTOopenfile.py
|
msgis/swwat-gzp-template
|
080afbe9d49fb34ed60ba45654383d9cfca01e24
|
[
"MIT"
] | 2 |
2019-07-11T14:03:25.000Z
|
2021-02-08T16:14:04.000Z
|
GZP_GTO_QGIS/INSTALLATION/GeoTaskOrganizer/mActionGTOopenfile.py
|
msgis/swwat-gzp-template
|
080afbe9d49fb34ed60ba45654383d9cfca01e24
|
[
"MIT"
] | 1 |
2019-06-12T11:07:37.000Z
|
2019-06-12T11:07:37.000Z
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from builtins import str
from qgis.core import QgsProject
import os
def run(id, gtotool, config, debug):
try:
#init
iface = gtotool.iface
info = gtotool.info
#metadata
layer = config['layer']
field = config['field']
onlyfirst = config['onlyfirst']
#do
if layer is None:
layer = iface.activeLayer()
else:
layer = QgsProject.instance().mapLayersByName(layer)[0]
for feat in layer.selectedFeatures():
file= feat[field]
try:
if file:
if debug: info.log (file)
os.startfile(str(file))
else:
info.gtoWarning('Feld <{0}> ist leer!'.format(field))
except Exception as e:
info.gtoWarning(e.args)
if onlyfirst: return True
return True
except Exception as e:
info.err(e)
| 26.945946 | 73 | 0.51655 |
74a04c83aadbdc1884746415fc7b8496e6ab8206
| 996 |
py
|
Python
|
game1/Players.py
|
JordanG8/Bahr
|
03911f3ac7275f46abc510cf85c8850c31572203
|
[
"MIT"
] | null | null | null |
game1/Players.py
|
JordanG8/Bahr
|
03911f3ac7275f46abc510cf85c8850c31572203
|
[
"MIT"
] | null | null | null |
game1/Players.py
|
JordanG8/Bahr
|
03911f3ac7275f46abc510cf85c8850c31572203
|
[
"MIT"
] | null | null | null |
class player_class:
number = 0
name = ""
HP = 10
live = True
raceWeapon = ""
comp = False
real_player_list = []
def addRealPlayers():
n = 0
real_player_list.append(player_class())
print("Enter the first player's name:")
real_player_list[n].name = input()
real_player_list[n].number = n
n += 1
print("Would you like to add another player? (yes or no)")
while True:
inp1 = input()
if inp1 == "no":
break
elif inp1 == "yes":
real_player_list.append(player_class())
print("Enter the player's name:")
real_player_list[n].name = input()
real_player_list[n].number = n
n += 1
print("Would you like to add another player? (yes or no)")
else:
print("Please enter yes or no")
#addRealPlayers()
#i = 0
#while i < len(real_player_list):
# print(real_player_list[i].name)
# i += 1
| 26.918919 | 71 | 0.543173 |
776a42827dbcedebf2a318afa9aebf089adeb9d2
| 4,753 |
py
|
Python
|
NN-modelSave2.py
|
bailejor/Behav_Interventions
|
8ef238ed913ee9b2744787a0bb2a67318df3fd3d
|
[
"MIT"
] | null | null | null |
NN-modelSave2.py
|
bailejor/Behav_Interventions
|
8ef238ed913ee9b2744787a0bb2a67318df3fd3d
|
[
"MIT"
] | null | null | null |
NN-modelSave2.py
|
bailejor/Behav_Interventions
|
8ef238ed913ee9b2744787a0bb2a67318df3fd3d
|
[
"MIT"
] | null | null | null |
import numpy as np
import pandas
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD
from math import sqrt
from numpy.random import seed
from keras.regularizers import l1
import random
from keras.models import model_from_json
import os
import tensorflow as tf
from sklearn.metrics import accuracy_score, f1_score, make_scorer, roc_auc_score, balanced_accuracy_score, confusion_matrix, precision_score, recall_score, fbeta_score
from sklearn.model_selection import LeaveOneOut, cross_val_score, cross_val_predict
from keras.wrappers.scikit_learn import KerasClassifier
from numpy import mean, std
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import RobustScaler, StandardScaler
from imblearn.pipeline import Pipeline, make_pipeline
import random
seed = 6
np.random.seed(seed)
dataframe = pandas.read_csv("FCTnoST.csv", header=0)
dataset = dataframe.values
# split into input (X) and output (Y) variables
X_orig = dataset[:,1:15].astype(float)
y_orig = dataset[:,15:16].astype(float)
print(X_orig)
print(y_orig)
def generate_data(data, number_samples):
generated_set = np.empty((0, 15))
print(data)
ran_sample = data[np.random.randint(data.shape[0], size=1), :]
print(ran_sample)
for i in range(number_samples):
ran_sample = data[np.random.randint(data.shape[0], size=1), :]
new_row = np.copy(ran_sample)
#Depending upon the function change the rate of behavior in test and control
#6 is attention, 7 is escape, 8 is tangible
if ran_sample[0][3] == 1:
new_row[0][9] = (np.random.uniform(low=0.83, high=1.17, size=(1,))) * ran_sample[0][9] # 83 to 100 percent random number between IOA error for aggression
new_row[0][10] = (np.random.uniform(low=0.83, high=1.17, size=(1,))) * ran_sample[0][10]#random number between IOA and error for aggression
generated_set = np.vstack((generated_set, new_row))
elif ran_sample[0][4]==1:
new_row[0][9] = (np.random.uniform(low=0.83, high=1.17, size=(1,))) * ran_sample[0][9]# 83 to 100 random number bettwen IOA and error for disruption
new_row[0][10] = (np.random.uniform(low=0.83, high=1.17, size=(1,))) * ran_sample[0][10]#random number between IOA and error for diruption
generated_set = np.vstack((generated_set, new_row))
elif ran_sample[0][2] == 1:
new_row[0][9] = (np.random.uniform(low=0.85, high=1.15, size=(1,))) * ran_sample[0][9] # 85 to 100 percent random number between IOA error for SIB
new_row[0][10] = (np.random.uniform(low=0.85, high=1.15, size=(1,))) * ran_sample[0][10] #random number between IOA and error for SIB
generated_set = np.vstack((generated_set, new_row))
elif ran_sample[0][5] == 1:
new_row[0][9] = (np.random.uniform(low=0.88, high=1.13, size=(1,))) * ran_sample[0][9]#88 to 99.8 random number bettwen IOA and error for other
new_row[0][10] = (np.random.uniform(low=0.88, high=1.13, size=(1,))) * ran_sample[0][10]#random number bettwen IOA and error for other
generated_set = np.vstack((generated_set, new_row))
return generated_set
################################################################################################################
def NeuralNet():
model = Sequential()
model.add(Dense(16, activation='linear', input_dim=X_orig.shape[1]))
model.add(Activation('relu'))
model.add(Dense(y_orig.shape[1], activation='sigmoid'))
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=[tf.keras.metrics.AUC()])
return model
cv = LeaveOneOut()
y_true, y_pred = list(), list()
for train_ix, test_ix in cv.split(X_orig):
# split data
X_train, X_test = X_orig[train_ix, :], X_orig[test_ix, :]
y_train, y_test = y_orig[train_ix], y_orig[test_ix]
#Generate New Samples
num_samp = 1000
data_send = np.append(X_train, y_train, axis = 1)
gen_data = generate_data(data_send, num_samp)
retrieved_data = gen_data
y_additional = retrieved_data[:, -1]
X_additional = retrieved_data[:, :-1]
X_train = np.vstack((X_train, X_additional))
y_additional =y_additional.reshape((-1, 1))
print(y_additional)
print(y_train)
y_train = np.vstack((y_train, y_additional))
#Fit model
model = KerasClassifier(NeuralNet, epochs=40, batch_size = 15)
model.fit(X_train, y_train)
# evaluate model
yhat = model.predict(X_test)
# store
y_true.append(y_test[0])
y_pred.append(yhat[0])
print(accuracy_score(y_true, y_pred))
print(balanced_accuracy_score(y_true, y_pred))
| 43.209091 | 167 | 0.680202 |
778e7868fad1486d1910460c266cb53f41a39a90
| 2,789 |
py
|
Python
|
tests/views/test_root.py
|
DanielGrams/gsevp
|
e94034f7b64de76f38754b56455e83092378261f
|
[
"MIT"
] | 1 |
2021-06-01T14:49:18.000Z
|
2021-06-01T14:49:18.000Z
|
tests/views/test_root.py
|
DanielGrams/gsevp
|
e94034f7b64de76f38754b56455e83092378261f
|
[
"MIT"
] | 286 |
2020-12-04T14:13:00.000Z
|
2022-03-09T19:05:16.000Z
|
tests/views/test_root.py
|
DanielGrams/gsevpt
|
a92f71694388e227e65ed1b24446246ee688d00e
|
[
"MIT"
] | null | null | null |
import os
from project import dump_path
def test_home(client, seeder, utils):
url = utils.get_url("home")
utils.get_ok(url)
url = utils.get_url("home", src="infoscreen")
response = client.get(url)
utils.assert_response_redirect(response, "home")
def test_organizations(client, seeder, utils):
url = utils.get_url("organizations")
utils.get_ok(url)
def test_tos(app, db, utils):
with app.app_context():
from project.services.admin import upsert_settings
settings = upsert_settings()
settings.tos = "Meine Nutzungsbedingungen"
db.session.commit()
url = utils.get_url("tos")
response = utils.get_ok(url)
assert b"Meine Nutzungsbedingungen" in response.data
def test_legal_notice(app, db, utils):
with app.app_context():
from project.services.admin import upsert_settings
settings = upsert_settings()
settings.legal_notice = "Mein Impressum"
db.session.commit()
url = utils.get_url("legal_notice")
response = utils.get_ok(url)
assert b"Mein Impressum" in response.data
def test_contact(app, db, utils):
with app.app_context():
from project.services.admin import upsert_settings
settings = upsert_settings()
settings.contact = "Mein Kontakt"
db.session.commit()
url = utils.get_url("contact")
response = utils.get_ok(url)
assert b"Mein Kontakt" in response.data
def test_privacy(app, db, utils):
with app.app_context():
from project.services.admin import upsert_settings
settings = upsert_settings()
settings.privacy = "Mein Datenschutz"
db.session.commit()
url = utils.get_url("privacy")
response = utils.get_ok(url)
assert b"Mein Datenschutz" in response.data
def test_developer(client, seeder, utils):
file_name = "all.zip"
all_path = os.path.join(dump_path, file_name)
if os.path.exists(all_path):
os.remove(all_path)
url = utils.get_url("developer")
utils.get_ok(url)
def test_favicon(app, utils):
utils.get_ok("favicon.ico")
def test_robots_txt(app, utils):
app.config["SERVER_NAME"] = "localhost"
runner = app.test_cli_runner()
runner.invoke(args=["seo", "generate-sitemap"])
result = runner.invoke(args=["seo", "generate-robots-txt"])
assert "Generated robots.txt" in result.output
utils.get_endpoint_ok("robots_txt")
def test_sitemap_xml(seeder, app, utils):
user_id, admin_unit_id = seeder.setup_base()
seeder.create_event(admin_unit_id)
app.config["SERVER_NAME"] = "localhost"
runner = app.test_cli_runner()
result = runner.invoke(args=["seo", "generate-sitemap"])
assert "Generated sitemap" in result.output
utils.get_endpoint_ok("sitemap_xml")
| 26.561905 | 63 | 0.684833 |
247c1a22827c11203217b99c29919e0f08c34ce6
| 162 |
py
|
Python
|
reverse/MasterPiece/script.py
|
killua4564/2019-AIS3-preexam
|
b13b5c9d3a2ec8beef7cca781154655bb51605e3
|
[
"MIT"
] | 1 |
2019-06-15T11:45:41.000Z
|
2019-06-15T11:45:41.000Z
|
reverse/MasterPiece/script.py
|
killua4564/2019-AIS3-preexam
|
b13b5c9d3a2ec8beef7cca781154655bb51605e3
|
[
"MIT"
] | null | null | null |
reverse/MasterPiece/script.py
|
killua4564/2019-AIS3-preexam
|
b13b5c9d3a2ec8beef7cca781154655bb51605e3
|
[
"MIT"
] | null | null | null |
data = open("data-14006B000", "r").read()
a = []
index = 0
for _ in range(266504):
index = data.find("dup(", index) + 4
a.append(int(data[index]))
print(a)
| 13.5 | 41 | 0.598765 |
24e0b2d4837ab5dd9943937938b6187617c6cf17
| 848 |
py
|
Python
|
30 Days of Code/30DoC-day-14/30DoC_day_14.py
|
nirobio/puzzles
|
fda8c84d8eefd93b40594636fb9b7f0fde02b014
|
[
"MIT"
] | null | null | null |
30 Days of Code/30DoC-day-14/30DoC_day_14.py
|
nirobio/puzzles
|
fda8c84d8eefd93b40594636fb9b7f0fde02b014
|
[
"MIT"
] | null | null | null |
30 Days of Code/30DoC-day-14/30DoC_day_14.py
|
nirobio/puzzles
|
fda8c84d8eefd93b40594636fb9b7f0fde02b014
|
[
"MIT"
] | null | null | null |
# class constructor takes an array of integers as a parameter and saves it to the __elements instance variable.
class Difference:
def __init__(self, a):
self.__elements = a
def computeDifference(self):
maxDiff = 0
# computeDifference method that finds the maximum absolute difference between any 2 numbers in __elements and stores it in the maximumDifference instance variable
for i in range(len(self.__elements)):
for j in range(len(self.__elements)):
absolute = abs(self.__elements[i] - self.__elements[j])
if absolute > maxDiff:
maxDiff = absolute
self.maximumDifference = maxDiff
# End of Difference class
_ = input()
a = [int(e) for e in input().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference)
| 27.354839 | 165 | 0.666274 |
704bd52ef8843f83305e2e04d15495f302b727e3
| 966 |
py
|
Python
|
Contrib-Microsoft/Olympus_rack_manager/python-ocs/commonapi/models/user_role.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/models/user_role.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/models/user_role.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.
# -*- coding: UTF-8 -*-
from sys_base import *
from controls.manage_role import *
class user_role(sys_base):
def __init__(self, roleid = None, info = None, works = None):
self.roleid = roleid
if info == None:
self.info = {}
else:
self.info = info
if works == None:
self.works = []
else:
self.works = works
def getRole(self):
return group_detail_by_name(self.roleid)
def getRoles(self):
return ocs_group_list()
def getrole(roleid = None):
return user_role(roleid = roleid, works = [])
| 27.6 | 68 | 0.60559 |
561185359411f00e5f3b001c6373cc97191aff53
| 191 |
py
|
Python
|
main_qr_scanner.py
|
Themishau/AGI_QR_CODE_PROJEKT
|
390bcd4d211e66f0520646591d7e542edc683ad6
|
[
"MIT"
] | null | null | null |
main_qr_scanner.py
|
Themishau/AGI_QR_CODE_PROJEKT
|
390bcd4d211e66f0520646591d7e542edc683ad6
|
[
"MIT"
] | null | null | null |
main_qr_scanner.py
|
Themishau/AGI_QR_CODE_PROJEKT
|
390bcd4d211e66f0520646591d7e542edc683ad6
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
#from GUI_rasp_noasyn import *
from GUI import *
if __name__ == '__main__':
print("start")
menu = Controller(['update_process'], 'controller')
menu.run()
| 21.222222 | 55 | 0.633508 |
568ee2e81e13d10d2ab110904919a0a24f58d7eb
| 2,572 |
py
|
Python
|
2-resources/__DATA-Structures/Code-Challenges/cc71meanMedianMode/meanMedianMode.py
|
eengineergz/Lambda
|
1fe511f7ef550aed998b75c18a432abf6ab41c5f
|
[
"MIT"
] | null | null | null |
2-resources/__DATA-Structures/Code-Challenges/cc71meanMedianMode/meanMedianMode.py
|
eengineergz/Lambda
|
1fe511f7ef550aed998b75c18a432abf6ab41c5f
|
[
"MIT"
] | null | null | null |
2-resources/__DATA-Structures/Code-Challenges/cc71meanMedianMode/meanMedianMode.py
|
eengineergz/Lambda
|
1fe511f7ef550aed998b75c18a432abf6ab41c5f
|
[
"MIT"
] | null | null | null |
# cc71 meanMedianMode https://repl.it/student/submissions/1871422
'''
Write a function that, given a list of numbers, calculates the
mean, median, and mode of those numbers. Return a dictionary with
properties for the mean, median and mode.
For example:
mmm_dict = meanMedianMode([1,2,3,4,5,6,7,8,9,10,10])
print(mmm_dict) should print:
{'mean': 5.909090909090909, 'median': 6, 'mode': 10}
'''
def meanMedianMode (nums):
# MEAN average total all nums, divide total by number of numbers
total = 0
for num in nums:
total += num
mean = total / len(nums)
# MEDIAN: https://www.mathsisfun.com/definitions/median.html
# sort the numbers, if there are two middle numbers, return the average
median = None
sortedNums = sorted(nums, key=int)
middle = len(nums) / 2
if (len(sortedNums) % 2 == 0):
median = (sortedNums[int(middle - 1)] + sortedNums[int(middle)]) / 2
else:
median = sortedNums[int(middle)]
# MODE https://en.wikipedia.org/wiki/Mode_(statistics)
mapping = {}
count = 0
mode = max(set(nums), key=nums.count)
# DICT
MMM = {}
MMM['mean'] = mean
MMM['median'] = median
MMM['mode'] = mode
return MMM
# TEST SUITE
mmm_dict = meanMedianMode([1,2,3,4,5,6,7,8,9,10,10])
print(mmm_dict) # ~~~> {'mean': 5.909090909090909, 'median': 6, 'mode': 10}
mmm_dict2 = meanMedianMode([1,2,3,4,5,6,7,8,9,10])
print(mmm_dict2)
mmm_dict3 = meanMedianMode([1,1,2,3,4,5,6,7,8,9,10,10])
print(mmm_dict3)
mmm_dict4 = meanMedianMode([951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 743, 527])
print(mmm_dict4)
mmm_dict5 = meanMedianMode([24, 47, 58, 67, 69, 81, 83, 93, 104, 105, 126, 141, 162, 165, 217, 219, 219, 236, 236, 237, 248, 263, 319, 328, 328, 344, 345, 360, 375, 379, 380, 386, 390, 399, 402, 408, 412, 418, 440, 445, 451, 462, 470, 485, 501, 507, 512, 527, 544, 547, 553, 566, 566, 575, 592, 597, 601, 609, 615, 615, 617, 626, 651, 685, 687, 688, 717, 721, 725, 742, 743, 753, 753, 758, 767, 815, 823, 826, 831, 842, 843, 854, 857, 865, 866, 892, 894, 907, 918, 941, 942, 949, 950, 951, 953, 958, 978, 980, 984, 984])
print(mmm_dict5)
| 48.528302 | 520 | 0.634526 |
d917fa47c8a01e532ee22f07c029dc93c2ec783b
| 616 |
py
|
Python
|
697-degree-of-an-array/697-degree-of-an-array.py
|
hyeseonko/LeetCode
|
48dfc93f1638e13041d8ce1420517a886abbdc77
|
[
"MIT"
] | 2 |
2021-12-05T14:29:06.000Z
|
2022-01-01T05:46:13.000Z
|
697-degree-of-an-array/697-degree-of-an-array.py
|
hyeseonko/LeetCode
|
48dfc93f1638e13041d8ce1420517a886abbdc77
|
[
"MIT"
] | null | null | null |
697-degree-of-an-array/697-degree-of-an-array.py
|
hyeseonko/LeetCode
|
48dfc93f1638e13041d8ce1420517a886abbdc77
|
[
"MIT"
] | null | null | null |
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
max_cnt = 0
for num in set(nums):
cur_cnt = nums.count(num)
if cur_cnt > max_cnt:
max_cnt=cur_cnt
max_num = [num]
elif cur_cnt == max_cnt:
max_num.append(num)
min_path = len(nums)
for cur_num in max_num:
cur_indices = [i for i, num in enumerate(nums) if num==cur_num]
path = cur_indices[-1]-cur_indices[0]+1
if path<min_path:
min_path=path
return min_path
| 34.222222 | 75 | 0.517857 |
d99062f3972070691aa56b50d43f312be1bf3393
| 6,324 |
py
|
Python
|
stiff_ode_solvers.py
|
patcher1/numerik
|
ad24c8522d61970a3a881e034a7940d43ba486be
|
[
"BSD-3-Clause"
] | null | null | null |
stiff_ode_solvers.py
|
patcher1/numerik
|
ad24c8522d61970a3a881e034a7940d43ba486be
|
[
"BSD-3-Clause"
] | null | null | null |
stiff_ode_solvers.py
|
patcher1/numerik
|
ad24c8522d61970a3a881e034a7940d43ba486be
|
[
"BSD-3-Clause"
] | 1 |
2019-10-01T14:36:03.000Z
|
2019-10-01T14:36:03.000Z
|
import numpy as np
import numpy.linalg
import scipy
import scipy.linalg
import scipy.optimize
import matplotlib.pyplot as plt
from ode_solvers import *
from scipy.linalg import expm
from numpy.linalg import solve, norm
from numpy import *
def exp_euler_long(f, Df, y0, t0, T, N):
"""
Exponentielles Euler Verfahren
@param {callable} f - function
@param {callable} Df - Jacobimatrix of f
@param {float} t0 - Anfangszeit
@param {float} T - Endzeit
@param {ndarray|float} y0 - Anfangswert
@param {int} N - Anzahl Iterationen
@return {array} t - Zeiten
@return {ndarray} y - Orte
"""
t, h = linspace(t0, T, N, retstep=True)
y0 = atleast_1d(y0)
y = zeros((N, y0.shape[0]))
y[0,:] = y0
for k in range(N-1):
J = Df(y[k,:])
x = solve(J, f(y[k,:]))
y[k+1,:] = y[k,:] + dot(expm(h*J) - eye(size(y0)), x)
return t, y
def exp_euler(f, Df, y0, t0, T, N):
"""
Exponentielles Euler Verfahren
@param {callable} f - function
@param {callable} Df - Jacobimatrix of f
@param {float} t0 - Anfangszeit
@param {float} T - Endzeit
@param {ndarray|float} y0 - Anfangswert
@param {int} N - Anzahl Iterationen
@return {array} t - Zeiten
@return {ndarray} y - Orte
"""
method = lambda rhs, y, t0, dt: exp_euler_step(f, Df, y, t0, dt)
return integrate(method, None, y0, t0, T, N)
def exp_euler_step(f, Df, y0, t0, dt):
x = solve(Df(y0), f(y0))
return y0 + dot(expm(dt*Df(y0)) - eye(size(y0)), x)
def row_2_step(f, Jf, y0, dt):
"""Rosenbrock-Wanner Methode der Ordnung 2
Input:
f : Die rechte Seite der ODE f(x).
Jf : Jacobi Matrix J(x) der Funktion, `shape == (n, n)`.
y0 : ndarray.
Aktueller Wert der approximativen Loesung der ODE.
dt : Schrittweite
Output:
y1 : Zeitpropagierter Wert y(t+h).
"""
n = y0.shape[0]
a = 1.0 / (2.0 + np.sqrt(2.0))
I = np.identity(n)
J = Jf(y0)
A = I - a*dt*J
# k1
b1 = f(y0)
k1 = solve(A, b1)
# k2
b2 = f(y0+0.5*dt*k1) - a*dt*np.dot(J,k1)
k2 = solve(A, b2)
return y0 + dt*k2
def row_3_step(f, Jf, y0, dt):
"""Rosenbrock-Wanner Methode der Ordnung 3
Input:
f : Die rechte Seite der ODE f(x).
Jf : Jacobi Matrix J(x) der Funktion, `shape == (n, n)`.
y0 : ndarray.
Aktueller Wert der approximativen Loesung der ODE.
dt : Schrittweite
Output:
y1 : Zeitpropagierter Wert y(t+h).
"""
n = y0.shape[0]
a = 1.0 / (2.0 + np.sqrt(2.0))
d31 = - (4.0 + np.sqrt(2.0)) / (2.0 + np.sqrt(2.0))
d32 = (6.0 + np.sqrt(2.0)) / (2.0 + np.sqrt(2.0))
I = np.identity(n)
J = Jf(y0)
A = I - a*dt*J
# k1
b1 = f(y0)
k1 = solve(A, b1)
# k2
b2 = f(y0+0.5*dt*k1) - a*dt*np.dot(J,k1)
k2 = solve(A, b2)
# k3
b3 = f(y0+dt*k2) - d31*dt*np.dot(J,k1) - d32*dt*np.dot(J,k2)
k3 = solve(A, b3)
return y0 + dt/6.0*(k1 + 4*k2 + k3)
if __name__ == '__main__':
"""
rhs = lambda t, y: -4*y*(y - 2)
rhs = lambda t, y: 5*y*(1 - y)
y0 = 0.1
t0 = 0
T = 5
Ng = int(T/0.2)
Nr = int(T/0.52)
# Butcher scheme for Radau
Brad = array([
[ 1/3, 5/12, -1/12 ],
[ 1, 3/4, 1/4 ],
#------|--------------
[ 0.0, 3/4, 1/4 ]
])
t1, y1 = runge_kutta(rhs, y0, t0, T, Ng, Brad)
t2, y2 = runge_kutta(rhs, y0, t0, T, Nr, Brad)
f = lambda x: x
dF = lambda x: 1
t3, y3 = exp_euler(rhs, Df, y0, t0, T, Ng)
plt.plot(t1, y1, 'g')
plt.plot(t2, y2, 'r')
plt.show()
"""
# exp euler Beispiel (S10A3)
# TODO Jacobi-Matrix
Df = lambda y: array([
[ -2.0*y[0]/y[1], (y[0]/y[1])**2 + log(y[1]) + 1.0 ],
[ -1.0, 0.0 ]
])
# TODO Rechte Seite
f = lambda y: array([ -y[0]**2/y[1] + y[1]*log(y[1]), -y[0] ])
# TODO Exakte Loesung
sol = lambda t: array([array([ -cos(t)*exp(sin(t)), exp(sin(t)) ]) for t in t])
# Anfangswert
y0 = array([-1, 1])
to = 0
te = 6
nsteps = 20
#ts, y = expEV(nsteps, to, te, y0, f, Df)
ts, y = exp_euler(f, Df, y0, to, te, nsteps)
t_ex = linspace(to, te, 1000)
y_ex = sol(t_ex)
plt.figure()
plt.subplot(1,2,1)
plt.plot(ts, y[:,0], 'r-x', label=r'$y[0]$')
plt.plot(ts, y[:,1], 'g-x', label=r'$y[1]$')
plt.plot(t_ex, y_ex[:,0],'r', label=r'$y_{ex}[0$]')
plt.plot(t_ex, y_ex[:,1],'g', label=r'$y_{ex}[1$]')
plt.legend(loc='best')
plt.xlabel('$t$')
plt.ylabel('$y$')
plt.grid(True)
plt.subplot(1,2,2)
plt.semilogy( ts, norm(y-sol(ts), axis=1), label=r'$|| y - y_{ex}||$')
plt.xlabel('$t$')
plt.ylabel('Abs. Fehler')
plt.legend(loc='best')
plt.grid(True)
plt.tight_layout()
plt.savefig('exp_euler.pdf')
plt.show()
# Konvergenzordung
plt.figure()
Ns = [24, 48, 96, 192, 384]
hs = zeros_like(Ns).astype(float) # Gitterweite.
errors = [] # Fehler.
e_abs = zeros_like(Ns).astype(float) # abs. Fehler
e_rel = zeros_like(Ns).astype(float) # rel. Fehler
# TODO Berechnen Sie die Konvergenzordung.
for i, N in enumerate(Ns):
t, y = exp_euler(f, Df, y0, to, te, N)
hs[i] = t[1] - t[0]
#e_abs[i] = norm(sol(t) - y).max()
e_abs[i] = norm(y - sol(t), axis=1).max()
e_rel[i] = norm(e_abs[i]/y_ex[-1])
# NOTE, die folgenden Zeilen könnten Ihnen beim plotten helfen.
plt.loglog(hs, e_abs)
plt.title('Konvergenzplot')
plt.gca().invert_xaxis()
plt.grid(True)
plt.xlabel('$h$')
plt.ylabel('Abs. Fehler')
plt.savefig('exp_euler_konvergenz.pdf')
plt.show()
# Berechnung der Konvergenzraten
conv_rate = polyfit(log(hs), log(e_abs), 1)[0]
print('Exponentielles Eulerverfahren konvergiert mit algebraischer Konvergenzordnung: %.2f' % conv_rate)
| 26.460251 | 109 | 0.502214 |
8de845bfa833cfc074c6fa3cb0f50088a38251b6
| 129 |
py
|
Python
|
nz_crawl_demo/day3/demo2.py
|
gaohj/nzflask_bbs
|
36a94c380b78241ed5d1e07edab9618c3e8d477b
|
[
"Apache-2.0"
] | null | null | null |
nz_crawl_demo/day3/demo2.py
|
gaohj/nzflask_bbs
|
36a94c380b78241ed5d1e07edab9618c3e8d477b
|
[
"Apache-2.0"
] | 27 |
2020-02-12T07:55:58.000Z
|
2022-03-12T00:19:09.000Z
|
nz_crawl_demo/day3/demo2.py
|
gaohj/nzflask_bbs
|
36a94c380b78241ed5d1e07edab9618c3e8d477b
|
[
"Apache-2.0"
] | 2 |
2020-02-18T01:54:55.000Z
|
2020-02-21T11:36:28.000Z
|
from lxml import etree
html = etree.parse('tencent.html') #读取外部文件
result = etree.tostring(html,pretty_print=True)
print(result)
| 21.5 | 47 | 0.775194 |
5c1c779cd3f8953665f6406dded8e3885de8e2eb
| 4,150 |
py
|
Python
|
vae2gan/vae_train.py
|
x6rulin/AiLab
|
b810590d4da645915b8472554794d0c6908109e3
|
[
"MIT"
] | null | null | null |
vae2gan/vae_train.py
|
x6rulin/AiLab
|
b810590d4da645915b8472554794d0c6908109e3
|
[
"MIT"
] | null | null | null |
vae2gan/vae_train.py
|
x6rulin/AiLab
|
b810590d4da645915b8472554794d0c6908109e3
|
[
"MIT"
] | null | null | null |
import sys
import os
import torch
import torchvision
rootpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(rootpath)
from dnnlib.miscs import ArgParse, Trainer
from dnnlib.util import Logger
from vae2gan.core.loss import G_loss, D_loss
class Args(ArgParse):
def __init__(self):
super(Args, self).__init__(description="Generative Adversarial Networks.")
self.parser.add_argument("--betas", nargs=2, type=float, default=(0.9, 0.999), help="betas for optimizer Adam")
self.parser.add_argument("--alpha", type=float, default=0.5, help="weight of the KLDiv loss for encoder")
self.parser.add_argument("--img-dir", type=str, default='images', help="directory saving images generated")
self.parser.add_argument("--log", type=str, default=None, help="file to save the training process log")
class VaeTrain(Trainer):
def __init__(self, latent_size, enet, dnet, train_dataset, args=Args()):
self.latent_size = latent_size
super(VaeTrain, self).__init__(train_dataset, args=args)
self.net = {'enet': enet.to(self.device), 'dnet': dnet.to(self.device)}
self.optimizer = {'enet': torch.optim.Adam(self.net['enet'].parameters(), lr=self.args.lr, betas=self.args.betas),
'dnet': torch.optim.Adam(self.net['dnet'].parameters(), lr=self.args.lr, betas=self.args.betas)}
self.criterion = {'enet': lambda mu, sigma2: torch.mean((-torch.log(sigma2) + mu ** 2 + sigma2 - 1) / 2),
'dnet': torch.nn.MSELoss(reduction='mean')}
self.epoch = 0
self.value = 0.
if not os.path.exists(self.args.img_dir):
os.makedirs(self.args.img_dir, 0o775)
def train(self):
with Logger(self.args.log, file_mode='a') as log:
log.write(f"epochs: {self.epoch}\n")
_i = 5
for i, reals in enumerate(self.train_loader, 1):
real_images = reals.to(self.device)
normal = self.net['enet'](real_images)
mu, sigma = normal[:, [0]], torch.exp(normal[:, [1]] / 2)
encoder_loss = self.criterion['enet'](mu, sigma ** 2) * self.args.alpha
latents = torch.randn(reals.size(0), self.latent_size, device=self.device) * sigma + mu
fake_images = self.net['dnet'](latents)
decoder_loss = self.criterion['dnet'](fake_images, real_images)
loss = encoder_loss + decoder_loss
self.optimizer['enet'].zero_grad()
self.optimizer['dnet'].zero_grad()
loss.backward()
self.optimizer['enet'].step()
self.optimizer['dnet'].step()
if i % self.args.print_freq == 0:
log.write(f"[epoch: {self.epoch} - {i}/{len(self.train_loader)}]"
f"Loss: {loss:.6f} - En_loss: {encoder_loss:.6f} - De_loss: {decoder_loss:.6f}\n")
torchvision.utils.save_image(real_images, os.path.join(self.args.img_dir, f"real_sample_{i}.png"),
nrow=round(pow(self.args.batch_size, 0.5)), normalize=True, scale_each=True)
torchvision.utils.save_image(fake_images, os.path.join(self.args.img_dir, f"fake_sample_{i}.png"),
nrow=round(pow(self.args.batch_size, 0.5)), normalize=True, scale_each=True)
def validate(self):
return self.value
if __name__ == "__main__":
from vae2gan.core.network import Lat2Img, Img2Dis
from vae2gan.core.dataset import FFHQDataset
img_root = r"/home/data/ffhq_thumbnails128x128"
resolution, num_channels, _latent_size, num_dis = 128, 3, 128, 2
_train_dataset = FFHQDataset(img_root, num_channels, resolution)
_enet = Img2Dis(num_dis, num_channels, resolution=resolution, nonlinearity='prelu', normalization='LN')
_dnet = Lat2Img(_latent_size, num_channels, resolution=resolution, nonlinearity='prelu', normalization='LN')
_train = VaeTrain(_latent_size, _enet, _dnet, _train_dataset)
_train()
| 45.604396 | 125 | 0.620964 |
308b4ed278155160def59d59484fc2cb5ee8c724
| 2,833 |
py
|
Python
|
src/onegov/foundation6/cli.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
src/onegov/foundation6/cli.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
src/onegov/foundation6/cli.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
import os
import shutil
import sys
from pathlib import Path
import click
from subprocess import check_output
from onegov.core.cli import command_group
from onegov.core.utils import module_path
cli = command_group()
def pre_checks():
node_version = check_output('node --version', shell=True)
if 'v10' not in node_version.decode('utf-8'):
click.secho('Foundation CLI currently works with node version 10')
sys.exit()
if not shutil.which('npm'):
click.secho('Install npm package manager')
sys.exit()
if not shutil.which('foundation'):
click.secho('Install foundation cli first: '
'npm install -g foundation-cli')
sys.exit()
@cli.command(context_settings={
'matches_required': False,
'default_selector': '*'
})
def update():
""" Update helper for foundation6 using node and webpack.
By the time this cli is used, probabely things already changed and
it needs to be adapted.
Also some import might not work and have to be adapted manually.
The Backup files can always be consulted.
"""
pre_checks()
module = Path(module_path('onegov.foundation6', 'foundation')).parent
assets = module / 'assets'
src = module / 'foundation'
vendor_src = module / 'foundation' / 'vendor'
# src_bckp = module / 'foundation.bak'
for p in (src, vendor_src, assets):
assert p.is_dir(), str(p)
foundation_js_files = ('foundation.min.js', 'foundation.js')
os.chdir('/tmp')
if not os.path.exists('/tmp/foundation-update'):
os.system(
'echo foundation-update | '
'foundation new --framework sites --template zurb'
)
os.chdir('foundation-update')
node_root = Path('/tmp/foundation-update/node_modules/foundation-sites')
# click.secho('Create a backup', fg='green')
# shutil.copytree(src, src_bckp)
for name in ('scss', '_vendor'):
click.secho(f'Copy {name} files')
dest_ = src / 'foundation' / name
src_ = node_root / name
assert src_.is_dir(), str(src_)
assert dest_.is_dir(), str(dest_)
shutil.copytree(src_, dest_, dirs_exist_ok=True)
click.secho('Copy foundation js files')
for name in foundation_js_files:
shutil.copyfile(
node_root / 'dist' / 'js' / name,
assets / name
)
click.secho('Copy motion-ui files')
mui_src = node_root.parent / 'motion-ui' / 'src'
assert mui_src.is_dir()
mui_dest = vendor_src / 'motion-ui'
assert mui_dest.is_dir()
shutil.copytree(mui_src, mui_dest, dirs_exist_ok=True)
click.secho('Run git add . to be sure everything is checked in.')
click.secho('To roll back the changes, just use the power of git!')
click.secho('Finished.', fg='green')
| 30.793478 | 76 | 0.643487 |
ccf73f0d1b8f873f11d2b58f0be1e4399a8c6dee
| 1,651 |
py
|
Python
|
Packs/MicrosoftGraphDeviceManagement/Integrations/MicrosoftGraphDeviceManagement/MicrosoftGraphDeviceManagement_test.py
|
jrauen/content
|
81a92be1cbb053a5f26a6f325eff3afc0ca840e0
|
[
"MIT"
] | 1 |
2021-11-02T05:36:38.000Z
|
2021-11-02T05:36:38.000Z
|
Packs/MicrosoftGraphDeviceManagement/Integrations/MicrosoftGraphDeviceManagement/MicrosoftGraphDeviceManagement_test.py
|
jrauen/content
|
81a92be1cbb053a5f26a6f325eff3afc0ca840e0
|
[
"MIT"
] | 61 |
2021-10-07T08:54:38.000Z
|
2022-03-31T10:25:35.000Z
|
Packs/MicrosoftGraphDeviceManagement/Integrations/MicrosoftGraphDeviceManagement/MicrosoftGraphDeviceManagement_test.py
|
jrauen/content
|
81a92be1cbb053a5f26a6f325eff3afc0ca840e0
|
[
"MIT"
] | null | null | null |
import pytest
import json
from CommonServerPython import DemistoException
from MicrosoftGraphDeviceManagement import MsGraphClient, build_device_object, try_parse_integer, find_managed_devices_command
with open('test_data/raw_device.json', 'r') as json_file:
data: dict = json.load(json_file)
raw_device = data.get('value')
with open('test_data/device_hr.json', 'r') as json_file:
device_hr: dict = json.load(json_file)
with open('test_data/device.json', 'r') as json_file:
device: dict = json.load(json_file)
def test_build_device_object():
assert build_device_object(raw_device) == device
def test_try_parse_integer():
assert try_parse_integer('8', '') == 8
assert try_parse_integer(8, '') == 8
with pytest.raises(DemistoException, match='parse failure'):
try_parse_integer('a', 'parse failure')
def test_find_managed_devices_command(mocker):
args = {'device_name': 'Managed Device Name value'}
with open('test_data/raw_device.json', 'r') as json_file:
data: dict = json.load(json_file)
raw_device = [data.get('value')]
client = MsGraphClient(False, 'tenant_id', 'auth_and_token_url', 'enc_key', 'app_name', 'base_url',
True, False, (200,), 'certificate_thumbprint',
'private_key')
mocker.patch.object(
client,
'find_managed_devices',
return_value=(raw_device, data),
)
outputs = mocker.patch('MicrosoftGraphDeviceManagement.return_outputs')
find_managed_devices_command(client, args=args)
context_output = outputs.call_args.args[0]
assert context_output is not None
| 34.395833 | 126 | 0.701393 |
15f013c2f580e0e4533d7434c3d7a954c320f8ae
| 2,072 |
py
|
Python
|
logya/main.py
|
yaph/logya
|
9647f58a0b8653b56ad64332e235a76cab3acda9
|
[
"MIT"
] | 12 |
2015-03-04T03:23:56.000Z
|
2020-11-17T08:09:17.000Z
|
logya/main.py
|
elaOnMars/logya
|
a9f256ac8840e21b348ac842b35683224e25b613
|
[
"MIT"
] | 78 |
2015-01-05T11:40:41.000Z
|
2022-01-23T21:05:39.000Z
|
logya/main.py
|
elaOnMars/logya
|
a9f256ac8840e21b348ac842b35683224e25b613
|
[
"MIT"
] | 6 |
2015-04-20T06:58:42.000Z
|
2022-01-31T00:36:29.000Z
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from logya import __version__
from logya.create import create
from logya.generate import generate
from logya.server import serve
def main():
parent = argparse.ArgumentParser(add_help=False)
parent.add_argument('--verbose', '-v', action='store_true', help='Print info messages during execution.')
parent.add_argument('--dir-site', '-d', default='.', help='Path to site directory, absolute or relative to current working directory.')
parser = argparse.ArgumentParser(description='Logya a static site generator.')
parser.add_argument('--version', '-V', action='version', version=__version__)
subparsers = parser.add_subparsers()
# create a basic site with the given name
p_create = subparsers.add_parser('create', parents=[parent], help='Create a starter site in the specified directory.')
p_create.add_argument('name', help='name of the directory to create.')
p_create.set_defaults(func=create)
p_create.add_argument('--site', '-s', default='base', help='Name one of the available sites.')
# generate a site in public directory, generate and gen sub commands do the same
p_generate = subparsers.add_parser('generate', aliases=('gen',), parents=[parent], help='Generate site in public directory.')
p_generate.set_defaults(func=generate)
hlp_keep = 'Keep existing `public` directory, by default it is removed.'
p_generate.add_argument('--keep', '-k', action='store_true', default=False, help=hlp_keep)
# serve static pages
p_serve = subparsers.add_parser('serve', parents=[parent], help='Serve static pages from public directory.')
p_serve.set_defaults(func=serve)
p_serve.add_argument('--host', '-a', default='localhost', help='server host name or IP')
p_serve.add_argument('--port', '-p', default=8080, type=int, help='server port to listen')
args = parser.parse_args()
if getattr(args, 'func', None):
args.func(**vars(args))
else:
parser.print_help()
if __name__ == '__main__':
main()
| 44.085106 | 139 | 0.707529 |
ba7f4030ae455e9f7ae26ae173007edd78136a9d
| 135 |
py
|
Python
|
setting.py
|
MaliziaGrimm/pbd2lodas
|
a2447084177c87d1f2e8d1e2a7c0c4607bbbde74
|
[
"MIT"
] | null | null | null |
setting.py
|
MaliziaGrimm/pbd2lodas
|
a2447084177c87d1f2e8d1e2a7c0c4607bbbde74
|
[
"MIT"
] | null | null | null |
setting.py
|
MaliziaGrimm/pbd2lodas
|
a2447084177c87d1f2e8d1e2a7c0c4607bbbde74
|
[
"MIT"
] | null | null | null |
Flask_Server_Name = 'localhost:1701'
Version_Titel = 'Tool pbd2lodas V0.3b'
Version_Program = 'Lohnabrechnungsdatenerfassung V0.3a'
| 33.75 | 56 | 0.8 |
307f46a0c84c6008055ac28c59d8daa035ed83a8
| 12,914 |
py
|
Python
|
ev3/sysroot/home/robot/roborinth/app/robo/Io.py
|
icebear8/roboRinth
|
c0789a9faf978f31b0ed020d26fee2b04fb298ee
|
[
"MIT"
] | null | null | null |
ev3/sysroot/home/robot/roborinth/app/robo/Io.py
|
icebear8/roboRinth
|
c0789a9faf978f31b0ed020d26fee2b04fb298ee
|
[
"MIT"
] | null | null | null |
ev3/sysroot/home/robot/roborinth/app/robo/Io.py
|
icebear8/roboRinth
|
c0789a9faf978f31b0ed020d26fee2b04fb298ee
|
[
"MIT"
] | 1 |
2019-10-22T07:47:51.000Z
|
2019-10-22T07:47:51.000Z
|
#!/usr/bin/env python3
import threading
from time import sleep
from ev3dev2.sensor.lego import TouchSensor
from ev3dev2.sensor.lego import ColorSensor
from ev3dev2.sensor.lego import UltrasonicSensor
from ev3dev2.sensor.lego import GyroSensor
from ev3dev2.motor import MediumMotor
from ev3dev2.motor import MoveSteering
from ev3dev2.sensor import list_sensors
from ev3dev2.motor import list_motors
from ev3dev2.power import PowerSupply
from ev3dev2 import DeviceNotFound
class Io(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.threadID = 1
self.name = 'io-thread'
self.isRunning = True
self.notificationCallbacks = dict()
self.period = 1
'''try:
touchSensorInputs = self.findTouchSensors()
if len(touchSensorInputs) == 0:
raise DeviceNotFound('No TouchSensors found')
self.touchSensor = TouchSensor(touchSensorInputs[0])
except DeviceNotFound as err:'''
self.touchSensor = None
# print(str(err))
try:
colorSensorInputs = self.findColorSensors()
if len(colorSensorInputs) == 0:
raise DeviceNotFound('No ColorSensors found')
self.colorSensor = ColorSensor(colorSensorInputs[0])
except DeviceNotFound as err:
self.colorSensor = None
print(str(err))
'''try:
ultrasonicSensorInputs = self.findUltrasonicSensors()
if len(ultrasonicSensorInputs) == 0:
raise DeviceNotFound('No UltrasonicSensors found')
self.ultrasonicSensor = UltrasonicSensor(ultrasonicSensorInputs[0])
except DeviceNotFound as err:'''
self.ultrasonicSensor = None
# print(str(err))
try:
gyroSensorInputs = self.findGyroSensors()
if len(gyroSensorInputs) == 0:
raise DeviceNotFound('No GyroSensors found')
self.gyroSensor = GyroSensor(gyroSensorInputs[0])
except DeviceNotFound as err:
self.gyroSensor = None
print(str(err))
'''try:
mediumMotorInputs = self.findMediumMotors()
if len(mediumMotorInputs) == 0:
raise DeviceNotFound('No MediumMotors found')
self.mediumMotor = MediumMotor(mediumMotorInputs[0])
except DeviceNotFound as err:'''
self.mediumMotor = None
# print(str(err))
try:
largeMotorInputs = self.findLargeMotors()
if len(largeMotorInputs) < 2:
raise DeviceNotFound('Too few LargeMotors found')
self.moveSteering = MoveSteering(largeMotorInputs[0], largeMotorInputs[1])
except DeviceNotFound as err:
self.moveSteering = None
print(str(err))
self.powerSupply = PowerSupply()
# observed many times application freezes when executing the following lines
# introduced sleeps as workaround. hopefully this gives the drivers enough time to reset and prevent freeze
print('reset sensors...')
sleep(3)
# self.resetMediumMotorPosition()
self.resetMoveSteering()
sleep(1)
self.resetGyroSensor()
sleep(3)
print('Done.')
def findDevices(self, driverName, ioNames, list_method):
findings = []
for io in ioNames:
result = list_method('*', driver_name=driverName, address=io)
found = bool(sum(1 for r in result))
if found:
findings.append(io)
print('found device with driver name ' + driverName + ' on io ' + io)
return findings
def findSensors(self, driverName):
ios = ['in1', 'in2', 'in3', 'in4']
return self.findDevices(driverName, ios, list_sensors)
def findTouchSensors(self):
driverName = 'lego-ev3-touch'
return self.findSensors(driverName)
def findColorSensors(self):
driverName = 'lego-ev3-color'
return self.findSensors(driverName)
def findUltrasonicSensors(self):
driverName = 'lego-ev3-us'
return self.findSensors(driverName)
def findGyroSensors(self):
driverName = 'lego-ev3-gyro'
return self.findSensors(driverName)
def findMotors(self, driverName):
ios = ['outA', 'outB', 'outC', 'outD']
return self.findDevices(driverName, ios, list_motors)
def findMediumMotors(self):
driverName = 'lego-ev3-m-motor'
return self.findMotors(driverName)
def findLargeMotors(self):
driverName = 'lego-ev3-l-motor'
return self.findMotors(driverName)
# TouchSensor
def touchSensorPresent(self):
return self.touchSensor is not None
def readTouchSensorPressed(self):
try:
return self.touchSensor.is_pressed == 1
except (OSError, AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable TouchSensor!')
self.touchSensor = None
except ValueError as e:
print(str(e))
return False
# ColorSensor
def colorSensorPresent(self):
return self.colorSensor is not None
def readReflectedLightIntensity(self):
try:
return self.colorSensor.reflected_light_intensity
except (OSError, AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable ColorSensor!')
self.colorSensor = None
except ValueError as e:
print(str(e))
return 0
def readAmbientLightIntensity(self):
try:
return self.colorSensor.ambient_light_intensity
except (OSError, AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable ColorSensor')
self.colorSensor = None
except ValueError as e:
print(str(e))
return 0
def readColor(self):
try:
return self.colorSensor.color
except (OSError, AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable ColorSensor')
self.colorSensor = None
except ValueError as e:
print(str(e))
return 0
def readColorName(self):
try:
return self.colorSensor.color_name
except (OSError, AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable ColorSensor')
self.colorSensor = None
except ValueError as e:
print(str(e))
return 'NoColor'
def readColorRaw(self):
try:
return self.colorSensor.raw
except (OSError, AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable ColorSensor')
self.colorSensor = None
except ValueError as e:
print(str(e))
return 0, 0, 0
# UltrasonicSensor
def ultrasonicSensorPresent(self):
return self.ultrasonicSensor is not None
def readDistanceCentimeter(self):
try:
return round(self.ultrasonicSensor.distance_centimeters_continuous, 1)
except (AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable UltrasonicSensor')
self.ultrasonicSensor = None
except ValueError as e:
print(str(e))
return 0.0
# GyroSensor
def gyroSensorPresent(self):
return self.gyroSensor is not None
def resetGyroSensor(self):
try:
# self.gyroSensor.reset() --> this official api method does not works
self.gyroSensor._direct = self.gyroSensor.set_attr_raw(self.gyroSensor._direct, 'direct', bytes(17, ))
return True
except (OSError, AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable GyroSensor')
self.gyroSensor = None
except ValueError as e:
print(str(e))
return False
def readGyroAngle(self):
try:
return self.gyroSensor.angle
except (OSError, AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable GyroSensor')
self.gyroSensor = None
except ValueError as e:
print(str(e))
return 0
# MediumMotor
def mediumMotorPresent(self):
return self.mediumMotor is not None
def readMediumMotorPosition(self):
try:
return self.mediumMotor.position
except (AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable MediumMotor')
self.mediumMotor = None
except ValueError as e:
print(str(e))
return 0
def resetMediumMotorPosition(self):
try:
self.mediumMotor.on(0, brake=False)
self.mediumMotor.position = 0
return True
except (AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable MediumMotor')
self.mediumMotor = None
except ValueError as e:
print(str(e))
return False
def turnMediumMotorByAngle(self, speed, angle):
try:
self.mediumMotor.on_for_degrees(speed, angle)
return True
except(AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable MediumMotor')
self.mediumMotor = None
except ValueError as e:
print(str(e))
return False
def activateMediumMotor(self, dutyCycle):
try:
self.mediumMotor.on(dutyCycle)
return True
except(AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable MediumMotor')
self.mediumMotor = None
except ValueError as e:
print(str(e))
return False
# MoveSteering
def moveSteeringPresent(self):
return self.moveSteering is not None
def resetMoveSteering(self):
try:
self.moveSteering.on(0, 0)
return True
except (AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable MoveSteering')
self.moveSteering = None
except ValueError as e:
print(str(e))
return False
def activateMoveSteering(self, steering, speed):
try:
self.moveSteering.on(steering, speed)
return True
except(AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable MoveSteering')
self.moveSteering = None
except ValueError as e:
print(str(e))
return False
def turnMoveSteeringByAngle(self, speed, steering, angle):
try:
self.moveSteering.on_for_degrees(steering, speed, angle)
return True
except(AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable MoveSteering')
self.moveSteering = None
except ValueError as e:
print(str(e))
return False
# PowerSupply
def readCurrentMA(self):
try:
return round(self.powerSupply.measured_current / 1000, 1)
except(AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable PowerSupply (ev3Driver)')
self.powerSupply = None
except ValueError as e:
print(str(e))
return 0
def readVoltageV(self):
try:
return round(self.powerSupply.measured_voltage / 1000000, 1)
except(AttributeError, DeviceNotFound) as e:
print(str(e))
print('Disable PowerSupply (ev3Driver)')
self.powerSupply = None
except ValueError as e:
print(str(e))
return 0
def enableNotification(self, topic, notificationId, data):
if notificationId in self.notificationCallbacks.keys():
print('enable notification for id: ' + notificationId)
self.notificationCallbacks[notificationId][0] = True
else:
print('cannot enable notification. no notification callback registered under id: ' + notificationId)
def disableNotification(self, topic, notificationId, data):
if notificationId in self.notificationCallbacks.keys():
print('disable notification for id: ' + notificationId)
self.notificationCallbacks[notificationId][0] = False
else:
print('cannot disable notification. no notification callback registered under id: ' + notificationId)
def registerNotificationCallback(self, notificationId, data, callback):
if notificationId in self.notificationCallbacks.keys():
print('notification callback for this device already registered')
else:
readFunc = self.getReadFunc(notificationId)
self.notificationCallbacks[notificationId] = [False, callback, data, readFunc]
def getReadFunc(self, notificationId):
if notificationId == 'color-present':
return self.colorSensorPresent
elif notificationId == 'color-reflected':
return self.readReflectedLightIntensity
elif notificationId == 'color-ambient':
return self.readAmbientLightIntensity
elif notificationId == 'color-id':
return self.readColor
elif notificationId == 'color-name':
return self.readColorName
elif notificationId == 'color-raw':
return self.readColorRaw
elif notificationId == 'touch-present':
return self.touchSensorPresent
elif notificationId == 'touch-pressed':
return self.readTouchSensorPressed
elif notificationId == 'ultrasonic-present':
return self.ultrasonicSensorPresent
elif notificationId == 'ultrasonic-distance':
return self.readDistanceCentimeter
elif notificationId == 'gyro-present':
return self.gyroSensorPresent
elif notificationId == 'gyro-angle':
return self.readGyroAngle
elif notificationId == 'motor-present':
return self.mediumMotorPresent
elif notificationId == 'motor-position':
return self.readMediumMotorPosition
elif notificationId == 'steering-present':
return self.moveSteeringPresent
elif notificationId == 'voltage':
return self.readVoltageV
elif notificationId == 'current':
return self.readCurrentMA
else:
print('no read func for id: ' + notificationId)
return None
def notify(self, notificationId, value):
if notificationId in self.notificationCallbacks.keys():
self.notificationCallbacks[notificationId](value)
def setNotificationPeriod(self, milliseconds):
if 10 <= milliseconds <= 10000:
self.period = milliseconds/1000
return True
return False
def run(self):
while self.isRunning:
for id in self.notificationCallbacks.keys():
enabled = self.notificationCallbacks[id][0]
callback = self.notificationCallbacks[id][1]
contextData = self.notificationCallbacks[id][2]
readFunc = self.notificationCallbacks[id][3]
if enabled:
callback(contextData, str(readFunc()))
sleep(self.period)
def stop(self):
self.isRunning = False
self.join()
| 27.653105 | 109 | 0.736178 |
234b02195d5d0a10461a732ea220e1e57ba24840
| 8,047 |
py
|
Python
|
src/main/python/gps/gpsmap.py
|
BikeAtor/WoMoAtor
|
700cc8b970dcfdd5af2f471df1a223d2a38cb1bf
|
[
"Apache-2.0"
] | null | null | null |
src/main/python/gps/gpsmap.py
|
BikeAtor/WoMoAtor
|
700cc8b970dcfdd5af2f471df1a223d2a38cb1bf
|
[
"Apache-2.0"
] | null | null | null |
src/main/python/gps/gpsmap.py
|
BikeAtor/WoMoAtor
|
700cc8b970dcfdd5af2f471df1a223d2a38cb1bf
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python3
import sys
import logging
import PIL.Image
import PIL.ImageDraw
import PIL.ImageTk
# GUI
import tkinter as tk
import tkinter.font as tkFont
# OSM
import smopy
# GPS
import pynmea2
class GPSMap(tk.Frame):
zoom = 13
font = None
spdLabel = None
mapLabel = None
lastGpsPosition = None
fg = "black"
bg = "white"
defaultImagename = None
defaultImage = None
postition = None
def __init__(self, master=None, position=None, font=None, bg=None, fg=None, defaultImagename=None, zoom=13):
# super().__init__()
self.font = font
if fg is not None:
self.fg = fg
if bg is not None:
self.bg = bg
self.zoom = zoom
self.defaultImagename = defaultImagename
self.position = position
tk.Frame.__init__(self, master, bg=self.bg)
self.initUI()
self.pack()
if self.position:
self.updateGUI(position=self.position)
def initUI(self):
try:
if self.defaultImagename:
image = PIL.Image.open(self.defaultImagename)
self.defaultImage = PIL.ImageTk.PhotoImage(image)
if self.font is None:
self.font = tkFont.Font(family="Lucida Grande", size=20)
positionFrame = tk.Frame(master=self, bg=self.bg) # , bg='red')
positionFrame.pack(side=tk.LEFT)
frameValue = tk.Frame(positionFrame, bg=self.bg)
frameValue.pack(side=tk.TOP, fill=tk.X)
label = tk.Label(frameValue, text="Time:", font=self.font, fg=self.fg, bg=self.bg)
label.pack(side=tk.LEFT)
self.timeLabel = tk.Label(frameValue, text="", font=self.font, anchor=tk.W, fg=self.fg, bg=self.bg)
self.timeLabel.pack(side=tk.RIGHT)
frameValue = tk.Frame(positionFrame, bg=self.bg)
frameValue.pack(side=tk.TOP, fill=tk.X)
label = tk.Label(frameValue, text="Lat:", font=self.font, fg=self.fg, bg=self.bg)
label.pack(side=tk.LEFT)
self.latLabel = tk.Label(frameValue, text="", font=self.font, anchor=tk.W, fg=self.fg, bg=self.bg)
self.latLabel.pack(side=tk.RIGHT)
frameValue = tk.Frame(positionFrame, bg=self.bg)
frameValue.pack(side=tk.TOP, fill=tk.X)
label = tk.Label(frameValue, text="Lon:", font=self.font, fg=self.fg, bg=self.bg)
label.pack(side=tk.LEFT)
self.lonLabel = tk.Label(frameValue, text="", font=self.font, anchor=tk.W, fg=self.fg, bg=self.bg)
self.lonLabel.pack(side=tk.RIGHT)
frameValue = tk.Frame(positionFrame, bg=self.bg)
frameValue.pack(side=tk.TOP, fill=tk.X)
label = tk.Label(frameValue, text="Alt:", font=self.font, fg=self.fg, bg=self.bg)
label.pack(side=tk.LEFT)
self.altLabel = tk.Label(frameValue, text="", font=self.font, anchor=tk.W, fg=self.fg, bg=self.bg)
self.altLabel.pack(side=tk.RIGHT)
frameValue = tk.Frame(positionFrame, bg=self.bg)
frameValue.pack(side=tk.TOP, fill=tk.X)
label = tk.Label(frameValue, text="Sat:", font=self.font, fg=self.fg, bg=self.bg)
label.pack(side=tk.LEFT)
self.satLabel = tk.Label(frameValue, text="", font=self.font, anchor=tk.W, fg=self.fg, bg=self.bg)
self.satLabel.pack(side=tk.RIGHT)
# frameValue = tk.Frame( positionFrame )
# frameValue.pack( side=tk.TOP, fill=tk.X )
# label = tk.Label( frameValue, text = "Speed:", font=self.font )
# label.pack( side=tk.LEFT )
# self.spdLabel = tk.Label( frameValue, text="", font=self.font, anchor=tk.W )
# self.spdLabel.pack( side=tk.RIGHT )
self.mapLabel = tk.Label(self, image=self.defaultImage, fg=self.fg, bg=self.bg)
self.mapLabel.pack(side=tk.LEFT)
buttonFrame = tk.Frame(master=self, bg=self.bg) # , bg='cyan')
buttonFrame.pack(side=tk.LEFT)
self.plusButton = tk.Button(buttonFrame, text="+", command=self.zoomIn, font=self.font, fg=self.fg, bg=self.bg)
self.plusButton.pack(side=tk.TOP, fill=tk.X)
self.zoomLabel = tk.Label(buttonFrame, text=str(self.zoom), font=self.font, fg=self.fg, bg=self.bg)
self.zoomLabel.pack(side=tk.TOP, fill=tk.X)
self.minusButton = tk.Button(buttonFrame, text="-", command=self.zoomOut, font=self.font, fg=self.fg, bg=self.bg)
self.minusButton.pack(side=tk.TOP, fill=tk.X)
except:
e = sys.exc_info()
logging.error(e, exc_info=True)
logging.info("GUI created")
def updateGUI(self, data=None, position=None, zoom=None):
try:
if self.mapLabel:
if zoom:
self.zoom = zoom
self.zoomLabel['text'] = str(self.zoom)
if data is not None and data.gpsPosition is not None:
self.lastGpsPosition = data.gpsPosition
if position is not None:
self.lastGpsPosition = position
if self.lastGpsPosition is not None:
lat = self.lastGpsPosition.latitude
lon = self.lastGpsPosition.longitude
self.timeLabel['text'] = self.lastGpsPosition.timestamp.strftime('%H:%M:%S')
if lat is not None:
self.latLabel['text'] = "{:.4f}".format(lat)
if lon is not None:
self.lonLabel['text'] = "{:.4f}".format(lon)
if self.lastGpsPosition.altitude is not None:
self.altLabel['text'] = "{:.1f}".format(self.lastGpsPosition.altitude)
if self.lastGpsPosition.num_sats is not None:
self.satLabel['text'] = "{}".format(self.lastGpsPosition.num_sats)
if self.spdLabel is not None:
self.spdLabel['text'] = "{}".format(self.lastGpsPosition.geo_sep)
s = 0.000001
map = smopy.Map((lat - s, lon - s, lat + s, lon + s), z=self.zoom)
# show position
x, y = map.to_pixels(lat, lon)
# logging.info( "pos: " + str(x) + "/" + str(y) )
image = map.img
draw = PIL.ImageDraw.Draw(image)
r = 5
shape = [(x - r, y - r), (x + r, y + r)]
draw.ellipse(shape, fill="red", outline="black")
del draw
# logging.info( "size: " + str(image.size) )
image = image.resize((256, 256))
self.img = PIL.ImageTk.PhotoImage(image)
self.mapLabel['image'] = self.img
self.mapLabel.pack()
logging.info("map updated")
else:
self.mapLabel['image'] = self.defaultImage
self.mapLabel.pack()
except:
e = sys.exc_info()
logging.error(e, exc_info=True)
logging.debug("GUI updated")
def zoomIn(self):
self.zoom += 1
if(self.zoom > 17):
self.zoom = 17
logging.info("zoom: " + str(self.zoom))
self.updateGUI()
def zoomOut(self):
self.zoom -= 1
if(self.zoom < 0):
self.zoom = 0
logging.info("zoom: " + str(self.zoom))
self.updateGUI()
def main():
logging.basicConfig(level=logging.INFO, format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s')
root = tk.Tk()
app = GPSMap(master=root, defaultImagename="../pic_free/karte.png", zoom=5)
gpsPosition = pynmea2.parse("$GPGGA,184353.07,1929.045,S,02410.506,E,1,04,2.6,100.00,M,-33.9,M,,0000*6D")
app.updateGUI(position=gpsPosition)
root.mainloop()
if __name__ == '__main__':
main()
| 40.034826 | 130 | 0.553001 |
001d01a64ab29960f6d6b58a05cef6b8e3e80ab0
| 4,339 |
py
|
Python
|
setup.py
|
spaeth/docassemble-onboarding
|
f4adc1d4123675a7ea564babb75e6c8f9723a593
|
[
"MIT"
] | null | null | null |
setup.py
|
spaeth/docassemble-onboarding
|
f4adc1d4123675a7ea564babb75e6c8f9723a593
|
[
"MIT"
] | null | null | null |
setup.py
|
spaeth/docassemble-onboarding
|
f4adc1d4123675a7ea564babb75e6c8f9723a593
|
[
"MIT"
] | null | null | null |
import os
import sys
from setuptools import setup, find_packages
from fnmatch import fnmatchcase
from distutils.util import convert_path
standard_exclude = ('*.pyc', '*~', '.*', '*.bak', '*.swp*')
standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info')
def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories):
out = {}
stack = [(convert_path(where), '', package)]
while stack:
where, prefix, package = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where, name)
if os.path.isdir(fn):
bad_name = False
for pattern in exclude_directories:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
break
if bad_name:
continue
if os.path.isfile(os.path.join(fn, '__init__.py')):
if not package:
new_package = name
else:
new_package = package + '.' + name
stack.append((fn, '', new_package))
else:
stack.append((fn, prefix + name + '/', package))
else:
bad_name = False
for pattern in exclude:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
break
if bad_name:
continue
out.setdefault(package, []).append(prefix+name)
return out
setup(name='docassemble.onboarding',
version='0.0.7',
description=('An Interview with docassemble for on-boarding employees'),
long_description='#on-boarding.tax-bot\r\nThis ist an interview with docassemble for on-boarding employees in client-companies. \r\n0.0.7:\r\n- messages improved\r\n\r\n0.0.6:\r\n- implemeted SMS and E-Mail Feature\r\n- multiple language templates\r\n\r\n0.0.5:\r\n- added settings\r\n- json attachement\r\n\r\n0.0.4:\r\n- div. verbesserungen\r\n- Stand Übergabe an Laura - Rückgabe an Thomas Ausgabe in PDF Personalfragebogeformular möglich\r\n\r\n0.0.2: \r\n- RV/PV/etc. removed\r\n- Insurance Combobox implemented\r\n- RV Option in Minijob inserted\r\n\r\n# TODOs:\r\n\r\nhttps://kanzleispaeth-my.sharepoint.com/:x:/g/personal/thomas_spaeth_kanzlei-spaeth_de/ETohst0E18xBmOgw0BgQPq8BHasdEzsAghDmYscC6p4rqQ\r\n\r\n## Automatisierung\r\n- Warum kein Autofill mehr bei Straße und CO?\r\n\r\nValidierung\r\n- Sozialverslicherungsnummer\r\n- Einstieg<Ausstiegsdatum\r\n- IBAN\r\n\r\nFelder\r\n- Datumfeld Einstieg\r\n- Jahr als erste Wahl\r\n- Tätigkeiten automatisch lernen und zur Bearbeitung in Profilseite\r\n- Sachbearbeiter in Profilseite\r\n- Exportmuster in Textfeld vorgeben\r\n- Krankenversicherung Vorschlagsliste\r\n\r\nHilfe\r\n- Hilfe unterschiedlich für Mandant und Mitarbeiter des Mandanten\r\n- Videos Einfahrung und erläuterung\r\n- Fachbegriffe erläutern\r\n- SPAM-Filter Hinweis für Mandanten\r\n\r\nDokumente\r\n- Mitteilungen in E-Mail an prominenter Stelle\r\n- Mehrsprachige E-Mail eingestellte Spache + englisch\r\n- Mehrsprachiges (romämisch und englische) Beschreibung zum drucken\r\n\r\nDokumentation\r\n - Einzelnen Felder Erläutern\r\n\r\nAblauf\r\n - Pflichtfelder einfordern von Unternhemen\r\n - Kontrolle von Untemrnehmen einführen\r\n - Arbeitsvertrag automatisieren, durch erste Eingaben, das Template je Mandant\r\n - Beschäftigungen Zeit bei kurzfristiger Beschäftigung\r\n\r\nUser\r\n - Untemrnehmensprofil an Nummer und PW koppeln\r\n - später IDM \r\n - (Mandanten) Benutzer über IDM anlegen\r\n\r\n\r\n',
long_description_content_type='text/markdown',
author='Thomas Späth',
author_email='[email protected]',
license='The MIT License (MIT)',
url='https://kanzlei-spaeth.de',
packages=find_packages(),
namespace_packages=['docassemble'],
install_requires=['qrcode>=6.1'],
zip_safe=False,
package_data=find_package_data(where='docassemble/onboarding/', package='docassemble.onboarding'),
)
| 71.131148 | 1,958 | 0.649228 |
cc40739c2f2da1ea2067e7244a419440bb8562f5
| 247 |
py
|
Python
|
rev/VerytriVialreVersing/gen.py
|
NoXLaw/RaRCTF2021-Challenges-Public
|
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
|
[
"MIT"
] | null | null | null |
rev/VerytriVialreVersing/gen.py
|
NoXLaw/RaRCTF2021-Challenges-Public
|
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
|
[
"MIT"
] | null | null | null |
rev/VerytriVialreVersing/gen.py
|
NoXLaw/RaRCTF2021-Challenges-Public
|
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
|
[
"MIT"
] | null | null | null |
flag = "rarctf{See,ThatWasn'tSoHard-1eb519ed}"
out = []
key = [0x13, 0x37]
for c in flag:
c = ord(c)
out.append((c ^ key[0]) + key[1])
key = key[::-1]
# print(', '.join([chr(c) for c in out]))
print(', '.join([hex(c) for c in out]))
| 20.583333 | 46 | 0.54251 |
d1d8ae1f41bdb41e7d29727dc4f5b6a469563ef4
| 16 |
py
|
Python
|
flask_rabbitmq/exception/__init__.py
|
NimzyMaina/flask-rabbitmq
|
0005577f9ad2ec4a692d117b25c01246862437bd
|
[
"MIT"
] | 55 |
2018-12-29T13:36:01.000Z
|
2022-01-13T09:49:44.000Z
|
schemas/__init__.py
|
pushyzheng/docker-oj-web
|
119abae3763cd2e53c686a320af7f4f5af1f16ca
|
[
"MIT"
] | 3 |
2019-04-25T14:57:42.000Z
|
2020-03-29T09:27:42.000Z
|
flask_rabbitmq/exception/__init__.py
|
PushyZqin/flask-rabbitmq
|
5d6f4b16e56dcd818953ba875ab838bfb1fc5529
|
[
"MIT"
] | 14 |
2019-02-12T12:38:50.000Z
|
2020-11-29T09:23:32.000Z
|
# encoding:utf-8
| 16 | 16 | 0.75 |
ae24fe4a14e5fd6f88af92fca4a5980dc9a34c1b
| 1,702 |
py
|
Python
|
frappe-bench/apps/erpnext/erpnext/patches/v8_0/update_student_groups_from_student_batches.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | 1 |
2021-04-29T14:55:29.000Z
|
2021-04-29T14:55:29.000Z
|
frappe-bench/apps/erpnext/erpnext/patches/v8_0/update_student_groups_from_student_batches.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
frappe-bench/apps/erpnext/erpnext/patches/v8_0/update_student_groups_from_student_batches.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | 1 |
2021-04-29T14:39:01.000Z
|
2021-04-29T14:39:01.000Z
|
# Copyright (c) 2017, Frappe and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.utils.rename_field import *
from frappe.model.mapper import get_mapped_doc
def execute():
if frappe.db.table_exists("Student Batch"):
student_batches = frappe.db.sql('''select name from `tabStudent Batch`''', as_dict=1)
for student_batch in student_batches:
if frappe.db.exists("Student Group", student_batch.get("name")):
student_group = frappe.get_doc("Student Group", student_batch.get("name"))
if frappe.db.table_exists("Student Batch Student"):
current_student_list = frappe.db.sql_list('''select student from `tabStudent Group Student`
where parent=%s''', (student_group.name))
batch_student_list = frappe.db.sql_list('''select student from `tabStudent Batch Student`
where parent=%s''', (student_group.name))
student_list = list(set(batch_student_list)-set(current_student_list))
if student_list:
student_group.extend("students", [{"student":d} for d in student_list])
if frappe.db.table_exists("Student Batch Instructor"):
current_instructor_list = frappe.db.sql_list('''select instructor from `tabStudent Group Instructor`
where parent=%s''', (student_group.name))
batch_instructor_list = frappe.db.sql_list('''select instructor from `tabStudent Batch Instructor`
where parent=%s''', (student_group.name))
instructor_list = list(set(batch_instructor_list)-set(current_instructor_list))
if instructor_list:
student_group.extend("instructors", [{"instructor":d} for d in instructor_list])
student_group.save()
| 43.641026 | 105 | 0.740306 |
ee4075c33fd77c8c28f8ff666551a31823214bc6
| 3,765 |
py
|
Python
|
app/user/forms.py
|
IoTServ/FlaskSimpleCMS
|
db0fc4464c6d514db14972156ca3e002a60a4876
|
[
"MIT"
] | null | null | null |
app/user/forms.py
|
IoTServ/FlaskSimpleCMS
|
db0fc4464c6d514db14972156ca3e002a60a4876
|
[
"MIT"
] | 4 |
2020-08-29T16:11:12.000Z
|
2022-03-12T00:47:03.000Z
|
app/user/forms.py
|
IoTServ/FlaskSimpleCMS
|
db0fc4464c6d514db14972156ca3e002a60a4876
|
[
"MIT"
] | null | null | null |
# coding:utf-8
from flask_wtf import Form
from wtforms import SelectField, StringField, TextAreaField, SubmitField, PasswordField,IntegerField,FileField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class CommonForm(Form):
types = SelectField(u'博文分类', coerce=int, validators=[DataRequired()])
class SubmitArticlesForm(Form):
area = StringField(u'所在城市', validators=[DataRequired(), Length(1, 64)])
types = SelectField(u'信息分类', coerce=int, validators=[DataRequired()])
callname = StringField(u'联系人', validators=[DataRequired(), Length(1, 64)])
tel = StringField(u'联系电话',validators=[DataRequired()])
addr = StringField(u'详细地址', validators=[DataRequired(), Length(1, 256)])
title = StringField(u'信息标题', validators=[DataRequired(), Length(1, 64)])
content = TextAreaField(u'内容', validators=[DataRequired()])
comname = StringField(u'公司/个人名称', validators=[DataRequired()])
price = StringField(u'服务价格', validators=[DataRequired()])
drivertypes = SelectField(u'证照类型', coerce=int, validators=[DataRequired()])
ip = StringField(validators=[DataRequired()])
province = StringField(validators=[DataRequired()])
city = StringField(validators=[DataRequired()])
class ManageArticlesForm(CommonForm):
pass
class DeleteArticleForm(Form):
articleId = StringField(validators=[DataRequired()])
class DeleteArticlesForm(Form):
articleIds = StringField(validators=[DataRequired()])
class DeleteCommentsForm(Form):
commentIds = StringField(validators=[DataRequired()])
class AddArticleTypeForm(Form):
name = StringField(u'分类名称', validators=[DataRequired(), Length(1, 64)])
introduction = TextAreaField(u'分类介绍')
setting_hide = SelectField(u'属性', coerce=int, validators=[DataRequired()])
menus = SelectField(u'所属导航', coerce=int, validators=[DataRequired()])
# You must add coerce=int, or the SelectFile validate function only validate the int data
class EditArticleTypeForm(AddArticleTypeForm):
articleType_id = StringField(validators=[DataRequired()])
class AddArticleTypeNavForm(Form):
name = StringField(u'导航名称', validators=[DataRequired(), Length(1, 64)])
class EditArticleNavTypeForm(AddArticleTypeNavForm):
nav_id = StringField(validators=[DataRequired()])
class SortArticleNavTypeForm(AddArticleTypeNavForm):
order = StringField(u'序号', validators=[DataRequired()])
class CustomBlogInfoForm(Form):
title = StringField(u'博客标题', validators=[DataRequired()])
signature = TextAreaField(u'个性签名', validators=[DataRequired()])
navbar = SelectField(u'导航样式', coerce=int, validators=[DataRequired()])
class AddBlogPluginForm(Form):
title = StringField(u'插件名称', validators=[DataRequired()])
note = TextAreaField(u'备注')
content = TextAreaField(u'内容', validators=[DataRequired()])
class ChangePasswordForm(Form):
old_password = PasswordField(u'原来密码', validators=[DataRequired()])
password = PasswordField(u'新密码', validators=[
DataRequired(), EqualTo('password2', message=u'两次输入密码不一致!')])
password2 = PasswordField(u'确认新密码', validators=[DataRequired()])
class EditUserInfoForm(Form):
username = StringField(u'昵称', validators=[DataRequired(), Length(1, 64)])
email = StringField(u'电子邮件', validators=[DataRequired(), Length(1, 64), Email()])
qq = StringField(u'QQ号', validators=[DataRequired(), Length(1, 64)])
tel = StringField(u'手机号', validators=[DataRequired(), Length(1, 64)])
wechat = StringField(u'微信号', validators=[DataRequired(), Length(1, 64)])
comname = StringField(u'公司名', validators=[Length(1, 64)])
password = PasswordField(u'密码确认', validators=[DataRequired()])
class GravatarForm(Form):
upload=FileField(u'上传新的头像!(大小不要超过1MB)', validators=[DataRequired()])
| 39.631579 | 110 | 0.726428 |
c9dc36d1051433a3833f90b43ab519958948fa3f
| 599 |
py
|
Python
|
tf/clasificador2/probador.py
|
alffore/lokroids-python
|
ac3bbc328140e53ab181034d2e3d5d5d17dc9203
|
[
"MIT"
] | null | null | null |
tf/clasificador2/probador.py
|
alffore/lokroids-python
|
ac3bbc328140e53ab181034d2e3d5d5d17dc9203
|
[
"MIT"
] | null | null | null |
tf/clasificador2/probador.py
|
alffore/lokroids-python
|
ac3bbc328140e53ab181034d2e3d5d5d17dc9203
|
[
"MIT"
] | null | null | null |
# coding=UTF-8
import cv2
import sys
import tensorflow as tf
CATEGORIAS = ['dormido', 'despierto', 'otro']
def preparaimg(filepath):
IMG_SIZE = 70
img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)
model = tf.keras.models.load_model(sys.argv[1])
prediction = model.predict([preparaimg(sys.argv[2])])
print('Modelo: '+sys.argv[1])
print(sys.argv[2]+' Clasificado: '+CATEGORIAS[int(prediction[0][0])]+' ('+str(prediction[0])+')')
print(CATEGORIAS)
print(prediction)
| 24.958333 | 97 | 0.709516 |
11c582fc493a90df167f7ad1d3230c9bf0b4c766
| 631 |
py
|
Python
|
frappe-bench/apps/erpnext/erpnext/patches/v6_6/remove_fiscal_year_from_leave_allocation.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | 1 |
2021-04-29T14:55:29.000Z
|
2021-04-29T14:55:29.000Z
|
frappe-bench/apps/erpnext/erpnext/patches/v6_6/remove_fiscal_year_from_leave_allocation.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
frappe-bench/apps/erpnext/erpnext/patches/v6_6/remove_fiscal_year_from_leave_allocation.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | 1 |
2021-04-29T14:39:01.000Z
|
2021-04-29T14:39:01.000Z
|
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doctype("Leave Allocation")
if frappe.db.has_column("Leave Allocation", "fiscal_year"):
for leave_allocation in frappe.db.sql("select name, fiscal_year from `tabLeave Allocation`", as_dict=True):
dates = frappe.db.get_value("Fiscal Year", leave_allocation["fiscal_year"],
["year_start_date", "year_end_date"])
if dates:
year_start_date, year_end_date = dates
frappe.db.sql("""update `tabLeave Allocation`
set from_date=%s, to_date=%s where name=%s""",
(year_start_date, year_end_date, leave_allocation["name"]))
| 35.055556 | 109 | 0.73851 |
11f7128f323718ee073335dd0c6aa3a87c371403
| 11,512 |
py
|
Python
|
tests/onegov/core/test_upgrade.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
tests/onegov/core/test_upgrade.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
tests/onegov/core/test_upgrade.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
import os.path
import pytest
import textwrap
from click.testing import CliRunner
from onegov.core.cli import cli
from onegov.core.upgrade import get_tasks, upgrade_task, get_module_order_key
from unittest.mock import patch
def test_upgrade_task_registration():
class MyUpgradeModule(object):
@upgrade_task(name='Add new field')
def add_new_field(request):
pass
@upgrade_task(name='Add another field', always_run=True)
def add_another_field(request):
pass
tasks = get_tasks([('onegov.core', MyUpgradeModule)])
assert len(tasks) == 2
assert tasks[0][0] == 'onegov.core:Add new field'
assert tasks[0][1].task_name == 'Add new field'
assert tasks[0][1].always_run is False
assert tasks[0][1].requires is None
assert tasks[1][0] == 'onegov.core:Add another field'
assert tasks[1][1].task_name == 'Add another field'
assert tasks[1][1].always_run is True
assert tasks[1][1].requires is None
def test_raw_task_requirement():
class MyUpgradeModule(object):
@upgrade_task(name='Add new field', raw=True, always_run=True)
def add_new_field(session_manager, schemas):
pass
@upgrade_task(name='Add another field', requires='one:Add new field')
def add_another_field(request):
pass
with pytest.raises(AssertionError) as e:
get_tasks([('one', MyUpgradeModule)])
assert "Raw tasks cannot be required" in str(e.value)
def test_upgrade_task_requirements():
class Two(object):
@upgrade_task(name='New Field', requires='one:Init Database')
def new_field(request):
pass
@upgrade_task(name='Destroy Database', requires='two:New Field')
def destroy_database(request):
pass
class One(object):
@upgrade_task(name='Init Database')
def init(request):
pass
tasks = get_tasks([('one', One), ('two', Two)])
assert len(tasks) == 3
assert tasks[0][0] == 'one:Init Database'
assert tasks[1][0] == 'two:New Field'
assert tasks[2][0] == 'two:Destroy Database'
assert tasks[0][1].task_name == 'Init Database'
assert tasks[1][1].task_name == 'New Field'
assert tasks[2][1].task_name == 'Destroy Database'
def test_upgrade_duplicate_tasks():
class MyUpgradeModule(object):
@upgrade_task(name='Add new field')
def add_new_field(request):
pass
@upgrade_task(name='Add new field')
def add_another_field(request):
pass
with pytest.raises(AssertionError):
get_tasks([('onegov.core.tests', MyUpgradeModule)])
def test_upgrade_duplicate_function_names():
class Foo(object):
@upgrade_task(name='Foo')
def task(request):
pass
class Bar(object):
@upgrade_task(name='Bar')
def task(request):
pass
with pytest.raises(AssertionError):
get_tasks([('foo', Foo), ('bar', Bar)])
def test_upgrade_cli(postgres_dsn, session_manager, temporary_directory,
redis_url):
config = os.path.join(temporary_directory, 'test.yml')
with open(config, 'w') as cfg:
cfg.write(textwrap.dedent(f"""\
applications:
- path: /foo/*
application: onegov.core.framework.Framework
namespace: foo
configuration:
dsn: {postgres_dsn}
redis_url: {redis_url}
identity_secure: False
identity_secret: asdf
csrf_secret: asdfasdf
filestorage: fs.osfs.OSFS
filestorage_options:
root_path: '{temporary_directory}/file-storage'
create: true
"""))
session_manager.ensure_schema_exists("foo-bar")
session_manager.ensure_schema_exists("foo-fah")
with patch('onegov.core.upgrade.get_upgrade_modules') as get_1:
with patch('onegov.core.cli.commands.get_upgrade_modules') as get_2:
class Upgrades:
@staticmethod
@upgrade_task(name='Foobar')
def run_upgrade(context):
pass
get_1.return_value = get_2.return_value = [
('onegov.test', Upgrades)
]
# first run, no tasks are executed because the db is empty
runner = CliRunner()
result = runner.invoke(cli, [
'--config', config,
'upgrade'
], catch_exceptions=False)
output = result.output.split('\n')
assert 'Running upgrade for foo/bar' in output[0]
assert 'no pending upgrade tasks found' in output[1]
assert 'Running upgrade for foo/fah' in output[2]
assert 'no pending upgrade tasks found' in output[3]
assert result.exit_code == 0
class NewUpgrades:
@staticmethod
@upgrade_task(name='Barfoo')
def run_upgrade(context):
pass
get_1.return_value = get_2.return_value = [
('onegov.test', NewUpgrades)
]
# second run with a new task which will be executed
runner = CliRunner()
result = runner.invoke(cli, [
'--config', config,
'upgrade',
'--dry-run'
], catch_exceptions=False)
output = result.output.split('\n')
assert 'Running upgrade for foo/bar' in output[0]
assert 'Barfoo' in output[1]
assert 'executed 1 upgrade tasks' in output[2]
assert 'Running upgrade for foo/fah' in output[3]
assert 'Barfoo' in output[4]
assert 'executed 1 upgrade tasks' in output[5]
assert result.exit_code == 0
# we used dry-run above, so running it again yields the same result
runner = CliRunner()
result = runner.invoke(cli, [
'--config', config,
'upgrade',
], catch_exceptions=False)
output = result.output.split('\n')
assert 'Running upgrade for foo/bar' in output[0]
assert 'Barfoo' in output[1]
assert 'executed 1 upgrade tasks' in output[2]
assert 'Running upgrade for foo/fah' in output[3]
assert 'Barfoo' in output[4]
assert 'executed 1 upgrade tasks' in output[5]
assert result.exit_code == 0
# the task has now been completed and it won't be executed again
runner = CliRunner()
result = runner.invoke(cli, [
'--config', config,
'upgrade',
], catch_exceptions=False)
output = result.output.split('\n')
assert 'Running upgrade for foo/bar' in output[0]
assert 'no pending upgrade tasks found' in output[1]
assert 'Running upgrade for foo/fah' in output[2]
assert 'no pending upgrade tasks found' in output[3]
assert result.exit_code == 0
def test_raw_upgrade_cli(postgres_dsn, session_manager, temporary_directory,
redis_url):
config = os.path.join(temporary_directory, 'test.yml')
with open(config, 'w') as cfg:
cfg.write(textwrap.dedent(f"""\
applications:
- path: /foo/*
application: onegov.core.framework.Framework
namespace: foo
configuration:
dsn: {postgres_dsn}
redis_url: {redis_url}
identity_secure: False
identity_secret: asdf
csrf_secret: asdfasdf
filestorage: fs.osfs.OSFS
filestorage_options:
root_path: '{temporary_directory}/file-storage'
create: true
"""))
session_manager.ensure_schema_exists("foo-bar")
session_manager.ensure_schema_exists("foo-fah")
with patch('onegov.core.upgrade.get_upgrade_modules') as get_1:
with patch('onegov.core.cli.commands.get_upgrade_modules') as get_2:
class Upgrades:
@staticmethod
@upgrade_task(name='Foobar', raw=True, always_run=True)
def run_upgrade(session_manager, schemas):
assert schemas == ['foo-bar', 'foo-fah']
return False
get_1.return_value = get_2.return_value = [
('onegov.test', Upgrades)
]
# tasks which return False, are not shown
runner = CliRunner()
result = runner.invoke(cli, [
'--config', config,
'upgrade'
], catch_exceptions=False)
output = result.output.split('\n')
assert 'Running raw upgrade for foo/*' in output[0]
assert 'no pending upgrade tasks found' in output[1]
assert 'Running upgrade for foo/bar' in output[2]
assert 'no pending upgrade tasks found' in output[3]
assert 'Running upgrade for foo/fah' in output[4]
assert 'no pending upgrade tasks found' in output[5]
assert result.exit_code == 0
class NewUpgrades:
@staticmethod
@upgrade_task(name='Barfoo', raw=True, always_run=True)
def run_upgrade(session_manager, schemas):
return True
get_1.return_value = get_2.return_value = [
('onegov.test', NewUpgrades)
]
# tasks wich return True are shown
runner = CliRunner()
result = runner.invoke(cli, [
'--config', config,
'upgrade',
], catch_exceptions=False)
output = result.output.split('\n')
assert 'Running raw upgrade for foo/*' in output[0]
assert 'Barfoo' in output[1]
assert 'executed 1 upgrade tasks' in output[2]
assert 'Running upgrade for foo/bar' in output[3]
assert 'no pending upgrade tasks found' in output[4]
assert 'Running upgrade for foo/fah' in output[5]
assert 'no pending upgrade tasks found' in output[6]
assert result.exit_code == 0
def test_get_module_order_key():
def first():
pass
def second():
pass
def third():
pass
def fourth():
pass
order_key = get_module_order_key({
'click:test': first,
'onegov.core:test': first,
'sqlalchemy:aaa': second,
'sqlalchemy:bbb': first,
'missing_module:test': first,
'onegov.user:foo': first,
'onegov.agency:bar': first,
})
ids = [
'missing_module:test',
'sqlalchemy:aaa',
'sqlalchemy:bbb',
'onegov.core:test',
'click:test',
'onegov.user:foo',
'onegov.agency:bar',
]
ids.sort(key=order_key)
assert ids == [
# sorted by module, then function order in source
'click:test',
'missing_module:test',
'sqlalchemy:bbb',
'sqlalchemy:aaa',
# core, before modules, before applications
'onegov.core:test',
'onegov.user:foo',
'onegov.agency:bar',
]
| 32.066852 | 79 | 0.562804 |
ee934c93a62c2d23a14f93d8d3b9f0fe16d29f7a
| 439 |
py
|
Python
|
us2/python/imports.py
|
chrbeckm/anfaenger-praktikum
|
51764ff23901de1bc3d16dc935acfdc66bb2b2b7
|
[
"MIT"
] | 2 |
2019-12-10T10:25:11.000Z
|
2021-01-26T13:59:40.000Z
|
us1/python/imports.py
|
chrbeckm/anfaenger-praktikum
|
51764ff23901de1bc3d16dc935acfdc66bb2b2b7
|
[
"MIT"
] | null | null | null |
us1/python/imports.py
|
chrbeckm/anfaenger-praktikum
|
51764ff23901de1bc3d16dc935acfdc66bb2b2b7
|
[
"MIT"
] | 1 |
2020-12-06T21:24:58.000Z
|
2020-12-06T21:24:58.000Z
|
import numpy as np
import matplotlib.pyplot as plt
from uncertainties import ufloat
import uncertainties.unumpy as unp
from scipy import optimize
import scipy.constants as const
from scipy.stats import sem
np.genfromtxt('python/*.txt', unpack=True)
np.savetxt('build/*.txt', np.column_stack([*, *]), header='*')
params, covariance_matrix = optimize.curve_fit(*function*, *array1*, *array2*)
errors = np.sqrt(np.diag(covariance_matrix))
| 29.266667 | 78 | 0.767654 |
e12381001b2d923bee7e3222971790c087ba30d1
| 85 |
py
|
Python
|
v2/test.py
|
timm/py
|
28be3bb63433895e2bcab27ad82cb0b0cc994f37
|
[
"Unlicense"
] | 1 |
2021-03-31T03:41:06.000Z
|
2021-03-31T03:41:06.000Z
|
v2/test.py
|
timm/py
|
28be3bb63433895e2bcab27ad82cb0b0cc994f37
|
[
"Unlicense"
] | null | null | null |
v2/test.py
|
timm/py
|
28be3bb63433895e2bcab27ad82cb0b0cc994f37
|
[
"Unlicense"
] | null | null | null |
def kk():
class B(A): pass
from fred import jj
B()
jj()
class A: pass
kk()
| 8.5 | 21 | 0.552941 |
09a720a5da9143b12d040c70979b514811400002
| 1,044 |
py
|
Python
|
autojail/utils/draw_tree.py
|
ekut-es/autojail
|
bc16e40e6df55c0a28a3059715851ffa59b14ba8
|
[
"MIT"
] | 6 |
2020-08-12T08:16:15.000Z
|
2022-03-05T02:25:53.000Z
|
autojail/utils/draw_tree.py
|
ekut-es/autojail
|
bc16e40e6df55c0a28a3059715851ffa59b14ba8
|
[
"MIT"
] | 1 |
2021-03-30T10:34:51.000Z
|
2021-06-09T11:24:00.000Z
|
autojail/utils/draw_tree.py
|
ekut-es/autojail
|
bc16e40e6df55c0a28a3059715851ffa59b14ba8
|
[
"MIT"
] | 1 |
2021-11-21T09:30:58.000Z
|
2021-11-21T09:30:58.000Z
|
# Adapted from https://rosettacode.org/wiki/Visualize_a_tree#Simple_decorated-outline_tree
from itertools import chain, repeat, starmap
from operator import add
def draw_tree(trees, nest=lambda x: x.children, str=str):
"""ASCII diagram of a tree."""
res = []
for tree in trees:
res += draw_node(tree, nest, str)
return "\n".join(res)
def draw_node(node, nest, str):
"""List of the lines of an ASCII
diagram of a tree."""
def shift(first, other, xs):
return list(
starmap(add, zip(chain([first], repeat(other, len(xs) - 1)), xs))
)
def draw_sub_trees(xs):
return (
(
(
shift("├─ ", "│ ", draw_node(xs[0], nest, str))
+ draw_sub_trees(xs[1:])
)
if 1 < len(xs)
else shift("└─ ", " ", draw_node(xs[0], nest, str))
)
if xs
else []
)
return (str(node)).splitlines() + (draw_sub_trees(nest(node)))
| 27.473684 | 90 | 0.516284 |
1147c8f2c6c02528184acd3929699f1cf35822e7
| 709 |
py
|
Python
|
Praxisseminar/run.py
|
EnjoyFitness92/Praxisseminar-SS2020
|
b5baba5d1512a5fad3391efc42f3ab232d79c4e2
|
[
"MIT"
] | null | null | null |
Praxisseminar/run.py
|
EnjoyFitness92/Praxisseminar-SS2020
|
b5baba5d1512a5fad3391efc42f3ab232d79c4e2
|
[
"MIT"
] | 2 |
2020-06-24T13:01:22.000Z
|
2020-06-24T13:10:07.000Z
|
Praxisseminar/run.py
|
EnjoyFitness92/Praxisseminar-SS2020
|
b5baba5d1512a5fad3391efc42f3ab232d79c4e2
|
[
"MIT"
] | null | null | null |
"""
Praxisseminar run.py
"""
from mininet.net import Mininet
from mininet.cli import CLI
from minicps.mcps import MiniCPS
from topo import CbTopo
import sys
class PraxisseminarCPS(MiniCPS):
"""Main container used to run the simulation."""
def __init__(self, name, net):
self.name = name
self.net = net
net.start()
net.pingAll()
# start devices
# plc1, s1 = self.net.get('plc1', )
# plc1.cmd(sys.executable + ' plc1.py &')
CLI(self.net)
net.stop()
if __name__ == "__main__":
topo = CbTopo()
net = Mininet(topo=topo)
Praxisseminarcps = PraxisseminarCPS(
name='PraxisseminarCPS',
net=net)
| 16.880952 | 52 | 0.605078 |
fed9ad1bc5a5b7035112e3428b4d466ea7d4b8ea
| 594 |
py
|
Python
|
sdiff/__init__.py
|
KeepSafe/html-structure-diff
|
83ea2b8ad4b78b140bb5f69e3f2966c9fda01a89
|
[
"Apache-2.0"
] | 3 |
2016-05-10T13:57:14.000Z
|
2016-09-29T21:01:53.000Z
|
sdiff/__init__.py
|
KeepSafe/html-structure-diff
|
83ea2b8ad4b78b140bb5f69e3f2966c9fda01a89
|
[
"Apache-2.0"
] | 3 |
2015-10-20T22:29:37.000Z
|
2022-01-18T18:20:06.000Z
|
sdiff/__init__.py
|
KeepSafe/html-structure-diff
|
83ea2b8ad4b78b140bb5f69e3f2966c9fda01a89
|
[
"Apache-2.0"
] | 1 |
2016-11-05T04:23:05.000Z
|
2016-11-05T04:23:05.000Z
|
from typing import Type
from .parser import parse, MdParser, ZendeskHelpMdParser # noqa
from .renderer import TextRenderer
from .compare import diff_struct, diff_links # noqa
def diff(md1, md2, renderer=TextRenderer(), parser_cls: Type[MdParser] = MdParser):
tree1 = parse(md1, parser_cls)
tree2 = parse(md2, parser_cls)
tree1, tree2, struct_errors = diff_struct(tree1, tree2)
# tree1, tree2, links_errors = diff_links(tree1, tree2)
# errors = struct_errors + links_errors
errors = struct_errors
return renderer.render(tree1), renderer.render(tree2), errors
| 31.263158 | 83 | 0.739057 |
fef9ff0a45e015d4033dd22ca2db4e79d3d4d848
| 1,913 |
py
|
Python
|
source/data/streaming/kafkaStream.py
|
aaarl/Spotify-Auswertung-Big-Data-Plattform
|
47684db8eb3a8764568c1365dd02a8c2b3975dba
|
[
"Apache-2.0"
] | 1 |
2021-12-29T20:06:54.000Z
|
2021-12-29T20:06:54.000Z
|
source/data/streaming/kafkaStream.py
|
aaarl/Spotify-Auswertung-Big-Data-Plattform
|
47684db8eb3a8764568c1365dd02a8c2b3975dba
|
[
"Apache-2.0"
] | null | null | null |
source/data/streaming/kafkaStream.py
|
aaarl/Spotify-Auswertung-Big-Data-Plattform
|
47684db8eb3a8764568c1365dd02a8c2b3975dba
|
[
"Apache-2.0"
] | null | null | null |
from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession
from pyspark.sql.functions import explode, split
def foreachBatch(dataframe, _id):
dataframe.write\
.mode("overwrite") \
.format("jdbc") \
.option("truncate", "true") \
.option("driver", "com.mysql.jdbc.Driver") \
.option("url", "jdbc:mysql://my-database-service:3306/spotifydb") \
.option("dbtable", "web_requests") \
.option("user", "root") \
.option("password", "mysecretpw") \
.save()
if __name__ == "__main__":
# instantiate a new SparkConf and SparkContext. The SparkSession is trying to create a new SparkContext and fails if we don't do it before manually.
conf = SparkConf().setAppName("test_import")
sc = SparkContext("local[*]", "DStream Example")
# new SparkSession in order to read from Kafka
spark = SparkSession.builder.config(conf=conf).getOrCreate()
# Change the log level to WARN, as otherwise Spark is showing the Kafka offset on every request, when no new data is available
spark.sparkContext.setLogLevel("WARN")
# DataSet representing the stream of input lines from kafka
# By using "startingOffsets" = "earliest", we will fetch all available data from Kafka
lines = spark.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", "my-kafka-cluster-kafka-bootstrap:9092") \
.option("subscribe", "web-requests") \
.option("startingOffsets", "earliest") \
.load()
# Split the lines into words
words = lines.select(
lines.value.alias("url")
)
# Generate running word count
wordCounts = words.groupBy("url").count()
# Start running the query
query = wordCounts \
.writeStream \
.outputMode("complete") \
.foreachBatch(foreachBatch) \
.start()
query.awaitTermination()
| 35.425926 | 152 | 0.652901 |
fefce893892fb66773e36fecf31825621dd9927e
| 2,866 |
py
|
Python
|
marsyas-vamp/marsyas/scripts/large-evaluators/tempo-reference-implementation/evaluate_bpms.py
|
jaouahbi/VampPlugins
|
27c2248d1c717417fe4d448cdfb4cb882a8a336a
|
[
"Apache-2.0"
] | null | null | null |
marsyas-vamp/marsyas/scripts/large-evaluators/tempo-reference-implementation/evaluate_bpms.py
|
jaouahbi/VampPlugins
|
27c2248d1c717417fe4d448cdfb4cb882a8a336a
|
[
"Apache-2.0"
] | null | null | null |
marsyas-vamp/marsyas/scripts/large-evaluators/tempo-reference-implementation/evaluate_bpms.py
|
jaouahbi/VampPlugins
|
27c2248d1c717417fe4d448cdfb4cb882a8a336a
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
import sys
import mar_collection
def exact_accuracy(bpm_detected, bpm_ground):
tolerance = 0.04
diff = abs(bpm_detected - bpm_ground)
if diff <= tolerance * bpm_ground:
return True
return False
def major_extended_harmonic_accuracy(bpm_detected, bpm_ground):
tolerance = 0.04
m = 1
cand = bpm_ground*m
while cand < 1000:
cand = bpm_ground*m
diff = abs(bpm_detected - cand)
if diff <= tolerance * bpm_ground:
return True
m += 1
return False
def extended_harmonic_accuracy(bpm_detected, bpm_ground):
tolerance = 0.04
for m in [1, 2, 3]:
#for m in [1, 2, 3]:
diff = abs(m*bpm_detected - bpm_ground)
if diff <= tolerance * bpm_ground:
return True
diff = abs(1.0/m*bpm_detected - bpm_ground)
if diff <= tolerance * bpm_ground:
return True
return False
def process_mfs(ground_mf, detected_mf, limit=None):
# load ground truth
ground_coll = mar_collection.MarCollection(ground_mf)
ground_bpms = {}
for dat in ground_coll.data:
filename = dat[0]
bpm_ground = float(dat[1])
ground_bpms[filename] = bpm_ground
user_coll = mar_collection.MarCollection(detected_mf)
good = 0
i = 0
for dat in user_coll.data:
#for dat in user_coll.data[:5]:
filename = dat[0]
cand_bpms = dat[1]
bpm_ground = ground_bpms[filename]
if "," in cand_bpms:
cand_bpms = [float(a) for a in cand_bpms.split(',')]
correct = False
if limit is not None and limit is not 0:
cand_bpms = cand_bpms[:limit]
if limit == 0:
for bpm_detected in cand_bpms[:1]:
corr = exact_accuracy(bpm_detected, bpm_ground)
if corr:
correct = True
if correct:
good += 1
i += 1
else:
for bpm_detected in cand_bpms:
corr = extended_harmonic_accuracy(bpm_detected, bpm_ground)
if corr:
correct = True
if correct:
good += 1
i += 1
#print cand_bpms
#print "Accuracy: %.2f (%i/%i)" % (100*float(good) / i, good, i)
accuracy = 100*float(good) / len(user_coll.data)
return accuracy
if __name__ == "__main__":
ground_filename = sys.argv[1]
user_filename = sys.argv[2]
zero = process_mfs(ground_filename, user_filename, 0)
one = process_mfs(ground_filename, user_filename, 1)
two = process_mfs(ground_filename, user_filename, 2)
four = process_mfs(ground_filename, user_filename, 4)
eight = process_mfs(ground_filename, user_filename, 8)
print "%s\t%.1f\t%.1f\t%.1f\t%.1f\t%.1f" % (
user_filename, zero, one, two, four, eight)
| 29.546392 | 75 | 0.592463 |
28af0f0dfc6dd3b88bd3053f57afc1c1a5468139
| 9,024 |
py
|
Python
|
Liquid-optimizer/serve_lstm.py
|
PasaLab/YAO
|
2e70203197cd79f9522d65731ee5dc0eb236b005
|
[
"Apache-2.0"
] | 2 |
2021-08-30T14:12:09.000Z
|
2022-01-20T02:14:22.000Z
|
Liquid-optimizer/serve_lstm.py
|
PasaLab/YAO
|
2e70203197cd79f9522d65731ee5dc0eb236b005
|
[
"Apache-2.0"
] | null | null | null |
Liquid-optimizer/serve_lstm.py
|
PasaLab/YAO
|
2e70203197cd79f9522d65731ee5dc0eb236b005
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/python
from threading import Thread
from threading import Lock
from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi
import json
from urllib import parse
import pandas as pd
import csv
from pandas import DataFrame
from pandas import Series
from pandas import concat
from pandas import read_csv
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from math import sqrt
import numpy
import random
import traceback
from keras.models import load_model
from sklearn.externals import joblib
PORT_NUMBER = 8080
lock = Lock()
models = {}
# frame a sequence as a supervised learning problem
def timeseries_to_supervised(data, lag=1):
df = DataFrame(data)
columns = [df.shift(i) for i in range(1, lag + 1)]
columns.append(df)
df = concat(columns, axis=1)
df = df.drop(0)
return df
# create a differenced series
def difference(dataset, interval=1):
diff = list()
for i in range(interval, len(dataset)):
value = dataset[i] - dataset[i - interval]
diff.append(value)
return Series(diff)
# invert differenced value
def inverse_difference(history, yhat, interval=1):
return yhat + history[-interval]
# inverse scaling for a forecasted value
def invert_scale(scaler, X, yhat):
new_row = [x for x in X] + [yhat]
array = numpy.array(new_row)
array = array.reshape(1, len(array))
inverted = scaler.inverse_transform(array)
return inverted[0, -1]
# fit an LSTM network to training data
def fit_lstm(train, batch_size2, nb_epoch, neurons):
X, y = train[:, 0:-1], train[:, -1]
X = X.reshape(X.shape[0], 1, X.shape[1])
model = Sequential()
model.add(LSTM(neurons, batch_input_shape=(batch_size2, X.shape[1], X.shape[2]), stateful=True))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
for i in range(nb_epoch):
model.fit(X, y, epochs=1, batch_size=batch_size2, verbose=0, shuffle=False)
# loss = model.evaluate(X, y)
# print("Epoch {}/{}, loss = {}".format(i, nb_epoch, loss))
print("Epoch {}/{}".format(i, nb_epoch))
model.reset_states()
return model
def train_models(job):
lock.acquire()
if job not in models:
models[job] = {
'lock': Lock()
}
lock.release()
models[job]['lock'].acquire()
# load dataset
series = read_csv('./data/' + job + '.csv', header=0, index_col=0, squeeze=True)
# transform data to be stationary
raw_values = series.values
diff_values = difference(raw_values, 1)
# transform data to be supervised learning
lag = 4
supervised = timeseries_to_supervised(diff_values, lag)
supervised_values = supervised.values
batch_size = 32
if supervised_values.shape[0] < 100:
batch_size = 16
if supervised_values.shape[0] < 60:
batch_size = 8
# split data into train and test-sets
train = supervised_values
# transform the scale of the data
# scale data to [-1, 1]
# fit scaler
scaler = MinMaxScaler(feature_range=(-1, 1))
scaler = scaler.fit(train)
# transform train
train = train.reshape(train.shape[0], train.shape[1])
train_scaled = scaler.transform(train)
# fit the model
t1 = train.shape[0] % batch_size
train_trimmed = train_scaled[t1:, :]
model = fit_lstm(train_trimmed, batch_size, 30, 4)
model.save('./data/checkpoint-' + job)
scaler_filename = './data/checkpoint-' + job + "-scaler.save"
joblib.dump(scaler, scaler_filename)
models[job]['batch_size'] = batch_size
models[job]['lock'].release()
def predict(job, seq):
if job not in models or 'batch_size' not in models[job]:
return -1, False
batch_size = int(models[job]['batch_size'])
data = {
'seq': seq,
'value': 0,
}
model = load_model('./data/checkpoint-' + job)
scaler_filename = './data/checkpoint-' + job + "-scaler.save"
scaler = joblib.load(scaler_filename)
file = './data/' + job + '.' + str(random.randint(1000, 9999)) + '.csv'
df = pd.read_csv('./data/' + job + '.csv', usecols=['seq', 'value'])
df = df.tail(batch_size * 2 - 1)
df = df.append(data, ignore_index=True)
df.to_csv(file, index=False)
# load dataset
df = read_csv(file, header=0, index_col=0, squeeze=True)
# transform data to be stationary
raw_values = df.values
diff_values = difference(raw_values, 1)
# transform data to be supervised learning
lag = 4
supervised = timeseries_to_supervised(diff_values, lag)
supervised_values = supervised[-batch_size:]
test = supervised_values.values
test = test.reshape(test.shape[0], test.shape[1])
test_scaled = scaler.transform(test)
# forecast the entire training dataset to build up state for forecasting
test_reshaped = test_scaled[:, 0:-1]
test_reshaped = test_reshaped.reshape(len(test_reshaped), 1, lag)
output = model.predict(test_reshaped, batch_size=batch_size)
predictions = list()
for i in range(len(output)):
yhat = output[i, 0]
X = test_scaled[i, 0:-1]
# invert scaling
yhat = invert_scale(scaler, X, yhat)
# invert differencing
yhat = inverse_difference(raw_values, yhat, len(test_scaled) + 1 - i)
# store forecast
predictions.append(yhat)
# report performance
rmse = sqrt(mean_squared_error(raw_values[-batch_size:], predictions))
print(predictions, raw_values[-batch_size:])
return predictions[-1], True
class MyHandler(BaseHTTPRequestHandler):
# Handler for the GET requests
def do_GET(self):
req = parse.urlparse(self.path)
query = parse.parse_qs(req.query)
if req.path == "/ping":
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes("pong", "utf-8"))
elif req.path == "/predict":
try:
job = query.get('job')[0]
seq = query.get('seq')[0]
msg = {'code': 0, 'error': ""}
pred, success = predict(job, int(seq))
if not success:
msg = {'code': 2, 'error': "Job " + job + " not exist"}
else:
msg = {'code': 0, 'error': "", "total": int(pred)}
except Exception as e:
track = traceback.format_exc()
print(track)
msg = {'code': 1, 'error': str(e)}
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(json.dumps(msg), "utf-8"))
elif req.path == "/feed":
try:
job = query.get('job')[0]
seq = query.get('seq')[0]
value = query.get('value')[0]
if int(seq) == 1:
with open('./data/' + job + '.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(
csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL
)
spamwriter.writerow(["seq", "value"])
with open('./data/' + job + '.csv', 'a+', newline='') as csvfile:
spamwriter = csv.writer(
csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL
)
spamwriter.writerow([seq, value])
msg = {'code': 0, 'error': ""}
except Exception as e:
msg = {'code': 1, 'error': str(e)}
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(json.dumps(msg), "utf-8"))
elif req.path == "/train":
try:
job = query.get('job')[0]
t = Thread(target=train_models, name='train_models', args=(job,))
t.start()
msg = {'code': 0, 'error': ""}
except Exception as e:
msg = {'code': 1, 'error': str(e)}
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(json.dumps(msg), "utf-8"))
else:
self.send_error(404, 'File Not Found: %s' % self.path)
# Handler for the POST requests
def do_POST(self):
if self.path == "/train2":
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={
'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': self.headers['Content-Type'],
})
try:
job = form.getvalue('job')[0]
seq = form.getvalue('seq')[0]
t = Thread(target=train_models(), name='train_models', args=(job, seq,))
t.start()
msg = {"code": 0, "error": ""}
except Exception as e:
msg = {"code": 1, "error": str(e)}
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(json.dumps(msg), "utf-8"))
else:
self.send_error(404, 'File Not Found: %s' % self.path)
if __name__ == '__main__':
try:
# Create a web server and define the handler to manage the
# incoming request
server = HTTPServer(('', PORT_NUMBER), MyHandler)
print('Started http server on port ', PORT_NUMBER)
# Wait forever for incoming http requests
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down the web server')
server.socket.close()
| 29.016077 | 98 | 0.653812 |
e92f9a8ff441e9c69572dfa4d665798b467df68d
| 386 |
py
|
Python
|
INBa/2015/SHEMYAKIN_A_V/task_1_31.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
INBa/2015/SHEMYAKIN_A_V/task_1_31.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
INBa/2015/SHEMYAKIN_A_V/task_1_31.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
# Задача 1. Вариант 31.
# Напишите программу, которая будет сообщать род деятельности и псевдоним под которым скрывается Эмиль Эрзог.
# Shemyakin A.V.
# 29.02.2016
input ("Андре Моруа, более известный как Эмиль Саломон Вильгельм Эрзог, французский писатель и член Французской академии. Примечание: впоследствии псевдоним стал его официальным именем.")
input ('Press "Enter" to exit')
| 55.142857 | 188 | 0.787565 |
3ac26ba81bff5703bf1f9963084b393544e98106
| 1,631 |
py
|
Python
|
checklisten/tests/test_views.py
|
mribrgr/StuRa-Mitgliederdatenbank
|
87a261d66c279ff86056e315b05e6966b79df9fa
|
[
"MIT"
] | 8 |
2019-11-26T13:34:46.000Z
|
2021-06-21T13:41:57.000Z
|
src/checklisten/tests/test_views.py
|
Sumarbrander/Stura-Mitgliederdatenbank
|
691dbd33683b2c2d408efe7a3eb28e083ebcd62a
|
[
"MIT"
] | 93 |
2019-12-16T09:29:10.000Z
|
2021-04-24T12:03:33.000Z
|
src/checklisten/tests/test_views.py
|
Sumarbrander/Stura-Mitgliederdatenbank
|
691dbd33683b2c2d408efe7a3eb28e083ebcd62a
|
[
"MIT"
] | 2 |
2020-12-03T12:43:19.000Z
|
2020-12-22T21:48:47.000Z
|
from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth import get_user_model
class TestViews(TestCase):
def setUp(self):
self.client = Client()
# Hinzufügen von Admin
user = get_user_model().objects.create_superuser(
username='testlukasadmin', password='0123456789test')
# Hinzufügen von Nutzern
user = get_user_model().objects.create_user(
username='testlukas', password='0123456789test')
# URLS
self.main_screen = reverse('checklisten:main_screen')
self.abhaken = reverse('checklisten:abhaken')
self.loeschen = reverse('checklisten:loeschen')
self.erstellen = reverse('checklisten:erstellen')
self.get_funktionen = reverse('checklisten:get_funktionen')
pass
def test_main_screen_GET(self):
# unangemeldet
response = self.client.get(self.main_screen)
self.assertEqual(response.status_code, 302)
# als admin
self.client.login(username='testlukasadmin', password='0123456789test')
response = self.client.get(self.main_screen)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'checklisten/main_screen.html')
self.client.logout()
# als user
self.client.login(username='testlukas', password='0123456789test')
response = self.client.get(self.main_screen)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'checklisten/main_screen.html')
self.client.logout()
pass
pass
| 35.456522 | 79 | 0.676885 |
c91fad73bc202f2f6ca2596c7f29b7587f9b2084
| 418 |
py
|
Python
|
code/fetch_nowcasts/fetch-LMU.py
|
Stochastik-TU-Ilmenau/hospitalization-nowcast-hub
|
df1b2f52060cfa5c275c8c25a0cf2d7b6ad5df0d
|
[
"MIT"
] | null | null | null |
code/fetch_nowcasts/fetch-LMU.py
|
Stochastik-TU-Ilmenau/hospitalization-nowcast-hub
|
df1b2f52060cfa5c275c8c25a0cf2d7b6ad5df0d
|
[
"MIT"
] | null | null | null |
code/fetch_nowcasts/fetch-LMU.py
|
Stochastik-TU-Ilmenau/hospitalization-nowcast-hub
|
df1b2f52060cfa5c275c8c25a0cf2d7b6ad5df0d
|
[
"MIT"
] | null | null | null |
import os
import pandas as pd
today = pd.to_datetime('today').date()
filename = f'data-processed/LMU_StaBLab-GAM_nowcast/{today}-LMU_StaBLab-GAM_nowcast.csv'
if os.path.exists(filename):
print(f'Nowcast for today ({today}) has already been added.')
else:
df = pd.read_csv('https://raw.githubusercontent.com/MaxWeigert/hospitalization-nowcast-hub/main/' + filename)
df.to_csv(filename, index = False)
| 34.833333 | 113 | 0.739234 |
a33607aa70c8061cf5f69960b1add31ab9a798b6
| 432 |
py
|
Python
|
oldp/apps/cases/processing/processing_steps/assign_topics.py
|
ImgBotApp/oldp
|
575dc6f711dde3470d910e21c9440ee9b79a69ed
|
[
"MIT"
] | 3 |
2020-06-27T08:19:35.000Z
|
2020-12-27T17:46:02.000Z
|
oldp/apps/cases/processing/processing_steps/assign_topics.py
|
ImgBotApp/oldp
|
575dc6f711dde3470d910e21c9440ee9b79a69ed
|
[
"MIT"
] | null | null | null |
oldp/apps/cases/processing/processing_steps/assign_topics.py
|
ImgBotApp/oldp
|
575dc6f711dde3470d910e21c9440ee9b79a69ed
|
[
"MIT"
] | null | null | null |
import logging
from oldp.apps.cases.models import Case
from oldp.apps.cases.processing.processing_steps import CaseProcessingStep
logger = logging.getLogger(__name__)
class AssignTopics(CaseProcessingStep):
description = 'Assign topics'
# default_court = Court.objects.get(pk=Court.DEFAULT_ID)
def __init__(self):
super(AssignTopics, self).__init__()
def process(self, case: Case):
return case
| 24 | 74 | 0.74537 |
95504bdf9712bfdfd314c59e6f807636cd8d722f
| 1,762 |
py
|
Python
|
solution/graph_traversal/2206/main.py
|
gkgg123/baekjoon
|
4ff8a1238a5809e4958258b5f2eeab7b22105ce9
|
[
"MIT"
] | 2,236 |
2019-08-05T00:36:59.000Z
|
2022-03-31T16:03:53.000Z
|
solution/graph_traversal/2206/main.py
|
juy4556/baekjoon
|
bc0b0a0ebaa45a5bbd32751f84c458a9cfdd9f92
|
[
"MIT"
] | 225 |
2020-12-17T10:20:45.000Z
|
2022-01-05T17:44:16.000Z
|
solution/graph_traversal/2206/main.py
|
juy4556/baekjoon
|
bc0b0a0ebaa45a5bbd32751f84c458a9cfdd9f92
|
[
"MIT"
] | 602 |
2019-08-05T00:46:25.000Z
|
2022-03-31T13:38:23.000Z
|
# Authored by : kis03160
# Co-authored by : tony9402
# Link : http://boj.kr/2cb5e18deb964794bec3e960225ad83e
from collections import deque
import sys
def input():
return sys.stdin.readline().rstrip()
def answer(row, col):
global m, n
shortest = 10000001
q = deque()
direction = [(1, 0), (0, 1), (-1, 0), (0, -1)]
visited = [[[0] * 2 for _ in range(m)] for _ in range(n)]
q.append((row, col, 1))
visited[row][col][1] = 1
while q:
r, c, is_able = q.popleft()
for r_, c_ in direction:
drow = r + r_
dcol = c + c_
if drow < 0 or dcol < 0 or drow >= n or dcol >= m:
continue
if visited[drow][dcol][is_able] == 0 and G[drow][dcol] == '0':
visited[drow][dcol][is_able] = visited[r][c][is_able] + 1
q.append((drow, dcol, is_able))
elif is_able == 1 and G[drow][dcol] == '1':
visited[drow][dcol][0] = visited[r][c][1] + 1
q.append((drow, dcol, 0))
shortest = visited[n - 1][m - 1]
return_val = None
if shortest[0] == 0 and shortest[1] == 0:
return_val = -1
else:
if shortest[0] > shortest[1]:
return_val = shortest[1]
if return_val == 0:
return_val = shortest[0]
else:
return_val = shortest[0]
if return_val == 0:
return_val = shortest[1]
return return_val
n, m = map(int, input().split())
G = []
walls = []
for i in range(n):
x = []
temp = input()
for j in range(m):
if temp[j] == '1':
walls.append((i, j))
x.append('1')
else:
x.append('0')
G.append(x)
print(answer(0, 0))
| 25.171429 | 74 | 0.494325 |
6c8ce6b17de9741630222627955901ecc88f2264
| 1,471 |
py
|
Python
|
research/cv/LightCNN/src/get_list.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 77 |
2021-10-15T08:32:37.000Z
|
2022-03-30T13:09:11.000Z
|
research/cv/LightCNN/src/get_list.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 3 |
2021-10-30T14:44:57.000Z
|
2022-02-14T06:57:57.000Z
|
research/cv/LightCNN/src/get_list.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.
# ============================================================================
"""Generate test lists"""
import scipy.io as io
import numpy as np
f1 = 'image_list_for_lfw.txt'
mat_lfw = io.loadmat('LightenedCNN_B_lfw.mat')
lfw_path_list = mat_lfw['image_path']
lfw_path_list = np.transpose(lfw_path_list)
lfw_label_list = mat_lfw['labels_original']
lfw_label_list = np.transpose(lfw_label_list)
for idx, ele in enumerate(lfw_path_list):
print(ele[0][0][10:], lfw_label_list[idx][0][0])
with open(f1, 'a') as f:
line = ele[0][0][10:] + ' ' + lfw_label_list[idx][0][0]
f.write(line + '\n')
f2 = 'image_list_for_blufr.txt'
mat_blufr = io.loadmat('BLUFR/config/lfw/blufr_lfw_config.mat')
blufr_path_list = mat_blufr['imageList']
for _, ele in enumerate(blufr_path_list):
print(ele[0][0])
with open(f2, 'a') as f:
f.write(ele[0][0] + '\n')
| 33.431818 | 78 | 0.67981 |
66a4c20641c6bdb09005a56ab1de9c436a1e1ca9
| 1,262 |
py
|
Python
|
02.Sort/M/B2578-M.py
|
SP2021-2/Algorithm
|
2e629eb5234212fad8bbc11491aad068e5783780
|
[
"MIT"
] | 1 |
2021-11-21T06:03:06.000Z
|
2021-11-21T06:03:06.000Z
|
02.Sort/M/B2578-M.py
|
SP2021-2/Algorithm
|
2e629eb5234212fad8bbc11491aad068e5783780
|
[
"MIT"
] | 2 |
2021-10-13T07:21:09.000Z
|
2021-11-14T13:53:08.000Z
|
02.Sort/M/B2578-M.py
|
SP2021-2/Algorithm
|
2e629eb5234212fad8bbc11491aad068e5783780
|
[
"MIT"
] | null | null | null |
array = [list(map(int, input().split())) for i in range(5)]
check = [list(map(int, input().split())) for i in range(5)]
def checkBingo(arr):
bingoNum = 0
rightSlide = 0
leftSlide = 0
for i in range(5):
colZeroNum = 0
verZeroNum = 0
for j in range(5):
if(arr[i][j] == 0):
colZeroNum += 1
if(arr[j][i] == 0):
verZeroNum += 1
if(i == j and arr[i][j]==0):
rightSlide += 1
if((i + j) == 4 and arr[i][j]==0):
leftSlide += 1
if(colZeroNum == 5):
bingoNum+=1
if(verZeroNum == 5):
bingoNum+=1
if(leftSlide == 5):
bingoNum+=1
if(rightSlide == 5):
bingoNum+=1
return bingoNum
def checkArr(num, arr):
for i in range(5):
for j in range(5):
if(arr[i][j] == num):
arr[i][j] = 0
bingoNum = checkBingo(arr)
return bingoNum
for i in range(5):
for j in range(5):
bingonum = checkArr(check[i][j], array)
#print(array)
if(bingonum >= 3):
print(i * 5 + j + 1)
break
if(bingonum >= 3):
break
| 24.745098 | 59 | 0.434231 |
dd4528d88f39cfca7fdec8f69f522d848fe2f268
| 2,308 |
py
|
Python
|
WebApp/WebApp/urls.py
|
wallamejorge/PepqaWebApp
|
20896a1224d1a2cea3a137950c4f0306f0269db7
|
[
"Apache-2.0"
] | null | null | null |
WebApp/WebApp/urls.py
|
wallamejorge/PepqaWebApp
|
20896a1224d1a2cea3a137950c4f0306f0269db7
|
[
"Apache-2.0"
] | null | null | null |
WebApp/WebApp/urls.py
|
wallamejorge/PepqaWebApp
|
20896a1224d1a2cea3a137950c4f0306f0269db7
|
[
"Apache-2.0"
] | null | null | null |
"""WebApp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from WebApp.Main.views import *
import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^Dash/$', AdminDashboard),
url(r'^AdminSave/$',AdminSave),
url(r'^AdminNewUser/$',AdminNewUser),
url(r'^AdminRemoveUser/$',AdminUserRemove),
url(r'^AdminNewOffer/$',AdminNewOffer),
url(r'^AdminRemoveOffer/$',AdminOfferRemove),
url(r'^AdminNewGroup/$',AdminNewGroup),
url(r'^AdminRemoveGroup/$',AdminGroupRemove),
url(r'^AdminNewArticle/$',AdminNewArticle),
url(r'^AdminNewFriendship/$',AdminNewFriendship),
url(r'^Upload/$',upload),
url(r'^Upload/upload_pic/$',upload_pic),
url(r'^setCookie/$',setCookie),
url(r'^getCookie/$',getCookie),
url(r'^Auth/$',AuthenticationApp),
url(r'^Profile/$',Profile),
url(r'^Offers/$',Offers),
url(r'^LoginApp/$',LoginApp),
url(r'^SignUp/$',registration),
url(r'^StartPageApp/$',StartPage),
url(r'^StartPageSave/$',StartPageSave),
url(r'^StartPageRemoveFriendship/$',StartPageRemoveFriendship),
url(r'^GroupApp/$',GroupApp),
url(r'^GroupsApp/$',Groups),
url(r'^AddCommentApp/$',AddCommentApp),
url(r'^AdminNewComment/$',AdminNewComment),
url(r'^AdminRemoveComment/$',AdminCommentRemove),
url(r'^oauth2callback/$',UploadDropbox),
url(r'^AdminRemoveFriendship/$',AdminRemoveFriendship),
url(r'AdminNewFriendshipRequest/$',AdminNewFriendshipRequest),
url(r'AdminRemoveFriendshipRequest/$',AdminRemoveFriendshipRequest),
url(r'(?:.*?/)?(?P<path>(css|jquery|jscripts|images)/.+)$','django.views.static.serve',{'document_root': settings.STATIC_ROOT}),
]
| 39.118644 | 132 | 0.694974 |
dd844e63e96defa0bb0844fd4a4da33befd17415
| 617 |
py
|
Python
|
api/celeb.py
|
Solutions-Incorporated/beige-as-a-service
|
dd832bff2b9add83b0ce53c028ce533396b73cf8
|
[
"MIT"
] | null | null | null |
api/celeb.py
|
Solutions-Incorporated/beige-as-a-service
|
dd832bff2b9add83b0ce53c028ce533396b73cf8
|
[
"MIT"
] | null | null | null |
api/celeb.py
|
Solutions-Incorporated/beige-as-a-service
|
dd832bff2b9add83b0ce53c028ce533396b73cf8
|
[
"MIT"
] | null | null | null |
import random
import re
BORING_COLOURS = [
"red",
"blue",
"green",
"yellow",
"pink",
"orange",
"purple",
"white",
]
def load_names():
with open("famous_names.txt") as f:
names = []
for line in f:
_, name, *_ = line.split(",")
names.append(name)
return names
def remove_boring_part(color_name):
name = random.choice(NAMES).rstrip()
for color in BORING_COLOURS:
new_color = color_name.replace(color, name)
if new_color != color_name:
return new_color
return color_name
NAMES = load_names()
| 18.147059 | 51 | 0.570502 |
05b57339627f5649ef93cf286cd6996df52242c0
| 1,184 |
py
|
Python
|
Python/zzz_training_challenge/Python_Challenge/solutions/ch08_binary_trees/solutions/ex04_lca.py
|
Kreijeck/learning
|
eaffee08e61f2a34e01eb8f9f04519aac633f48c
|
[
"MIT"
] | null | null | null |
Python/zzz_training_challenge/Python_Challenge/solutions/ch08_binary_trees/solutions/ex04_lca.py
|
Kreijeck/learning
|
eaffee08e61f2a34e01eb8f9f04519aac633f48c
|
[
"MIT"
] | null | null | null |
Python/zzz_training_challenge/Python_Challenge/solutions/ch08_binary_trees/solutions/ex04_lca.py
|
Kreijeck/learning
|
eaffee08e61f2a34e01eb8f9f04519aac633f48c
|
[
"MIT"
] | null | null | null |
# Beispielprogramm für das Buch "Python Challenge"
#
# Copyright 2020 by Michael Inden
from ch08_binary_trees.util import TreeUtils
from ch08_binary_trees.intro.intro_binary_tree_node import BinaryTreeNode
from ch08_binary_trees.intro.intro_binary_search_tree import insert
def create_lca_example_tree():
_6 = BinaryTreeNode(6)
insert(_6, 7)
insert(_6, 4)
insert(_6, 5)
insert(_6, 2)
insert(_6, 1)
insert(_6, 3)
return _6
def find_lca(start_node, value1, value2):
# rekursiver Abbruch
if start_node is None:
return None
current_value = start_node.item
# rekursiver Abstieg
if value1 < current_value and value2 < current_value:
return find_lca(start_node.left, value1, value2)
if value1 > current_value and value2 > current_value:
return find_lca(start_node.right, value1, value2)
# Hier gilt value1 < currentValue && currentValue < value2 bzw.
# value2 < currentValue && currentValue < value1
return start_node
def main():
root = create_lca_example_tree()
print("LCA: ", find_lca(root, 1, 5).item)
TreeUtils.nice_print(root)
if __name__ == "__main__":
main()
| 23.215686 | 73 | 0.706081 |
bb83eda8aec15b8b1e6b12caec27e31f2991c933
| 3,340 |
py
|
Python
|
tests/addons/reqs2reqs/test_empty_guard.py
|
ihatov08/jumeaux
|
7d983474df4b6dcfa57ea1a66901fbc99ebababa
|
[
"MIT"
] | 11 |
2017-10-02T01:29:12.000Z
|
2022-03-31T08:37:22.000Z
|
tests/addons/reqs2reqs/test_empty_guard.py
|
ihatov08/jumeaux
|
7d983474df4b6dcfa57ea1a66901fbc99ebababa
|
[
"MIT"
] | 79 |
2017-07-16T14:47:17.000Z
|
2022-03-31T08:49:14.000Z
|
tests/addons/reqs2reqs/test_empty_guard.py
|
ihatov08/jumeaux
|
7d983474df4b6dcfa57ea1a66901fbc99ebababa
|
[
"MIT"
] | 2 |
2019-01-28T06:11:58.000Z
|
2021-01-25T07:21:21.000Z
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from unittest.mock import patch
import pytest
from owlmixin import TOption
from owlmixin.util import load_yaml
from jumeaux.addons.reqs2reqs.empty_guard import Executor
from jumeaux.domain.config.vo import Config as JumeauxConfig
from jumeaux.models import Reqs2ReqsAddOnPayload, Notifier
EMPTY = (
"Guard empty",
"""
notifies:
- notifier: jumeaux
message: "{{ title }} notify!"
""",
[],
"""
title: empty test
one:
name: one
host: http://one
other:
name: other
host: http://other
output:
response_dir: responses
notifiers:
jumeaux:
type: slack
channel: "#jumeaux"
username: jumeaux
dummy:
type: slack
channel: "#dummy"
username: dummy
addons:
log2reqs:
name: plain
""",
)
NOT_EMPTY = (
"Not guard not empty",
"""
notifies:
- notifier: jumeaux
message: "notify!"
""",
[{"name": "req", "method": "GET", "path": "/sample", "headers": {}, "qs": {}}],
"""
one:
name: one
host: http://one
other:
name: other
host: http://other
output:
response_dir: responses
addons:
log2reqs:
name: plain
""",
[
{
"name": "req",
"method": "GET",
"path": "/sample",
"headers": {},
"qs": {},
"url_encoding": "utf-8",
}
],
)
def send_for_test(message: str, notifier: Notifier) -> TOption[str]:
return TOption(message)
@patch("jumeaux.addons.reqs2reqs.empty_guard.send")
class TestExec:
@pytest.mark.parametrize(
"title, config_yml, requests, jumeaux_config_yml, expected_result", [NOT_EMPTY]
)
def test_not_use_notify(
self, send, title, config_yml, requests, jumeaux_config_yml, expected_result
):
payload: Reqs2ReqsAddOnPayload = Reqs2ReqsAddOnPayload.from_dict({"requests": requests})
actual: Reqs2ReqsAddOnPayload = Executor(load_yaml(config_yml)).exec(
payload, JumeauxConfig.from_yaml(jumeaux_config_yml)
)
assert expected_result == actual.requests.to_dicts()
@pytest.mark.parametrize("title, config_yml, requests, jumeaux_config_yml", [EMPTY])
def test_use_notify(self, send, title, config_yml, requests, jumeaux_config_yml):
send.side_effect = send_for_test
payload: Reqs2ReqsAddOnPayload = Reqs2ReqsAddOnPayload.from_dict({"requests": requests})
try:
Executor(load_yaml(config_yml)).exec(
payload, JumeauxConfig.from_yaml(jumeaux_config_yml)
)
except SystemExit:
assert send.call_args[0][0] == "empty test notify!"
assert send.call_args[0][1].to_dict() == {
"type": "slack",
"version": 1,
"channel": "#jumeaux",
"username": "jumeaux",
"use_blocks": False,
}
| 28.067227 | 96 | 0.526946 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.