blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107 values | src_encoding stringclasses 20 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 4 6.02M | extension stringclasses 78 values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8fad0e1ffc2107d073e1e36d04a28101f3819657 | 741663bc3d7dfc49c4b881eafd24e387e925392a | /src/multimodal/models/predict_model.py | feed72242acc25cc48d02f3229d36ee81ff20aca | [
"MIT"
] | permissive | markrofail/multi-modal-deep-learning-for-vehicle-sensor-data-abstraction-and-attack-detection | e957731ca293eb65d1b56dfce6abe607ec20bbf7 | 2f252c072f3091bb27506978dd90311f7f82f386 | refs/heads/master | 2023-07-30T02:22:28.412955 | 2020-06-20T17:12:54 | 2020-06-20T17:12:54 | 273,745,779 | 0 | 0 | MIT | 2021-09-08T02:12:12 | 2020-06-20T16:37:18 | HTML | UTF-8 | Python | false | false | 6,173 | py | import os
import click
import cv2
import matplotlib.pyplot as plt
import numpy as np
from src.helpers import paths
from src.helpers.flags import AttackModes, Verbose
from src.multimodal import multimodal
from src.multimodal.data import make_dataset
###############################################################################
# DATA PARAMETERS
###############################################################################
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
np.set_printoptions(suppress=True, precision=4, sign=' ')
config = paths.config.read(paths.config.multimodal())
VERBOSE = config['ENVIROMENT_CONFIG']['VERBOSE']
DEFAULT_DRIVE = '2011_09_26'
DEFAULT_NUMBER = 1
DEFAULT_FRAME = 1
DEFAULT_ATTACK = 1
DEFAULT_ATTACK_FLAG = True
def print_results(**kargs):
keys = np.array(list(kargs.keys()))
keys = np.sort(keys)
print('# results:')
for key in keys:
value = kargs[key]
print('## {k} = {v}'.format(k=key, v=value))
print()
def display_results(drive_date, drive_number, drive_frame, attack, result):
if attack:
img_path = paths.attack.interim_frame(drive_date, drive_number, drive_frame)
else:
img_path = paths.rgb.interim_frame(drive_date, drive_number, drive_frame)
img = cv2.imread(str(img_path))
if img is None:
raise Exception("could not load image !")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img, interpolation="bicubic")
result = 'result: {}!'.format('PASS' if result else 'FAIL')
plt.xlabel(result)
plt.show()
def feed_forward(input_image, input_depth, label):
# Create the network
net = multimodal.Multimodal()
# Load pretrained model
model_path = str(paths.checkpoints.multimodal()) # ./checkpoints/multimodal/train
net.model.load_weights(model_path)
# Predict
pred = net.model.predict([[input_image], [input_depth]])
print_args = dict()
print_args['predict_raw'] = pred
notations = ['Normal', 'Attack']
pred = np.argmax(pred)
label = np.argmax(label)
verdict = 'PASS' if label == pred else 'FAIL'
print_args['label'] = str(notations[label])
print_args['predict'] = str(notations[pred])
print_args['verdict'] = verdict
print_results(**print_args)
return label == pred
def predict(drive_date, drive_number, frame, attack, attack_type):
# create the frame data
print('# generating data...')
frame_data = [(drive_date, drive_number, frame)]
make_dataset.make_data(
frame_data, attack_type=attack_type, verbose=Verbose.SILENT, keep=True)
if attack:
rgb_path = paths.attack.processed_tensor(drive_date, drive_number, frame)
label_data = np.array([0, 1])
else:
rgb_path = paths.rgb.processed_tensor(drive_date, drive_number, frame)
label_data = np.array([1, 0])
rgb_data = np.load(rgb_path)
depth_path = paths.depth.processed_tensor(drive_date, drive_number, frame)
depth_data = np.load(depth_path)
print('# feedforward data...')
return feed_forward(input_image=rgb_data, input_depth=depth_data, label=label_data)
def get_arguments_interactively():
args_dict = dict()
print('\nEnter drive details:')
default_drive = DEFAULT_DRIVE
input_date = input(
'# drive date (format: \'yyyy_mm_dd\') [\'{}\']:'.format(
default_drive))
if input_date:
args_dict['drive_date'] = input_date
default_number = DEFAULT_NUMBER
input_number = input('# drive number (int) [{}]:'.format(default_number))
if input_number:
args_dict['drive_number'] = int(input_number)
default_frame = DEFAULT_FRAME
input_frame = input('# drive frame (int) [{}]:'.format(default_frame))
if input_frame:
args_dict['drive_frame'] = int(input_frame)
default_attack_flag = DEFAULT_ATTACK_FLAG
input_attack_flag = input('# normal/attack (0/1) [{}]:'.format(int(default_attack_flag)))
if input_attack_flag:
args_dict['attack'] = bool(int(input_attack_flag))
if input_attack_flag and not args_dict['attack']:
print()
return args_dict
default_attack = DEFAULT_ATTACK
input_attack = input('# inpainting/translation (1/2) [{}]:'.format(int(default_attack)))
if input_attack:
args_dict['attack_type'] = int(input_attack)
print()
return args_dict
@click.option(
'--drive_date', type=str, default=DEFAULT_DRIVE, help='date of the drive')
@click.option(
'--drive_number',
type=int,
default=DEFAULT_NUMBER,
help='date of the drive')
@click.option(
'--drive_frame',
type=int,
default=DEFAULT_FRAME,
help='frame within the drive')
@click.option(
'--attack_type',
type=int,
default=DEFAULT_ATTACK,
help='frame within the drive')
@click.option(
'--attack/--normal',
help='normal or attack',
)
@click.option(
'--interactive',
'-i',
is_flag=True,
help='interactively',
)
@click.option(
'--display',
'-d',
is_flag=True,
help='display image',
)
@click.command()
def main(interactive=False,
display=False,
drive_date=DEFAULT_DRIVE,
drive_number=DEFAULT_NUMBER,
drive_frame=DEFAULT_FRAME,
attack_type=DEFAULT_ATTACK,
attack=True):
if interactive:
args_dict = get_arguments_interactively()
if 'drive_date' in args_dict:
drive_date = args_dict['drive_date']
if 'drive_number' in args_dict:
drive_number = args_dict['drive_number']
if 'drive_frame' in args_dict:
drive_frame = args_dict['drive_frame']
if 'attack_type' in args_dict:
attack_type = args_dict['attack_type']
if 'attack' in args_dict:
attack = args_dict['attack']
path = paths.rgb.external_frame(drive_date, drive_number, drive_frame)
assert path.exists(), 'frame does not exist'
result = predict(drive_date, drive_number, drive_frame, attack, attack_type)
if display:
display_results(drive_date, drive_number, drive_frame, attack, result)
if __name__ == '__main__':
main()
'''
# for attack:
python -m src.multimodal.models.predict_model -d \
--drive_date 2011_09_26 --drive_number 1 --drive_frame 1 --attack --attack_type 2
# for normal:
python -m src.multimodal.models.predict_model -d \
--drive_date 2011_09_26 --drive_number 1 --drive_frame 1 --normal --attack_type 2
'''
| [
"markm.rofail@gmail.com"
] | markm.rofail@gmail.com |
f9a070cd4f54bb5db6172fe1754a0c3ce4c8635e | 32c1f5e296e3fdfd5583b767ba388450c22d4920 | /xclib/tests/prosody_test.py | 0105858d2c138d2284a48ac4bc09dbd37cfca878 | [
"MIT"
] | permissive | wenzhuoz/xmpp-cloud-auth | 848a930677a282e942211a129bff801d85e13ca1 | 8359b80197d2d7743a41cc3c60475d8c8cd2920d | refs/heads/master | 2020-03-16T21:57:13.370802 | 2018-05-11T09:46:13 | 2018-05-11T09:46:13 | 133,021,003 | 0 | 0 | null | 2018-05-11T09:41:24 | 2018-05-11T09:41:24 | null | UTF-8 | Python | false | false | 1,001 | py | import sys
import unittest
from xclib.prosody_io import prosody_io
from xclib.tests.iostub import iostub
class TestProsody(unittest.TestCase, iostub):
def test_input(self):
self.stub_stdin('isuser:login:\n' +
'auth:log:dom:pass\n')
tester = iter(prosody_io.read_request())
output = tester.next()
assert output == ('isuser', 'login', '')
output = tester.next()
assert output == ('auth', 'log', 'dom', 'pass')
try:
output = tester.next()
assert False # Should raise StopIteration
except StopIteration:
pass
def test_output_false(self):
self.stub_stdout()
prosody_io.write_response(False)
self.assertEqual(sys.stdout.getvalue(), '0\n')
# Cannot be merged, as getvalue() returns the aggregate value
def test_output_true(self):
self.stub_stdout()
prosody_io.write_response(True)
self.assertEqual(sys.stdout.getvalue(), '1\n')
| [
"marcel.waldvogel@uni-konstanz.de"
] | marcel.waldvogel@uni-konstanz.de |
273419d8074c1ba7bc5bf2633a855f024edd0d7c | 00e3bc6d538cb0f1cfcb14cb725c11e1be2503b0 | /steps/offer_steps.py | 71e28eadf0a67c74d36002e46472f77f44d463a0 | [] | no_license | minhwang/carousell_appium_automation | 960e9a433efdd61026cadffdf58f403c7a71759c | 554fda4c1fcf7cecefc2e513a0b6ebad042c6203 | refs/heads/master | 2020-12-30T14:19:21.096863 | 2017-08-21T07:00:48 | 2017-08-21T07:00:48 | 91,303,260 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 610 | py | from behave import *
from carousell import App, Platform
use_step_matcher("re")
@when('I submit an offer')
def step_impl(context):
app = App(Platform.ANDROID)
context.chat = app\
.welcome_view\
.create(context.wd)\
.login_with_email()\
.login(context.user_id, context.user_pwd)\
.browse()\
.browse_category('Cars')\
.view_product(0)\
.buy()\
.submit()\
.yes()
@then('The app brings me chat')
def step_impl(context):
assert context.chat | [
"min81.hwang@gmail.com"
] | min81.hwang@gmail.com |
d57b2b6ba4918837e7dbca3a7ab328705da2f0df | 0593fbd857b5286f93c60056982e9b4d2b23eff7 | /automaton_t.py | 8b8fbfe222d8adc889c56645509ec4df7b0ec6bf | [] | no_license | Moysenko/NFA-converter | 5c74145b081eff6efb834a8a7458f4bb0f83419c | 82de98b2d6bf7602387b5e82a0b246ef406334d9 | refs/heads/main | 2023-01-05T16:12:31.640233 | 2020-10-16T21:52:31 | 2020-10-16T21:52:31 | 300,353,590 | 0 | 2 | null | 2020-10-16T21:52:33 | 2020-10-01T16:51:01 | null | UTF-8 | Python | false | false | 10,366 | py | from vertex_t import Vertex
from collections import defaultdict, namedtuple
import sys, os
import json
class Automaton:
def __init__(self, start=0, vertices=None, alphabet=None, other_automaton=None):
if other_automaton is None:
self.start = start
self.vertices = vertices or dict()
self._free_vertex_id = (max(self.vertices) + 1) if len(self.vertices) else 0
self.alphabet = alphabet or set()
else:
self.start = other_automaton.start
self._free_vertex_id = other_automaton._free_vertex_id
self.vertices = dict(other_automaton.vertices)
self.alphabet = other_automaton.alphabet.copy()
def __getitem__(self, vertex_id):
if vertex_id not in self.vertices:
self._free_vertex_id = max(self._free_vertex_id, vertex_id + 1)
self.vertices[vertex_id] = Vertex(vertex_id)
return self.vertices[vertex_id]
def add_edge(self, vertex_from, vertex_to, word):
self[vertex_to] # in order to add vertex_to in self.vertices
self[vertex_from].add_edge(word, vertex_to)
def scan(self):
self.alphabet = set(input('Alphabet: '))
number_of_edges = int(input('Number of edges: '))
print('Edges: (in format "{from} {to} {word}", symbol "-" stands for empty string)')
self.vertices = dict()
self._free_vertex_id = 0
for edge_id in range(number_of_edges):
vertex_from, vertex_to, word = input('Edge #{0}: '.format(edge_id)).split()
if word == '-': # null edge
word = None
self.add_edge(int(vertex_from), int(vertex_to), word)
self.start = int(input('Start state: '))
for terminal_vertex_id in list(map(int, input('Terminal states: ').split())):
self[terminal_vertex_id].is_terminal = True
def read_from_json(self, filename):
with open(filename, 'r') as input_file, open(os.devnull, 'w') as output_file:
sys.stdin = input_file
sys.stdout = output_file
self.scan()
sys.stdin = sys.__stdin__
sys.stdout = sys.__stdout__
def __str__(self):
output = 'Automaton:\n'
prefix = ' ' * 4
output += prefix + 'Edges:\n'
terminal_vertices = []
for vertex in self.vertices:
if self[vertex].is_terminal:
terminal_vertices.append(vertex)
for word, neighbors in self[vertex].edges.items():
for vertex_to in neighbors:
output += prefix * 2 + 'From {0} to {1} by {2}\n'.format(vertex, vertex_to, word or '-')
output += prefix + 'Start state: {0}'.format(self.start)
output += prefix + 'Terminal states: ' + ', '.join(str(v) for v in terminal_vertices) + '\n'
return output
def _split_long_edges(self): # replaces all edges with keys longer than 1 with multiple edges
edges_to_delete = []
for vertex_id in self.vertices:
for word in self[vertex_id].edges:
if word is not None and len(word) > 1:
edges_to_delete.append((vertex_id, word))
for vertex_id, word in edges_to_delete:
for edge_end in self[vertex_id].neighbors_by_word(word):
last_vertex = vertex_id
for i, letter in enumerate(word):
if i + 1 == len(word):
vertex_to = edge_end
else:
vertex_to = self._free_vertex_id
self._free_vertex_id += 1
self.add_edge(last_vertex, vertex_to, letter)
last_vertex = vertex_to
self[vertex_id].remove_edge(word)
def _shorten_path(self, vertex_from, word, visited_vertices): # dfs in wich every step except first is using null edge
if word in vertex_from.edges:
for vertex_to in vertex_from.edges[word]:
if vertex_to not in visited_vertices:
visited_vertices.add(vertex_to)
self._shorten_path(self[vertex_to], None, visited_vertices)
def _get_shortened_null_paths(self, vertex):
new_edges = defaultdict(set)
reached_by_null_edges = set()
self._shorten_path(vertex, None, reached_by_null_edges)
for vertex_to in reached_by_null_edges:
for word in self[vertex_to].edges:
if word is not None:
new_edges[word] |= self[vertex_to].edges[word]
return new_edges
def _remove_null_edges(self):
for vertex in self.vertices.values(): # add new terminal vertices
if not vertex.is_terminal:
reached_by_null_edges = set()
self._shorten_path(vertex, None, reached_by_null_edges)
for terminal_vertex in reached_by_null_edges:
vertex.is_terminal |= self[terminal_vertex].is_terminal
new_edges = dict()
for vertex_id, vertex in self.vertices.items(): # add new adges and delete null edges
new_edges[vertex_id] = self._get_shortened_null_paths(vertex)
for vertex_id, edges in new_edges.items():
vertex = self[vertex_id]
if None in vertex.edges:
del vertex.edges[None]
for word, vertices_to in edges.items():
vertex.edges[word] |= vertices_to
def _reachable_from_vertex(self, current_vertex, visited):
for neighbors in current_vertex.edges.values():
for vertex_to in neighbors:
if vertex_to not in visited:
visited.add(vertex_to)
self._reachable_from_vertex(self[vertex_to], visited)
def _init_from_automaton_subsets(self, other):
for subset in range(2**other._free_vertex_id): # build automaton on subsets
for vertex_id, vertex in other.vertices.items():
if (2**vertex_id) & subset:
if other.start == vertex_id and (2**vertex_id) == subset:
self.start = subset
self[subset].is_terminal |= vertex.is_terminal
for word in vertex.edges:
self[subset].edges[word] |= vertex.edges[word]
def _replace_edges_with_subsets(self):
for vertex in self.vertices:
for word in self[vertex].edges:
subset_to = 0
for vertex_to in self[vertex].edges[word]:
subset_to += 2**vertex_to
self[vertex].edges[word] = {subset_to}
def _init_from_useful_vertices(self, automaton):
useful_vertices = {automaton.start}
automaton._reachable_from_vertex(automaton[automaton.start], useful_vertices)
useful_vertex_id = {old_vertex_id: vertex_id
for vertex_id, old_vertex_id in enumerate(useful_vertices)}
self.vertices = dict()
self._free_vertex_id = len(useful_vertices)
self.start = useful_vertex_id[automaton.start]
for vertex in useful_vertices:
self[useful_vertex_id[vertex]].is_terminal |= automaton[vertex].is_terminal
for word, neighbors in automaton[vertex].edges.items():
for vertex_to in neighbors:
self.add_edge(useful_vertex_id[vertex], useful_vertex_id[vertex_to], word)
def _remove_duplicate_edges(self):
new_automaton = Automaton(start=0, vertices=dict(), alphabet=set())
new_automaton._init_from_automaton_subsets(self)
new_automaton._replace_edges_with_subsets()
self._init_from_useful_vertices(new_automaton)
def to_dfa(self):
self._split_long_edges()
self._remove_null_edges()
self._remove_duplicate_edges()
def accept_string(self, word):
current_state = self.start
for letter in word:
try:
current_state = self[current_state].go(letter)
except KeyError:
return False
return self[current_state].is_terminal
def to_cdfa(self): # it is assumed that automaton is already deterministic
missing_edges = []
Edge = namedtuple('Edge', 'vertex, letter')
for vertex in self.vertices.values():
missing_edges += [Edge(vertex=vertex, letter=letter) for letter in self.alphabet if letter not in vertex.edges]
if missing_edges:
dummy_vertex = self._free_vertex_id
self._free_vertex_id += 1
for edge in missing_edges:
self.add_edge(edge.vertex.id, dummy_vertex, edge.letter)
for letter in self.alphabet:
self.add_edge(dummy_vertex, dummy_vertex, letter)
self._free_vertex_id += 1
def reverse_cdfa(self):
for vertex in self.vertices.values():
vertex.is_terminal ^= 1
def _equivalence_groups(self):
group = dict()
for vertex in self.vertices.values():
group[vertex.id] = int(vertex.is_terminal)
old_number_of_classes = 1
current_number_of_classes = 2
step_id = 0
while old_number_of_classes != current_number_of_classes:
step_id += 1
output_groups = defaultdict(list)
for vertex in self.vertices.values():
key = tuple([group[vertex.id]] + [group[vertex.go(letter)] for letter in self.alphabet])
output_groups[key].append(vertex.id)
old_number_of_classes = current_number_of_classes
current_number_of_classes = len(output_groups)
group = dict()
for group_id, vertices in enumerate(output_groups.values()):
for vertex in vertices:
group[vertex] = group_id
return group
def to_minimal_cdfa(self):
group = self._equivalence_groups()
new_automaton = Automaton(start=group[self.start], alphabet=self.alphabet, vertices={})
for vertex in self.vertices.values():
new_automaton[group[vertex.id]].is_terminal |= vertex.is_terminal
for word in self.alphabet:
new_automaton.add_edge(group[vertex.id], group[vertex.go(word)], word)
self.__init__(other_automaton=new_automaton)
| [
"moysenkom@gmail.com"
] | moysenkom@gmail.com |
f6b1a60691f6f53ffd82e4d7f873cb546ad3dc71 | 25c9290b26cf39888aad8890c7778b4f4f5c5daa | /Triode-Car/microbit(only)/1.1 Control motor with button/main.py | fd61a508c41d0449300ed51c09c856f5e028b8b9 | [] | no_license | vtt-info/Micropython-10 | 0ca3feaf2297ce5b9c24e46ea0e538316a9e5980 | 1dfc63af4ea863c9c61170974bd022e10ee59a1c | refs/heads/main | 2023-08-29T02:45:49.280754 | 2021-11-03T09:36:45 | 2021-11-03T09:36:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,193 | py | #用micro:bit的AB按钮控制triodecar电机
'''
一切与硬件交互直接相关的东西都存在于 microbit函数库中,
一般直接从中引用全部功能。
'''
from microbit import *
'''
使用def来创建自定义函数,将可能重复应用的某些功能的代码写入其中以便调用。
micro:bit的pin14引脚控制着triodecar的左电机,pin15引脚控制着右电机,
引脚输出高电平将使电机停转,低电平将使电机运行。
'''
def direction_stop():
pin14.write_digital(1)
pin15.write_digital(1)
def direction_foward():
pin14.write_digital(0)
pin15.write_digital(0)
'''右电机转,左电机停转,triodecar向左行驶。'''
def direction_left():
pin14.write_digital(1)
pin15.write_digital(0)
'''右电机停转,左电机转,triodecar向右行驶。'''
def direction_right():
pin14.write_digital(0)
pin15.write_digital(1)
'''开始主循环,进入循环后如果不执行break语句将在系统关机前永远循环下去'''
while True:
'''if条件判断,若满足条件则执行。
当按钮A和按钮B都被按下时,显示北向箭头,控制triodecar向前行驶。'''
if button_a.is_pressed() and button_b.is_pressed():
display.show(Image.ARROW_N, delay=0, wait=True, loop=False, clear=False)
direction_foward()
'''elif表示“否则如果”,“不满足if的条件但满足这个条件”的意思。
此处即为:若仅按钮A被按下,则显示西向箭头,控制triodecar向右行驶。'''
elif button_a.is_pressed():
display.show(Image.ARROW_W, delay=0, wait=True, loop=False, clear=False)
direction_right()
'''若仅按钮B被按下,则显示东向箭头,控制triodecar向左行驶。'''
elif button_b.is_pressed():
display.show(Image.ARROW_E, delay=0, wait=True, loop=False, clear=False)
direction_left()
'''else为if和elif都判定为否的情况下将执行。
此处为:若按钮A或按钮B都没被按下,则显示困倦图标,控制triodecar停车。'''
else:
display.show(Image.ASLEEP, delay=0, wait=True, loop=False, clear=False)
direction_stop()
| [
"76462385+Wind-stormger@users.noreply.github.com"
] | 76462385+Wind-stormger@users.noreply.github.com |
d2ca8ecfa155dc2a582b16faf400c3ff2d5b08a0 | 3999521ed32fc384ecb0446f2956cd44734bc989 | /apiconfig.py | 6424b51cb212f1139d52645e4fea6f38cd245aa0 | [
"Apache-2.0"
] | permissive | yangyzp/shadowsocksdd | 56789be92be33e45044900caf5b6eb08dc924b21 | 2ecc23db49b28a51e07758b4968d8bcd54ad18d3 | refs/heads/manyuser | 2021-06-19T06:13:08.005075 | 2018-05-07T03:39:52 | 2018-05-07T03:39:52 | 132,402,930 | 2 | 1 | Apache-2.0 | 2021-06-01T22:22:08 | 2018-05-07T03:36:02 | Python | UTF-8 | Python | false | false | 887 | py | # Config
NODE_ID = 1
# hour,set 0 to disable
SPEEDTEST = 0
CLOUDSAFE = 1
ANTISSATTACK = 0
AUTOEXEC = 0
MU_SUFFIX = 'v1m3cc2x'
MU_REGEX = '%5m'
SERVER_PUB_ADDR = '127.0.0.1' # mujson_mgr need this to generate ssr link
API_INTERFACE = 'glzjinmod' # glzjinmod, modwebapi
WEBAPI_URL = 'https://zhaoj.in'
WEBAPI_TOKEN = 'glzjin'
# mudb
MUDB_FILE = 'mudb.json'
# Mysql
MYSQL_HOST = '23.234.197.24'
MYSQL_PORT = 3306
MYSQL_USER = 'sspanel'
MYSQL_PASS = 'qq469566135'
MYSQL_DB = 'sspanel'
MYSQL_SSL_ENABLE = 0
MYSQL_SSL_CA = ''
MYSQL_SSL_CERT = ''
MYSQL_SSL_KEY = ''
# API
API_HOST = '127.0.0.1'
API_PORT = 80
API_PATH = '/mu/v2/'
API_TOKEN = 'abcdef'
API_UPDATE_TIME = 60
# Manager (ignore this)
MANAGE_PASS = 'ss233333333'
# if you want manage in other server you should set this value to global ip
MANAGE_BIND_IP = '127.0.0.1'
# make sure this port is idle
MANAGE_PORT = 23333
| [
"noreply@github.com"
] | noreply@github.com |
49b2a27304baa0fd8ed633b0cf8b738d64a581b3 | 1345dc02bbe664db2a8804a0fc0e8a5a7129147b | /sale.py | 43b89520cc39bbaaae2ae1f6992dadd73933e3d1 | [] | no_license | gavindav/DataScienceRepo | e2f9c68a9352c51f72678c7bc2247fd5b83a2a28 | 6378e854ff2428962f8f2d571eeea92a1b3d3edd | refs/heads/main | 2023-02-17T01:26:04.980578 | 2021-01-11T08:59:55 | 2021-01-11T08:59:55 | 328,593,942 | 0 | 0 | null | 2021-01-11T08:59:56 | 2021-01-11T08:18:28 | Python | UTF-8 | Python | false | false | 3,700 | py | # (C) Copyright IBM Corp. 2020
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
"""SaleOrder."""
from odoo import api, fields, models
from odoo.tools.config import config
import re
class SaleOrder(models.Model):
"""SaleOrder."""
_inherit = 'sale.order'
case_number = fields.Char('case_number', required=False)
def _get_ddb_service_types(self):
return self.env['delivery.carrier']._get_ddb_service_types()
ddb_service_type = fields.Selection(
_get_ddb_service_types, string="DDB Service Type")
@api.onchange('carrier_id')
def _onchange_carrier_id(self):
"""Return the element value."""
orders = self.env['sale.order'].sudo().search(
[('package_delivery_group', '=', self.package_delivery_group)])
delivery_type = self.carrier_id.delivery_type
for order in orders:
order.carrier_id = self.carrier_id
if hasattr(
self.carrier_id, delivery_type + "_default_service_type"):
expr = "order." + delivery_type + \
"_service_type = self.carrier_id." + \
delivery_type + "_default_service_type"
exec(expr)
order.ibmorder_data.deliverymethod = self.carrier_id.name
def generate_next_case_number_in_sequence(self, base_initialisation):
ddbcase_obj = self.env['ibmddb.case_number'].with_user(2).create({'ordno': self.name, })
case_num = ddbcase_obj.id
while case_num < base_initialisation:
ddbcase_obj.unlink()
ddbcase_obj = self.env['ibmddb.case_number'].with_user(2).create({'ordno': self.name, })
case_num = ddbcase_obj.id
return case_num
def int2base36(self, x, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
"""Convert an integer to its string representation to base 36."""
val = ''
while x > 0:
x, idx = divmod(x, 36)
val = alphabet[idx] + val
return "0" * (5 - len(val)) + val
def get_ddb_case_number(self):
"""Return the element value."""
# format is 76ZSWAaaaaa00
# initialise from 00000 so sumber is from 76ZSWA0000000 to
# 76ZSWAZZZZZ00
ddbprefix = config.get("ddbprefix")
ddb_base_initialisation = config.get("ddb_base_initialisation")
if ddb_base_initialisation and re.match("^[0-9]*$", ddb_base_initialisation.strip()):
ddb_base_initialisation = int(ddb_base_initialisation.strip(), 36)
else:
ddb_base_initialisation = 0 # 10 = 'AXXXXX', 11='BXXXXX'
if ddbprefix and re.match("^[0-9]*$", ddbprefix.strip()):
ddbprefix = int(ddbprefix.strip())
else:
ddbprefix = 10 # 10 = 'AXXXXX', 11='BXXXXX'
foundation = 36 * ddbprefix * 36 * 36 * 36 * 36
if self.case_number:
return self.case_number
else:
case_number_prefix = "76ZSW"
case_num = self.generate_next_case_number_in_sequence(ddb_base_initialisation)
case_num = self.int2base36(case_num + foundation)
case_number_suffix = "00"
self.case_number = case_number_prefix + case_num + \
case_number_suffix
pdg_sale_objects = self.env['sale.order'].sudo().search(
[('package_delivery_group', '=', self.package_delivery_group)])
for pdg_so in pdg_sale_objects:
pdg_so.case_number = case_number_prefix + case_num + \
case_number_suffix
return self.case_number
| [
"noreply@github.com"
] | noreply@github.com |
9adcc12b7ba970cf3f19bbad83bbd0ecb835aa85 | f15c8b3a6b093c3b70a900221f485d74a1bc1f95 | /0_joan_stark/golf.py | 2f646ee459477d0f80708844a426c3b1cdd2b1bf | [
"MIT"
] | permissive | wang0618/ascii-art | 2955023e47b988f491b9d46bc8a300ba4a6cdd60 | 7ce6f152541716034bf0a22d341a898b17e2865f | refs/heads/master | 2023-07-17T23:17:31.187906 | 2021-09-04T12:46:31 | 2021-09-04T12:46:31 | 400,987,004 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,978 | py | # Hole in One!
# https://web.archive.org/web/20000307135811/http://geocities.com/SoHo/Gallery/6446/golfanim.htm
duration = 200
name = "Golf"
frames = [
" \n" +
" |>18>>\n" +
" |\n" +
" O |\n" +
" /|\\o |\n" +
" | | |\n" +
" ,|/| |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^",
" \n" +
" |>18>>\n" +
" |\n" +
" __O |\n" +
" / /\\o |\n" +
" ,/ | |\n" +
" | |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^",
" \n" +
" |>18>>\n" +
" |\n" +
" |\n" +
" __O |\n" +
" \\ \\ |\n" +
" / o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" |>18>>\n" +
" |\n" +
" __O |\n" +
" / /\\ |\n" +
" ,/ |\\ |\n" +
" |/ o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" |>18>>\n" +
" |\n" +
" O |\n" +
" |\\ |\n" +
" /\\| |\n" +
" / ||o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" |>18>>\n" +
" |\n" +
" O |\n" +
" |\\ |\n" +
" |\\| |\n" +
" / ||o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" |>18>>\n" +
" |\n" +
" O |\n" +
" /> |\n" +
" //\\ |\n" +
" ,// / o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" |>18>>\n" +
" |\n" +
" O |\n" +
" ,___/| |\n" +
" /\\ |\n" +
" / / o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" `\\ |>18>>\n" +
" \\ |\n" +
" <<O |\n" +
" | |\n" +
" |\\ |\n" +
" / | o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" /` |>18>>\n" +
" / |\n" +
" <<O |\n" +
" \\ |\n" +
" /\\ |\n" +
" / / o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" /` |>18>>\n" +
" / |\n" +
" <<O |\n" +
" \\ |\n" +
" /\\ |\n" +
" / / o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" /` |>18>>\n" +
" / |\n" +
" <<O |\n" +
" \\ |\n" +
" /\\ |\n" +
" / / o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" `\\ |>18>>\n" +
" \\ |\n" +
" <<O |\n" +
" | |\n" +
" |\\ |\n" +
" / | o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" |>18>>\n" +
" |\n" +
" O |\n" +
" ,___/| |\n" +
" /\\ |\n" +
" / / o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" |>18>>\n" +
" |\n" +
" O |\n" +
" |\\ |\n" +
" |\\| |\n" +
" / ||o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" |>18>>\n" +
" `/ |\n" +
" O__/ |\n" +
" \\-` o |\n" +
" /\\ . |\n" +
" / / .' |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" '\\ . o |>18>>\n" +
" \\ . |\n" +
" O>> . |\n" +
" \\ . |\n" +
" /\\ . |\n" +
" / / .' |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" '\\ . . |>18>>\n" +
" \\ . ' . |\n" +
" O>> . 'o |\n" +
" \\ . |\n" +
" /\\ . |\n" +
" / / .' |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" '\\ . . |>18>>\n" +
" \\ . ' . |\n" +
" O>> . ' |\n" +
" \\ . ' . |\n" +
" /\\ . . |\n" +
" / / .' o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" '\\ . . |>18>>\n" +
" \\ . ' . |\n" +
" O>> . ' |\n" +
" \\ . ' . |\n" +
" /\\ . . . o |\n" +
" / / .' . |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" '\\ . . |>18>>\n" +
" \\ . ' . |\n" +
" O>> . ' |\n" +
" \\ . ' . |\n" +
" /\\ . . . ' . |\n" +
" / / .' . o |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" '\\ . . |>18>>\n" +
" \\ . ' . |\n" +
" O>> . ' |\n" +
" \\ . ' . |\n" +
" /\\ . . . ' . |\n" +
" / / .' . . o\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" '\\ . . |>18>>\n" +
" \\ . ' . |\n" +
" O>> . ' |\n" +
" \\ . ' . |\n" +
" /\\ . . . ' . |\n" +
" / / .' . . .|\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" `/ . . |>18>>\n" +
" / . ' . |\n" +
" \\O/ . ' |\n" +
" | . ' . |\n" +
" /\\ . . . ' . |\n" +
" / | .' . . .|\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" `/ . . |>18>>\n" +
" / . ' . |\n" +
" __O/ . ' |\n" +
" | . ' . |\n" +
" /\\ . . . ' . |\n" +
" | \\ .' . . .|\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" . . |>18>>\n" +
" `/ . ' . |\n" +
" O__/ . ' |\n" +
" /| . ' . |\n" +
" /\\ . . . ' . |\n" +
" / / .' . . .|\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" |>18>>\n" +
" |\n" +
" \\O |\n" +
" |\\ |\n" +
" /\\\\ |\n" +
" / | \\, |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" |>18>>\n" +
" |\n" +
" O |\n" +
" /|\\ |\n" +
" |\\\\ |\n" +
" / | \\, |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" yipee! |>18>>\n" +
" |\n" +
" \\O |\n" +
" |\\ |\n" +
" /\\\\ |\n" +
" / | \\, |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" yipee! |>18>>\n" +
" |\n" +
" O |\n" +
" /|\\ |\n" +
" |\\\\ |\n" +
" / | \\, |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" yipee! |>18>>\n" +
" |\n" +
" O |\n" +
" /|\\ |\n" +
" / |\\ |\n" +
" /,/ | |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ",
" \n" +
" |>18>>\n" +
" |\n" +
" O |\n" +
" /|\\o |\n" +
" | | |\n" +
" ,|/| |\n" +
" jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ "
]
| [
"wang0.618@qq.com"
] | wang0.618@qq.com |
fb004d77dcce82d96824cd25b93bca814fdb7157 | e4aa60a4f8d5f7d85be02b10f05aa956dc92ca68 | /venv/bin/pip | a288e2a0ae32ac4cbff413bfd22b155817b4fa31 | [] | no_license | SerenaPaley/WordUp | 37c29fb2f673421a26ad89a70ae62e75ae2e79a3 | 86b4bb82382abc241eaf8d8e1847d1796365936c | refs/heads/master | 2023-03-18T08:54:53.396244 | 2021-03-02T18:12:50 | 2021-03-02T18:12:50 | 343,645,743 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 259 | #!/Users/spaley/PycharmProjects/WordGame/venv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"serena.paley8@gmail.com"
] | serena.paley8@gmail.com | |
3a409d438db536481f5aef2b5b889704149e23f9 | 0d6ecf1dd8d84b1a8ab8f929c0ea4e08531a63fa | /alexa_auth.py | caea5f70132e7c23c54d6f2da3f5a58195ddd124 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | molodoj88/AlexaDevice | 846f1d99fc8e918999c3c47a1996e3eeaaaff13f | 957bdf79970a04f7e85fd0f7835801d0cca08d92 | refs/heads/master | 2021-01-22T21:07:07.390869 | 2017-02-24T13:54:17 | 2017-02-24T13:54:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,232 | py | #!/usr/bin/env python3
import alexa_params
import alexa_control
import alexa_http_config
import socket
import threading
from zeroconf import raw_input, ServiceInfo, Zeroconf
from http.server import HTTPServer
localHTTP = None
zeroconf = None
info = None
def get_local_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("www.amazon.com", 80))
res = s.getsockname()[0]
s.close()
return res
def start():
global localHTTP, zeroconf, info, httpthread
ip = get_local_address()
print("Local IP is " + ip)
desc = {'version': '0.1'}
info = ServiceInfo("_http._tcp.local.",
"Alexa Device._http._tcp.local.",
socket.inet_aton(ip), alexa_params.LOCAL_PORT, 0, 0,
desc, alexa_params.LOCAL_HOST + ".")
zeroconf = Zeroconf()
zeroconf.registerService(info)
print("Local mDNS is started, domain is " + alexa_params.LOCAL_HOST)
localHTTP = HTTPServer(("", alexa_params.LOCAL_PORT), alexa_http_config.AlexaConfig)
httpthread = threading.Thread(target=localHTTP.serve_forever)
httpthread.start()
print("Local HTTP is " + alexa_params.BASE_URL)
alexa_control.start()
def close():
localHTTP.shutdown()
httpthread.join()
zeroconf.unregisterService(info)
zeroconf.close()
alexa_control.close()
| [
"2xl@mail.ru"
] | 2xl@mail.ru |
a02ede264cfadd79a5af66ac1ef5a8d3658d7477 | 37ccb985555670df4a9df2650b41b7cc49c4cecd | /WEEK4/Hamburger.py | b858d3968a4b65a31b4f1171d97e7fd9d66f339a | [] | no_license | PeravitK/PSIT | f525620ad72fdcf55c84b115e8a0484f9f941f60 | f31522199fff312b26d2e3f5d54b0d34a2bec675 | refs/heads/main | 2023-08-18T04:36:09.966788 | 2021-09-19T13:55:37 | 2021-09-19T13:55:37 | 405,643,641 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 171 | py | '''Hambergur'''
def main():
'''docstring'''
num1 = int(input())
num2 = int(input())
print("%s%s%s" %("|"*num1, "*"*(num1+num2)*2, "|"*num2))
main()
| [
"noreply@github.com"
] | noreply@github.com |
348fc47cef3dc9dc96c748af7cf91394fd8222e7 | 2d7c21a793c8080a090ce8c9f05df38f6477c7c7 | /tests/data_templates/test_field_definitions.py | c4f05eb9f57000460d8661f4d47b2a554f7826ea | [
"Apache-2.0"
] | permissive | kids-first/kf-api-study-creator | c40e0a8a514fd52a857e9a588635ef76d16d5bc7 | ba62b369e6464259ea92dbb9ba49876513f37fba | refs/heads/master | 2023-08-17T01:09:38.789364 | 2023-08-15T14:06:29 | 2023-08-15T14:06:29 | 149,347,812 | 3 | 0 | Apache-2.0 | 2023-09-08T15:33:40 | 2018-09-18T20:25:38 | Python | UTF-8 | Python | false | false | 5,204 | py | import os
import json
import pytest
import pandas
from marshmallow import ValidationError
from pprint import pprint
from creator.data_templates.models import TemplateVersion
from creator.data_templates.field_definitions_schema import (
coerce_number,
coerce_bool,
FieldDefinitionSchema,
FieldDefinitionsSchema
)
@pytest.mark.parametrize(
"in_value, expected_out",
[
("0.0", 0.0),
(0.0, 0.0),
("0", 0),
(0, 0),
("10.0", 10),
(10.0, 10),
("200", 200),
(200, 200),
("1.234", 1.234),
(1.234, 1.234),
("foo", "foo"),
(None, None),
]
)
def test_coerce_number(in_value, expected_out):
"""
Test helper function that coerces strings to float/int
"""
assert coerce_number(in_value) == expected_out
@pytest.mark.parametrize(
"in_value, expected_out",
[
(True, True),
(False, False),
("foo", "foo"),
("0.0", False),
("1", True),
("True", True),
("FALSE", False),
("Yes", True),
("no", False),
("Required", True),
("Not Required", False),
(None, False),
]
)
def test_coerce_bool(in_value, expected_out):
"""
Test helper function that coerces strings to booleans
"""
assert coerce_bool(in_value) == expected_out
def test_schema_clean():
"""
Test FieldDefinitionSchema.clean method
"""
schema = FieldDefinitionSchema()
# Test keys are all snake cased
in_data = {
"Label": None,
"Data Type": None,
}
out_data = schema.clean(in_data)
assert {"label", "data_type"} == set(out_data.keys())
# Test data_type default
assert out_data["data_type"] == "string"
# Test data_type casing
in_data["data_type"] = "Number"
out_data = schema.clean(in_data)
assert out_data["data_type"] == "number"
# Test accepted_values
in_data["accepted_values"] = None
out_data = schema.clean(in_data)
assert out_data["accepted_values"] is None
in_data["data_type"] = "foobar"
in_data["accepted_values"] = "1.0, 2.0, 3.0"
out_data = schema.clean(in_data)
assert out_data["accepted_values"] == ["1.0", "2.0", "3.0"]
assert out_data["data_type"] == "enum"
# Test missing values
in_data["missing_values"] = None
out_data = schema.clean(in_data)
assert out_data["missing_values"] is None
in_data["missing_values"] = "None, Unknown"
out_data = schema.clean(in_data)
assert ["None", "Unknown"] == out_data["missing_values"]
# Test empty strings handled properly
in_data["accepted_values"] = " "
in_data["missing_values"] = ""
in_data["required"] = " "
in_data["data_type"] = " "
out_data = schema.clean(in_data)
assert out_data["accepted_values"] is None
assert out_data["missing_values"] is None
assert out_data["required"] == False # noqa
assert out_data["data_type"] == "string"
def test_validation_error():
"""
Test custom handling of validation errors
"""
in_fields = {
"fields": [
{
"Key": "person.id",
"Label": "Person ID",
# Missing description, but has required keys
},
{
"Key": "specimen.id",
"Description": "Identifier for specimen"
# Missing label but has other required keys
}
]
}
schema = FieldDefinitionsSchema()
# Test custom validation message
with pytest.raises(ValidationError) as e:
schema.load(in_fields)
errors = e.value.messages[0]
assert "fields" not in errors
assert "Field Definition [1]" in errors
assert "Field Definition [Person ID]" in errors
# Test normal validation message
with pytest.raises(ValidationError) as e:
schema.load("foo")
assert {'_schema': ['Invalid input type.']} == e.value.messages
def test_schema_load():
"""
End to end test using the field definitions schema to clean and validate
input data
"""
in_fields = {
"fields": [
{
"Key": "person.id",
"Label": "Person ID",
"Description": "Identifier for person"
},
{
"Key": "specimen.id",
"Label": "Specimen ID",
"Description": "Identifier for specimen"
}
]
}
schema = FieldDefinitionsSchema()
data = schema.load(in_fields)
out_fields = data["fields"]
# Check version
assert data["schema_version"]["number"] == schema.SCHEMA_VERSION["number"]
# Check all fields are in output
assert len(out_fields) == len(in_fields["fields"])
# Check that defaults were set right and all components of a field
# definition are present in each field definition instance
for out in out_fields:
assert set(FieldDefinitionsSchema.key_order) == set(out.keys())
assert out["data_type"] == "string"
assert out["required"] == False # noqa
assert out["accepted_values"] is None
assert out["instructions"]is None
| [
"dukedesi22@gmail.com"
] | dukedesi22@gmail.com |
9044ef4372639411577526182e2432646d7b8420 | 1b0934b52c2db1ae96b74b51efc3747989b763e1 | /contacts/serializers.py | 8d5176072ed96dfcbc4b5430efc648b411275355 | [] | no_license | swarajgaidhane15/real_estate_app | 96f7f491ed0994c5f09f3dc654e9266e43a0b0cb | c2473194dcf1d160f54ae4e26446c037290b2775 | refs/heads/master | 2023-04-12T06:30:00.560571 | 2021-05-01T13:24:12 | 2021-05-01T13:24:12 | 359,822,992 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 191 | py | from rest_framework import serializers
from .models import Contact
class ContactSerializer(serializers.ModelSerializer):
class Meta:
model = Contact
fields = "__all__"
| [
"rutvikgaidhane1508@gmail.com"
] | rutvikgaidhane1508@gmail.com |
c091fb2e440475a0d6d7fdded18bfbd31026ea4e | 85398ab1933641284edb49f77ab2c8f21411129e | /gui/visualization.py | d146d659d4919965a7f2f37ae5ea136604a5d04a | [] | no_license | olavvatne/EANN | 4dcd030fab40548175f236c80cbaa8f13b4ba3aa | dd58375256dc83237f1678506ddb4e9eb53651f9 | refs/heads/master | 2021-01-16T22:51:49.080191 | 2015-04-08T18:45:48 | 2015-04-08T18:45:48 | 32,599,494 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,101 | py | from tkinter import Toplevel, Button
from simulator.environment import Environment
from tkinter import *
from tkinter import ttk
from enum import Enum
from math import fabs, floor
from gui.elements import LabelledSelect
from collections import deque
#Subclass of the tkinters Canvas object. Contains methods
#for setting a graph model and drawing a graph, and changing
#the vertices' colors.
class PixelDisplay(Canvas):
cWi = 500
cHi = 500
def __init__(self, parent):
self.queue = deque([])
self.model = None
self.width = self.cWi
self.height = self.cHi
self.padding = int(self.width/64)
self.parent = parent
self.offset = 1
self.event_rate = 400
self._callback_id = None
super().__init__(parent, bg='white', width=self.width, height=self.height, highlightthickness=0)
def set_rate(self, n):
self.event_rate = n
def set_model(self, model):
self.model = model
def get_model(self):
return self.model
def draw(self):
'''
Draw will call itself and redraw (colorize nodes) as long
as the display is in running mode or there are timeslices left
in the queue. The queue of timeslices allow the algorithm to run at
full speed while the display is delaying the rendering, so it is easy to
watch it's progress
Draw will pop a timeslice from the draw queue, and
use it's data to draw the partial solution on screen.
Each cell will be assigned a color, and a arrow/point to indicate
direction the cell gives its output.
'''
if len(self.queue)>0:
timeslice = self.queue.popleft()
if timeslice:
self.draw_model(timeslice)
if not self.stopped or len(self.queue) > 0:
self._callback_id =self.after(self.event_rate, self.draw)
def colorize_item(self, item, color):
self.itemconfig(item, fill=color)
def draw_label(self, x_pos, y_pos, w, h, text,t="label", c="black"):
x = self.translate_x(x_pos)
y = self.translate_y(y_pos)
w = self.translate_y(x_pos + w)
h = self.translate_y(y_pos + h)
penalty = len(text)
font_size = 35 -penalty*2
font = ("Helvetica", font_size, "bold")
self.create_text((x+w)/2, (y+h)/2, text=text, tags=t, fill=c, font=font)
#Method for drawing a graph from a ProblemModel.
#Draws the model and add tags so individual nodes can later
#be changed.
def draw_model(self, timeslice):
pass
def start(self):
self.stopped = False
self.draw()
def stop(self):
self.after_cancel(self._callback_id)
self.stopped = True
#The actual x position of the graph element on screen
def translate_x(self, x):
self.padding = 0
x_norm = fabs(self.min_x) + x
available_width = min(self.width, self.height)
x_screen = (self.padding/2) + x_norm*(float((available_width-self.padding)/self.w))
return x_screen
#The actual y position of the graph element on screen
def translate_y(self, y):
self.padding = 0
available_height= min(self.width, self.height)
y_norm = fabs(self.min_y) + y
y_screen = (self.padding/2) + y_norm*(float((available_height-self.padding)/self.h))
return y_screen
def reset(self):
self.delete(ALL)
def set_padding(self, padding):
self.padding = padding
#draws a cell.
def draw_pixel(self, x,y, w, h, c, tag=""):
self.create_rectangle(self.translate_x(x),
self.translate_y(y),
self.translate_x(x+w),
self.translate_y(y+h),
fill=c,
tags=tag)
def draw_rounded(self, x_pos, y_pos, width, height, color, rad=5, tags="", padding=0, line="black"):
x = self.translate_x(x_pos)+padding
y = self.translate_y(y_pos)+padding
w = self.translate_x(x_pos+width)-padding
h = self.translate_y(y_pos+height)-padding
self.create_oval(x, y, x +rad, y + rad, fill=color, tag=tags, width=1, outline=line)
self.create_oval(w -rad, y, w, y + rad, fill=color, tag=tags, width=1, outline=line)
self.create_oval(x, h-rad, x +rad, h, fill=color, tag=tags, width=1, outline=line)
self.create_oval(w-rad, h-rad, w , h, fill=color, tag=tags, width=1, outline=line)
self.create_rectangle(x + (rad/2.0), y, w-(rad/2.0), h, fill=color, tag=tags, width=0)
self.create_rectangle(x , y + (rad/2.0), w, h-(rad/2.0), fill=color, tag=tags, width=0)
def set_dimension(self, max_x, max_y, min_x, min_y):
self.w = fabs(min_x) + max_x
self.h = fabs(min_y) + max_y
self.max_x = max_x
self.max_y = max_y
self.min_y = min_y
self.min_x = min_x
def set_queue(self, data):
self.queue.clear()
self.queue.extend(data)
def event(self, data):
self.queue.append(data)
class FlatlandsDisplay(PixelDisplay):
def __init__(self, parent, dim):
super().__init__(parent)
self.dim = dim
self.bg = "#bbada0"
self.empty_cell = "#ccc0b3"
self.set_dimension(self.dim, self.dim, 0, 0 )
self.draw_board()
def draw_board(self):
self.reset()
self.draw_pixel(0, 0, self.dim, self.dim, self.bg, tag="bg")
for i in range(self.dim):
for j in range(self.dim):
self.draw_rounded(i,j, 1, 1, self.empty_cell, padding=2, line=self.bg, tags="bg")
def draw_model(self, timeslice):
if timeslice:
t, x,y,dir,b = timeslice
self.delete("Piece")
for i in range(self.dim):
for j in range(self.dim):
tile = b[i][j]
if tile > 0:
self.draw_piece("Piece", j, i, tile)
self.draw_piece("Piece", x,y, 3)
self.draw_direction("Piece", x, y, dir)
self.create_text(20, 20, font=("Arial",20), text=str(t+1), fill="white", tags="Piece")
def draw_direction(self,id, tx, ty ,dir):
x = self.translate_x(tx)
y = self.translate_y(ty)
x2 = self.translate_x(tx+1)
y2 = self.translate_y(ty+1)
if dir == Environment.WEST:
self.create_line(x, (y+y2)/2,(x+x2)/2 ,(y+y2)/2, tags=id, fill="#F5C60A", width=3)
elif dir == Environment.NORTH:
self.create_line((x+x2)/2, y,(x+x2)/2 ,(y+y2)/2, tags=id, fill="#F5C60A", width=3)
elif dir == Environment.SOUTH:
self.create_line((x+x2)/2, y2,(x+x2)/2 ,(y+y2)/2, tags=id, fill="#F5C60A", width=3)
else:
self.create_line((x+x2)/2, (y+y2)/2, x2 ,(y+y2)/2, tags=id, fill="#F5C60A", width=3)
def draw_piece(self, piece_id, x, y, piece_type):
self.draw_rounded(x,y, 1, 1, self._get_color(piece_type), padding=8, line=self.bg, tags=piece_id)
#self.draw_label( x,y, 1,1, str(piece_id), t=piece_id)
def _get_color(self, type):
c = {1:"green", 2:"red", 3:"blue"}
return c.get(type)
class ResultDialog(object):
'''
The flatlands agent can be visualized by the resultDialog. The dialog consists of a pixel display, speed adjuster,
restart button, scenario list box and a new scenario button.
'''
def __init__(self, parent, individual, scenarios, config):
self.config = config
self.individual = individual
self.s = scenarios
#TODO: Generate a new scenario. But what to do for static?
self.dim = self.config["fitness"]["flatlands"]["parameters"]["grid_dimension"]
dynamic = self.config["fitness"]["flatlands"]["parameters"]["dynamic"]
if dynamic:
self.scenarios = [Environment(self.dim)]
self.current = self.scenarios[0]
else:
self.scenarios = scenarios
self.current = self.scenarios[0]
top = self.top = Toplevel(parent)
top.title("Flatlands - results")
top.grid()
self.canvas = FlatlandsDisplay(top, self.dim)
self.canvas.set_model(self.current)
self.canvas.grid(row=0, column=0, columnspan=5, sticky=N ,padx=4, pady=4)
self.v = StringVar()
speed_adjuster = Scale(top, from_=200, to=1000, command=self.set_speed,orient=HORIZONTAL, variable=self.v)
speed_adjuster.set(400)
speed_adjuster.grid(row=1, column=0,padx=4, pady=4)
self.scenario_select = LabelledSelect(top, list(range(len(self.scenarios)+1)), "Scenario", command=self.change_scenario)
self.scenario_select.grid(row=1, column=1,padx=4, pady=4)
restart_button = Button(top, text="Restart", command=self.reset)
restart_button.grid(row=1, column=4,padx=4, pady=4)
new_button = Button(top, text="New scenario", command=self.new_scenario)
new_button.grid(row=1, column=2,padx=4, pady=4)
finish_button = Button(top, text="OK", command=self.ok)
finish_button.grid(row=2, column=4,padx=4, pady=10)
self.record_agent()
def reset(self):
self.canvas.stop()
self.canvas.set_queue(self.recording)
self.canvas.start()
def set_speed(self, *args):
self.canvas.set_rate(int(self.v.get()))
def new_scenario(self):
self.scenarios.append(Environment(self.dim))
self.scenario_select.add_option(len(self.scenarios))
self.canvas.stop()
self.change_scenario(len(self.scenarios))
def change_scenario(self, picked):
print(picked)
self.current = self.scenarios[picked-1]
self.canvas.set_model(self.current)
self.canvas.stop()
self.record_agent()
def record_agent(self):
p = self.individual.phenotype_container.get_ANN()
self.current.score_agent(p, 60)
self.recording = self.current.get_recording()
print(self.recording)
self.canvas.set_queue(self.recording)
self.canvas.start()
def ok(self):
self.top.destroy() | [
"olavvatne@gmail.com"
] | olavvatne@gmail.com |
9a94ff41afbb90503d4a11767ceae7cee397f000 | 2a764b51f3c6b8d0032b31228bf3d2f9ae3d4ab7 | /firstPythonProject/globalAndLocalScopes.py | ec80d5bc97d87d29cf1be29d84620cec6fbdbcae | [] | no_license | Okles/python | c67a7007106778a3828077660846696dfa72e43d | 60eba9e5e6013be280f3b1c165580de1a60e6594 | refs/heads/master | 2020-03-16T23:17:50.907071 | 2018-06-29T14:23:45 | 2018-06-29T14:23:45 | 133,072,135 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 212 | py | def spam():
eggs = 99
bacon()
print(eggs)
#global variableName creates a global variable inside a function
def bacon():
ham = 101
eggs = 0
print(eggs)
spam()
eggs = 42
print(eggs) | [
"l.oklesinski@gmail.com"
] | l.oklesinski@gmail.com |
8b84f45fa19f09a482011666f1125ef4cea7f135 | a2cdc4b934d57da60190d250784af59d94ce6767 | /led8x8m/__init__.py | da50e3ff9e4d2345325ae3a97d5679d89cafdd90 | [
"MIT"
] | permissive | soundmaking/led8x8m | 1a9152a02e9d80b1b25200d7bd087d00b88ce5b8 | 383fe39c9e328951a25fd23298a4a4c11e8c964e | refs/heads/main | 2023-01-12T00:37:47.832057 | 2020-11-20T09:15:29 | 2020-11-20T09:15:29 | 310,889,233 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,485 | py | # led8x8m/__init__.py
import RPi.GPIO as IO
from time import sleep
class LedMatrix():
PIN_X = (12, 22, 27, 25, 17, 24, 23, 18)
PIN_Y = (21, 20, 26, 16, 19, 13, 6, 5)
matrix_buffer = [
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
]
def __init__(self):
IO.setwarnings(False)
IO.setmode(IO.BCM)
for pin_number in self.PIN_X + self.PIN_Y:
IO.setup(pin_number, IO.OUT)
def xy_on(self, x, y):
"""x and y are int 0-7"""
for index, pin in enumerate(self.PIN_X):
IO.output(pin, 1 if index == x else 0)
for index, pin in enumerate(self.PIN_Y):
IO.output(pin, 0 if index == y else 1)
def buffer_to_pins(self):
for y, row in enumerate(self.matrix_buffer):
for x, val in enumerate(row):
if val:
self.xy_on(x, y)
# sleep(0.00125)
if __name__ == '__main__':
ledmx = LedMatrix()
mode = input("\n/! choose mode, xy or buffer (x or b): ")
while mode == 'x':
print('\n/! set x and y ... ')
x = int(input('x (0-7): '))
y = int(input('y (0-7): '))
ledmx.xy_on(x, y)
while mode == 'b':
ledmx.buffer_to_pins()
print('error')
| [
"soundmaking@merfasmean.com"
] | soundmaking@merfasmean.com |
26b5977a9cdd6177a1d5b17a3b207e49b4f83eb4 | da6e2f791c8b4610775ecc4db273f2a8fc80a015 | /pixivrss.py | 4dba695605fe8a75fa939246eadbcf3bcb114dc7 | [
"CC0-1.0"
] | permissive | tsudoko/pixivrss | 5faf3e035c59bfe23fbed60498f677d75920ecca | b0b62a5f929f7365492e250bc9b1ee8c4afef5a7 | refs/heads/master | 2021-01-18T22:59:13.844762 | 2019-09-06T11:26:38 | 2019-09-06T11:26:38 | 41,524,243 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 4,465 | py | #!/usr/bin/env python3
# This work is subject to the CC0 1.0 Universal (CC0 1.0) Public Domain
# Dedication license. Its contents can be found in the LICENSE file or at:
# http://creativecommons.org/publicdomain/zero/1.0/
from datetime import datetime, timezone
from email.utils import formatdate as rfc822
from xml.sax.saxutils import escape
import argparse
import getpass
import hashlib
import os.path
import platform
import sys
import requests
CLIENT_ID = "bYGKuGVw91e0NMfPGp44euvGt59s"
CLIENT_SECRET = "HP3RmkgAmEGro0gn1x9ioawQE8WMfvLXDz3ZqxpK"
TIME_SECRET = "28c1fdd170a5204386cb1313c7077b34f83e4aaf4aa829ce78c231e05b0bae2c"
API_URL = "https://public-api.secure.pixiv.net/v1"
ILLUST_URL = "https://pixiv.net/i/{illust_id}"
THUMB_URL = "https://embed.pixiv.net/decorate.php?illust_id={}"
def get_access_token(username, password):
#timestamp = datetime.now(timezone.utc).isoformat(timespec='seconds') # python 3.6+
timestamp = datetime.now(timezone.utc).isoformat().rsplit('.')[0] + "+00:00"
timehash = hashlib.md5(timestamp.encode() + TIME_SECRET.encode()).hexdigest()
headers = {
"x-client-time": timestamp,
"x-client-hash": timehash,
}
auth = {
"username": username,
"password": password,
"grant_type": "password",
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
}
r = requests.post("https://oauth.secure.pixiv.net/auth/token", data=auth, headers=headers)
r = r.json()
if "response" not in r or "access_token" not in r['response']:
raise Exception("unexpected json:\n" + str(r))
return r['response']['access_token']
def get_following(access_token):
headers = {"Authorization": "Bearer " + access_token}
r = requests.get(API_URL + "/me/following/works.json", headers=headers)
r = r.json()
if "response" not in r:
raise Exception("unexpected json:\n" + str(r))
return r['response']
def make_rss(works):
def mkdate(d):
format_string = "%Y-%m-%d %H:%M:%S %z"
r = rfc822(datetime.strptime(d + " +0900", format_string).timestamp())
return r
now = rfc822(datetime.now().timestamp())
ver = platform.python_version()
print('<?xml version="1.0"?>')
print('<rss version="2.0">')
print("<channel>")
print(" <title>[pixiv] フォロー新着作品</title>")
print(" <link>http://www.pixiv.net/bookmark_new_illust.php</link>")
print(" <pubDate>" + now + "</pubDate>")
print(" <description />")
print(" <generator>pixivrss (Python " + ver + ")</generator>")
for i in works:
title = "「%s」/「%s」" % (i['title'], i['user']['name'])
url = ILLUST_URL.format(user_id=str(i['user']['id']), illust_id=str(i['id']))
thumb_available = i['age_limit'] == "all-age"
print("\n <item>")
print(" <title>" + escape(title) + "</title>")
print(" <link>" + escape(url) + "</link>")
print(" <description><![CDATA[")
if i['caption']:
print(" " + i['caption'].replace("\r\n", "<br />"))
if thumb_available:
print(" <br />")
if thumb_available:
print(' <img src="' + escape(THUMB_URL.format(i['id'])) + '" />')
print(" ]]></description>")
print(" <pubDate>" + mkdate(i['created_time']) + "</pubDate>")
print(" <guid>" + escape(url) + "</guid>")
print(" </item>")
print("</channel>")
print("</rss>")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--username")
parser.add_argument("-p", "--password")
parser.add_argument("-n", "--unattended", action="store_true", help="don't ask for credentials")
parser.add_argument("-t", "--token", help="use the API token instead of username/password; it's generated after logging in through the API and is usually valid for an hour")
args = parser.parse_args()
if not args.unattended and not args.token:
if not args.username:
args.username = input("Pixiv ID: ")
if not args.password:
args.password = getpass.getpass("Password: ")
if not ((args.username and args.password) or args.token):
raise Exception("not enough credentials")
if not args.token:
args.token = get_access_token(args.username, args.password)
make_rss(get_following(args.token))
if __name__ == "__main__":
main()
| [
"flan@flande.re"
] | flan@flande.re |
fb34fef5a994d27aa76b19358a3979cd8df5aaf8 | 26ce347a68ce7ab060ee6d60459b0fb33a61b155 | /lesson1_4_name_spaces_and_scopes.py | 483e54fc2942f0da50f476a2922395f4ee595eb5 | [] | no_license | ekstash/stepik_python_course | d7864bdeb1bd501cf69f85702f1a0c5f48917a85 | 342b2b6b196af90a891957ac8f8300f2361451f6 | refs/heads/main | 2023-02-05T15:48:14.425728 | 2020-12-28T20:55:26 | 2020-12-28T20:55:26 | 321,792,701 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 707 | py | # большая часть урока понятна и так, но есть интересные моменты, о которых я не задумывалась.
for i in range(5):
x = i * i
print(x) # здесь x создастся как глобальная переменная.
x = 0
def function():
global x # работаем с глобальной переменной x. Именно глобальной, это не работает для функции в функции
x = 1
print(x) # x=1
def f():
x = 0
def g():
nonlocal x # возьмет x из ближайшего пространства имен, содержащего x
x = 1 | [
"ekstash@yandex.ru"
] | ekstash@yandex.ru |
df42974f8feaba118778818317b26cfb50904473 | 94c9bcf833689a7f64099531bfb67ca827eb9bf8 | /bot/modules/rclone.py | d7cf48216f67dccb84926ea1e0cadbedffd9f717 | [] | no_license | boyerharold033/ARPT-Bot | f9685140de2eafb0f5a99c9eabad276c9907621a | 644dc7c9018bb8586fcbbc27bd3dff2cccd20c93 | refs/heads/main | 2023-08-28T09:06:51.171170 | 2021-11-10T13:16:48 | 2021-11-10T13:16:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,776 | py | import time
import subprocess
import sys
import re
import json
import os
import threading
import requests
from config import Rclone_share,Aria2_secret
from modules.control import cal_time,only_progessbar
def hum_convert(value):
value=float(value)
units = ["B", "KB", "MB", "GB", "TB", "PB"]
size = 1024.0
for i in range(len(units)):
if (value / size) < 1:
return "%.2f%s" % (value, units[i])
value = value / size
async def start_rclonecopy(client, message):
try:
firstdir = message.text.split()[1]
seconddir= message.text.split()[2]
print(f"rclone {firstdir} {seconddir}")
sys.stdout.flush()
rc_url = f"http://root:{Aria2_secret}@127.0.0.1:5572"
info = await client.send_message(chat_id=message.chat.id, text=f"添加任务:", parse_mode='markdown')
rcd_copyfile_url = f"{rc_url}/sync/copy"
data = {
"srcFs": firstdir,
"dstFs": seconddir,
"createEmptySrcDirs": True,
"_async": True,
}
html = requests.post(url=rcd_copyfile_url, json=data)
result = html.json()
jobid = result["jobid"]
rcd_status_url = f"{rc_url}/job/status"
while requests.post(url=rcd_status_url, json={"jobid": jobid}).json()['finished'] == False:
job_status = requests.post(url=f"{rc_url}/core/stats", json={"group": f"job/{jobid}"}).json()
print(job_status)
if "transferring" in job_status:
if job_status['eta'] == None:
eta = "暂无"
else:
eta = cal_time(job_status['eta'])
print(f"剩余时间:{eta}")
text = f"任务ID:`{jobid}`\n" \
f"源地址:`{firstdir}`\n" \
f"目标地址:`{seconddir}`\n" \
f"传输部分:`{hum_convert(job_status['bytes'])}/{hum_convert(job_status['totalBytes'])}`\n" \
f"传输进度:`{only_progessbar(job_status['bytes'], job_status['totalBytes'])}%`\n" \
f"传输速度:`{hum_convert(job_status['speed'])}/s`\n" \
f"剩余时间:`{eta}`"
try:
await client.edit_message_text(text=text, chat_id=info.chat.id, message_id=info.message_id,
parse_mode='markdown')
except:
continue
else:
print("等待信息")
time.sleep(1)
requests.post(url=f"{rc_url}/core/stats-delete", json={"group": f"job/{jobid}"}).json()
requests.post(url=f"{rc_url}/fscache/clear").json()
except Exception as e:
print(f"rclonecopy :{e}")
sys.stdout.flush()
async def start_rclonecopyurl(client, message):
try:
url = message.text.split()[1]
print(f"rclonecopyurl {url} ")
sys.stdout.flush()
rc_url = f"http://root:{Aria2_secret}@127.0.0.1:5572"
Rclone_remote = os.environ.get('Remote')
Upload = os.environ.get('Upload')
title = os.path.basename(url)
info = await client.send_message(chat_id=message.chat.id, text=f"添加任务:`{title}`", parse_mode='markdown')
rcd_copyfile_url = f"{rc_url}/operations/copyurl"
data = {
"fs": f"{Rclone_remote}:{Upload}",
"remote": "",
"url": url,
"autoFilename": True,
"_async": True,
}
html = requests.post(url=rcd_copyfile_url, json=data)
result = html.json()
jobid = result["jobid"]
rcd_status_url = f"{rc_url}/job/status"
while requests.post(url=rcd_status_url, json={"jobid": jobid}).json()['finished'] == False:
job_status = requests.post(url=f"{rc_url}/core/stats", json={"group": f"job/{jobid}"}).json()
if "transferring" in job_status:
if job_status['transferring'][0]['eta'] == None:
eta = "暂无"
else:
eta = cal_time(job_status['transferring'][0]['eta'])
text = f"任务ID:`{jobid}`\n" \
f"任务名称:`{title}`\n" \
f"传输部分:`{hum_convert(job_status['transferring'][0]['bytes'])}/{hum_convert(job_status['transferring'][0]['size'])}`\n" \
f"传输进度:`{job_status['transferring'][0]['percentage']}%`\n" \
f"传输速度:`{hum_convert(job_status['transferring'][0]['speed'])}/s`\n" \
f"平均速度:`{hum_convert(job_status['transferring'][0]['speedAvg'])}/s`\n" \
f"剩余时间:`{eta}`"
try:
await client.edit_message_text(text=text, chat_id=info.chat.id, message_id=info.message_id,
parse_mode='markdown')
except:
continue
else:
print("等待信息加载")
time.sleep(1)
requests.post(url=f"{rc_url}/core/stats-delete", json={"group": f"job/{jobid}"}).json()
requests.post(url=f"{rc_url}/fscache/clear").json()
print("上传结束")
except Exception as e:
print(f"rclonecopy :{e}")
sys.stdout.flush()
async def start_rclonelsd(client, message):
try:
firstdir = message.text.split()[1]
child1 = subprocess.Popen(f'rclone lsd {firstdir}',shell=True, stdout=subprocess.PIPE)
out = child1.stdout.read()
print(out)
i = str(out,encoding='utf-8').replace(" ","")
print(i)
await client.send_message(chat_id=message.chat.id,text=f"`{str(i)}`",parse_mode='markdown')
except Exception as e:
print(f"rclonelsd :{e}")
sys.stdout.flush()
async def start_rclonels(client, message):
try:
firstdir = message.text.split()[1]
child1 = subprocess.Popen(f'rclone lsjson {firstdir}',shell=True, stdout=subprocess.PIPE)
out = child1.stdout.read()
print(out)
i = str(out,encoding='utf-8').replace("","")
print(i)
info=i.replace("[\n","").replace("\n]","")
print(info)
info_list=info.split(",\n")
print(info_list)
text=""
for a in info_list:
new=json.loads(a)
print(new)
filetime=str(new['ModTime']).replace("T"," ").replace("Z"," ")
text=text+f"{filetime}--{new['Name']}\n"
await client.send_message(chat_id=message.chat.id,text=f"`{text}`",parse_mode='markdown')
except Exception as e:
print(f"rclone :{e}")
sys.stdout.flush()
| [
"769020367@qq.com"
] | 769020367@qq.com |
dba3ee426705b4ed70feb471665fa78dfd7174d7 | 73bebf4fc3cf6b72193292c92ae2228f62facb3f | /utcnormal.py | 3468b870b7447a5982c82bb5dba4fa761bda47d6 | [] | no_license | Atari-Frosch/utcnormalise | 4bfe9720e34c2a67c790994d97b4ccc1b2f54f22 | 2fb5869dace892011a31b310ae6d61ec5b42d303 | refs/heads/master | 2016-09-11T12:43:04.417008 | 2015-04-16T17:57:49 | 2015-04-16T17:57:49 | 34,066,257 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,933 | py | #!/usr/bin/env python
# coding: utf8
import datetime
'''
This works only as long as the difference to UTC is in full hours!
'''
class date_normaliser(object):
def invert_utcdiff(self, utc):
if "+" in utc:
if utc == "+0":
utcdiff = 0
else:
utcdiff = 0 - int(utc[1:])
elif "-" in utc:
utcdiff = int(utc[1:])
else:
utcdiff = "ERROR"
return utcdiff
def check_leapyear(self, myDate):
myYear = int(myDate[0] + myDate[1] + myDate[2] + myDate[3])
leapyear = False
if myYear % 4 == 0:
leapyear = True
if myYear % 100 == 0:
leapyear = False
return leapyear
def utc_normalise(self, myTimestamp):
myTimestamp = myTimestamp.split(" ")
myDate = myTimestamp[0] + " " + myTimestamp[1]
utc = myTimestamp[2]
utcdiff = self.invert_utcdiff(utc)
myYear = myDate[0] + myDate[1] + myDate[2] + myDate[3]
myMonth = int(myDate[5] + myDate[6])
myDay = int(myDate[8] + myDate[9])
myHour = int(myDate[11] + myDate[12])
myMinute = int(myDate[14] + myDate[15])
mySecond = int(myDate[17] + myDate[18])
if utcdiff == 0:
outTimestamp = myDate
elif utcdiff > 0:
if myHour + utcdiff > 23:
myHour = 24 - myHour - utcdiff
myDay +=1
leapyear = self.check_leapyear(myDate)
if leapyear:
if myMonth == 2:
if myDay == 29:
myDay = 1
myMonth = 3
elif myDay == 28:
myDay = 29
else:
if myMonth == 2 and myDay == 28:
myDay = 1
myMonth = 3
if myMonth == 1 or myMonth == 3 or myMonth == 5 or myMonth == 7 or myMonth == 8 or myMonth == 10 or myMonth == 12:
if myDay > 31:
myDay = 1
myMonth += 1
if myMonth > 12:
myMonth = 1
myYear += 1
elif myMonth == 4 or myMonth == 6 or myMonth == 9 or myMonth == 11:
if myDay > 30:
myDay = 1
myMonth += 1
else:
myHour = myHour + utcdiff
elif utcdiff < 0:
if myHour + utcdiff < 0:
myHour = 24 - myHour + utcdiff
myDay -= 1
if myDay == 0:
if myMonth == 1 or myMonth == 2 or myMonth == 4 or myMonth == 6 or myMonth == 8 or myMonth == 9 or myMonth == 11:
myDay = 31
myMonth -= 1
if myMonth == 0:
myMonth = 1
myYear -= 1
elif myMonth == 5 or myMonth == 7 or myMonth == 10 or myMonth == 12:
myDay = 30
myMonth -= 1
elif myMonth == 3:
leapyear = self.check_leapyear(myDate)
myMonth = 2
if leapyear:
myDay = 29
else:
myDay = 28
else:
myHour = myHour + utcdiff
myYear = str(myYear)
myMonth = str(myMonth)
if len(myMonth) == 1:
myMonth = "0" + myMonth
myDay = str(myDay)
if len(myDay) == 1:
myDay = "0" + myDay
myHour = str(myHour)
if len(myHour) == 1:
myHour = "0" + myHour
myMinute = str(myMinute)
if len(myMinute) == 1:
myMinute = "0" + myMinute
mySecond = str(mySecond)
if len(mySecond) == 1:
mySecond = "0" + mySecond
outTimestamp = myYear + "-" + myMonth + "-" + myDay + " " + myHour + ":" + myMinute + ":" + mySecond + " +0"
return outTimestamp
myNormaliser = date_normaliser()
sourcefile = "spammail.lst"
source = open(sourcefile, "r")
fulltext = source.read()
source.close()
myLines = fulltext.split("\n")
targetfile = "spammail-utc.lst"
target = open(targetfile, "w")
for i in range(len(myLines)):
# tmpout = "myLines[" + str(i) + "] = " + myLines[i]
# print tmpout
if myLines[i] != "":
currentLine = myLines[i].split(" ")
myTimestamp = currentLine[0] + " " + currentLine[1] + " " + currentLine[2].replace(",", "")
outTimestamp = myNormaliser.utc_normalise(myTimestamp)
outLine = outTimestamp + ", " + currentLine[3] + " " + currentLine[4] + " " + currentLine[5] + " " + currentLine[6] + "\n"
target.write(outLine)
target.close()
| [
"frosch@atari-frosch.de"
] | frosch@atari-frosch.de |
7e8548d8a6de1e92bfe9ae3a868ce13ea025c259 | cc4f5f736adef13c5d259b4d061681bdef238576 | /great_expectations/expectations/metrics/column_aggregate_metrics/column_min.py | 7b82733a813ca0aafa863bd643df5dce22d26e90 | [
"Apache-2.0"
] | permissive | chsigjan/great_expectations | 3f133271abd24c4ea1d9d6b8cfada83fd58f520a | 56d048f4cca073154ce67ca9696a75917ad8c81c | refs/heads/main | 2023-08-12T08:41:52.709139 | 2021-09-30T15:51:40 | 2021-09-30T15:51:40 | 412,717,483 | 1 | 0 | Apache-2.0 | 2021-10-02T06:59:22 | 2021-10-02T06:59:21 | null | UTF-8 | Python | false | false | 1,054 | py | from great_expectations.execution_engine import (
PandasExecutionEngine,
SparkDFExecutionEngine,
)
from great_expectations.execution_engine.sqlalchemy_execution_engine import (
SqlAlchemyExecutionEngine,
)
from great_expectations.expectations.metrics.column_aggregate_metric_provider import (
ColumnAggregateMetricProvider,
column_aggregate_partial,
column_aggregate_value,
)
from great_expectations.expectations.metrics.column_aggregate_metric_provider import (
sa as sa,
)
from great_expectations.expectations.metrics.import_manager import F
class ColumnMin(ColumnAggregateMetricProvider):
metric_name = "column.min"
@column_aggregate_value(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.min()
@column_aggregate_partial(engine=SqlAlchemyExecutionEngine)
def _sqlalchemy(cls, column, **kwargs):
return sa.func.min(column)
@column_aggregate_partial(engine=SparkDFExecutionEngine)
def _spark(cls, column, **kwargs):
return F.min(column)
| [
"noreply@github.com"
] | noreply@github.com |
e695d0df27a389029524c11afe920770636319d2 | d6d2b61aeb44b3e9fbed8fd9839f1e8abaaf74a8 | /tests/unit/peapods/runtimes/container/test_container_runtime.py | 42143d96d76a7c4656cd9f57f01a92854cdd3430 | [
"Apache-2.0"
] | permissive | 10zinten/jina | b9776b8e28fc546e7eb205b67857ebbf56bcc51d | f18b04eb82d18a3c554e2892bbae4b95fc0cb13e | refs/heads/master | 2023-08-26T22:01:58.578591 | 2021-10-25T23:06:49 | 2021-10-25T23:06:49 | 400,064,091 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,029 | py | import os
import time
from sys import platform
import multiprocessing
import pytest
from jina.checker import NetworkChecker
from jina.executors import BaseExecutor
from jina.executors.decorators import requests
from jina import Flow, __windows__
from jina.helper import random_name
from jina.parsers import set_pea_parser
from jina.parsers.ping import set_ping_parser
from jina.peapods import Pea
from jina.peapods.runtimes.container import ContainerRuntime
from jina.peapods.runtimes.container.helper import get_gpu_device_requests
from tests import random_docs, validate_callback
if __windows__:
pytest.skip(msg='Windows containers are not supported yet', allow_module_level=True)
cur_dir = os.path.dirname(os.path.abspath(__file__))
img_name = 'jina/mwu-encoder'
defaulthost = '0.0.0.0'
@pytest.fixture
def _logforward():
class _LogForward(BaseExecutor):
@requests
def foo(self, **kwargs):
pass
return _LogForward
@pytest.fixture(scope='module')
def docker_image_built():
import docker
client = docker.from_env()
client.images.build(path=os.path.join(cur_dir, 'mwu-encoder/'), tag=img_name)
client.close()
yield
time.sleep(2)
client = docker.from_env()
client.containers.prune()
def test_simple_container(docker_image_built):
args = set_pea_parser().parse_args(['--uses', f'docker://{img_name}'])
with Pea(args):
pass
time.sleep(2)
Pea(args).start().close()
def test_flow_with_one_container_pod(docker_image_built):
f = Flow().add(name='dummyEncoder1', uses=f'docker://{img_name}')
with f:
f.post(on='/index', inputs=random_docs(10))
def test_flow_with_one_container_pod_shards(docker_image_built):
f = Flow().add(name='dummyEncoder1', shards=2, uses=f'docker://{img_name}')
with f:
pod = f._pod_nodes['dummyEncoder1']
assert pod.args.shards == pod.args.parallel == 2
for idx, shard in enumerate(pod.shards):
assert shard.args.pea_id == shard.args.shard_id == idx
assert shard.args.shards == shard.args.parallel == 2
f.post(on='/index', inputs=random_docs(10))
def test_flow_with_replica_container_ext_yaml(docker_image_built):
f = Flow().add(
name='dummyEncoder3',
uses=f'docker://{img_name}',
shards=3,
entrypoint='jina pea',
)
with f:
f.post(on='/index', inputs=random_docs(10))
f.post(on='/index', inputs=random_docs(10))
f.post(on='/index', inputs=random_docs(10))
def test_flow_topo1(docker_image_built):
f = (
Flow()
.add(
name='d0',
uses='docker://jinaai/jina:test-pip',
entrypoint='jina executor',
)
.add(
name='d1',
uses='docker://jinaai/jina:test-pip',
entrypoint='jina executor',
)
.add(
name='d2',
uses='docker://jinaai/jina:test-pip',
needs='d0',
entrypoint='jina executor',
)
.join(['d2', 'd1'])
)
with f:
f.post(on='/index', inputs=random_docs(10))
def test_flow_topo_mixed(docker_image_built, _logforward):
f = (
Flow()
.add(
name='d4',
uses='docker://jinaai/jina:test-pip',
entrypoint='jina executor',
)
.add(name='d5', uses=_logforward)
.add(
name='d6',
uses='docker://jinaai/jina:test-pip',
needs='d4',
entrypoint='jina executor',
)
.join(['d6', 'd5'])
)
with f:
f.post(on='/index', inputs=random_docs(10))
def test_flow_topo_shards():
f = (
Flow()
.add(
name='d7',
uses='docker://jinaai/jina:test-pip',
entrypoint='jina executor',
shards=3,
)
.add(name='d8', shards=3)
.add(
name='d9',
uses='docker://jinaai/jina:test-pip',
entrypoint='jina executor',
needs='d7',
)
.join(['d9', 'd8'])
)
with f:
f.post(on='/index', inputs=random_docs(10))
def test_flow_topo_ldl_shards():
f = (
Flow()
.add(name='d10')
.add(
name='d11',
uses='docker://jinaai/jina:test-pip',
entrypoint='jina executor',
shards=3,
)
.add(name='d12')
)
with f:
f.post(on='/index', inputs=random_docs(10))
def test_container_ping(docker_image_built):
a4 = set_pea_parser().parse_args(['--uses', f'docker://{img_name}'])
a5 = set_ping_parser().parse_args(
['0.0.0.0', str(a4.port_ctrl), '--print-response']
)
# test with container
with pytest.raises(SystemExit) as cm:
with Pea(a4):
NetworkChecker(a5)
assert cm.value.code == 0
def test_tail_host_docker2local_shards():
f = (
Flow()
.add(
name='d10',
uses='docker://jinaai/jina:test-pip',
entrypoint='jina executor',
shards=3,
)
.add(name='d11')
)
with f:
assert getattr(f._pod_nodes['d10'].tail_args, 'host_out') == defaulthost
def test_tail_host_docker2local():
f = (
Flow()
.add(
name='d12',
uses='docker://jinaai/jina:test-pip',
entrypoint='jina executor',
)
.add(name='d13')
)
with f:
assert getattr(f._pod_nodes['d12'].tail_args, 'host_out') == defaulthost
def test_pass_arbitrary_kwargs(monkeypatch, mocker):
import docker
mock = mocker.Mock()
mocker.patch(
'jina.peapods.runtimes.container.ContainerRuntime.is_ready',
return_value=True,
)
class MockContainers:
class MockContainer:
def reload(self):
pass
def logs(self, **kwargs):
return []
def __init__(self):
pass
def get(self, *args):
pass
def run(self, *args, **kwargs):
mock_kwargs = {k: kwargs[k] for k in ['hello', 'environment']}
mock(**mock_kwargs)
assert 'ports' in kwargs
assert 'environment' in kwargs
assert kwargs['environment'] == ['VAR1=BAR', 'VAR2=FOO']
assert 'hello' in kwargs
assert kwargs['hello'] == 0
return MockContainers.MockContainer()
class MockClient:
def __init__(self, *args, **kwargs):
pass
def close(self):
pass
def version(self):
return {'Version': '20.0.1'}
@property
def networks(self):
return {'bridge': None}
@property
def containers(self):
return MockContainers()
@property
def images(self):
return {}
monkeypatch.setattr(docker, 'from_env', MockClient)
args = set_pea_parser().parse_args(
[
'--uses',
'docker://jinahub/pod',
'--docker-kwargs',
'hello: 0',
'environment: ["VAR1=BAR", "VAR2=FOO"]',
]
)
_ = ContainerRuntime(args, ctrl_addr='', ready_event=multiprocessing.Event())
expected_args = {'hello': 0, 'environment': ['VAR1=BAR', 'VAR2=FOO']}
mock.assert_called_with(**expected_args)
def test_pass_arbitrary_kwargs_from_yaml():
f = Flow.load_config(os.path.join(cur_dir, 'flow.yml'))
assert f._pod_nodes['executor1'].args.docker_kwargs == {
'hello': 0,
'environment': ['VAR1=BAR', 'VAR2=FOO'],
}
def test_container_override_params(docker_image_built, tmpdir, mocker):
def validate_response(resp):
assert len(resp.docs) > 0
for doc in resp.docs:
assert doc.tags['greetings'] == 'overriden greetings'
mock = mocker.Mock()
abc_path = os.path.join(tmpdir, 'abc')
f = Flow().add(
name=random_name(),
uses=f'docker://{img_name}',
volumes=abc_path + ':' + '/mapped/here/abc',
uses_with={'greetings': 'overriden greetings'},
uses_metas={
'name': 'ext-mwu-encoder',
'workspace': '/mapped/here/abc',
},
)
with f:
f.index(random_docs(10), on_done=mock)
assert os.path.exists(
os.path.join(abc_path, 'ext-mwu-encoder', '0', 'ext-mwu-encoder.bin')
)
validate_callback(mock, validate_response)
def test_container_volume(docker_image_built, tmpdir):
abc_path = os.path.join(tmpdir, 'abc')
f = Flow().add(
name=random_name(),
uses=f'docker://{img_name}',
volumes=abc_path + ':' + '/mapped/here/abc',
uses_metas={
'name': 'ext-mwu-encoder',
'workspace': '/mapped/here/abc',
},
)
with f:
f.index(random_docs(10))
assert os.path.exists(
os.path.join(abc_path, 'ext-mwu-encoder', '0', 'ext-mwu-encoder.bin')
)
@pytest.mark.parametrize(
(
'gpus_value',
'expected_count',
'expected_device',
'expected_driver',
'expected_capabilities',
),
[
('all', -1, [], '', [['gpu']]), # all gpus
('2', 2, [], '', [['gpu']]), # use two gpus
(
'device=GPU-fake-gpu-id',
0,
['GPU-fake-gpu-id'],
'',
[['gpu']],
), # gpu by one device id
(
'device=GPU-fake-gpu-id1,device=GPU-fake-gpu-id2',
0,
['GPU-fake-gpu-id1', 'GPU-fake-gpu-id2'],
'',
[['gpu']],
), # gpu by 2 device id
(
'device=GPU-fake-gpu-id,driver=nvidia,capabilities=utility,capabilities=display',
0,
['GPU-fake-gpu-id'],
'nvidia',
[['gpu', 'utility', 'display']],
), # gpu with id, driver and capability
(
'device=GPU-fake-gpu-id1,device=GPU-fake-gpu-id2,driver=nvidia,capabilities=utility',
0,
['GPU-fake-gpu-id1', 'GPU-fake-gpu-id2'],
'nvidia',
[['gpu', 'utility']],
), # multiple ids
],
)
def test_gpu_container(
gpus_value, expected_count, expected_device, expected_driver, expected_capabilities
):
args = set_pea_parser().parse_args(
['--uses', f'docker://{img_name}', '--gpus', gpus_value]
)
device_requests = get_gpu_device_requests(args.gpus)
assert device_requests[0]['Count'] == expected_count
assert device_requests[0]['DeviceIDs'] == expected_device
assert device_requests[0]['Driver'] == expected_driver
assert device_requests[0]['Capabilities'] == expected_capabilities
def test_pass_native_arg(monkeypatch, mocker):
import docker
mocker.patch(
'jina.peapods.runtimes.container.ContainerRuntime.is_ready',
return_value=True,
)
class MockContainers:
class MockContainer:
def reload(self):
pass
def logs(self, **kwargs):
return []
def __init__(self):
pass
def get(self, *args):
pass
def run(self, *args, **kwargs):
assert '--native' in args[1]
return MockContainers.MockContainer()
class MockClient:
def __init__(self, *args, **kwargs):
pass
def close(self):
pass
def version(self):
return {'Version': '20.0.1'}
@property
def networks(self):
return {'bridge': None}
@property
def containers(self):
return MockContainers()
@property
def images(self):
return {}
monkeypatch.setattr(docker, 'from_env', MockClient)
args = set_pea_parser().parse_args(
[
'--uses',
'docker://jinahub/pod',
]
)
_ = ContainerRuntime(args, ctrl_addr='', ready_event=multiprocessing.Event())
| [
"noreply@github.com"
] | noreply@github.com |
fb4a0f6047e8b49dd942360dcb017c97f5fe04f5 | a4b2e0612d765429e4dccd037daa3763eb54c12c | /code/model/comment.py | 92ee39692d72148be2a45e0a16ac3b0f2eb6de33 | [] | no_license | evertheylen/SmartHome | b98238ed43d1a39e08ae7e8f7deaea93505384db | 542468e7ba03f81be765a876797cdd0c7094f22b | refs/heads/master | 2020-04-10T19:09:14.047037 | 2016-05-19T11:08:59 | 2016-05-19T11:08:59 | 51,506,014 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 466 | py |
from sparrow import *
from .owentity import *
from .status import Status
from .user import User
class Comment(RTOwEntity):
key = CID = KeyProperty()
status = RTReference(Status)
author = RTReference(User)
date = Property(int)
date_edited = Property(int) # If they are the same, no edits
text = Property(str)
async def can_delete(self, usr_uid, db):
u = await User.find_by_key(self.author, db)
return u.key == usr_uid
| [
"hermans.anthony@hotmail.com"
] | hermans.anthony@hotmail.com |
845e06146026e7a00fd10824220dd35e50e2ccab | 127d8c209b00978f4f660534363e95eca3f514f2 | /backend/home/migrations/0002_load_initial_data.py | 110b21901b630cf3f96ad807523e091bfc8ac157 | [] | no_license | crowdbotics-apps/sitespace-19938 | afd070e64d32ab455f9b2b05e376152e9e28e5ad | 416b5cef0bdb25018ec3b634bf3096e61fe8b662 | refs/heads/master | 2022-12-10T15:52:58.601025 | 2020-09-02T15:20:15 | 2020-09-02T15:20:15 | 292,319,517 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,290 | py | from django.db import migrations
def create_customtext(apps, schema_editor):
CustomText = apps.get_model("home", "CustomText")
customtext_title = "Sitespace"
CustomText.objects.create(title=customtext_title)
def create_homepage(apps, schema_editor):
HomePage = apps.get_model("home", "HomePage")
homepage_body = """
<h1 class="display-4 text-center">Sitespace</h1>
<p class="lead">
This is the sample application created and deployed from the Crowdbotics app.
You can view list of packages selected for this application below.
</p>"""
HomePage.objects.create(body=homepage_body)
def create_site(apps, schema_editor):
Site = apps.get_model("sites", "Site")
custom_domain = "sitespace-19938.botics.co"
site_params = {
"name": "Sitespace",
}
if custom_domain:
site_params["domain"] = custom_domain
Site.objects.update_or_create(defaults=site_params, id=1)
class Migration(migrations.Migration):
dependencies = [
("home", "0001_initial"),
("sites", "0002_alter_domain_unique"),
]
operations = [
migrations.RunPython(create_customtext),
migrations.RunPython(create_homepage),
migrations.RunPython(create_site),
]
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
82dd296e5b4516cc622e3a206cb39c14e931ec3c | 84123de245cbea1c3d299421fec03401b27c274c | /Lecture 8 programming exercise/lecture8.3.largest.py | 43be0d2b64ebb00699f40518cbcb854c80297170 | [] | no_license | udanzo-p/Lectures38 | ae43801f6770a6f05a4fa7ef4bc57b597181e992 | 65128508931573517f4ef850d699ea95c780258c | refs/heads/master | 2020-12-12T21:31:29.949256 | 2020-02-04T08:54:41 | 2020-02-04T08:54:41 | 234,233,096 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 275 | py | import math
k=int(input())
target=int(input())
print("To find largest digit no. divisible by ",target)
pow=math.pow
a=(pow(10,k)-1)
while(int x=target):
if(a%target=0):
print("The largest no. divisible by is ",target,a)
else:
a=a-1
x=x-1
| [
"noreply@github.com"
] | noreply@github.com |
ba508a2958f5325258855671103405bc641ebe97 | a5e591dc09e11e88af56fb5a881fae064fb9c495 | /recruitment/recruitment/doctype/interview/interview.py | 0449ed7ff48f9261f3c429e7522f6aad25c3b49d | [
"MIT"
] | permissive | barathprathosh/recruitment | 6b61dd1ee9c0b9d7851b0b3e5bab307f7ee2d1b5 | 9660944856e72288e47960e6802ec97a220a656d | refs/heads/master | 2020-04-29T03:03:51.722972 | 2019-03-15T08:58:32 | 2019-03-15T08:58:32 | 175,794,797 | 0 | 0 | NOASSERTION | 2019-03-15T10:00:32 | 2019-03-15T10:00:31 | null | UTF-8 | Python | false | false | 250 | py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, VHRS and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Interview(Document):
pass
| [
"abdulla.pi@voltechgroup.com"
] | abdulla.pi@voltechgroup.com |
b63af80e07a7db51998cd62a6b59a52a243d8216 | ec0fe7fa7951a42dcf8fb9e3a910cc78ea58ab3d | /aeroctf/solution.py | 56610d813c8ea411df6bbbdb4ac618819f5cd4ca | [
"MIT"
] | permissive | S7uXN37/CTF-Writeups | 6111f70f0d811734cd8b4fcc41c73a0a4d582dc4 | ffbbae7e3c98bf47786d9996e114412325117a3a | refs/heads/master | 2021-02-08T18:59:25.115539 | 2020-04-20T16:04:36 | 2020-04-20T16:04:36 | 244,186,440 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,643 | py | from pwn import *
from binascii import *
from time import sleep
from z3 import *
ciphers = [
"7685737a9f7895737a9f84857b769f7a" + "657b769f78898378",
"717785747885858d6f7e917364686776",
"7393a992708d8fad708d83aa7273707d" + "6f3939856b7d398bb53b8b34b573b6c5618e7135"
]
plains = [
"test_test_test_t" + "est_test",
"qwertyuiopasdfgh",
"skIllaoInasJjklq" + "o19akq9k13k45k69alq1"
]
secret = "8185748f7b3b3a3565454584b8babbb8" + "b441323ebc8b3a86b5899283b9c2c56d64388889b781"
#for i in range(len(ciphers)):
# ciphers[i] = unhexlify(ciphers[i])
keysize = 16
# allowed key chars: 0-9, a-h
solver = Solver()
key = [BitVec("key" + str(i), 8) for i in range(keysize)]
for (p,c) in zip(plains, ciphers[:3]):
for pos in range(len(p)):
solver.add(int(c[2*pos:2*pos+2], 16) == (key[pos % 16] + (key[pos % 16] ^ ord(p[pos]))) & 0xff)
# constrain to aero{...}
start = "Aero{"
for i in range(len(start)):
v = int(secret[2*i:2*i+2], 16)
dec = ((v - key[i]) & 0xff) ^ key[i]
dec = dec & 0xff
solver.add( dec == ord(start[i]))
print("Solving...")
# Solve the equations
while solver.check() == sat:
modl = solver.model()
keyVals = [modl[key[i]].as_long() for i in range(keysize)]
#print("Found key: " + str(keyVals))
flag = [int(secret[2*pos:2*pos+2], 16) for pos in range(len(secret) // 2)]
flag = [((flag[i] - keyVals[i % 16]) & 0xff) ^ keyVals[i % 16] for i in range(len(flag))]
f = ""
for i in range(len(flag)):
f += chr(flag[i])
full_ascii = True
for c in f:
if ord(c) < 0x20 or ord(c) > 0x80:
full_ascii = False
if full_ascii:
print(f)
# Encryption works like:
# output byte = key[mod 16] + key[mod 16] ^ plain byte | [
"S7uXN37@users.noreply.github.com"
] | S7uXN37@users.noreply.github.com |
268ab70d2790ee69fd6584adc601abb2cb0fafbc | 05487c52248d7b185fadd7824d709c23c4877e43 | /modules/GuiWidgetManager.py | 291596dc304137d9d45439efd37e177776cb3ed0 | [
"MIT"
] | permissive | reality3d/molefusion | 6b3751bcb0c4350eccced2a2ffa1f3190cd610b0 | df6e3486a412777117aa63d68d169102065051fd | refs/heads/master | 2016-08-04T04:58:38.925897 | 2013-09-02T19:42:20 | 2013-09-02T19:42:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,027 | py | import pygame
from pygame.locals import *
from GW_TextInput import GW_TextInput
from Event import Event
from Constants import Constants
class GuiWidgetManager:
"Widget Manager Container"
def __init__(self , widgetlist):
"Sets up the widget Manager"
self.background=Constants.BACKGROUND
self.screen=Constants.SCREEN
self.widgets = pygame.sprite.RenderUpdates() #RenderUpdates Sprite Group type
self.widgetlist = widgetlist #internal list for indexable access
for widget in widgetlist:
self.widgets.add(widget)
self.currentfocus=-1 #by default no widgets focused
self.draw=True
def set_draw(self,value):
self.draw=value
def get_widgets(self):
return self.widgets
def has_input_focus(self):
return isinstance(self.currentfocus,GW_TextInput)
def run(self):
for event in pygame.event.get(): #Process events
if event.type == MOUSEMOTION:
for widget in self.widgetlist:
if(widget.get_active()): #Is active or disabled?
if(widget.get_rect().collidepoint(pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1])):
if(not widget.get_mouse_over()): #Was already mouse over it?
widget.notify(Event("onmouseover",event))
#print "onmouseover"
elif widget.get_mouse_over(): #Widget was mouseover and mouse has gone out
widget.notify(Event("onmouseout",event))
#print "onmouseout"
elif event.type == MOUSEBUTTONDOWN and event.button==1: #Left Mouse click
for widget in self.widgetlist:
if(widget.get_active()):
if(widget.get_rect().collidepoint(pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1])):
widget.notify(Event("onmouseclick",event))
#print "onmouseclick"
if(not widget.get_focus()):
widget.notify(Event("onfocus",event))
self.currentfocus=widget
#print "onfocus"
elif widget.get_focus():
widget.notify(Event("onblur",event))
if(widget==self.currentfocus):#We could have put the focus already on another widget!
self.currentfocus=-1
#print "onblur"
elif event.type == MOUSEBUTTONUP and event.button==1:
for widget in self.widgetlist:
if(widget.get_active()):
if(widget.get_rect().collidepoint(pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1])):
widget.notify(Event("onmouseclickup",event))
elif event.type == KEYDOWN:
if(self.currentfocus!=-1):
if(self.currentfocus.get_active()):
if(isinstance(self.currentfocus,GW_TextInput)):
if(event.key!=K_ESCAPE and event.key!=K_RETURN):
self.currentfocus.notify(Event("onkeydown",event))
else:
self.currentfocus.notify(Event("onblur",event))
self.currentfocus=-1
else:
pygame.event.post(event) #Reinject the event into the queue for maybe latter process
if self.draw==True:
self.widgets.clear(self.screen,self.background)
self.widgets.update()
self.rectlist = self.widgets.draw(self.screen)
pygame.display.update(self.rectlist)
| [
"reality3d@gmail.com"
] | reality3d@gmail.com |
7a80572cd829ac7a970a7e869f590fbca51c840e | b410a506bd4bdbbc55a770ab76e0507625ebb52e | /app/admin/forms.py | 651179a851d4b8765a8b9efd99cd96820ecce34e | [] | no_license | fadebowaley/MO-App | 6a219a984c89c2dd0601a6f3f3d46810b644dcb3 | b7de965390d69e349533765db0ac190e8a67684b | refs/heads/main | 2023-08-24T06:17:17.510741 | 2021-09-14T12:31:30 | 2021-09-14T12:31:30 | 403,637,924 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 694 | py | from flask_wtf import FlaskForm
from wtforms import Form, FieldList, StringField, StringField, SubmitField, BooleanField, \
PasswordField, TextAreaField, SubmitField, FormField, SelectField,\
FileField, IntegerField, TextField, FieldList
from wtforms.validators import DataRequired, Length,ValidationError, InputRequired
from flask_wtf.file import FileField, FileAllowed
from wtforms.fields.html5 import DateTimeField, DateField
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.validators import ValidationError, DataRequired, Length
#from flask_babel import _, lazy_gettext as _l
from flask_login import current_user, login_required
from app.models import User
| [
"fadebowaley@gmail.com"
] | fadebowaley@gmail.com |
1b97ca333f9999257c9f67250e6f7ea46ba7df58 | 605936a6e51061b25dd04b688ddab41f10c24153 | /Easter Competition.py | 9bacdd0f037d3c209eb241e3a89588453b2e855f | [] | no_license | EmanuilManev/Python | d8e16f8c48ef55d9ef6063eb7702fea94b5078f5 | 8f0f454ebba08857c3bfcd76db75e6dd3bb6de84 | refs/heads/master | 2021-04-11T02:36:55.146516 | 2020-03-23T14:08:47 | 2020-03-23T14:08:47 | 248,986,319 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 533 | py | kozunak = int(input())
index = 1
vhod = str("")
score = 0
m_score = 0
top_chef = str("")
for index in range(kozunak):
chef = input()
while vhod != "Stop":
vhod = input()
if vhod != "Stop":
score += int(vhod)
print(str(chef) + " has " + str(score) + " points.")
if score > m_score:
m_score = score
top_chef = chef
print(str(chef) + " is the new number 1!")
vhod = str("")
score = 0
print(str(top_chef) + " won competition with " + str(m_score) + " points!")
| [
"noreply@github.com"
] | noreply@github.com |
3d033f53f447828b966051b34b7913e92aa9b31b | 772a1fad7ff949c41920004579166fcab58af7a5 | /app/main/views.py | 198cfee8dab5b104352c62526b6aa218495243ed | [
"MIT"
] | permissive | saudahabib/news_highlight | c29a461ba185be23fd0a183239af245557f11d6c | 6d59b85b93497e14e988be2bf9e0fb358d871622 | refs/heads/master | 2020-05-09T10:02:56.993083 | 2019-04-17T08:00:00 | 2019-04-17T08:00:00 | 181,026,997 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 924 | py | from flask import render_template
from . import main
from ..request import get_sources, get_source, get_articles
from ..models import Article, Source
#Views
@main.route('/')
def index():
'''
View root page that returns the index page and its data
'''
sources = get_sources()
articles = get_articles('kenya')
title = "All the spice, under one roof"
return render_template('index.html', title = title, sources = sources, articles = articles)
@main.route('/news/<int:news_id>')
def news(news_id):
'''
View news page function that returns page with news
'''
return render_template('news.html', id = news_id)
@main.route('/source/<int:id>')
def source(id):
'''
View source page function that returns the source details page and its data
'''
source = get_source(id)
name = f'{source.name}'
return render_template('news.html',name = name, source = source)
| [
"saudababs00@gmail.com"
] | saudababs00@gmail.com |
19caab41b1e7e5822d71d8e70217b1ac6dda3b67 | 847273de4b1d814fab8b19dc651c651c2d342ede | /.history/Sudoku_II_005_20180620141234.py | 396d0dea7f396d2fdc9165bfceb7cd75b20f3c37 | [] | no_license | Los4U/sudoku_in_python | 0ba55850afcffeac4170321651620f3c89448b45 | 7d470604962a43da3fc3e5edce6f718076197d32 | refs/heads/master | 2020-03-22T08:10:13.939424 | 2018-07-04T17:21:13 | 2018-07-04T17:21:13 | 139,749,483 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 4,622 | py | from random import randint
sudoku1 = [
[5, 9, 8, 6, 1, 2, 3, 4, 7],
[2, 1, 7, 9, 3, 4, 8, 6, 5],
[6, 4, 3, 5, 8, 7, 1, 2, 9],
[1, 6, 5, 4, 9, 8, 2, 7, 3],
[3, 2, 9, 7, 6, 5, 4, 1, 8],
[7, 8, 4, 3, 2, 1, 5, 9, 6],
[8, 3, 1, 2, 7, 6, 9, 5, 4],
[4, 7, 2, 8, 5, 9, 6, 3, 1],
[9, 5, 6, 1, 4, 3, 7, 8, " "]
]
sudoku2 = [
[9, 8, 7, 4, 3, 2, 5, 6, 1],
[2, 4, 3, 5, 1, 6, 8, 7, 9],
[5, 6, 1, 7, 9, 8, 4, 3, 2],
[3, 9, 5, 6, 4, 7, 2, 1, 8],
[8, 2, 4, 3, 5, 1, 6, 9, 7],
[1, 7, 6, 2, 8, 9, 3, 4, 5],
[7, 1, 2, 8, 6, 3, 9, 5, 4],
[4, 3, 8, 9, 7, 5, 1, 2, 6],
[' ', 5, ' ', ' ', 2, ' ', 7, ' ', ' ']
]
sudoku3 = [
[9, 8, 7, 4, 3, 2, 5, 6, 1],
[2, 4, 3, 5, 1, 6, 8, 7, 9],
[5, 6, 1, 7, 9, 8, 4, 3, 2],
[3, 9, 5, 6, 4, 7, 2, 1, 8],
[8, 2, 4, 3, 5, 1, 6, 9, 7],
[1, 7, 6, 2, 8, 9, 3, 4, 5],
[7, 1, 2, 8, 6, 3, 9, 5, 4],
[4, 3, 8, 9, 7, 5, 1, 2, 6],
[' ', 5, ' ', ' ', 2, ' ', 7, ' ', ' ']
]
def printSudoku():
i = 0
while i < 10:
if i == 0:
print(" 1 2 3 4 5 6 7 8 9")
print(" -------------------------")
elif i == 3 or i == 6 or i == 9:
print(" -------------------------")
line = "|"
if i < 9:
print('{2} {1} {0[0]} {0[1]} {0[2]} {1} {0[3]} {0[4]} {0[5]} {1} {0[6]} {0[7]} {0[8]} {1}'.format(sudoku[i], line, i+1))
i = i + 1
print(" ")
print(" %@@@@@@@ @@@ @@@ (@@@@@@@@@ ,@@@@2@@@@@ @@@, /@@@/ @@@, @@@ ")
print(" @@@* @@@ @@@ (@@( /@@@# .@@@% (@@@ @@@, @@@% @@@, @@@. ")
print(" @@@& @@@ @@@ (@@( @@@* @@@% #@@% @@@,.@@@. @@@, @@@. ")
print(" ,@@@@@@* @@@ @@@ (@@( (@@% .@@@* ,@@@ @@@%@@% @@@, @@@. ")
print(" /@@@@@# @@@ @@@ (@@( (@@% .@@@* ,@@@ @@@,@@@( @@@, @@@. ")
print(" *@@@. @@@ .@@& (@@( @@@. @@@% &@@( @@@, &@@@. @@@* .@@@. ")
print(" &, &@@@ #@@@. ,@@@, (@@( ,&@@@* ,@@@& .@@@@ @@@, (@@@/ #@@@* @@@# ")
print(",@@@@@@@@( (@@@@@@@@% (@@@@@@@@@( #@@@@@@@@@, @@@, ,@@@% ,@@@@@@@@@. \n ")
print("To start game input:")
print(" r - to load random puzzle:")
print(" 1 - to load chart nr 1:")
print(" 2 - to load chart nr 2:")
print(" 3 - to load chart nr 3:")
choice = input("Input here: ")
s = 0
if choice == "R" or choice == "r":
listaSudoku = [sudoku1, sudoku2, sudoku3]
sudoku_number = randint(0, 2)
print("dupa", sudoku_number)
sudoku = listaSudoku[sudoku_number]
#print("ktore = ", sudoku)
elif int(choice) == 1:
s = 1
sudoku = sudoku1
elif int(choice) == 2:
s = 2
sudoku = sudoku2
elif int(choice) == 3:
s = 3
sudoku = sudoku3
while True: # prints Sudoku until is solved
print("Your sudoku to solve:")
printSudoku()
print("Input 3 numbers in format a b c, np. 4 5 8")
print(" a - row number")
print(" b - column number ")
print(" c - value")
# vprint(" r - reset chart to start\n ")
x = input("Input a b c: ")
print("")
numbers = " 0123456789" # conditions of entering the numbers !
if (len(x) != 5) or (str(x[0]) not in numbers) or (str(x[2]) not in numbers) or (
str(x[4]) not in numbers) or (str(x[1]) != " ") or (str(x[3]) != " "):
if x == "r": # reset
if s == 1 :
sudoku = sudoku1
elif s == 1 :
sudoku = sudoku1
s == 1 :
sudoku = sudoku1
print(" Function reset() will be ready in Next Week")
else:
print("Error - wrong number format \n ")
continue
sudoku[int(x[0])-1][int(x[2])-1] = int(x[4])
column1 = 0
column2 = 0
try:
i = 0
list = []
while i < 9:
column = 0
for item in sudoku:
column = column + item[i]
list.append(column)
#p rint(list)
# print("Suma columny ", i, " = ", column)
i += 1
is45 = 0
for listElement in list:
if listElement == 45:
is45 = is45 + 1
# print("Ile kolumen OK", is45)
i = 0
for item in sudoku:
if sum(item) == 45 and is45 == 9:
i = i + 1
if i == 9:
printSudoku()
print("@@@@@@@@@@ YOU WIN @@@@@@@@@@")
break
except TypeError:
print()
| [
"inz.kamil.wos@gmail.com"
] | inz.kamil.wos@gmail.com |
cac8cca8bbafc756a771cbbd21f316a640e98cd7 | 6b4a48fb6142789326654c48d32acda3eb5e7b08 | /formationproject/wsgi.py | a9ea3c0a982ffb7af95cba5e2211d90796a89dd1 | [] | no_license | mwesterhof/formationproject | 0d9795c218b5010bfbb716216d3d8f4fa5bd4799 | 1b4a057b996829609e308c78721aca840ec58ee7 | refs/heads/master | 2023-08-19T00:08:58.282341 | 2021-10-08T16:19:18 | 2021-10-08T16:19:18 | 401,425,998 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 413 | py | """
WSGI config for formationproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "formationproject.settings.dev")
application = get_wsgi_application()
| [
"m.westerhof@lukkien.com"
] | m.westerhof@lukkien.com |
b236c8c4e623cf11c90bb5c8d15b7e0df7aba00b | 7d66ec851a0bbba1403848e2caf7323d89797936 | /abra/inference/__init__.py | 40fcd85e690de6a5a0222958aa03e7e2ddf5acce | [
"MIT"
] | permissive | seekshreyas/abracadabra | d19aceb9de2dbbcfb7feb3c3e14ccb1c4c164095 | a79f03bba2917ab4cc99d4c3ec0459401842ee9f | refs/heads/master | 2022-10-05T07:41:21.163255 | 2020-06-12T17:43:04 | 2020-06-12T17:43:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 899 | py | from abra.inference.inference_base import InferenceProcedure, FrequentistProcedure
def get_inference_procedure(method, **infer_params):
_method = method.lower().replace('-', '').replace('_', '').replace(' ', '')
if _method in ('meansdelta'):
from abra import MeansDelta as IP
elif _method in ('proportionsdelta'):
from abra import ProportionsDelta as IP
elif _method in ('ratesratio'):
from abra import RatesRatio as IP
elif method in (
'gaussian',
'bernoulli',
'binomial',
'beta_binomial',
'gamma_poisson'
):
from abra import BayesianDelta as IP
infer_params.update({"model_name": method})
else:
raise ValueError('Unknown inference method {!r}'.format(method))
return IP(method=method, **infer_params)
__all__ = [
"InferenceProcedure",
"FrequentistProcedure"
]
| [
"dustin@quizlet.com"
] | dustin@quizlet.com |
89b1685f529264b86004c272eb59419b27a1315b | 4a42fefd8945c73402ddf36f8943e011cd9c4151 | /projects/myhellowebapp/hellowebapp/wsgi.py | 2b6fe00b6b8875c39ed849cf147b0eb94f51d25b | [] | no_license | momentum-cohort-2018-10/hello-web-app-SowmyaAji | c2c1374b460232822ff91fc1d034f1d89a400332 | 2cfe7fd6d22db4f9b9ac0d8fdc611787cb1372c5 | refs/heads/master | 2020-04-06T11:53:35.991478 | 2018-11-18T20:48:49 | 2018-11-18T20:48:49 | 157,434,877 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 399 | py | """
WSGI config for hellowebapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hellowebapp.settings")
application = get_wsgi_application()
| [
"sowmya.aji@gmail.com"
] | sowmya.aji@gmail.com |
bc87958ada6e6684a8aae3abd9d9e9d963c1b983 | 92f5057eeab3b5fb6952f478917bd84858907588 | /socialbayes.py | 0d959c7bb67bcedaecf9d8530d00f1e641ff07e9 | [] | no_license | enjoylife/mlsocial | 6e16c8f5fd836e34bbca1192b1b94cf1e2914f8a | 0ac877e4ffa013cd075ee65a09247b8a65cb8185 | refs/heads/master | 2021-01-22T23:33:40.081502 | 2012-02-18T06:16:16 | 2012-02-18T06:16:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,261 | py | # -*- coding: UTF-8 -*-
import Stemmer
#twitter_search
import requests
from requests import RequestException
from requests import async
from urllib import urlencode
from urllib2 import urlopen
import json
from multiprocessing import Process
from thread import Thread
#redisbayes
import re
import math
import redis
import random
from redis import WatchError
stemmer = Stemmer.Stemmer('english')
english_ignore = set()
with open('stoplist.txt', 'r') as stops:
for word in stops:
english_ignore.add(stemmer.stemWord(word.strip()))
class DataConsumer(Process):
""" Consumer process that will extract data given a Joinable queue """
def __init__(self, q, stoplist, stemmer, data):
Process.__init__(self)
self.input_q = q
self.stemmer = stemmer
self.stoplist = stoplist
self.data = data
def run(self):
while True:
data = self.input_q.get()
# Replace with real extraction work later
print data
self.input_q.task_done()
class RedisExtract(object):
def __init__(self, redis=None, prefix='data:'):
if not redis: import redis; self.redis = redis.Redis()
else: self.redis = redis
self.prefix = prefix
def flush(self):
for cat in self.redis.smembers(self.prefix + 'categories'):
self.rpipe.delete(self.prefix + cat)
self.rpipe.delete(self.prefix + 'categories')
self.rpipe.execute()
def train(self, category, text):
self.redis.sadd(self.prefix + 'categories', category)
## TODO create a super class that has a whole set of text extraction
#tools
def tidy(text):
if not isinstance(text, basestring):
text = str(text)
if not isinstance(text, unicode):
text = text.decode('utf8')
text = text.lower()
return re.sub(r'[\_.,<>:;~+|\[\]?`"!@#$%^&*()\s]', ' ', text, re.UNICODE)
def english_tokenizer(text, stem=True, stops=english_ignore):
if stem:
words = stemmer.stemWords(tidy(text).split())
else:
words = text.split()
return [w for w in words if len(w) > 2 and w not in stops ]
def occurances(words):
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
class RedisBayes(object):
u""" Naïve Bayesian Text Classifier on Redis.
redisbayes
~~~~~~~~~~
I wrote this to filter spammy comments from a high traffic forum website
and it worked pretty well. It can work for you too :)
For example::
>>> rb = RedisBayes(redis.Redis(), prefix='bayes:test:')
>>> rb.flush()
>>> rb.classify('nothing trained yet') is None
True
>>> rb.train('good', 'sunshine drugs love sex lobster sloth')
>>> rb.train('bad', 'fear death horror government zombie god')
>>> rb.classify('sloths are so cute i love them')
'good'
>>> rb.classify('i fear god and love the government')
'bad'
>>> int(rb.score('i fear god and love the government')['bad'])
-9
>>> int(rb.score('i fear god and love the government')['good'])
-14
>>> rb.untrain('good', 'sunshine drugs love sex lobster sloth')
>>> rb.untrain('bad', 'fear death horror government zombie god')
>>> rb.score('lolcat')
{}
Words are lowercased and unicode is supported::
>>> print tidy(english_tokenizer("Æther")[0])
æther
Common english words and 1-2 character words are ignored::
>>> english_tokenizer("greetings mary a b aa bb")
[u'mari']
Some characters are removed::
>>> print english_tokenizer("contraction's")[0]
contract
>>> print english_tokenizer("what|is|goth")[0]
goth
"""
def __init__(self, redis=None, prefix='bayes:', correction=0.1,
tokenizer=None):
self.redis = redis
self.prefix = prefix
self.correction = correction
self.tokenizer = tokenizer or english_tokenizer
if not self.redis:
import redis
redis = redis.Redis()
self.rpipe = redis.pipeline()
def flush(self):
for cat in self.redis.smembers(self.prefix + 'categories'):
self.rpipe.delete(self.prefix + cat)
self.rpipe.delete(self.prefix + 'categories')
self.rpipe.execute()
def train(self, category, text, twitdata=False, multi=False):
self.redis.sadd(self.prefix + 'categories', category)
words = self.tokenizer(text)
for word, count in occurances(words).iteritems():
self.rpipe.hincrby(self.prefix + category, word, count)
self.rpipe.execute()
if twitdata and not multi:
words = set(self.tokenizer(text, stem=False))
sample = random.sample(words, 2)
tweets = twitter_search(sample, twit_pages=5)
data = self.tokenizer(tweets,stops=(words|english_ignore))
for word, count in occurances(data).iteritems():
self.rpipe.hincrby(self.prefix + category, word, count)
self.rpipe.execute()
if multi:
words = set(self.tokenizer(text, stem=False))
sample = random.sample(words, 2)
twitter_search_async(sample, twit_pages=5)
def untrain(self, category, text):
for word, count in occurances(self.tokenizer(text)).iteritems():
cur = self.redis.hget(self.prefix + category, word)
if cur:
new = int(cur) - count
if new > 0:
self.redis.hset(self.prefix + category, word, new)
else:
self.redis.hdel(self.prefix + category, word)
with self.rpipe:
while 1:
try:
self.rpipe.watch(self.prefix + category)
if self.rpipe.hlen(self.prefix + category) == 0:
self.rpipe.multi()
self.rpipe.delete(self.prefix + category)
self.rpipe.srem(self.prefix + 'categories', category)
self.rpipe.execute()
break
except WatchError:
continue
def classify(self, text):
score = self.score(text)
if not score:
return None
return sorted(score.iteritems(), key=lambda v: v[1])[-1][0]#hackish?
def guess(self, text):
score = self.score(text)
if not score:
return None
values = sorted(score.iteritems(), key=lambda v: v[1], reverse=True)#hackish?
for key, value in values:
print key
def score(self, text):
occurs = occurances(self.tokenizer(text))
scores = {}
for category in self.redis.smembers(self.prefix + 'categories'):
tally = self.tally(category)
scores[category] = 0.0
for word, count in occurs.iteritems():
score = self.redis.hget(self.prefix + category, word)
assert not score or score > 0, "corrupt bayesian database"
score = score or self.correction
scores[category] += math.log(float(score) / tally)
return scores
def tally(self, category):
tally = sum(int(x) for x in self.redis.hvals(self.prefix + category))
assert tally >= 0, "corrupt bayesian database" #TODO better error check
return tally
def twitter_search(words, twit_pages):
"""input: list of words, returns a list of results
Filtering out the multiple retweets and named entities
TODO: Error checking and better func params"""
sentences=[]
pagenum = twit_pages
twit_base = "http://search.twitter.com/search.json?"
for page in range(1,pagenum+1):
twit_ops = {'lang':'en', 'result_type':'mixed','include_entities':1,'page':page, 'rpp':100,
'q': ' '.join(words)}
try:
r =requests.get(twit_base+urllib.urlencode(twit_ops), prefetch=True,
timeout=.4)
content = json.loads(r.text)
except RequestException:
continue
print "adding new sentences for page %s" % page
for sents in content['results']:
# Dont want retweets
if not sents['text'].startswith('RT'):
new_sent = sents['text']
# Test if their is urls in string, if so remove them before appending
if sents['entities'].get('urls', False):
for urls in sents['entities'].get('urls'):
i = urls['indices']
# Hackish with indices, but it works :)
new_sent=sents['text'].replace(sents['text'][i[0]:i[1]],'')
sentences.append(new_sent.encode('utf-8'))
return sentences
red = redis.Redis()
rp = red.pipeline()
def twitter_search_async(words, twit_pages):
"""input: list of words, returns a list of results
Filtering out the multiple retweets and named entities
TODO: Error checking and better func params"""
urls=[]
pagenum = twit_pages
twit_base = "http://search.twitter.com/search.json?"
for page in range(1,pagenum+1):
twit_ops = {'lang':'en', 'result_type':'mixed','include_entities':1,'page':page, 'rpp':100,
'q': ' '.join(words)}
urls.append(async.get(twit_base+urllib.urlencode(twit_ops),
timeout=.4, hooks={'response': parse_tweets}))
async.map(urls)
def parse_tweets(data):
sentences=[]
tweets = json.load(data.text)
for sents in tweets['results']:
print decoding
# Dont want retweets
if not sents['text'].startswith('RT'):
new_sent = sents['text']
# Test if their is urls in string, if so remove them before appending
if sents['entities'].get('urls', False):
for urls in sents['entities'].get('urls'):
i = urls['indices']
# Hackish with indices, but it works :)
new_sent=sents['text'].replace(sents['text'][i[0]:i[1]],'')
sentences.append(new_sent.encode('utf-8'))
for word, count in occurances(sentences).iteritems():
rp.hincrby(self.prefix + category, word, count)
rp.execute()
if __name__ =='__main__':
#import doctest
#doctest.testmod()
#rb = RedisBayes(redis.Redis(), prefix="bayes:test:")
#rb.train('food', ' pizza apples yogurt water' , True,)
#rb.train('sports', ' baseball hockey football soccer' , True)
#rb.train('sports', ' bat glove goal field rink hoop helmet ' , True)
#rb.train('school', ' paper pencil laptop hw' , True)
#rb.train('book', 'read table of contents paper cover', True )
#rb.train('car', 'ford nissan gmc wheel headlight ', True)
# rb.train('math', ' subtract times multiple divide log ', True , True)
# print rb.classify('sit down at the table')
# print rb.classify(' i read')
# print rb.classify('puck')
# print rb.classify('honda')
# print rb.classify('division')
| [
"mclemens66+github@gmail.com"
] | mclemens66+github@gmail.com |
63b940320659fb0fc6204694ab667047cfce35e3 | 7f957ab6a6a0d9b6d21c126134aad956eaad8fb0 | /mod/data_encoding/__init__.py | b7d241a4e2f630278f21584a37a01f09889618bf | [
"MIT"
] | permissive | wangludewdrop/algorithm-tools | a3fc96118c38306e017812c2b93fd930985c50f8 | 094fd0c8587efbead704ff1b49e06fb7a00468b7 | refs/heads/main | 2023-04-12T18:39:50.240765 | 2021-05-06T10:32:56 | 2021-05-06T10:32:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 168 | py | # -*- coding: utf-8 -*-
'''
Created on 2021/02/27 18:02:32
@File -> __init__.py
@Author: luolei
@Email: dreisteine262@163.com
@Describe: 初始化
'''
__all__ = [] | [
"dreisteine@stu.scu.edu.cn"
] | dreisteine@stu.scu.edu.cn |
b9e4db8d80d9a37b23a0d85cebf5894410c987cd | 3b97c64fcee27cb19faab732ff1b7d71347881c8 | /Consumption_Prediction/Codes/Data_Processing.py | 40e615d8149cb51b73ce5732771b5c9319d8fb1c | [] | no_license | pedrobranco0410/E4C-Forecast | 43a6048ac2520401fab152103b971090f2864bdb | 5807bd8f4053f18298387cf596cc88f518b0e402 | refs/heads/master | 2023-07-02T07:29:40.076176 | 2021-08-06T09:44:46 | 2021-08-06T09:44:46 | 375,277,477 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,500 | py | import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
def read_csv(path, interval):
"""
Reads the csv file in the corresponding path and returns a dataframe with all data rearranged in desired intervals
"""
df = pd.read_csv(path, usecols=[0,5, 6,7,8,21,24], index_col=0, parse_dates=True)
df = df.fillna(method='ffill')
df = df.resample(interval).mean()
df = df.fillna(method='ffill')
return df
def feature_and_targets(data):
"""
It removes from the dataset the features that will be used in the prediction model and the data that must be predicted so that we can validate the model.
"""
data['day of the week'] = data.index.dayofweek
data['day of the year'] = data.index.dayofyear
data['hour of the day'] = data.index.hour
data['minute of the hour'] = data.index.minute
data["Consumption"] = data['T1']+data['T2']+data['T3']+data['T4']
#data["Consumption"] = data["TGBT"]
features = ['day of the week','day of the year','hour of the day','minute of the hour', 'AirTemp','rh']#, 'wd', 'ws','rh', 'rain']
labels = ["Consumption"]
inputs = features + labels
data = data[inputs]
return data, features,labels,len(features), len(labels)
def normalize(data):
"""
Normalizes the dataset individually for each column between -1 and 1
"""
scaler = MinMaxScaler(feature_range=(-1, 1))
data_scaled = pd.DataFrame(scaler.fit_transform(data.values), columns=data.columns, index=data.index)
return data_scaled,scaler
def split_data(data, sequence_length, features, labels, test_size=0.25):
"""
splits data to training and testing parts
"""
#Cut the dataset into 2 parts: the first will be for training and the second for validation
ntest = int(round(len(data) * (1 - test_size)))
df_train, df_test = data.iloc[:ntest], data.iloc[ntest:]
#Separates the data between the features that will be used and the results that should be predicted
x_train = np.asarray(df_train[features].iloc[:-sequence_length])
x_test = np.asarray(df_test[features].iloc[:-sequence_length])
y_test = np.asarray(df_test[labels].iloc[sequence_length:])
y_train = np.asarray(df_train[labels].iloc[sequence_length:])
return x_train, x_test, y_test, y_train,df_train, df_test
def batch_generator(batch_size, sequence_length, num_features, num_labels, x, y):
"""
Generator function for creating random batches of training-data.
"""
while True:
# Allocate a new array for the batch of input-signals.
x_shape = (batch_size, sequence_length, num_features)
x_batch = np.zeros(shape=x_shape, dtype=np.float16)
# Allocate a new array for the batch of output-signals.
y_shape = (batch_size, sequence_length, num_labels)
y_batch = np.zeros(shape=y_shape, dtype=np.float16)
# Fill the batch with random sequences of data.
for i in range(batch_size):
# Get a random start-index.
# This points somewhere into the training-data.
if len(x)<sequence_length:
print("there will be a problem test too short", len(x))
idx = np.random.randint(len(x) - 2*sequence_length)
# Copy the sequences of data starting at this index.
x_batch[i] = x[idx:idx+sequence_length]
y_batch[i] = y[idx:idx+sequence_length]
yield (x_batch, y_batch) | [
"pedrobrancondrade@gmail.com"
] | pedrobrancondrade@gmail.com |
433dc5780c6bf966236e507e8947e87df83870a2 | 43e900f11e2b230cdc0b2e48007d40294fefd87a | /Amazon/VideoOnsite/926.flip-string-to-monotone-increasing.py | d4efde64ddbe2e4540f93d5acfa3516e947730ab | [] | no_license | DarkAlexWang/leetcode | 02f2ed993688c34d3ce8f95d81b3e36a53ca002f | 89142297559af20cf990a8e40975811b4be36955 | refs/heads/master | 2023-01-07T13:01:19.598427 | 2022-12-28T19:00:19 | 2022-12-28T19:00:19 | 232,729,581 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 472 | py | #
# @lc app=leetcode id=926 lang=python3
#
# [926] Flip String to Monotone Increasing
#
# @lc code=start
class Solution:
def minFlipsMonoIncr(self, s: str) -> int:
n = len(s)
cnt0 = s.count('0')
cnt1 = 0
res = n - cnt0
for i in range(n):
if s[i] == '0':
cnt0 -= 1
elif s[i] == '1':
res = min(res, cnt1 + cnt0)
cnt1 += 1
return res
# @lc code=end
| [
"wangzhihuan0815@gmail.com"
] | wangzhihuan0815@gmail.com |
fc3a2dd07ead6d429cbfb7267d00260f4065db16 | e6a8e129c14c641072645f55dad5248d67a6b7ef | /Project/backend/accounts/urls.py | c6ba47a7d390ed7facf66cbfd465f6f50c374589 | [] | no_license | Dongock/aiosk | 6fcb3f5b5d360f9cead3aaf3bac07a615b5b86f2 | ca761ad258938214ceee09c42b6152c9d8a50198 | refs/heads/master | 2023-02-10T00:05:23.172411 | 2020-12-21T03:53:45 | 2020-12-21T03:53:45 | 323,223,272 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 182 | py | from django.urls import path
from . import views
urlpatterns = [
path('coupon/', views.coupon),
path('class5/', views.class5),
# path('coupon/use/', views.use_coupon),
] | [
"okdong23@naver.com"
] | okdong23@naver.com |
533417aa0ac2c08e47b14885a90b9b910347f2d1 | e9fc61eff5ef4f73dd7cb810dff10ea71d402b16 | /find_sum.py | b85dc25e48b59b5d12f74d2ded3c0f7ca6149455 | [] | no_license | syasuhiro2019/08_if_and_for | 7720d7e4d9f06bcba012bb7379ef2eed03bd92c5 | 092b0515f9a0541e86ef712e1e54281b5d585242 | refs/heads/master | 2020-04-27T20:31:15.285801 | 2019-03-09T08:34:36 | 2019-03-09T08:34:36 | 174,661,095 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 305 | py | numbers = [34, 432, 1, 99]
total = 0
total = total + numbers[0]
total = total + numbers[1]
total = total + numbers[2]
total = total + numbers[3]
print(total)
total = 0
for number in numbers:
total = total + number
total = 0
print(total)
for number in numbers:
total += number
print(total)
| [
"s_ychm@yahoo.co.jp"
] | s_ychm@yahoo.co.jp |
2e309a5345ef496934edd7635284f37e09219c00 | 8c67f4d3df0dcb9c94420239f0e5dca0d054371c | /functions/soccer_results.py | e91217277e9cbeeef99ff1c877d380f73614a4d2 | [] | no_license | Sanusi1997/python_power_of_computing_exercises | 49ea74ac83d513f4703a9026176882db49e24810 | cd1626b5ab6d5d5e88a7eecf8c723965a4caf5ef | refs/heads/master | 2021-01-14T23:40:20.245877 | 2020-07-03T20:15:16 | 2020-07-03T20:15:16 | 242,799,419 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 615 | py | def soccer_scores(first_team_scores, second_team_scores ):
""" A function that takes two integer arguments that represents a
soccer result and prints the winner from the score """
if first_team_scores > second_team_scores:
print(f"Final score is {first_team_scores}:{second_team_scores} \nTeam one won the match")
elif first_team_scores == second_team_scores:
print(f"Final score is {first_team_scores}:{second_team_scores} \nMatch ended in a draw")
else:
print(f"Final score is {second_team_scores}:{first_team_scores} \nTeam two won the match")
soccer_scores(3,2) | [
"sanusihameedolayiwola@gmail.com"
] | sanusihameedolayiwola@gmail.com |
bd3316480a59c494040f990aefb5deb06677a1bf | e44301fb87ecce8defe68fdaa5f540753e8dbccf | /server/app/services/base/views/file_system.py | c951f50d81399432afdfbde5d532b90b72bbe4df | [
"Apache-2.0"
] | permissive | dlsurainflow/actorcloud_BE | d2766a6937ca87a3fc77de849d43938abd3276e9 | c7eff034185d6f39c408f2b6c75c138c7febdf47 | refs/heads/master | 2023-06-16T19:53:46.188814 | 2020-11-11T07:00:02 | 2020-11-11T07:00:02 | 297,188,795 | 0 | 0 | Apache-2.0 | 2021-07-19T07:39:45 | 2020-09-21T00:25:36 | Vue | UTF-8 | Python | false | false | 2,327 | py | import hashlib
import time
from flask import jsonify, g, request, send_from_directory, current_app
from flask_uploads import UploadNotAllowed
from actor_libs.decorators import limit_upload_file
from actor_libs.errors import APIException, ParameterInvalid
from app import auth, images, packages
from app.models import UploadInfo
from . import bp
@bp.route('/download')
def download_file():
file_type = request.args.get('fileType', None, type=str)
filename = request.args.get('filename', None, type=str)
download_path = {
'template': 'DOWNLOAD_TEMPLATE_EXCEL_DEST',
'export_excel': 'EXPORT_EXCEL_PATH',
'image': 'UPLOADED_IMAGES_DEST',
'package': 'UPLOADED_PACKAGES_DEST'
}
if not file_type:
raise ParameterInvalid(field='fileType')
if not filename:
raise ParameterInvalid(field='filename')
path = current_app.config.get(download_path.get(file_type))
return send_from_directory(path, filename)
@bp.route('/upload', methods=['POST'])
@auth.login_required(permission_required=False)
@limit_upload_file()
def upload_file():
file_type = request.args.get('fileType', None, type=str)
file_type_dict = {
'package': {
'type': 1,
'upload_set': packages
},
'image': {
'type': 2,
'upload_set': images
}
}
if file_type not in file_type_dict.keys():
raise ParameterInvalid(field='fileType')
try:
unique_name = hashlib.md5((str(g.user_id) + str(time.time())).encode()).hexdigest()
upload_set = file_type_dict.get(file_type).get('upload_set')
request_file = request.files.get('file')
file_name = upload_set.save(request_file, name=unique_name + '.')
file_url = '/api/v1/download?fileType=%s&filename=%s' % (file_type, file_name)
except UploadNotAllowed:
raise APIException()
request_dict = {
'fileName': file_name,
'displayName': request_file.filename,
'userIntID': g.user_id,
'fileType': file_type_dict.get(file_type).get('type')
}
upload_info = UploadInfo()
created_upload = upload_info.create(request_dict)
return jsonify({
'name': created_upload.displayName,
'url': file_url,
'uploadID': created_upload.id
}), 201
| [
"wilyfreddie@github.com"
] | wilyfreddie@github.com |
a9e8d88a96e19be6e971f475c10c84ebd1e981f2 | cb6e5c8a91dce5911afbbbb7a8a4b55bc0c7687e | /scripts/SuperRod/superrod_GUI_pyqtgraph_chemlab.py | a439ead1fc9fcc5dd2d90dc7e86ea2982ea0dcae | [] | no_license | jackey-qiu/DaFy_P23 | 3870d4e436b0e9df7f1dcb747caaf38589274f92 | ad2ca8e16e92935233e84c2d9fe2b59f4f114444 | refs/heads/master | 2022-04-10T18:32:24.392046 | 2020-03-22T18:22:46 | 2020-03-22T18:22:46 | 198,180,139 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 26,159 | py | import sys,os
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyQt5 import uic
import random
import numpy as np
import pandas as pd
import types
import matplotlib.pyplot as plt
try:
from . import locate_path
except:
import locate_path
script_path = locate_path.module_path_locator()
DaFy_path = os.path.dirname(os.path.dirname(script_path))
sys.path.append(DaFy_path)
sys.path.append(os.path.join(DaFy_path,'dump_files'))
sys.path.append(os.path.join(DaFy_path,'EnginePool'))
sys.path.append(os.path.join(DaFy_path,'FilterPool'))
sys.path.append(os.path.join(DaFy_path,'util'))
from fom_funcs import *
import parameters
import data_superrod as data
import model
import solvergui
import time
import matplotlib
matplotlib.use("Qt5Agg")
import pyqtgraph as pg
import pyqtgraph.exporters
from PyQt5 import QtCore
from PyQt5.QtWidgets import QCheckBox, QRadioButton, QTableWidgetItem, QHeaderView, QAbstractItemView
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QTransform, QFont, QBrush, QColor
from pyqtgraph.Qt import QtGui
import syntax_pars
from chemlab.graphics.renderers import AtomRenderer
from chemlab.db import ChemlabDB
from PyQt5.QtOpenGL import *
from superrod_new import *
#from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar)
class RunFit(QtCore.QObject):
updateplot = QtCore.pyqtSignal(str,object)
def __init__(self,solver):
super(RunFit, self).__init__()
self.solver = solver
self.running = True
def run(self):
if self.running:
self.solver.optimizer.stop = False
self.solver.StartFit(self.updateplot)
def stop(self):
self.solver.optimizer.stop = True
class MyMainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent = None):
super(MyMainWindow, self).__init__(parent)
self.setupUi(self)
context = QGLContext(QGLFormat())
self.widget_edp = MSViewer(context,self.tab_4)
context.makeCurrent()
self.widget_edp.setObjectName("widget_edp")
self.horizontalLayout_9.addWidget(self.widget_edp)
pg.setConfigOptions(imageAxisOrder='row-major')
pg.mkQApp()
#uic.loadUi(os.path.join(DaFy_path,'scripts','SuperRod','superrod_new.ui'),self)
self.setWindowTitle('Data analysis factory: CTR data modeling')
self.stop = False
self.show_checkBox_list = []
#set fom_func
#self.fom_func = chi2bars_2
#parameters
#self.parameters = parameters.Parameters()
#scripts
#self.script = ''
#script module
#self.script_module = types.ModuleType('genx_script_module')
self.model = model.Model()
# self.solver = solvergui.SolverController(self)
self.run_fit = RunFit(solvergui.SolverController(self.model))
self.fit_thread = QtCore.QThread()
self.structure_view_thread = QtCore.QThread()
self.widget_edp.moveToThread(self.structure_view_thread)
self.run_fit.moveToThread(self.fit_thread)
self.run_fit.updateplot.connect(self.update_plot_data_view_upon_simulation)
self.run_fit.updateplot.connect(self.update_par_during_fit)
self.run_fit.updateplot.connect(self.update_status)
#self.run_fit.updateplot.connect(self.update_structure_view)
# self.run_fit.updateplot.connect(self.start_timer_structure_view)
self.fit_thread.started.connect(self.run_fit.run)
#tool bar buttons to operate modeling
self.actionNew.triggered.connect(self.init_new_model)
self.actionOpen.triggered.connect(self.open_model)
self.actionSave.triggered.connect(self.save_model)
self.actionSimulate.triggered.connect(self.simulate_model)
self.actionRun.triggered.connect(self.run_model)
self.actionStop.triggered.connect(self.stop_model)
#pushbuttons for data handeling
self.pushButton_load_data.clicked.connect(self.load_data_ctr)
self.pushButton_append_data.clicked.connect(self.append_data)
self.pushButton_delete_data.clicked.connect(self.delete_data)
self.pushButton_save_data.clicked.connect(self.save_data)
self.pushButton_calculate.clicked.connect(self.calculate)
#pushbutton for changing plotting style
self.pushButton_plot_style.clicked.connect(self.change_plot_style)
#pushbutton to load/save script
self.pushButton_load_script.clicked.connect(self.load_script)
self.pushButton_save_script.clicked.connect(self.save_script)
#pushbutton to load/save parameter file
self.pushButton_load_table.clicked.connect(self.load_par)
self.pushButton_save_table.clicked.connect(self.save_par)
#select dataset in the viewer
self.comboBox_dataset.activated.connect(self.update_data_view)
#syntax highlight
self.plainTextEdit_script.setStyleSheet("""QPlainTextEdit{
font-family:'Consolas';
font-size:11pt;
color: #ccc;
background-color: #2b2b2b;}""")
self.plainTextEdit_script.setTabStopWidth(self.plainTextEdit_script.fontMetrics().width(' ')*4)
#self.data = data.DataList()
#table view for parameters set to selecting row basis
#self.tableWidget_pars.itemChanged.connect(self.update_par_upon_change)
self.tableWidget_pars.setSelectionBehavior(QAbstractItemView.SelectRows)
self.timer_save_data = QtCore.QTimer(self)
self.timer_save_data.timeout.connect(self.save_model)
self.timer_update_structure = QtCore.QTimer(self)
self.timer_update_structure.timeout.connect(self.update_structure_view)
self.setup_plot()
print(self.widget_edp.update)
def setup_plot(self):
self.selected_data_profile = self.widget_data.addPlot()
self.fom_evolution_profile = self.widget_fom.addPlot()
self.par_profile = self.widget_pars.addPlot()
self.fom_scan_profile = self.widget_fom_scan.addPlot()
# water = ChemlabDB().get('molecule', 'example.water')
# ar = AtomRenderer(self.widget_edp, water.r_array, water.type_array)
# ar = self.widget_edp.renderers.append(AtomRenderer(self.widget_edp, water.r_array, water.type_array))
#self.widget_edp.setup_view()
def update(self):
super(MyMainWindow, self).update()
self.widget_edp.update()
def update_plot_data_view(self):
plot_data_index = []
for i in range(len(self.model.data)):
if self.tableWidget_data.cellWidget(i,1).isChecked():
# self.selected_data_profile.plot(self.data[i].x, self.data[i].y, clear = True)
self.selected_data_profile.plot(self.model.data[i].x, self.model.data[i].y,pen={'color': 'y', 'width': 1}, symbolBrush=(255,0,0), symbolSize=5,symbolPen='w', clear = (len(plot_data_index) == 0))
plot_data_index.append(i)
self.selected_data_profile.setLogMode(x=False,y=True)
self.selected_data_profile.autoRange()
def update_plot_data_view_upon_simulation(self):
plot_data_index = []
for i in range(len(self.model.data)):
if self.tableWidget_data.cellWidget(i,1).isChecked():
# self.selected_data_profile.plot(self.data[i].x, self.data[i].y, clear = True)
self.selected_data_profile.plot(self.model.data[i].x, self.model.data[i].y,pen={'color': 'y', 'width': 0}, symbolBrush=(255,0,0), symbolSize=5,symbolPen='w', clear = (len(plot_data_index) == 0))
self.selected_data_profile.plot(self.model.data[i].x, self.model.data[i].y_sim,pen={'color': 'r', 'width': 2}, clear = False)
plot_data_index.append(i)
self.selected_data_profile.setLogMode(x=False,y=True)
self.selected_data_profile.autoRange()
fom_log = np.array(self.run_fit.solver.optimizer.fom_log)
#print(fom_log)
self.fom_evolution_profile.plot(fom_log[:,0],fom_log[:,1],pen={'color': 'r', 'width': 2}, clear = True)
self.fom_evolution_profile.autoRange()
def update_plot(self):
pass
def init_new_model(self):
pass
def open_model(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","rod file (*.rod);;zip Files (*.rar)", options=options)
if fileName:
self.model.load(fileName)
self.update_table_widget_data()
self.update_combo_box_dataset()
self.update_plot_data_view()
self.update_par_upon_load()
self.update_script_upon_load()
def save_model(self):
path, _ = QFileDialog.getSaveFileName(self, "Save file", "", "rod file (*.rod);zip files (*.rar)")
if path:
self.model.script = (self.plainTextEdit_script.toPlainText())
self.model.save(path)
def simulate_model(self):
# self.update_par_upon_change()
self.model.script = (self.plainTextEdit_script.toPlainText())
self.model.simulate()
'''
self.compile_script()
# self.update_pars()
(funcs, vals) = self.get_sim_pars()
# Set the parameter values in the model
#[func(val) for func,val in zip(funcs, vals)]
i = 0
for func, val in zip(funcs,vals):
try:
func(val)
except Exception as e:
(sfuncs_tmp, vals_tmp) = self.parameters.get_sim_pars()
raise ParameterError(sfuncs_tmp[i], i, str(e), 1)
i += 1
self.evaluate_sim_func()
'''
self.update_plot_data_view_upon_simulation()
self.init_structure_view()
def run_model(self):
# self.solver.StartFit()
self.start_timer_structure_view()
self.structure_view_thread.start()
self.fit_thread.start()
def stop_model(self):
self.run_fit.stop()
self.fit_thread.terminate()
self.stop_timer_structure_view()
def load_data(self, loader = 'ctr'):
exec('self.load_data_{}()'.format(loader))
def load_data_ctr(self):
#8 columns in total
#X, H, K, Y, I, eI, LB, dL
#for CTR data, X column is L column, Y column all 0
#for RAXR data, X column is energy column, Y column is L column
# self.data = data.DataList()
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","csv Files (*.csv);;data Files (*.dat);txt Files (*.txt)", options=options)
if fileName:
with open(fileName,'r') as f:
data_loaded = np.loadtxt(f,comments = '#',delimiter=None)
data_loaded_pd = pd.DataFrame(data_loaded, columns = ['X','h','k','Y','I','eI','LB','dL'])
data_loaded_pd['h'] = data_loaded_pd['h'].apply(lambda x:int(np.round(x)))
data_loaded_pd['k'] = data_loaded_pd['k'].apply(lambda x:int(np.round(x)))
data_loaded_pd.sort_values(by = ['h','k'], inplace = True)
# print(data_loaded_pd)
hk_unique = list(set(zip(list(data_loaded_pd['h']), list(data_loaded_pd['k']))))
hk_unique.sort()
h_unique = [each[0] for each in hk_unique]
k_unique = [each[1] for each in hk_unique]
for i in range(len(h_unique)):
h_temp, k_temp = h_unique[i], k_unique[i]
name = 'Data-{}{}L'.format(h_temp, k_temp)
self.model.data.add_new(name = name)
self.model.data.items[-1].x = data_loaded_pd[(data_loaded_pd['h']==h_temp) & (data_loaded_pd['k']==k_temp)]['X'].to_numpy()
self.model.data.items[-1].y = data_loaded_pd[(data_loaded_pd['h']==h_temp) & (data_loaded_pd['k']==k_temp)]['I'].to_numpy()
self.model.data.items[-1].error = data_loaded_pd[(data_loaded_pd['h']==h_temp) & (data_loaded_pd['k']==k_temp)]['eI'].to_numpy()
self.model.data.items[-1].x_raw = data_loaded_pd[(data_loaded_pd['h']==h_temp) & (data_loaded_pd['k']==k_temp)]['X'].to_numpy()
self.model.data.items[-1].y_raw = data_loaded_pd[(data_loaded_pd['h']==h_temp) & (data_loaded_pd['k']==k_temp)]['I'].to_numpy()
self.model.data.items[-1].error_raw = data_loaded_pd[(data_loaded_pd['h']==h_temp) & (data_loaded_pd['k']==k_temp)]['eI'].to_numpy()
self.model.data.items[-1].set_extra_data(name = 'h', value = data_loaded_pd[(data_loaded_pd['h']==h_temp) & (data_loaded_pd['k']==k_temp)]['h'].to_numpy())
self.model.data.items[-1].set_extra_data(name = 'k', value = data_loaded_pd[(data_loaded_pd['h']==h_temp) & (data_loaded_pd['k']==k_temp)]['k'].to_numpy())
self.model.data.items[-1].set_extra_data(name = 'Y', value = data_loaded_pd[(data_loaded_pd['h']==h_temp) & (data_loaded_pd['k']==k_temp)]['Y'].to_numpy())
self.model.data.items[-1].set_extra_data(name = 'LB', value = data_loaded_pd[(data_loaded_pd['h']==h_temp) & (data_loaded_pd['k']==k_temp)]['LB'].to_numpy())
self.model.data.items[-1].set_extra_data(name = 'dL', value = data_loaded_pd[(data_loaded_pd['h']==h_temp) & (data_loaded_pd['k']==k_temp)]['dL'].to_numpy())
#now remove the empty datasets
empty_data_index = []
i=0
for each in self.model.data.items:
if len(each.x_raw) == 0:
empty_data_index.append(i)
i += 1
for i in range(len(empty_data_index)):
self.model.data.delete_item(empty_data_index[i])
for ii in range(len(empty_data_index)):
if empty_data_index[ii]>empty_data_index[i]:
empty_data_index[ii] = empty_data_index[ii]-1
else:
pass
#update script_module
#self.model.script_module.__dict__['data'] = self.data
#update the view
self.update_table_widget_data()
self.update_combo_box_dataset()
self.update_plot_data_view()
def update_table_widget_data(self):
self.tableWidget_data.clear()
self.tableWidget_data.setRowCount(len(self.model.data))
self.tableWidget_data.setColumnCount(4)
self.tableWidget_data.setHorizontalHeaderLabels(['DataID','Show','Use','Errors'])
# self.tableWidget_pars.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
for i in range(len(self.model.data)):
current_data = self.model.data[i]
name = current_data.name
for j in range(4):
if j == 0:
qtablewidget = QTableWidgetItem(name)
self.tableWidget_data.setItem(i,j,qtablewidget)
else:
check_box = QCheckBox()
#self.show_checkBox_list.append(check_box)
check_box.setChecked(True)
check_box.stateChanged.connect(self.update_plot_data_view)
self.tableWidget_data.setCellWidget(i,j,check_box)
def update_combo_box_dataset(self):
new_items = [each.name for each in self.model.data]
self.comboBox_dataset.clear()
self.comboBox_dataset.addItems(new_items)
def update_data_view(self):
dataset_name = self.comboBox_dataset.currentText()
dataset = None
for each in self.model.data:
if each.name == dataset_name:
dataset = each
break
else:
pass
column_labels_main = ['x','y','error']
extra_labels = ['h', 'k', 'dL', 'LB']
all_labels = ['x','y','error','h','k','dL','LB','mask']
self.tableWidget_data_view.setRowCount(len(dataset.x))
self.tableWidget_data_view.setColumnCount(len(all_labels))
self.tableWidget_data_view.setHorizontalHeaderLabels(all_labels)
for i in range(len(dataset.x)):
for j in range(len(all_labels)):
if all_labels[j] in column_labels_main:
# print(getattr(dataset,'x')[i])
qtablewidget = QTableWidgetItem(str(getattr(dataset,all_labels[j])[i]))
elif all_labels[j] in extra_labels:
qtablewidget = QTableWidgetItem(str(dataset.get_extra_data(all_labels[j])[i]))
else:
qtablewidget = QTableWidgetItem('True')
self.tableWidget_data_view.setItem(i,j,qtablewidget)
def init_structure_view(self):
xyz, e = self.model.script_module.sample.extract_exyz(1)
ar = self.widget_edp.renderers.append(AtomRenderer(self.widget_edp, xyz, e))
#self.widget_edp.show_structure(xyz)
def update_structure_view(self):
#xyz = self.model.script_module.sample.extract_xyz(1)
xyz, e = self.model.script_module.sample.extract_exyz(1)
self.widget_edp.renderers[0].update_positions(xyz)
#ar = self.widget_edp.renderers.append(AtomRenderer(self.widget_edp, water.r_array, water.type_array))
def start_timer_structure_view(self):
self.timer_update_structure.start(2000)
def stop_timer_structure_view(self):
self.timer_update_structure.stop()
def append_data(self):
pass
def delete_data(self):
pass
def save_data(self):
pass
def calculate(self):
pass
def change_plot_style(self):
pass
def load_script(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","script Files (*.py);;text Files (*.txt)", options=options)
if fileName:
with open(fileName,'r') as f:
self.plainTextEdit_script.setPlainText(f.read())
self.model.script = (self.plainTextEdit_script.toPlainText())
#self.compile_script()
def update_script_upon_load(self):
self.plainTextEdit_script.setPlainText(self.model.script)
def save_script(self):
pass
def update_par_upon_load(self):
vertical_labels = []
lines = self.model.parameters.data
how_many_pars = len(lines)
self.tableWidget_pars.clear()
self.tableWidget_pars.setRowCount(how_many_pars)
self.tableWidget_pars.setColumnCount(6)
self.tableWidget_pars.setHorizontalHeaderLabels(['Parameter','Value','Fit','Min','Max','Error'])
# self.tableWidget_pars.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
for i in range(len(lines)):
items = lines[i]
#items = line.rstrip().rsplit('\t')
j = 0
if items[0] == '':
#self.model.parameters.data.append([items[0],0,False,0, 0,'-'])
vertical_labels.append('')
j += 1
else:
#add items to parameter attr
#self.model.parameters.data.append([items[0],float(items[1]),items[2]=='True',float(items[3]), float(items[4]),items[5]])
#add items to table view
if len(vertical_labels)==0:
vertical_labels.append('1')
else:
if vertical_labels[-1] != '':
vertical_labels.append('{}'.format(int(vertical_labels[-1])+1))
else:
vertical_labels.append('{}'.format(int(vertical_labels[-2])+1))
for item in items:
if j == 2:
check_box = QCheckBox()
check_box.setChecked(item==True)
self.tableWidget_pars.setCellWidget(i,2,check_box)
else:
qtablewidget = QTableWidgetItem(str(item))
# qtablewidget.setTextAlignment(Qt.AlignCenter)
if j == 0:
qtablewidget.setFont(QFont('Times',10,QFont.Bold))
elif j == 1:
qtablewidget.setForeground(QBrush(QColor(255,0,255)))
self.tableWidget_pars.setItem(i,j,qtablewidget)
j += 1
self.tableWidget_pars.resizeColumnsToContents()
self.tableWidget_pars.resizeRowsToContents()
self.tableWidget_pars.setShowGrid(False)
self.tableWidget_pars.setVerticalHeaderLabels(vertical_labels)
def load_par(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","Table Files (*.tab);;text Files (*.txt)", options=options)
vertical_labels = []
if fileName:
with open(fileName,'r') as f:
lines = f.readlines()
# self.parameters.set_ascii_input(f)
lines = [each for each in lines if not each.startswith('#')]
how_many_pars = len(lines)
self.tableWidget_pars.setRowCount(how_many_pars)
self.tableWidget_pars.setColumnCount(6)
self.tableWidget_pars.setHorizontalHeaderLabels(['Parameter','Value','Fit','Min','Max','Error'])
# self.tableWidget_pars.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
for i in range(len(lines)):
line = lines[i]
items = line.rstrip().rsplit('\t')
j = 0
if items[0] == '':
self.model.parameters.data.append([items[0],0,False,0, 0,'-'])
vertical_labels.append('')
j += 1
else:
#add items to parameter attr
self.model.parameters.data.append([items[0],float(items[1]),items[2]=='True',float(items[3]), float(items[4]),items[5]])
#add items to table view
if len(vertical_labels)==0:
vertical_labels.append('1')
else:
if vertical_labels[-1] != '':
vertical_labels.append('{}'.format(int(vertical_labels[-1])+1))
else:
vertical_labels.append('{}'.format(int(vertical_labels[-2])+1))
for item in items:
if j == 2:
check_box = QCheckBox()
check_box.setChecked(item=='True')
self.tableWidget_pars.setCellWidget(i,2,check_box)
else:
qtablewidget = QTableWidgetItem(item)
# qtablewidget.setTextAlignment(Qt.AlignCenter)
if j == 0:
qtablewidget.setFont(QFont('Times',10,QFont.Bold))
elif j == 1:
qtablewidget.setForeground(QBrush(QColor(255,0,255)))
self.tableWidget_pars.setItem(i,j,qtablewidget)
j += 1
self.tableWidget_pars.resizeColumnsToContents()
self.tableWidget_pars.resizeRowsToContents()
self.tableWidget_pars.setShowGrid(False)
self.tableWidget_pars.setVerticalHeaderLabels(vertical_labels)
@QtCore.pyqtSlot(str,object)
def update_par_during_fit(self,string,model):
#labels = [data[0] for each in self.model.parameters.data]
for i in range(len(model.parameters.data)):
if model.parameters.data[i][0]!='':
# print(self.model.parameters.data[i][0])
#print(len(self.model.parameters.data))
# print(model.parameters.data[i][0])
item_temp = self.tableWidget_pars.item(i,1)
#print(type(item_temp))
item_temp.setText(str(model.parameters.data[i][1]))
self.tableWidget_pars.resizeColumnsToContents()
self.tableWidget_pars.resizeRowsToContents()
self.tableWidget_pars.setShowGrid(False)
# self.update_structure_view()
def update_par_upon_change(self):
self.model.parameters.data = []
for each_row in range(self.tableWidget_pars.rowCount()):
if self.tableWidget_pars.item(each_row,0)==None:
items = ['',0,False,0,0,'-']
elif self.tableWidget_pars.item(each_row,0).text()=='':
items = ['',0,False,0,0,'-']
else:
# print(each_row,type(self.tableWidget_pars.item(each_row,0)))
items = [self.tableWidget_pars.item(each_row,0).text()] + [float(self.tableWidget_pars.item(each_row,i).text()) for i in [1,3,4]] + [self.tableWidget_pars.item(each_row,5).text()]
items.insert(2, self.tableWidget_pars.cellWidget(each_row,2).isChecked())
self.model.parameters.data.append(items)
@QtCore.pyqtSlot(str,object)
def update_status(self,string,model):
self.statusbar.clearMessage()
self.statusbar.showMessage(string)
self.label_2.setText('FOM {}:{}'.format(self.model.fom_func.__name__,self.run_fit.solver.optimizer.best_fom))
def save_par(self):
pass
if __name__ == "__main__":
QApplication.setStyle("windows")
app = QApplication(sys.argv)
myWin = MyMainWindow()
myWin.setWindowIcon(QtGui.QIcon('dafy.PNG'))
hightlight = syntax_pars.PythonHighlighter(myWin.plainTextEdit_script.document())
myWin.plainTextEdit_script.show()
myWin.plainTextEdit_script.setPlainText(myWin.plainTextEdit_script.toPlainText())
myWin.show()
sys.exit(app.exec_())
| [
"cqiu@alaska.edu"
] | cqiu@alaska.edu |
9dec5036ce036c0f4f8ece900dbe9b0c7f4709df | 0e8be64523c1fca6594118f61e8f9ef6d26ccb00 | /2017/0924_boys_names.py | a51ffd5cca53989959741ae2ed9071c5999921a7 | [
"CC0-1.0"
] | permissive | boisvert42/npr-puzzle-python | 782184540d8e9f62a9f8ab8a39ef51088839c1e8 | 5e3761e7cf3d9f6a05c9f32d6a26444375e73aff | refs/heads/master | 2020-05-22T01:14:51.732606 | 2019-12-29T17:32:40 | 2019-12-29T17:32:40 | 56,475,366 | 1 | 2 | null | null | null | null | UTF-8 | Python | false | false | 721 | py | #!/usr/bin/env python
"""
NPR 2017-09-24
http://www.npr.org/2017/09/24/553147004/sunday-puzzle-what-s-in-a-name
Think of a familiar 6-letter boy's name starting with a vowel.
Change the first letter to a consonant to get another familiar boy's name.
Then change the first letter to another consonant to get another familiar boy's name.
What names are these?
"""
from nltk.corpus import names
from collections import defaultdict
#%%
name_dict = defaultdict(set)
for name in names.words('male.txt'):
name_dict[name[1:]].add(name[0])
#%%
for k,v in name_dict.iteritems():
if len(v) >= 3 and len(k) == 5 and set('AEIOU').intersection(v):
for letter in v:
print letter+k,
print | [
"boisvert42@gmail.com"
] | boisvert42@gmail.com |
35de3051422fc58eeb8bcd5a8d99d3ce2a367973 | 107e7aca94b888b36f67c24a740c4aae7f827341 | /tacker/tests/unit/vm/test_plugin.py | 2ba2c91015a21cd35c15845285bbd463d7abc9a1 | [
"Apache-2.0"
] | permissive | vmehmeri/tacker | b397292511242bfe50540d10c5e116c23f312749 | d05cbaa26361090f36275a942ad87f6ecd3dd480 | refs/heads/master | 2020-05-29T10:23:21.900489 | 2015-10-08T15:46:15 | 2015-10-08T15:46:15 | 57,904,655 | 0 | 0 | null | 2016-05-02T16:41:15 | 2016-05-02T16:41:15 | null | UTF-8 | Python | false | false | 6,776 | py | # Copyright 2015 Brocade Communications System, Inc.
# 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 mock
import uuid
from tacker import context
from tacker.db.vm import vm_db
from tacker.tests.unit.db import base as db_base
from tacker.tests.unit.db import utils
from tacker.vm import plugin
class FakeDriverManager(mock.Mock):
def invoke(self, *args, **kwargs):
if 'create' in args:
return str(uuid.uuid4())
class FakeDeviceStatus(mock.Mock):
pass
class FakeGreenPool(mock.Mock):
pass
class TestVNFMPlugin(db_base.SqlTestCase):
def setUp(self):
super(TestVNFMPlugin, self).setUp()
self.addCleanup(mock.patch.stopall)
self.context = context.get_admin_context()
self._mock_device_manager()
self._mock_device_status()
self._mock_green_pool()
self.vnfm_plugin = plugin.VNFMPlugin()
def _mock_device_manager(self):
self._device_manager = mock.Mock(wraps=FakeDriverManager())
self._device_manager.__contains__ = mock.Mock(
return_value=True)
fake_device_manager = mock.Mock()
fake_device_manager.return_value = self._device_manager
self._mock(
'tacker.common.driver_manager.DriverManager', fake_device_manager)
def _mock_device_status(self):
self._device_status = mock.Mock(wraps=FakeDeviceStatus())
fake_device_status = mock.Mock()
fake_device_status.return_value = self._device_status
self._mock(
'tacker.vm.monitor.DeviceStatus', fake_device_status)
def _mock_green_pool(self):
self._pool = mock.Mock(wraps=FakeGreenPool())
fake_green_pool = mock.Mock()
fake_green_pool.return_value = self._pool
self._mock(
'eventlet.GreenPool', fake_green_pool)
def _mock(self, target, new=mock.DEFAULT):
patcher = mock.patch(target, new)
return patcher.start()
def _insert_dummy_device_template(self):
session = self.context.session
device_template = vm_db.DeviceTemplate(
id='eb094833-995e-49f0-a047-dfb56aaf7c4e',
tenant_id='ad7ebc56538745a08ef7c5e97f8bd437',
name='fake_template',
description='fake_template_description',
infra_driver='fake_driver',
mgmt_driver='fake_mgmt_driver')
session.add(device_template)
session.flush()
return device_template
def _insert_dummy_device(self):
session = self.context.session
device_db = vm_db.Device(id='6261579e-d6f3-49ad-8bc3-a9cb974778ff',
tenant_id='ad7ebc56538745a08ef7c5e97f8bd437',
name='fake_device',
description='fake_device_description',
instance_id=
'da85ea1a-4ec4-4201-bbb2-8d9249eca7ec',
template_id=
'eb094833-995e-49f0-a047-dfb56aaf7c4e',
status='ACTIVE')
session.add(device_db)
session.flush()
return device_db
def test_create_vnfd(self):
vnfd_obj = utils.get_dummy_vnfd_obj()
result = self.vnfm_plugin.create_vnfd(self.context, vnfd_obj)
self.assertIsNotNone(result)
self.assertIn('id', result)
self.assertIn('service_types', result)
self.assertIn('attributes', result)
self._device_manager.invoke.assert_called_once_with(mock.ANY,
mock.ANY,
plugin=mock.ANY,
context=mock.ANY,
device_template=
mock.ANY)
def test_create_vnf(self):
device_template_obj = self._insert_dummy_device_template()
vnf_obj = utils.get_dummy_vnf_obj()
vnf_obj['vnf']['vnfd_id'] = device_template_obj['id']
result = self.vnfm_plugin.create_vnf(self.context, vnf_obj)
self.assertIsNotNone(result)
self.assertIn('id', result)
self.assertIn('instance_id', result)
self.assertIn('status', result)
self.assertIn('attributes', result)
self.assertIn('mgmt_url', result)
self._device_manager.invoke.assert_called_with(mock.ANY, mock.ANY,
plugin=mock.ANY,
context=mock.ANY,
device=mock.ANY)
self._pool.spawn_n.assert_called_once_with(mock.ANY)
def test_delete_vnf(self):
self._insert_dummy_device_template()
dummy_device_obj = self._insert_dummy_device()
self.vnfm_plugin.delete_vnf(self.context, dummy_device_obj[
'id'])
self._device_manager.invoke.assert_called_with(mock.ANY, mock.ANY,
plugin=mock.ANY,
context=mock.ANY,
device_id=mock.ANY)
self._device_status.delete_hosting_device.assert_called_with(mock.ANY)
self._pool.spawn_n.assert_called_once_with(mock.ANY, mock.ANY,
mock.ANY)
def test_update_vnf(self):
self._insert_dummy_device_template()
dummy_device_obj = self._insert_dummy_device()
vnf_config_obj = utils.get_dummy_vnf_config_obj()
result = self.vnfm_plugin.update_vnf(self.context, dummy_device_obj[
'id'], vnf_config_obj)
self.assertIsNotNone(result)
self.assertEqual(dummy_device_obj['id'], result['id'])
self.assertIn('instance_id', result)
self.assertIn('status', result)
self.assertIn('attributes', result)
self.assertIn('mgmt_url', result)
self._pool.spawn_n.assert_called_once_with(mock.ANY, mock.ANY,
mock.ANY) | [
"sseetha@brocade.com"
] | sseetha@brocade.com |
76d04754ce5210635d52dd9cebffe88b8f70157b | 14a4864b10c64ed0f2d9662dae0dfe7bfb9b367e | /blog/urls.py | 268192c06ad190b9c2de92b9b58b875a26eef86f | [] | no_license | PungentLemon/My-portfolio | 0e54126992474e74c31d3d02aa8653f45350d99d | f7603cbc68f7a1db9ef57c78e2a7739e5e7637be | refs/heads/master | 2020-05-22T23:19:58.083478 | 2019-05-14T06:09:47 | 2019-05-14T06:09:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 176 | py |
from django.urls import path
from . import views
urlpatterns = [
path('',views.allblogs, name='allblogs'),
path('<int:blog_id>/',views.detail,name='detail'),
]
| [
"kukurureloaded@gmail.com"
] | kukurureloaded@gmail.com |
0ec26afbb8f3455b69bdcaa43e81f526289e0d08 | 97c418826161258cd6eb6c636689a6e649104cb4 | /Codigo/Aula-10-Processos/threads_e_sockets/app/aula8_fixed_client.py | fcb9abb07914e59c0f6f0e120d3faec734ef14e6 | [] | no_license | mairags/cet-100 | b53347799df3c5aee4010c53adf9b2eda6492274 | 21567e3f0623c34995c8dc2252c9c77f4053a9b6 | refs/heads/master | 2023-04-17T20:52:50.293209 | 2021-05-04T14:37:31 | 2021-05-04T14:37:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 660 | py | from socket import socket
from threading import Thread, Lock
TAM_BUFFER = 1000
NUM_REQ = 10
LOCK = Lock()
def enviar():
sock = socket()
server_info = ('127.0.0.1', 5000)
sock.connect(server_info)
dados_recebidos = sock.recv(TAM_BUFFER)
if LOCK.acquire():
print(dados_recebidos, flush=True)
LOCK.release()
sock.close()
def requisicoes():
try:
count = 0
while count < NUM_REQ:
count += 1
th = Thread(target=enviar)
th.start()
except KeyboardInterrupt:
print("Interrompido!")
def main():
requisicoes()
if __name__ == '__main__':
main()
| [
"mathias.brito@me.com"
] | mathias.brito@me.com |
c718408ccc29e4bca88b5deef7e84bb586acddfc | ea0c0b8d67a42086f840149b3dbe1c0e4f58e56f | /members_area/forms.py | 06d19b868f16f535ae4172f3cc5f191a2c75b8b0 | [
"MIT"
] | permissive | AzeezBello/raodoh | 78b27e0886f8882144a4def160d9c3f53bcc6af9 | 296bd44069bd750557bf49995374601f5052d695 | refs/heads/master | 2022-05-03T05:07:21.632642 | 2020-02-26T10:16:08 | 2020-02-26T10:16:08 | 235,878,080 | 0 | 0 | MIT | 2022-04-22T23:01:27 | 2020-01-23T20:15:39 | JavaScript | UTF-8 | Python | false | false | 194 | py | from django.forms import ModelForm
from .models import Lesson
class LessonForm(ModelForm):
class Meta:
model = Lesson
fields = ('title', 'course', 'body', 'url', 'video')
| [
"azeez@scholarx.co"
] | azeez@scholarx.co |
2a0e0bf2a10cc41a975d515cc6c614e82a56b20b | 2655a633b6c5f89400901179a7c19d76a7edc127 | /smili2/uvdata/uvdata/antable.py | 252d488532abdda27b395382fdea81720c9e9832 | [] | no_license | astrosmili/smili2_dev | c069d943405bd78ac95addc4d36ee0c9eb419cf6 | 06a389ebe054d9b285adf820e570484f56489fdb | refs/heads/master | 2021-09-17T06:13:40.090548 | 2021-03-18T06:18:17 | 2021-03-18T06:18:17 | 238,537,673 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,903 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
'''
__author__ = "Smili Developer Team"
# ------------------------------------------------------------------------------
# Modules
# ------------------------------------------------------------------------------
# internal
from ...util.table import DataTable, DataSeries, TableHeader
# ------------------------------------------------------------------------------
# functions
# ------------------------------------------------------------------------------
class ANTable(DataTable):
header = TableHeader([
dict(name="antname", dtype="U32", unit="", comment="Antenna Name"),
dict(name="antid", dtype="int32", unit="", comment="Antenna ID"),
dict(name="mjd", dtype="float64", unit="day",
comment="Modified Jurian Day"),
dict(name="gst", dtype="float64", unit="hourangle",
comment="Greenwich Sidereal Time"),
dict(name="ra", dtype="float64", unit="deg",
comment="GCRS Right Ascention"),
dict(name="dec", dtype="float64", unit="deg", comment="GCRS Declination"),
dict(name="x", dtype="float64", unit="m",
comment="Geocenric Coordinate x"),
dict(name="y", dtype="float64", unit="m",
comment="Geocenric Coordinate y"),
dict(name="z", dtype="float64", unit="m",
comment="Geocenric Coordinate z"),
dict(name="az", dtype="float64", unit="deg", comment="Azimuthal Angle"),
dict(name="el", dtype="float64", unit="deg", comment="Elevation Angle"),
dict(name="par", dtype="float64", unit="deg",
comment="Parallactic Angle"),
dict(name="fra", dtype="float64", unit="deg",
comment="Field Roation Angle"),
dict(name="sefd1", dtype="float64", unit="Jy", comment="SEFD at Pol 1"),
dict(name="sefd2", dtype="float64", unit="Jy", comment="SEFD at Pol 2"),
dict(name="d1", dtype="float128", unit="", comment="D-term at Pol 1"),
dict(name="d2", dtype="float128", unit="", comment="D-term at Pol 2")
])
@property
def _constructor(self):
return ANTable
@property
def _constructor_sliced(self):
return ANSeries
@classmethod
def make(cls, utc, array, source):
from pandas import concat
from astropy.coordinates import GCRS
# number of time and utc bins
Nant = len(array.table)
# compute apparent source coordinates and GST
skycoord = source.skycoord.transform_to(GCRS(obstime=utc))
gst = utc.sidereal_time(
kind="apparent", longitude="greenwich", model="IAU2006A")
# run loop
def map_func(iant): return _antable_make_iant(
iant=iant, utc=utc, gst=gst, array=array, skycoord=skycoord)
antab = concat([map_func(iant) for iant in range(Nant)])
return antab
class ANSeries(DataSeries):
@property
def _constructor(self):
return ANSeries
@property
def _constructor_expanddim(self):
return ANTable
# define internal function to compute antenna based tables
def _antable_make_iant(iant, utc, gst, array, skycoord):
from numpy import exp, cos, sin, tan, arctan2
from astropy.coordinates import AltAz, EarthLocation
from ...util.units import DEG, RAD, M, DIMLESS
# get values
ant = array.table.loc[iant, :]
location = EarthLocation(x=ant.x, y=ant.y, z=ant.z, unit=M)
lon = location.lon
lat = location.lat
ra = skycoord.ra
dec = skycoord.dec
# compute LST
lst = utc.sidereal_time(kind="apparent", longitude=lon, model="IAU2006A")
# compute AZ / alt
site = AltAz(location=location, obstime=utc)
altaz = skycoord.transform_to(site)
el = altaz.alt
az = altaz.az
secz = altaz.secz
# compute sefd
sefd1 = ant.sefd1 * exp(-ant.tau1*secz)
sefd2 = ant.sefd2 * exp(-ant.tau2*secz)
# compute pallactic angle
H = lst.radian - ra.radian
cosH = cos(H)
sinH = sin(H)
tanlat = tan(lat.radian)
cosdec = cos(dec.radian)
sindec = sin(dec.radian)
par = arctan2(sinH, cosdec*tanlat - sindec*cosH)*RAD
# compute field rotation angle
fra = (ant.fr_pa_coeff * DIMLESS) * par
fra += (ant.fr_el_coeff * DIMLESS) * el
fra += ant.fr_offset * DEG
# antab
antab = ANTable(
dict(
antid=iant,
antname=ant.antname,
mjd=utc.mjd,
gst=gst.hour,
ra=ra.deg,
dec=dec.deg,
x=ant.x,
y=ant.y,
z=ant.z,
az=az.deg,
el=el.deg,
sefd1=sefd1,
sefd2=sefd2,
par=par.to_value(DEG),
fra=fra.to_value(DEG),
d1=ant.d1,
d2=ant.d2
),
columns=ANTable.header.name.to_list()
)
antab.convert_format()
return antab
| [
"kazunori.akiyama.kazu@gmail.com"
] | kazunori.akiyama.kazu@gmail.com |
415003695854767481118785de3b9da037c212d6 | 8db966ce80c6f5ae18243e42f8912bbc9e2bafa3 | /BPNN/BPNN_Regression/polution2/no2.py | 75e8cd74f81027481c28777156ba0022fe5872d3 | [] | no_license | soar200/PythonWorkSpace | 720d2066355089873651e926804de410157b7c93 | 95c90253981a6ea650f6191d1036e11eb2c936a6 | refs/heads/master | 2021-01-30T13:13:24.570947 | 2018-11-26T08:28:04 | 2018-11-26T08:28:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,043 | py | #-*- coding:utf-8 -*-
# &Author AnFany
# 适用于多维输出
from HB_Data_Reg import model_data as R_data
from HB_Data_Reg import L as LL
from HB_Data_Reg import n as N
import numpy as np
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import matplotlib.pyplot as plt
'''第一部分:数据准备'''
'''第二部分: 基于TensorFlow构建训练函数'''
# 创建激活函数
def activate(input_layer, weights, biases, actfunc):
layer = tf.add(tf.matmul(input_layer, weights), biases)
if actfunc == 'relu':
return tf.nn.relu(layer)
elif actfunc == 'tanh':
return tf.nn.tanh(layer)
elif actfunc == 'sigmoid':
return tf.nn.sigmoid(layer)
# 权重初始化的方式和利用激活函数的关系很大
# sigmoid: xavir tanh: xavir relu: he
# 构建训练函数
def Ten_train(xdata, ydata,prexdata,key,hiddenlayers=3, hiddennodes=5, \
learn_rate=0.0012, itertimes=10000, batch_size=3, activate_func='sigmoid', break_error=0.005):
# 开始搭建神经网络
Input_Dimen = len(xdata[0])
Unit_Layers = [Input_Dimen] + [hiddennodes] * hiddenlayers + [len(ydata[0])] # 输入的维数,隐层的神经数,输出的维数1
# 创建占位符
x_data = tf.placeholder(shape=[None, Input_Dimen], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, len(ydata[0])], dtype=tf.float32)
# 实现动态命名变量
VAR_NAME = locals()
for jj in range(hiddenlayers + 1):
VAR_NAME['weight%s' % jj] = tf.Variable(np.random.rand(Unit_Layers[jj], Unit_Layers[jj + 1]), dtype=tf.float32,\
name='weight%s' % jj) / np.sqrt(Unit_Layers[jj]) # sigmoid tanh
# VAR_NAME['weight%s'%jj] = tf.Variable(np.random.rand(Unit_Layers[jj], Unit_Layers[jj + 1]), dtype=tf.float32,name='weight%s' % jj) \/ np.sqrt(Unit_Layers[jj] / 2) # relu
VAR_NAME['bias%s' % jj] = tf.Variable(tf.random_normal([Unit_Layers[jj + 1]], stddev=10, name='bias%s' % jj),
dtype=tf.float32)
if jj == 0:
VAR_NAME['ooutda%s' % jj] = activate(x_data, eval('weight%s' % jj), eval('bias%s' % jj), actfunc=activate_func)
else:
VAR_NAME['ooutda%s' % jj] = activate(eval('ooutda%s' % (jj - 1)), eval('weight%s' % jj), \
eval('bias%s' % jj), actfunc=activate_func)
# 均方误差
loss = tf.reduce_mean(tf.reduce_sum(tf.square(y_target - eval('ooutda%s' % (hiddenlayers))), reduction_indices=[1]))
# 优化的方法
my_opt = tf.train.AdamOptimizer(learn_rate)
train_step = my_opt.minimize(loss)
# 初始化
init = tf.global_variables_initializer()
loss_vec = [] # 训练误差
with tf.Session() as sess:
saver = tf.train.Saver()
sess.run(init)
for i in range(itertimes):
rand_index = np.random.choice(len(xdata), size=batch_size, replace=False)
rand_x = xdata[rand_index]
rand_y = ydata[rand_index]
sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
temp_loss = sess.run(loss, feed_dict={x_data: xdata, y_target: ydata})
loss_vec.append(temp_loss)
# 根据输出的误差,判断训练的情况
if (i + 1) % 50 == 0:
print(key+' '+'Generation: ' + str(i + 1) + '. 训练误差:Loss = ' + str(temp_loss))
# 提前退出的判断
if temp_loss < break_error: # 根据经验获得此数值, 因为采用的是随机下降,因此误差在前期可能出现浮动
break
# 计算预测数据的输出
pre_in_data0 = np.array(prexdata, dtype=np.float32)
for ipre in range(hiddenlayers + 1):
VAR_NAME['pre_in_data%s' % (ipre + 1)] = activate(eval('pre_in_data%s' % ipre), eval('weight%s' % ipre).eval(),\
eval('bias%s' % ipre).eval(), actfunc=activate_func)
# 计算训练数据的输出
train_in_data0 = np.array(xdata, dtype=np.float32)
for ipre in range(hiddenlayers + 1):
VAR_NAME['train_in_data%s' % (ipre + 1)] = activate(eval('train_in_data%s' % ipre), eval('weight%s' % ipre).eval(),\
eval('bias%s' % ipre).eval(), actfunc=activate_func)
# path = 'model2/'+key+'checkpoint/model.ckpt'
# saver.save(sess,path)
return eval('train_in_data%s'%(hiddenlayers+1)).eval(), eval('pre_in_data%s'%(hiddenlayers+1)).eval(), loss_vec
'''第三部分: 结果展示函数'''
#import matplotlib.pyplot as plt
from pylab import mpl # 作图显示中文
mpl.rcParams['font.sans-serif'] = ['FangSong'] # 设置中文字体新宋体
# 绘制图像
def figure(real, net, le='训练', real_line='ko-', net_line='r.-', width=3):
length = len(real[0])
# 绘制每个维度的对比图
for iwe in range(length):
plt.subplot(length, 1, iwe+1)
plt.plot(list(range(len(real.T[iwe]))), real.T[iwe], real_line, linewidth=width)
plt.plot(list(range(len(net.T[iwe]))), net.T[iwe], net_line, linewidth=width - 1)
plt.legend(['%s真实值'%le, '网络输出值'])
if length == 1:
plt.title('%s结果对比'%le)
else:
if iwe == 0:
plt.title('%s结果: %s维度对比'%(le, iwe))
else:
plt.title('%s维度对比'%iwe)
plt.show()
# 绘制成本函数曲线图
def costfig(errlist, le='成本函数曲线图'):
plt.plot(list(range(len(errlist))), errlist, linewidth=3)
plt.title(le)
plt.xlabel('迭代次数')
plt.ylabel('成本函数值')
plt.show()
def batchSizefigure(batch,error,le='batchSize分析图'):
plt.plot(batch,error,linewidth=3)
plt.title(le)
plt.xlabel('batchSize')
plt.ylabel('error')
plt.show()
# 因为训练数据较多,为了不影响展示效果,按序随机选取一定数量的数据,便于展示
def select(datax, datay, count=200):
sign = list(range(len(datax)))
selectr_sign = np.random.choice(sign, count, replace=False)
dx=datax[selectr_sign]
dy=datay[selectr_sign]
return dx,dy
# 将输出的数据转换尺寸,变为原始数据的尺寸
# def trans(ydata, minumber=R_data[4][0], maxumber=R_data[4][1]):
# return ydata * (maxumber - minumber) + minumber
#处理训练和测试的输入数据
def InputHandler(dat,LL):
rows = dat.shape[0]
cols = dat.shape[1]
data = []
for index in range(rows-LL+1):
dd = []
for k in range(index,index+LL):
dd.append(dat[k])
dt = [0]*36
for p in range(len(dd)):
nd = dd[p]
for q in range(cols):
dt[q+p*cols] = nd[q]
data.append(dt)
return data
if __name__ == '__main__':
errordic = {}
data = R_data.get('NO2')
train_x_data = data[0] # 训练输入
train_y_data = data[1] # 训练输出
predict_x_data = data[2] # 测试输入
predict_y_data = data[3] # 测试输出
for nodeNum in range(5,20):
er = []
batchSizelist = []
for batchSize in range(1,100):
# 训练
tfrelu = Ten_train(train_x_data, train_y_data, predict_x_data,'NO2', hiddennodes=nodeNum,batch_size=batchSize)
minumber = data[4][1]
maxumber = data[4][0]
#训练和测试的真实输出
train_y_data_tran = train_y_data*(maxumber - minumber) + minumber
predict_y_data_tran = predict_y_data*(maxumber - minumber) + minumber
#训练和测试的预测输出
train_output = tfrelu[0] * (maxumber - minumber) + minumber
predict_output = tfrelu[1] * (maxumber - minumber) + minumber
error = [0] * len(predict_output)
for index in range(len(predict_output)):
error[index] = abs(predict_y_data_tran[index] - predict_output[index]) / predict_y_data_tran[index]
count = 0
for k in range(len(error)):
if error[k] <= 0.4:
count = count + 1
auc = count / len(predict_output)
key = str(nodeNum)+'and'+str(batchSize)
errordic.setdefault(key, auc)
print(key+","+str(auc))
er.append(auc)
batchSizelist.append(batchSize)
if auc >= 0.75:
break
batchSizefigure(batchSizelist,er)
print(errordic)
# 数据多影响展示,随机挑选100条数据
# random_train_x_data = select(train_output, train_y_data_tran, 200)
# random_predict_x_data = select(predict_output, predict_y_data_tran, 100)
# figure(random_train_x_data[1], random_train_x_data[0], le='训练')
# figure(random_predict_x_data[1], random_predict_x_data[0], le='预测')
# costfig(tfrelu[2])
| [
"595001741@qq.com"
] | 595001741@qq.com |
c04f34aa199ad324a1340a32baf2c128a229bff8 | 1b0b44c8cb454d0241a732766f381ac908a3db96 | /merchant/backend/src/currency/__init__.py | f474fb25e8ed449f118c1ee2a0623071fd559e61 | [] | no_license | zeeis/reference-merchant | 35515ffba1b26fed29789cd26d26eaf265fee30c | f62c4185a0b53cf7512862a50c5a1bb74a86b377 | refs/heads/master | 2023-08-21T22:10:39.781860 | 2021-07-18T12:51:45 | 2021-07-18T12:51:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 87 | py | from .amount import Amount
from .currency import FiatCurrency
from .price import Price
| [
"ericnakagawa@gmail.com"
] | ericnakagawa@gmail.com |
f4dc6c951770b51ced2bc9a8a162b854c7b97c23 | 8ddd9445d773e8f10c0726a7503968557413d363 | /veri.py | 0fc85fe190025887014dad1816edcf31bbba9b56 | [] | no_license | Tuuf/telegrambot | 50b928794213b185dc2c51d9b21e0fc5dc801a94 | 241665629bc4ef4f2c2b60ba6e30f2d04373070c | refs/heads/master | 2022-12-16T01:46:04.775399 | 2020-09-02T14:45:18 | 2020-09-02T14:45:18 | 288,405,358 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 859 | py | import httpx
url="https://finans.truncgil.com/today.json"
response=httpx.get(url)
veri=response.json()
x = veri['ABD DOLARI']
amerika = x['Alış']
x=veri['İNGİLİZ STERLİNİ']
sterlin = x['Alış']
x=veri['İSVİÇRE FRANGI']
frank = x['Alış']
#
x=veri['KANADA DOLARI']
kanada = x['Alış']
#
x=veri['KUVEYT DİNARI']
kuveytdinar = x['Alış']
#
x=veri['NORVEÇ KRONU']
norveckron = x['Alış']
x=veri['SUUDİ ARABİSTAN RİYALİ']
sudiriyal = x['Alış']
#
x=veri['JAPON YENİ']
japyen= x['Alış']
#
x=veri['BULGAR LEVASI']
bulgarleva = x['Alış']
#
x=veri['RUMEN LEYİ']
romenleyi= x['Alış']
x=veri['RUS RUBLESİ']
ruble= x['Alış']
x=veri['İRAN RİYALİ']
riyaliran= x['Alış']
x=veri['ÇİN YUANI']
yuan= x['Alış']
x = veri['PAKİSTAN RUPİSİ']
pakistanrubi = x['Alış']
x = veri['KATAR RİYALİ']
katarriyali = x['Alış']
| [
"noreply@github.com"
] | noreply@github.com |
dd06fdb0ad1fa5a35fe8493e6cb4d7907be97e88 | 493915d74f4ad666a3673b8cf55d3521c8e10fad | /GMail_Alerts.py | e3e53abe4500a17fb21380f27002396d514cc7d9 | [] | no_license | tifabi/allTheGiNeed | e106e92cb91d8f5cfca27d4de09dfc759f7cc311 | 8a5c8f92113938c7b84e4a9c3f70b770078293c6 | refs/heads/master | 2020-03-22T06:36:53.772508 | 2018-07-03T23:39:36 | 2018-07-03T23:39:36 | 139,646,250 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 44,149 | py | '''
Tiffany Fabianac Modified code from:
Reading GMAIL using Python
- https://github.com/abhishekchhibber/Gmail-Api-through-Python
- Abhishek Chhibber
'''
'''
This script does the following:
- Go to Gmal inbox
- Find and read all the Google Alert messages
- Extract details (Date, Snippet,URL) and export them to a .csv file / DB
'''
'''
Before running this script, the user should get the authentication by following
the link: https://developers.google.com/gmail/api/quickstart/python
Also, client_secret.json should be saved in the same directory as this file
'''
# Importing required libraries
import base64
import email
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
import urllib
import re
import dateutil.parser as parser
import json
# Creating a storage.JSON file with authentication details
SCOPES = 'https://www.googleapis.com/auth/gmail.modify' # we are using modify and not readonly, as we will be marking the messages Read
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
GMAIL = discovery.build('gmail', 'v1', http=creds.authorize(Http()))
user_id = 'me'
label_id_one = 'INBOX'
# Getting Google Alert messages from Inbox
#maxResults=1, q='from:googlealerts-noreply@google.com is:unread'
alert_msgs = GMAIL.users().messages().list(userId='me', labelIds=[label_id_one], maxResults=1,
q='from:googlealerts-noreply@google.com').execute()
##RETURNS: {'messages': [{'id': '1645db225f22f01b', 'threadId': '1644e1a892b315c7'}], 'nextPageToken': '16344340453457345441', 'resultSizeEstimate': 4}
# Read values for the key 'messages'
mssg_list = alert_msgs['messages']
##RETURNS: [{'id': '1645db225f22f01b', 'threadId': '1644e1a892b315c7'}]
final_list = []
for mssg in mssg_list:
temp_dict = {}
# get id of individual message
m_id = mssg['id']
# fetch the message using API
# format='raw'
message = GMAIL.users().messages().get(userId=user_id, id=m_id).execute()
'''
RETURNS: {
'id': '1645db225f22f01b',
'threadId': '1644e1a892b315c7',
'labelIds': ['IMPORTANT', 'CATEGORY_UPDATES', 'INBOX'],
'snippet': 'Google Phase III trial As-it-happens update ⋅ July 3, 2018 NEWS Dr. Yardley on the Role of Biosimilars in Breast Cancer OncLive The phase III trial showed an equivalent pathologic complete response',
'historyId': '3276761',
'internalDate': '1530580312000',
'payload': {
'partId': '',
'mimeType': 'multipart/alternative',
'filename': '',
'headers': [
{'name': 'Delivered-To',
'value': 'tiffanyfabianac@gmail.com'
},
{'name': 'Received', 'value': 'by 2002:a67:7cc7:0:0:0:0:0 with SMTP id x190-v6csp496217vsc; Mon, 2 Jul 2018 18:11:53 -0700 (PDT)'},
{'name': 'X-Received', 'value': 'by 2002:a25:e7c8:: with SMTP id e191-v6mr14135883ybh.358.1530580313504; Mon, 02 Jul 2018 18:11:53 -0700 (PDT)'},
{'name': 'ARC-Seal', 'value': 'i=1; a=rsa-sha256; t=1530580313; cv=none; d=google.com; s=arc-20160816; b=mU8UUtj7ocw8+KCZLIUQeoVIqGlkGEjdt5y/rHB9zIu9WivLp4nhm/EQDwhSEiKWQz fu/ooKubGTQnsa80kfxPkkGQI5n6KCgyiZ3lrCbNO6LLq0vvmp4C/5IR+pMlT8Eim+5t h6gEc8ssn7pPg+r0JrwmD3A5TA8G7XhP9Iz910icHKiPfyg3yhXXYkGXrpCUqyuDXTnD SpXGa5OWwIAF0hh/s2hZPwewvQr+UtjZvjHG8Q5bzCBQsnVDhxDNbvRTK7zMwyG41OM9 l2bV+wJbxmqeVKolU/Qrm5t/B+4pH2M6JF0RfP5AVX6+ZFr/LV4PJCdArmdTJn2ZgtE7 a07A=='},
{'name': 'ARC-Message-Signature', 'value': 'i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=to:from:subject:message-id:list-unsubscribe:list-id:date :mime-version:dkim-signature:arc-authentication-results; bh=9r86Eg1CwIukfK0DSWCms++zhn5NAd7rfZJut81wR5k=; b=Ecn/KekxBObsgIke5n9Wale55ksCncSFWNlv/xpcek2o/kKm+pBSYC2HsXEOR9Uk9n dmaC0c9ueAUYCtL0nTypZ+gMgcka/vsiZeYoo+TS0cd08Z0CW2rRYVRWCPe/FfVUB8HP Oh7zTixDjiCBMvil7ktG/iSjVgxFkE40QyRmCB95yr5BMF/iQJ8iiLoVybqy+KmmRXf2 eC+e8ifmyv+T/dJ3/X+AdSzMnWBReAKJCGqfrLxKDFpQwdnMiPAtSnwYJzB8reEMgCuz hnPJ0QczzYp06/m8u8nPTbUW3OoQ9XxnpNLlvLv6HFuq9ku9X9RNRU8jx8ByeDVyRh1d Z6WQ=='},
{'name': 'ARC-Authentication-Results', 'value': 'i=1; mx.google.com; dkim=pass header.i=@google.com header.s=20161025 header.b=BqSripFi; spf=pass (google.com: domain of 3wm06wxqkal0jrrjohdohuwv-qruhso1jrrjoh.frp@alerts.bounces.google.com designates 209.85.220.69 as permitted sender) smtp.mailfrom=3WM06WxQKAL0jrrjohdohuwv-qruhso1jrrjoh.frp@alerts.bounces.google.com; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com'},
{'name': 'Return-Path', 'value': '<3WM06WxQKAL0jrrjohdohuwv-qruhso1jrrjoh.frp@alerts.bounces.google.com>'}, {'name': 'Received', 'value': 'from mail-sor-f69.google.com (mail-sor-f69.google.com. [209.85.220.69]) by mx.google.com with SMTPS id 82-v6sor4071997ybz.185.2018.07.02.18.11.53 for <tiffanyfabianac@gmail.com> (Google Transport Security); Mon, 02 Jul 2018 18:11:53 -0700 (PDT)'},
{'name': 'Received-SPF', 'value': 'pass (google.com: domain of 3wm06wxqkal0jrrjohdohuwv-qruhso1jrrjoh.frp@alerts.bounces.google.com designates 209.85.220.69 as permitted sender) client-ip=209.85.220.69;'},
{'name': 'Authentication-Results', 'value': 'mx.google.com; dkim=pass header.i=@google.com header.s=20161025 header.b=BqSripFi; spf=pass (google.com: domain of 3wm06wxqkal0jrrjohdohuwv-qruhso1jrrjoh.frp@alerts.bounces.google.com designates 209.85.220.69 as permitted sender) smtp.mailfrom=3WM06WxQKAL0jrrjohdohuwv-qruhso1jrrjoh.frp@alerts.bounces.google.com; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com'},
{'name': 'DKIM-Signature', 'value': 'v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20161025; h=mime-version:date:list-id:list-unsubscribe:message-id:subject:from :to; bh=9r86Eg1CwIukfK0DSWCms++zhn5NAd7rfZJut81wR5k=; b=BqSripFiLq2sqIN/PHts9wLXr9/hlqCJpYmx97azZzfGJrUCcJVHrFj+H+ft7a2F47 Piu+fkmprHFN1NanT0OuYWjTVmTKDvzwTSJ2gSfDR49jpYveXZSrxjoQXBesoXQUxh98 94FvRCzsw0Vem24g0lUnTvjmcATlse1J+OL+BCT/6uv1cpCWkBMWtoCNBp2bb8Todx/C CJNenfuBDjoFIoE9XcpmEuVmaNvk36m3rWdAr3XBIt0rVDMABMbQujWm+QimF/M040gG ao0ehCb+QKgI+So+vUwRK7aioCOGngsxAjCTVnFlGlhoTnAF9HieLcpTt4tIxdvgi6yu fR5Q=='},
{'name': 'X-Google-DKIM-Signature', 'value': 'v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:mime-version:date:list-id:list-unsubscribe :message-id:subject:from:to; bh=9r86Eg1CwIukfK0DSWCms++zhn5NAd7rfZJut81wR5k=; b=GfY1Y5PqRYnF7NMu15paoNqquSXnDYOM/VsbWBm1x/i5auUs+FhBNOmrLZo/Kn5PaS 4aH+x6tEldP5V0OmS4lLL2NDZwGN5Z57R2e6b5GMfN60nrL2TLZih+D7mMpIcauq5eWb FGZJYivEM4z+COSpCSB/K3o4jCQKRSGs5o070HwhbNIB3eB2XHFfbyC57h+xlnfTssxD 9Si4I0naSPc4aFkD5HzXUZ8c80wdVpjZQSUy25K4W1WZQ5lTp7fLrXm5JX7YlCPV9CcE 4sccIXiUGKql021JhbiorMYf52yP8w2uZm5MeeucHiPeBOdbSrxqu4zRy0XLCkoJT5zT RfMQ=='}, {'name': 'X-Gm-Message-State', 'value': 'APt69E27szFihIx5AGfr09D5H3zL9qmvELdzWXRPVMCX8g4Ylmmrfujp hlPEW7ugivU='}, {'name': 'X-Google-Smtp-Source', 'value': 'ADUXVKJk9ZZV72gBSPr06HYC5DTltujUq4EoDXGBs0mvbz2wiFZMzKQnzlUC3eKAMN0/GfE20c4='},
{'name': 'MIME-Version', 'value': '1.0'},
{'name': 'X-Received', 'value': 'by 2002:a25:8706:: with SMTP id a6-v6mr8168201ybl.49.1530580312922; Mon, 02 Jul 2018 18:11:52 -0700 (PDT)'}, {'name': 'Date', 'value': 'Mon, 02 Jul 2018 18:11:52 -0700'}, {'name': 'List-Id', 'value': '<11057473802345533838.alerts.google.com>'}, {'name': 'List-Unsubscribe', 'value': '<mailto:ur@unsubscribe.alerts.google.com?subject=AB2Xq4hvjI58wr9UK4tU7q0qsP1xftiU6kOl3SA>'}, {'name': 'Message-ID', 'value': '<000000000000da1bf605700dffc3@google.com>'},
{'name': 'Subject', 'value': 'Google Alert - Phase III trial'},
{'name': 'From', 'value': 'Google Alerts <googlealerts-noreply@google.com>'},
{'name': 'To', 'value': 'tiffanyfabianac@gmail.com'},
{'name': 'Content-Type', 'value': 'multipart/alternative; boundary="000000000000da1bcf05700dffc0"'}],
'body': {'size': 0},
'parts': [{'partId': '0', 'mimeType': 'text/plain', 'filename': '',
'headers': [
{'name': 'Content-Type', 'value': 'text/plain; charset="UTF-8"; format=flowed; delsp=yes'},
{'name': 'Content-Transfer-Encoding', 'value': 'base64'}],
'body': {'size': 2131, 'data': 'PT09IE5ld3MgLSAzIG5ldyByZXN1bHRzIGZvciBbUGhhc2UgSUlJIHRyaWFsXSA9PT0NCg0KRHIuIFlhcmRsZXkgb24gdGhlIFJvbGUgb2YgQmlvc2ltaWxhcnMgaW4gQnJlYXN0IENhbmNlcg0KT25jTGl2ZQ0KVGhlIHBoYXNlIElJSSB0cmlhbCBzaG93ZWQgYW4gZXF1aXZhbGVudCBwYXRob2xvZ2ljIGNvbXBsZXRlIHJlc3BvbnNlIHJhdGUNCmJldHdlZW4gdHJhc3R1enVtYWIgKEhlcmNlcHRpbikgYW5kIHRoZSBiaW9zaW1pbGFyIEFCUCA5ODAuIEFsdGhvdWdoIC4uLg0KPGh0dHBzOi8vd3d3Lmdvb2dsZS5jb20vdXJsP3JjdD1qJnNhPXQmdXJsPWh0dHBzOi8vd3d3Lm9uY2xpdmUuY29tL29uY2xpdmUtdHYvZHIteWFyZGxleS1vbi10aGUtcm9sZS1vZi1iaW9zaW1pbGFycy1pbi1icmVhc3QtY2FuY2VyJmN0PWdhJmNkPUNBRVlBQ29UTWpRNE9Ea3pNVGd3TlRZM01UTTJPRFF5TVRJY04yUTRNR0V4T1dObE1UbGhNVGM0TmpwamIyMDZaVzQ2VlZNNlVnJnVzZz1BRlFqQ05Ha3U3R19TN3Z2UzlmMENkRVlBRmVhdmd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TVRNMk9EUXlNUT4NCg=='}},
{'partId': '1', 'mimeType': 'text/html', 'filename': '',
'headers': [{'name': 'Content-Type', 'value': 'text/html; charset="UTF-8"'},
{'name': 'Content-Transfer-Encoding', 'value': 'quoted-printable'}],
'body': {'size': 22634, 'data': 'PGh0bWwgbGFuZz0iZW4tVVMiPiA8aGVhZD4gIDwvaGVhZD4gPGJvZHk-IDxkaXY-ICA8c2NyaXB0IGRhdGEtc2NvcGU9ImluYm94bWFya3VwIiB0eXBlPSJhcHBsaWNhdGlvbi9qc29uIj57DQogICJhcGlfdmVyc2lvbiI6ICIxLjAiLA0KICAicHVibGlzaGVyIjogew0KICAgICJhcGlfa2V5IjogIjY2ODI2OWU3MmNmZWRlYTMxYjIyNTI0MDQxZmYyMWQ5IiwNCiAgICAibmFtZSI6ICJHb29nbGUgQWxlcnRzIg0KICB9LA0KICAiZW50aXR5Ijogew0KICAgICJleHRlcm5hbF9rZXkiOiAiR29vZ2xlIEFsZXJ0IC0gUGhhc2UgSUlJIHRyaWFsIiwNCiAgICAidGl0bGUiOiAiR29vZ2xlIEFsZXJ0IC0gUGhhc2UgSUlJIHRyaWFsIiwNCiAgICAic3VidGl0bGUiOiAiTGF0ZXN0OiBKdWx5IDMsIDIwMTgiLA0KICAgICJhdmF0YXJfaW1hZ2VfdXJsIjogImh0dHBzOi8vd3d3LmdzdGF0aWMuY29tL2ltYWdlcy9icmFuZGluZy9wcm9kdWN0LzF4L2dzYV81MTJkcC5wbmciLA0KICAgICJtYWluX2ltYWdlX3VybCI6ICJodHRwczovL3d3dy5nc3RhdGljLmNvbS9idC9DMzM0MUFBN0ExQTA3Njc1NjQ2MkVFMkU1Q0Q3MUMxMS9zbWFydG1haWwvbW9iaWxlL2lsX25ld3NwYXBlcl9oZWFkZXJfcjEucG5nIg0KICB9LA0KICAidXBkYXRlcyI6IHsNCiAgICAic25pcHBldHMiOiBbIHsNCiAgICAgICJpY29uIjogIkJPT0tNQVJLIiwNCiAgICAgICJtZXNzYW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owOyB6LWluZGV4OjE7JyBzcmM9Imh0dHBzOi8vaW1nLnlvdXR1YmUuY29tL3ZpL052Nk9hYXpiWEM4L2RlZmF1bHQuanBnIi8-DQogICAgICAgPHY6cmVjdCB4bWxuczp2PSJ1cm46c2NoZW1hcy1taWNyb3NvZnQtY29tOnZtbCINCiAgICAgICAgICAgICAgIHN0eWxlPSdiZWhhdmlvcjogdXJsKCNkZWZhdWx0I1ZNTCk7DQogICAgICAgICAgICAgICAgICAgICAgZGlzcGxheTppbmxpbmUtYmxvY2s7DQogICAgICAgICAgICAgICAgICAgICAgcG9zaXRpb246IGFic29sdXRlOyB0b3A6IDgycHg7IGxlZnQ6IDBweDsNCiAgICAgICAgICAgICAgICAgICAgICB3aWR0aDoxMDBweDsgYm9yZGVyOjA7IHotaW5kZXg6MjsnIHN0cm9rZWNvbG9yPSJub25lIj4NCiAgICAgICA8djpmaWxsIG9wYWNpdHk9IjUwJSIgY29sb3I9IiMwMDAwMDAiLz4NCiAgICAgICA8djp0ZXh0Ym94IHN0eWxlPSJtc28tZml0LXNoYXBlLXRvLXRleHQ6dDsNCiAgICAgICAgICAgICAgICAgICAgICAgICBtc28tY29sdW1uLW1hcmdpbjogMHB0Ow0KICAgICAgICAgICAgICAgICAgICAgICAgIGxldHRlci1zcGFjaW5nOiAwLjhweDsiDQogICAgICAgICAgICAgICAgICAgICAgICAgaW5zZXQ9IjBwdCwwcHQsMHB0LDBwdCI-DQogICAgICAgICA8Zm9udCBzaXplPSItMSIgY29sb3I9IiNmZmZmZmYiPjwvZm9udD4NCiAgICAgICA8L3Y6dGV4dGJveD4NCiAgICAgICA8L3Y6cmVjdD4NCiAgICAgICA8ZGl2IHN0eWxlPSJkaXNwbGF5OiBub25lIj4NCiAgICAgICA8IVtlbmRpZl0tLT4gPGRpdiBzdHlsZT0iY29sb3I6I2ZmZjtmb250LXNpemU6OXB4O2xldHRlci1zcGFjaW5nOjAuOHB4Ij4gPGRpdiBzdHlsZT0icGFkZGluZzozcHgg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ZhbXA7Z2w9VVMmYW1wO21zZ2lkPU1qUTRPRGt6TVRnd05UWTNNVE0yT0RReU1RJmFtcDtzPUFCMlhxNGh2akk1OHdyOVVLNHRVN3EwcXNQMXhmdGlVNmtPbDNTQSZhbXA7ZmZ1PSIgc3R5bGU9InRleHQtZGVjb3JhdGlvbjpub25lO2NvbG9yOiM0MjdmZWQiPiA8ZGl2IHN0eWxlPSJkaXNwbGF5OmlubGluZTtsaW5lLWhlaWdodDoxNnB4O3ZlcnRpY2FsLWFsaWduOm1pZGRsZSI-IFNlbmQgRmVlZGJhY2sgPC9kaXY-IDwvYT4gPC90ZD4gPC90cj4gPC90YWJsZT4gPC9kaXY-IDwvZGl2PiA8IS0tW2lmIG1zb10-DQo8L3RkPjwvdHI-PC90YWJsZT4NCjwhW2VuZGlmXS0tPg0KICAgPC9kaXY-ICA8L2JvZHk-IDwvaHRtbD4='}}]}, 'sizeEstimate': 32554}
'''
# Get the data from the message
payld = message['payload']
# Get Date
headr = payld['headers'] # get header of the payload
for two in headr:
if two['name'] == 'Date':
msg_date = two['value']
date_parse = (parser.parse(msg_date))
m_date = (date_parse.date())
msg_date = str(m_date)
else:
pass
# Get Message
parts = payld['parts']
for i in parts:
if i['partId'] == '0':
msg_str = base64.urlsafe_b64decode(i['body'].get('data'))
mime_msg = email.message_from_string(bytes.decode(msg_str))
else:
pass
# Remove the Unsubscribe and Google related links from message
msg_string = mime_msg.as_string()
msg_string = msg_string.rsplit('- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -', 1)[0]
msg_string = re.sub(r'===*.*===\n\n', '', msg_string)
# Extract Hyperlinks
myList =[]
# summaries = []
#urls = re.sub(r'>', '',re.search("(?P<url>https?://[^\s]+)", msg_string).group("url"))
urls = re.findall("(=https://www.*.*?>)",msg_string)
for i in range(len(urls)):
sURL = urls[i][1:-1]
summaries = re.sub(r'\n', ' ', msg_string.partition(urls[i])[0]).rsplit('<https://www.google.com', 1)[0]
if i != 0:
temp_link = urls[i-1][1:-1]
summaries = summaries.partition(temp_link)[2]
temp_dict = ({'Date': msg_date, 'URL': sURL, 'Summary': summaries})
myList.append(temp_dict)
print (myList) | [
"noreply@github.com"
] | noreply@github.com |
44f0a16cb6fcf836890a2a7383410fd334e0908d | e45c6f36a065b6a44e873a773428105de4d3758e | /bases/br_me_caged/code/caged_antigo/scpts/caged.py | 5a26195ed1c67ee805eb3133d1c765f73239f8c8 | [
"MIT"
] | permissive | basedosdados/mais | 080cef1de14376699ef65ba71297e40784410f12 | 2836c8cfad11c27191f7a8aca5ca26b94808c1da | refs/heads/master | 2023-09-05T20:55:27.351309 | 2023-09-02T03:21:02 | 2023-09-02T03:21:02 | 294,702,369 | 376 | 98 | MIT | 2023-08-30T21:17:28 | 2020-09-11T13:26:45 | SQL | UTF-8 | Python | false | false | 25,196 | py | """
Extract and clean CAGED data
"""
# pylint: disable=invalid-name,unnecessary-comprehension,import-error
import sys
import time
import os
import shutil
from contextlib import closing
from urllib import request
import pandas as pd
import numpy as np
import manipulation
sys.path.insert(0, "../")
def create_folder_structure():
"""
Create folder structure for CAGED data
"""
### cria pasta data caso n exista
if not os.path.exists("../data"):
os.mkdir("../data")
if not os.path.exists("../data/caged/"):
os.mkdir("../data/caged/")
if not os.path.exists("../data/caged/raw"):
os.mkdir("../data/caged/raw")
if not os.path.exists("../data/caged/raw/caged_antigo"):
os.mkdir("../data/caged/raw/caged_antigo")
if not os.path.exists("../data/caged/raw/caged_novo"):
os.mkdir("../data/caged/raw/caged_novo")
if not os.path.exists("../data/caged/raw/caged_antigo_ajustes"):
os.mkdir("../data/caged/raw/caged_antigo_ajustes")
if not os.path.exists("../data/caged/clean/"):
os.mkdir("../data/caged/clean")
if not os.path.exists("../data/caged/clean/caged_antigo"):
os.mkdir("../data/caged/clean/caged_antigo")
if not os.path.exists("../data/caged/clean/caged_novo"):
os.mkdir("../data/caged/clean/caged_novo")
if not os.path.exists("../data/caged/clean/caged_antigo_ajustes"):
os.mkdir("../data/caged/clean/caged_antigo_ajustes")
def download_data(download_link, download_path, filename):
"""
Download data from link and save it in path
"""
## download do arquivo
with closing(request.urlopen(download_link)) as r:
with open(os.path.join(download_path, filename), "wb") as f:
shutil.copyfileobj(r, f)
#####======================= ANTIGO CAGED DOWNLOAD =======================#####
def download_caged_normal(download_link, download_path_year, ano, mes):
"""
download dos arquivos do caged para os anos 2007 a 2019.
Tambem vale para arquivos de ajustes entre 2010 e 2019
"""
download_path_month = download_path_year + f"/{int(mes)}/"
## cria pastas
if os.path.exists(download_path_year):
if not os.path.exists(download_path_month):
os.mkdir(download_path_month)
else:
os.mkdir(download_path_year)
if not os.path.exists(download_path_month):
os.mkdir(download_path_month)
if "AJUSTE" not in download_link:
filename = f"CAGEDEST_{mes}{ano}.7z"
else:
filename = f"CAGEDEST_AJUSTES_{mes}{ano}.7z"
## verifica se arquivo ja existe
if os.path.exists(os.path.join(download_path_month, filename)):
print(f"{mes}/{ano} | já existe")
else:
try:
ti = time.time()
download_data(download_link, download_path_month, filename)
t = time.strftime("%M:%S", time.gmtime((time.time() - ti)))
print(f"{mes}/{ano} | criado em {t}")
except Exception:
print(f"{mes}/{ano} | não conseguiu baixar")
def download_caged_ajustes_2002a2009(download_link, download_path_year, ano):
"""
download dos arquivos de ajustes do caged para os anos 2002 a 2009
"""
if not os.path.exists(download_path_year):
os.mkdir(download_path_year)
os.mkdir(download_path_year + "/1")
download_path_year = download_path_year + "/1"
## verifica se arquivo ja existe
filename = filename = f"CAGEDEST_AJUSTES_{ano}.7z"
if os.path.exists(os.path.join(download_path_year, filename)):
print(f"{ano} | já existe")
else:
try:
ti = time.time()
download_data(download_link, download_path_year, filename)
t = time.strftime("%M:%S", time.gmtime((time.time() - ti)))
print(f"{ano} | criado em {t}")
except Exception:
print(f"{ano} | não conseguiu baixar")
def download_caged_file(download_link, ano=None, mes=None, raw_path=None):
"""
Download CAGED file
"""
# cria estrutura de pastas
create_folder_structure()
## cria link e path das pastas
download_path_year = raw_path + f"/{ano}"
if isinstance(ano, int):
download_caged_normal(download_link, download_path_year, ano, mes)
else:
download_caged_ajustes_2002a2009(download_link, download_path_year, ano)
def caged_antigo_download():
"""
Download CAGED antigo
"""
## define caminhos
raw_path = "../data/caged/raw/caged_antigo"
# seleciona anos e meses a serem baixados
anos = [i for i in range(2007, 2020)]
meses = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]
print("#===== CAGED ANTIGO =====#\n")
for ano in anos:
for mes in meses:
download_link = f"ftp://ftp.mtps.gov.br/pdet/microdados/CAGED/{ano}/CAGEDEST_{mes}{ano}.7z"
download_caged_file(download_link, ano, mes, raw_path)
print("\n")
def caged_antigo_ajustes_download():
"""
Download CAGED antigo ajustes
"""
## define caminhos
raw_path = "../data/caged/raw/caged_antigo_ajustes"
# seleciona anos e meses a serem baixados
anos = [i for i in range(2010, 2020)]
meses = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]
print("#===== CAGED ANTIGO AJUSTES =====#\n")
for ano in anos:
for mes in meses:
download_link = f"ftp://ftp.mtps.gov.br/pdet/microdados/CAGED_AJUSTES/{ano}/CAGEDEST_AJUSTES_{mes}{ano}.7z"
download_caged_file(download_link, ano, mes, raw_path)
print("\n")
def caged_antigo_ajustes_2002a2009_download():
"""
Ajustes CAGED antigo
"""
raw_path = "../data/caged/raw/caged_antigo_ajustes"
anos = [str(i) for i in range(2007, 2010)]
print("#===== CAGED ANTIGO AJUSTES 2002a2009 =====#\n")
for ano in anos:
download_link = f"ftp://ftp.mtps.gov.br/pdet/microdados/CAGED_AJUSTES/2002a2009/CAGEDEST_AJUSTES_{ano}.7z"
download_caged_file(download_link, ano, mes=None, raw_path=raw_path)
print("\n")
def caged_antigo_ajustes_2002a2009_extract_organize(folders, force_remove_csv=False):
"""
Os anos de 2002 a 2009 nao possuem arquivos para cada mes.
Essa funcão extrai o arquivo .7z e cria o .csv na mesma
estrutura de ano/mes
"""
folders = [
folder
for folder in folders
for ano in ["2007", "2008", "2009"]
if ano in folder
]
for folder in folders:
ano = folder.split("/")[-2]
filename_7z = get_file_names_and_clean_residues(folder, force_remove_csv)
extract_file(folder, filename_7z, save_rows=None)
print(f"{ano} | extraido")
filename = [file for file in os.listdir(folder) if ".csv" in file][0][:-4]
df = pd.read_csv(f"{folder}{filename}.csv", dtype="str")
df["ano"] = df["competencia_declarada"].apply(lambda x: str(x)[:4])
df["mes"] = df["competencia_declarada"].apply(lambda x: str(x)[4:])
for mes in df["mes"].unique():
if not os.path.exists(f"{folder}{str(int(mes))}"):
os.mkdir(f"{folder}{str(int(mes))}")
mask = df["mes"] == mes
dd = df[mask]
dd = dd.drop(["ano", "mes"], 1)
dd.to_csv(
f"{folder}{str(int(mes))}/{filename_7z[:-5]}_{mes}{ano}.csv",
index=False,
encoding="utf-8",
)
#####======================= MANIPULA ARQUIVOS =======================#####
def extract_file(path_month, filename, save_rows=10):
"""
Extrai arquivo .7z
"""
if not os.path.exists(f"{path_month}{filename}.csv"):
filename_txt = [
file for file in os.listdir(path_month) if ".txt" in file.lower()
][0]
try:
df = pd.read_csv(
f"{path_month}{filename_txt}",
sep=";",
encoding="latin-1",
nrows=save_rows,
dtype="str",
)
except Exception:
## caso de erro de bad lines por conter um ; extra no arquivo txt
with open(
f"{path_month}{filename_txt}",
encoding="latin-1",
) as f:
newText = f.read().replace(";99;", ";99")
with open(f"{path_month}{filename_txt}", "w", encoding="latin-1") as f:
f.write(newText)
df = pd.read_csv(
f"{path_month}{filename_txt}",
sep=";",
encoding="latin-1",
nrows=save_rows,
dtype="str",
)
df.columns = manipulation.normalize_cols(df.columns)
df.to_csv(f"{path_month}{filename}.csv", index=False, encoding="utf-8")
os.remove(f"{path_month}{filename_txt}")
def get_file_names_and_clean_residues(path_month, force_remove_csv=True):
"""
Get file names and clean residues
"""
filename_txt = [file for file in os.listdir(path_month) if ".txt" in file.lower()]
filename_csv = [file for file in os.listdir(path_month) if ".csv" in file]
try:
filename_7z = [file for file in os.listdir(path_month) if ".7z" in file][0][:-3]
except Exception:
filename_7z = filename_csv[0][:-4]
if filename_txt != []:
os.remove(f"{path_month}{filename_txt[0]}")
if filename_csv != [] and force_remove_csv is True:
os.remove(f"{path_month}{filename_csv[0][:-4]}.csv")
return filename_7z
def make_dirs(path, folder, var):
"""
Make dirs
"""
if not os.path.exists(f"{path}{var}={folder}/"):
os.mkdir(f"{path}{var}={folder}/")
def make_folder_tree(clean_path, ano, mes, uf="SP"):
"""
Make folder tree
"""
make_dirs(clean_path, ano, var="ano")
path_ano = f"{clean_path}/ano={ano}/"
make_dirs(path_ano, mes, var="mes")
path_mes = f"{clean_path}/ano={ano}/mes={mes}/"
make_dirs(path_mes, uf, var="sigla_uf")
return f"{clean_path}/ano={ano}/mes={mes}/sigla_uf={uf}/"
def save_partitioned_file(df, clean_save_path, ano, mes, file_name):
"""
Save partitioned file
"""
for uf in df.sigla_uf.unique():
## filtra apenas o estado de interesse
df_uf = df[df["sigla_uf"] == uf]
## exclui colunas particionadas
df_uf = df_uf.drop(["sigla_uf"], 1)
## cria estrutura de pastas
path_uf = make_folder_tree(clean_save_path, ano, mes, uf)
df_uf.to_csv(f"{path_uf}{file_name}.csv", index=False)
def caged_antigo_padronize_and_partitioned(
folders, clean_save_path, municipios, force_remove_csv=True
):
"""
Padroniza e particiona arquivos CAGED
"""
# all_cols = pd.DataFrame()
for folder in folders:
ano = folder.split("/")[-3]
mes = folder.split("/")[-2]
if "ajustes" in clean_save_path:
mode = "ajustes"
save_name = "caged_antigo_ajustes"
else:
mode = "padrao"
save_name = "caged_antigo"
if mode == "padrao" or (int(ano)) > 2009:
filename_7z = get_file_names_and_clean_residues(folder, force_remove_csv)
else:
filename_7z = get_file_names_and_clean_residues(folder, False)
## verifica se o arquivo ja foi tratado
if (
os.path.exists(f"{clean_save_path}/ano={ano}/mes={mes}")
and len(os.listdir(f"{clean_save_path}/ano={ano}/mes={mes}")) == 27
):
print(f"{ano}-{mes} | já tratado | arquivo {mode}\n")
else:
## extrai o arquivo zipado, cria um novo arquivo .csv e deleta o arquivo extraido (.txt)
if mode == "padrao" or (int(ano)) > 2009:
extract_file(folder, filename_7z, save_rows=None)
print(f"{ano}-{mes} | extraido | arquivo {mode}")
## le o arquivo
filename = [file for file in os.listdir(folder) if ".csv" in file][0][:-4]
df = pd.read_csv(
f"{folder}{filename}.csv",
dtype="str",
)
## padronizacao dos dados | caso seja o Path de ajustes chama funcao de padronizacao de ajustes
if mode == "ajustes":
df = padroniza_caged_antigo_ajustes(df, municipios)
else:
df = padroniza_caged_antigo(df, municipios)
print(f"{ano}-{mes} | padronizado | arquivo {mode}")
save_partitioned_file(df, clean_save_path, ano, mes, file_name=save_name)
# remove arquivo csv do raw files
if mode == "padrao" or (int(ano)) > 2009:
os.remove(f"{folder}{filename}.csv")
print(f"{ano}-{mes} | finalizado | arquivo {mode}\n")
# # checa nome de todas as colunas
# dd = pd.DataFrame(df.columns.tolist(), columns=["cols"])
# dd = dd.transpose().reset_index(drop=True)
# cols = dd.columns.tolist()
# dd["ano"] = ano
# dd["mes"] = mes
# dd = dd[["ano", "mes"] + cols]
# all_cols = pd.concat([all_cols, dd])
#####======================= PADRONIZA CAGED FUNCOES =======================#####
def clean_caged(df, municipios):
"""
Clean CAGED
"""
## cria coluna ano e mes apartir da competencia declarada
df["competencia_declarada"] = df["competencia_declarada"].apply(
lambda x: str(x)[:4] + "-" + str(x)[4:]
)
if "competencia_movimentacao" in df.columns.tolist():
df["competencia_movimentacao"] = df["competencia_movimentacao"].apply(
lambda x: str(x)[:4] + "-" + str(x)[4:]
)
# renomeia municipio para padrao do diretorio de municipios
rename_cols = {
"municipio": "id_municipio_6",
}
df = df.rename(columns=rename_cols)
# adiciona id_municio do diretorio de municipios
df = df.merge(municipios, on="id_municipio_6", how="left")
# remove strings do tipo {ñ e converte salario e tempo de emprego para float
objct_cols = df.select_dtypes(include=["object"]).columns.tolist()
for col in objct_cols:
if col in ["salario_mensal", "tempo_emprego"]:
df[col] = pd.to_numeric(
df[col].str.replace(",", "."), downcast="float", errors="coerce"
)
else:
df[col] = np.where(df[col].str.contains("{ñ"), np.nan, df[col])
df = df.drop(["mesorregiao", "microrregiao", "uf", "competencia_declarada"], 1)
df = df[df["sigla_uf"].notnull()]
return df
#####======================= PADRONIZA DADOS CAGED AJUSTES =======================#####
def padroniza_caged_antigo_ajustes(df, municipios):
"""
Padroniza dados CAGED ajustes
"""
## cria colunas que nao existem em outros arquivos
check_cols = ["ind_trab_parcial", "ind_trab_intermitente"]
create_cols = [col for col in check_cols if col not in df.columns.tolist()]
for col in create_cols:
df[col] = np.nan
hard_coded_cols = [
"admitidos_desligados",
"competencia_movimentacao",
"municipio",
"ano_movimentacao",
"cbo_94_ocupacao",
"cbo_2002_ocupacao",
"cnae_10_classe",
"faixa_empr_inicio_jan",
"grau_instrucao",
"qtd_hora_contrat",
"ibge_subsetor",
"idade",
"ind_aprendiz",
"salario_mensal",
"saldo_mov",
"sexo",
"tempo_emprego",
"tipo_estab",
"tipo_mov_desagregado",
"uf",
"competencia_declarada",
"bairros_sp",
"bairros_fortaleza",
"bairros_rj",
"distritos_sp",
"regioes_adm_df",
"mesorregiao",
"microrregiao",
"regiao_adm_rj",
"regiao_adm_sp",
"regiao_corede",
"regiao_corede_04",
"regiao_gov_sp",
"regiao_senac_pr",
"regiao_senai_pr",
"regiao_senai_sp",
"subregiao_senai_pr",
"regiao_metro_mte",
"cnae_20_subclas",
"raca_cor",
"ind_portador_defic",
"tipo_defic",
"ind_trab_parcial",
"ind_trab_intermitente",
]
df = df[hard_coded_cols]
# df.columns = hard_coded_cols
#### remove typos e define tipos
df = clean_caged(df, municipios)
df = df.drop(["ano_movimentacao"], 1)
organize_cols = [
"competencia_movimentacao",
"sigla_uf",
"id_municipio",
"id_municipio_6",
"admitidos_desligados",
"tipo_estab",
"tipo_mov_desagregado",
"faixa_empr_inicio_jan",
"tempo_emprego",
"qtd_hora_contrat",
"salario_mensal",
"saldo_mov",
"ind_aprendiz",
"ind_trab_intermitente",
"ind_trab_parcial",
"ind_portador_defic",
"tipo_defic",
"cbo_94_ocupacao",
"cnae_10_classe",
"cbo_2002_ocupacao",
"cnae_20_subclas",
"grau_instrucao",
"idade",
"sexo",
"raca_cor",
"ibge_subsetor",
"bairros_sp",
"bairros_fortaleza",
"bairros_rj",
"distritos_sp",
"regioes_adm_df",
"regiao_adm_rj",
"regiao_adm_sp",
"regiao_corede",
"regiao_corede_04",
"regiao_gov_sp",
"regiao_senac_pr",
"regiao_senai_pr",
"regiao_senai_sp",
"subregiao_senai_pr",
"regiao_metro_mte",
]
df = df[organize_cols]
columns_rename = {
"cbo_2002_ocupacao": "cbo_2002",
"cbo_94_ocupacao": "cbo_1994",
"cnae_10_classe": "cnae_1",
"cnae_20_subclas": "cnae_2_subclasse",
"faixa_empr_inicio_jan": "faixa_emprego_inicio_janeiro",
"qtd_hora_contrat": "quantidade_horas_contratadas",
"ibge_subsetor": "subsetor_ibge",
"ind_aprendiz": "indicador_aprendiz",
"ind_portador_defic": "indicador_portador_deficiencia",
"saldo_mov": "saldo_movimentacao",
"tipo_estab": "tipo_estabelecimento",
"tipo_defic": "tipo_deficiencia",
"tipo_mov_desagregado": "tipo_movimentacao_desagregado",
"regioes_adm_df": "regiao_administrativas_df",
"regiao_adm_rj": "regiao_administrativas_rj",
"regiao_adm_sp": "regiao_administrativas_sp",
"ind_trab_parcial": "indicador_trabalho_parcial",
"ind_trab_intermitente": "indicador_trabalho_intermitente",
"regiao_metro_mte": "regiao_metropolitana_mte",
}
df = df.rename(columns=columns_rename)
return df
#####======================= PADRONIZA DADOS CAGED ANTIGO =======================#####
def padroniza_caged_antigo(df, municipios):
"""
Padroniza dados do CAGED antigo
"""
## cria colunas que nao existem em outros arquivos
check_cols = ["ind_trab_parcial", "ind_trab_intermitente"]
create_cols = [col for col in check_cols if col not in df.columns.tolist()]
for col in create_cols:
df[col] = np.nan
## renomeia colunas para alguns casos typo nos arquivos originais
rename_typo_columns = {
"competaancia_declarada": "competencia_declarada",
"municapio": "municipio",
"cbo_2002_ocupaaao": "cbo_2002_ocupacao",
"faixa_empr_inacio_jan": "faixa_empr_inicio_jan",
"grau_instruaao": "grau_instrucao",
"raaa_cor": "raca_cor",
"regiaes_adm_df": "regioes_adm_df",
}
df = df.rename(columns=rename_typo_columns)
hard_coded_cols = [
"admitidos_desligados",
"competencia_declarada",
"municipio",
"ano_declarado",
"cbo_2002_ocupacao",
"cnae_10_classe",
"cnae_20_classe",
"cnae_20_subclas",
"faixa_empr_inicio_jan",
"grau_instrucao",
"qtd_hora_contrat",
"ibge_subsetor",
"idade",
"ind_aprendiz",
"ind_portador_defic",
"raca_cor",
"salario_mensal",
"saldo_mov",
"sexo",
"tempo_emprego",
"tipo_estab",
"tipo_defic",
"tipo_mov_desagregado",
"uf",
"bairros_sp",
"bairros_fortaleza",
"bairros_rj",
"distritos_sp",
"regioes_adm_df",
"mesorregiao",
"microrregiao",
"regiao_adm_rj",
"regiao_adm_sp",
"regiao_corede",
"regiao_corede_04",
"regiao_gov_sp",
"regiao_senac_pr",
"regiao_senai_pr",
"regiao_senai_sp",
"subregiao_senai_pr",
"ind_trab_parcial",
"ind_trab_intermitente",
]
df = df[hard_coded_cols]
# df.columns = hard_coded_cols
#### remove typos e define tipos
df = clean_caged(df, municipios)
df = df.drop(["ano_declarado"], 1)
organize_cols = [
"sigla_uf",
"id_municipio",
"id_municipio_6",
"admitidos_desligados",
"tipo_estab",
"tipo_mov_desagregado",
"faixa_empr_inicio_jan",
"tempo_emprego",
"qtd_hora_contrat",
"salario_mensal",
"saldo_mov",
"ind_aprendiz",
"ind_trab_intermitente",
"ind_trab_parcial",
"ind_portador_defic",
"tipo_defic",
"cnae_10_classe",
"cbo_2002_ocupacao",
"cnae_20_classe",
"cnae_20_subclas",
"grau_instrucao",
"idade",
"sexo",
"raca_cor",
"ibge_subsetor",
"bairros_sp",
"bairros_fortaleza",
"bairros_rj",
"distritos_sp",
"regioes_adm_df",
"regiao_adm_rj",
"regiao_adm_sp",
"regiao_corede",
"regiao_corede_04",
"regiao_gov_sp",
"regiao_senac_pr",
"regiao_senai_pr",
"regiao_senai_sp",
"subregiao_senai_pr",
]
df = df[organize_cols]
columns_rename = {
"cbo_2002_ocupacao": "cbo_2002",
"cnae_10_classe": "cnae_1",
"cnae_20_classe": "cnae_2",
"cnae_20_subclas": "cnae_2_subclasse",
"faixa_empr_inicio_jan": "faixa_emprego_inicio_janeiro",
"qtd_hora_contrat": "quantidade_horas_contratadas",
"ibge_subsetor": "subsetor_ibge",
"ind_aprendiz": "indicador_aprendiz",
"ind_portador_defic": "indicador_portador_deficiencia",
"saldo_mov": "saldo_movimentacao",
"tipo_estab": "tipo_estabelecimento",
"tipo_defic": "tipo_deficiencia",
"tipo_mov_desagregado": "tipo_movimentacao_desagregado",
"regioes_adm_df": "regiao_administrativas_df",
"regiao_adm_rj": "regiao_administrativas_rj",
"regiao_adm_sp": "regiao_administrativas_sp",
"ind_trab_parcial": "indicador_trabalho_parcial",
"ind_trab_intermitente": "indicador_trabalho_intermitente",
}
df = df.rename(columns=columns_rename)
return df
#####======================= PADRONIZA DADOS NOVO CAGED =======================#####
def padroniza_caged_novo(df, municipios):
"""
Padroniza dados do CAGED novo
"""
## cria coluna ano e mes apartir da competencia declarada
df["ano"] = df["competencia_declarada"].apply(lambda x: int(str(x)[:4]))
df["mes"] = df["competencia_declarada"].apply(lambda x: int(str(x)[4:]))
## cria colunas que nao existem em outros arquivos
df = df.drop(
["competencia_declarada", "uf", "regiao"],
1,
)
df = clean_caged(df, municipios)
return df
def rename_caged_novo(df, option):
"""
Renomeia colunas do CAGED novo
"""
rename_cols_estabelecimentos = {
"competaancia": "competencia_declarada",
"regiao": "regiao",
"uf": "uf",
"municapio": "municipio",
"seaao": "cnae_20_classe",
"subclasse": "cnae_20_subclas",
"admitidos": "admitidos",
"desligados": "desligados",
"fonte_desl": "fonte_desligamento",
"saldomovimentaaao": "saldo_movimentacao",
"tipoempregador": "tipo_empregador",
"tipoestabelecimento": "tipo_estab",
"tamestabjan": "faixa_empr_inicio_jan",
}
rename_cols_movimentacao = {
"competaancia": "competencia_declarada",
"regiao": "regiao",
"uf": "uf",
"municapio": "municipio",
"seaao": "cnae_20_classe",
"subclasse": "cnae_20_subclas",
"saldomovimentaaao": "saldo_mov",
"cbo2002ocupaaao": "cbo_2002_ocupacao",
"categoria": "categoria_trabalhador",
"graudeinstruaao": "grau_instrucao",
"idade": "idade",
"horascontratuais": "qtd_hora_contrat",
"raaacor": "raca_cor",
"sexo": "sexo",
"tipoempregador": "tipo_empregador",
"tipoestabelecimento": "tipo_estab",
"tipomovimentaaao": "tipo_movimentacao",
"tipodedeficiaancia": "tipo_defic",
"indtrabintermitente": "ind_trab_intermitente",
"indtrabparcial": "ind_trab_parcial",
"salario": "salario_mensal",
"tamestabjan": "faixa_empr_inicio_jan",
"indicadoraprendiz": "ind_aprendiz",
"fonte": "fonte_movimentacao",
}
if option == "movimentacao":
df = df.rename(columns=rename_cols_movimentacao)
else:
df = df.rename(columns=rename_cols_estabelecimentos)
return df
| [
"noreply@github.com"
] | noreply@github.com |
cc5e512c40eeb3d7ecfa986f9e8245d9a2c05f43 | 48b2fd9da2b8c67b1d732dae445c21cd6d878504 | /warrior/test_WarriorCore/test_defects_driver.py | 37eaf27fccb5059193d351b85a125d7a5aa51870 | [
"Apache-2.0"
] | permissive | shubhendra-tomar/warriorframework_py3 | 6ca4f59cd44c2420c48c7ccab505ffdcc76820fd | fc268c610c429f5a60e5627c2405aa66036487dd | refs/heads/master | 2023-07-17T09:34:35.025678 | 2021-05-10T06:43:57 | 2021-05-10T06:43:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,423 | py | """
Copyright 2017, Fujitsu Network Communications, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import sys
import os
from os.path import abspath, dirname
from unittest import TestCase
try:
import warrior
# except ModuleNotFoundError as error:
except Exception as e:
WARRIORDIR = dirname(dirname(dirname(abspath(__file__))))
print(WARRIORDIR)
sys.path.append(WARRIORDIR)
import warrior
from warrior.WarriorCore.defects_driver import DefectsDriver
temp_cwd = os.path.split(__file__)[0]
path = os.path.join(temp_cwd, 'UT_results')
try:
os.makedirs(path, exist_ok=True)
result_dir = os.path.join(dirname(abspath(__file__)), 'UT_results')
except OSError as error:
pass
class test_DefectsDriver(TestCase):
""" Defects Driver Class """
def test_get_defect_json_list(self):
"""Gets the list of defect json files for the testcase execution """
wt_resultfile = os.path.join(os.path.split(__file__)[0], "defects_driver_results_tc.xml")
wt_defectsdir = result_dir
with open(result_dir+'/'+'myfile.log', 'w'):
pass
wt_logsdir = os.path.join(result_dir, 'myfile.log')
wt_testcase_filepath = os.path.join(os.path.split(__file__)[0], "defects_driver_tc.xml")
data_repository = {'wt_resultfile':wt_resultfile, 'wt_defectsdir':wt_defectsdir, \
'wt_logsdir':wt_logsdir, 'wt_testcase_filepath': wt_testcase_filepath, 'jiraproj':None}
cls_obj = DefectsDriver(data_repository)
result = cls_obj.get_defect_json_list()
assert type(result) == list
def test_create_failing_kw_json_without_keywords(self):
"""Create a json file each failing keyword """
wt_resultfile = os.path.join(os.path.split(__file__)[0], "defects_driver_results_tc1.xml")
wt_defectsdir = result_dir
with open(result_dir+'/'+'myfile.log', 'w'):
pass
wt_logsdir = os.path.join(result_dir, 'myfile.log')
wt_testcase_filepath = os.path.join(os.path.split(__file__)[0], "defects_driver_tc1.xml")
data_repository = {'wt_resultfile':wt_resultfile, 'wt_defectsdir':wt_defectsdir, \
'wt_logsdir':wt_logsdir, 'wt_testcase_filepath': wt_testcase_filepath, 'jiraproj':None}
cls_obj = DefectsDriver(data_repository)
result = cls_obj.create_failing_kw_json()
assert result == None
def test_create_failing_kw_json_no_failed_keywords(self):
"""Create a json file each failing keyword """
wt_resultfile = os.path.join(os.path.split(__file__)[0], "defects_driver_results_tc2.xml")
wt_defectsdir = result_dir
with open(result_dir+'/'+'myfile.log', 'w'):
pass
wt_logsdir = os.path.join(result_dir, 'myfile.log')
wt_testcase_filepath = os.path.join(os.path.split(__file__)[0], "defects_driver_tc2.xml")
data_repository = {'wt_resultfile':wt_resultfile, 'wt_defectsdir':wt_defectsdir, \
'wt_logsdir':wt_logsdir, 'wt_testcase_filepath': wt_testcase_filepath, 'jiraproj':None}
cls_obj = DefectsDriver(data_repository)
result = cls_obj.create_failing_kw_json()
assert result == False
def test_create_failing_kw_json(self):
"""Create a json file each failing keyword """
wt_resultfile = os.path.join(os.path.split(__file__)[0], "defects_driver_results_tc.xml")
wt_defectsdir = result_dir
with open(result_dir+'/'+'myfile.log', 'w'):
pass
wt_logsdir = os.path.join(result_dir, 'myfile.log')
wt_testcase_filepath = os.path.join(os.path.split(__file__)[0], "defects_driver_tc.xml")
data_repository = {'wt_resultfile':wt_resultfile, 'wt_defectsdir':wt_defectsdir, \
'wt_logsdir':wt_logsdir, 'wt_testcase_filepath': wt_testcase_filepath, 'jiraproj':None}
cls_obj = DefectsDriver(data_repository)
result = cls_obj.create_failing_kw_json()
assert result == True | [
"venkatadhri.kotakonda@us.fujitsu.com"
] | venkatadhri.kotakonda@us.fujitsu.com |
878f1d4c667f843e3a31085b1d0d6aba7e6df757 | 3deaa908ee9bd781921f5581182b5537b6a340ea | /P2-plagiarism-detection/source_sklearn/train.py | 24656b134ac5337d07152183af799aa2c4706d5a | [
"MIT"
] | permissive | suryasanchez/machine-learning-engineer-nanodegree | b68372d73b59eb7cb5d0a11e9a55dca0e361bbd1 | 8bb4c7b1258dd1aad95011d9fcb25546ed9d9324 | refs/heads/master | 2020-12-27T20:53:33.373136 | 2020-03-29T03:31:21 | 2020-03-29T03:31:21 | 238,049,325 | 7 | 3 | null | null | null | null | UTF-8 | Python | false | false | 2,130 | py | from __future__ import print_function
import argparse
import os
import pandas as pd
from sklearn.externals import joblib
## TODO: Import any additional libraries you need to define a model
from sklearn import svm
# Provided model load function
def model_fn(model_dir):
"""Load model from the model_dir. This is the same model that is saved
in the main if statement.
"""
print("Loading model.")
# load using joblib
model = joblib.load(os.path.join(model_dir, "model.joblib"))
print("Done loading model.")
return model
## TODO: Complete the main code
if __name__ == '__main__':
# All of the model parameters and training parameters are sent as arguments
# when this script is executed, during a training job
# Here we set up an argument parser to easily access the parameters
parser = argparse.ArgumentParser()
# SageMaker parameters, like the directories for training data and saving models; set automatically
# Do not need to change
parser.add_argument('--output-data-dir', type=str, default=os.environ['SM_OUTPUT_DATA_DIR'])
parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])
parser.add_argument('--data-dir', type=str, default=os.environ['SM_CHANNEL_TRAIN'])
## TODO: Add any additional arguments that you will need to pass into your model
parser.add_argument('--epochs', type=int, default=1000)
# args holds all passed-in arguments
args = parser.parse_args()
# Read in csv training file
training_dir = args.data_dir
train_data = pd.read_csv(os.path.join(training_dir, "train.csv"), header=None, names=None)
# Labels are in the first column
train_y = train_data.iloc[:,0]
train_x = train_data.iloc[:,1:]
## --- Your code here --- ##
## TODO: Define a model
model = svm.LinearSVC(max_iter=args.epochs)
## TODO: Train the model
model.fit(train_x, train_y)
## --- End of your code --- ##
# Save the trained model
joblib.dump(model, os.path.join(args.model_dir, "model.joblib")) | [
"suryasanchez@outlook.com"
] | suryasanchez@outlook.com |
43c9fbe98cd91e26a7efe54a86ba1b5103909a08 | 328581c2430f061e379192dacefc0f272f3ef27a | /scifin/exceptions/exceptions.py | 3d5423cf70e34417429b357d0aede8f648625eec | [
"MIT"
] | permissive | sg48/SciFin | e6b70d03d86d4e44caf977b70981678a1c6ed7ce | e4e3d1a32e060c911e43d89df833b3ad078ba6df | refs/heads/master | 2023-03-20T03:49:23.190132 | 2020-10-17T07:29:10 | 2020-10-17T07:29:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 421 | py | # Created on 2020/8/14
# This module is for storing built-in classes for exceptions.
class AccessError(Exception):
"""Raised when a file or url cannot be accessed."""
pass
class SamplingError(Exception):
"""Raised when the sampling of a time series is not uniform."""
pass
class ArgumentsError(Exception):
"""Raised when provided arguments of a function are not satisfactory."""
pass
| [
"fabien.nugier@googlemail.com"
] | fabien.nugier@googlemail.com |
7ea0060a4ae2c77bf6b62d6084705a5bd61a261b | ef458faffdf14ee518f479f0db0b19ba18e8596f | /send.py | ea5159063fbae4a59c92126919d8a6025dcc4520 | [] | no_license | shadowkernel/PyMailStress | eafc2fe87db25b60957ea3ab0fe35dd99b747e4c | 1dce4f066ea7f38ddbdc94b574b37a260fd19cc5 | refs/heads/master | 2021-01-10T04:20:00.086020 | 2013-03-05T06:30:49 | 2013-03-05T06:30:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,984 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Send mail script
# Author: Xiaoyang Li <hsiaoyonglee@gmail.com>
import smtplib
import time
import threading
import ConfigParser
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
config = ConfigParser.ConfigParser()
config.read('config')
server_addr = config.get('server', 'smtp')
port = 587
username = config.get('account', 'username')
password = config.get('account', 'password')
To = config.get('account', 'to')
From = username
thread_count = int(config.get('send_model', 'thread_count'))
send_count = int(config.get('send_model', 'send_count'))
login_times = int(config.get('send_model', 'login_times'))
login_interval=int(config.get('send_model', 'login_interval'))
fp = open('att.png', 'rb')
img = MIMEImage(fp.read())
fp.close()
msg = MIMEMultipart()
msg['Subject'] = 'TEST'
msg['From'] = "Joe Jeong"
msg['To'] = "Whatever"
content = "It's a Long Way to the Top if You Wanna Rock'N'Roll!!!!"
msg.attach(MIMEText(content,'plain'));
msg.attach(img)
class SendMail(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def send_mail(self, usingTLS=True):
if usingTLS == True :
server = smtplib.SMTP(server_addr, port)
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
for x in xrange(send_count):
try:
server.sendmail(From, To, msg.as_string())
except:
pass
server.close()
def run(self):
for i in range(login_times):
# logging
self.send_mail()
time.sleep(login_interval)
def go():
threads = [SendMail() for i in xrange(thread_count)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
if __name__ == "__main__":
go()
| [
"Joe.Jeong@icloud.com"
] | Joe.Jeong@icloud.com |
f1143c5015ebcd88c7912f5c54bdc340466fa1fe | 2172a26b843ee1466d6c33e805335dadbd853ed4 | /p097.py | 3b11cf862ac80ce2d27fa3bf79ff3838bfa82801 | [] | no_license | stewSquared/project-euler | aca2b8a610954c7e0eb2cab90d48cbbca839ad4a | 9369b4a6b6d97b2baeb44e81424e4f2e0aa0f870 | refs/heads/master | 2020-12-30T11:03:35.004325 | 2018-01-31T06:36:57 | 2018-01-31T06:36:57 | 21,247,626 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 142 | py | from functools import reduce
from itertools import repeat
ans = reduce(lambda m, n: m*n % 10**10, repeat(2, 7830457), 28433) + 1
print(ans)
| [
"stewinsalot@gmail.com"
] | stewinsalot@gmail.com |
e077975f79cef8246e26e09b0c121db7baa3577b | 5256a2412950c9c9df5ee7e37fdf748f34e0ff1c | /tests/system/springboothystrixbeat.py | 296d59ade0581021a0d74c0a812ced19fdf9fd23 | [
"Apache-2.0"
] | permissive | defus/springboothystrixbeat | 8276abdd687c43aedfb0ebb788000ba28383cfa5 | a85f8c33789669a2773e77126cf139d1ece4561a | refs/heads/master | 2020-08-23T02:13:25.761545 | 2019-10-22T15:50:06 | 2019-10-22T15:50:06 | 216,521,528 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 386 | py | import os
import sys
sys.path.append('../../vendor/github.com/elastic/beats/libbeat/tests/system')
from beat.beat import TestCase
class BaseTest(TestCase):
@classmethod
def setUpClass(self):
self.beat_name = "springboothystrixbeat"
self.beat_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))
super(BaseTest, self).setUpClass()
| [
"ldefokuate@octo.com"
] | ldefokuate@octo.com |
cdf6845bb895f5e4820d2059d293dc3b6e70ad83 | 58af4e8d6a41fd10d3e8d9a1e36e589729a50dd2 | /Networker.py | 85651068695f321012e4154402acfda8c31c39ce | [] | no_license | intrabit/blacklight | ff3087e8d58cb9f8857423fd13fabe3e75325bbd | 53397f709332a5fed3cfafd835d1c691d7ca68fa | refs/heads/master | 2020-12-30T09:58:30.844038 | 2019-09-05T19:41:21 | 2019-09-05T19:41:21 | 99,246,659 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,216 | py | # Connects to webservers requesting page data.
# Written by Louis Kennedy
import gzip
import re
import ssl
import socket
import threading
import Settings as settings
def finddata(source):
lastfind = 0
current = 0
while current != -1:
lastfind = current
current = source.find(b"\r\n", lastfind + 1)
else:
return lastfind + 2
def getheader(data, header):
start_index = data.find(header)
end_index = data.find(b"\r\n", start_index)
try:
return (data[start_index + len(header):end_index]).strip()
except Exception as exception:
raise Exception("Header Doesn't Exist")
def decoderesponse(data):
encoding_type = getheader(data, b"Content-Encoding:")
temp_data = data[0:int(len(data) / 10)]
data_end = finddata(temp_data)
data = data[data_end:]
data = data[:len(data) - 7]
if encoding_type == b"gzip":
decoded_response = gzip.decompress(data)
decoded_response = str(decoded_response, settings.DEFAULT_ENCODING)
return decoded_response
else:
data = str(data, settings.DEFAULT_ENCODING)
return data
def requestpage(address, retryCounter = 0):
resource = address[address.find("/"):]
csocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 80
if settings.ENCRYPTED:
csocket = ssl.wrap_socket(csocket)
port = 443
csocket.settimeout(settings.SOCKET_TIMEOUT)
try:
csocket.connect((socket.gethostbyname(settings.BASE_SERVER), port))
except socket.timeout:
if retryCounter < settings.MAX_RETRIES:
print("Network Error: Attempt to connect failed. Retrying...\n")
requestpage(address, retryCounter + 1)
else:
print("Network Error: Max retries reached. Aborting server request.\n")
request = "GET " + resource + " HTTP/1.1\r\n" + "User-Agent: Blacklight/" + \
settings.VERSION + "\r\nHost: " + settings.BASE_SERVER + \
"\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip\r\nAccept-Charset: utf-8\r\n\r\n"
csocket.send(request.encode(settings.DEFAULT_ENCODING))
encoded_response = b''
while True:
try:
chunk = csocket.recv(settings.RESPONSE_BUFFER_SIZE)
if not chunk:
break
encoded_response += chunk
except socket.timeout:
break
csocket.close()
if encoded_response != b'':
code = re.search(b"([0-9]{3} .+?)\r\n", encoded_response)
if code:
code = (code.group()).rstrip(b"\n\r")
if code == b"200 OK":
try:
return decoderesponse(encoded_response)
except:
return None
elif code == b"404 Not Found":
raise Exception("Page Not Found")
elif code == b"301 Moved Permanently" or code == b"302 Moved Temporarily":
try:
location = getheader(encoded_response, b"Location:")
if location.find(settings.MAIN_BRANCH) != -1:
check = (b"https://" if settings.ENCRYPTED else b"http://") + bytes(settings.BASE_SERVER, settings.DEFAULT_ENCODING) + bytes(resource, settings.DEFAULT_ENCODING)
if location != check:
if location.find(b"https") != -1:
settings.ENCRYPTED = True
elif location.find(b"http") != -1:
settings.ENCRYPTED = False
return requestpage(settings.BASE_SERVER + resource)
else:
raise Exception("Cyclical Redirection Detected") # The relocation link is identical to the original link followed.
else:
raise Exception("Invalid Link")
except:
raise Exception("Relocation URI Is Invalid")
else:
raise Exception("Unhandled Code: " + str(code))
else:
raise Exception("Corrupt HTTP Response")
else:
raise Exception("Couldn't Find HTTP Status Code Header")
| [
"noreply@github.com"
] | noreply@github.com |
adaefc6cb4c5988401db3a5e39c183ad7f465be6 | d4d162ee2ff1fd68121ec237bf8d19107abc9ae8 | /Arsen_Osipyan/game_of_life/styles.py | 4216118276e7ebabc28f5a49f5f031c3e941ad36 | [] | no_license | droidroot1995/DAFE_Python_015 | 48e1571cebd27a6bd978e3020b878f699a54c92c | f6c739e3be40e7737a173e1fdf327e10c5ae0cab | refs/heads/main | 2023-03-05T14:47:51.014141 | 2020-12-17T17:54:53 | 2020-12-17T17:54:53 | 308,549,551 | 1 | 21 | null | 2021-02-23T18:29:47 | 2020-10-30T06:57:00 | Python | UTF-8 | Python | false | false | 1,169 | py | # Window styles
WINDOW_CSS = "background-color: #fff;" \
"font-family: Arial;" \
"text-transform: uppercase;" \
"font-weight: 800;"
# Buttons styles
BUTTON_CSS = "border-radius: 0.4em;" \
"font-size: 14px;" \
"color: #fff;" \
"border: 0;"
START_CSS = BUTTON_CSS + \
"background-color: #007bff;"
CLEAR_CSS = BUTTON_CSS + \
"background-color: #007bff;"
CLOSE_CSS = BUTTON_CSS + \
"background-color: #dc3545;"
CONFIRM_CSS = BUTTON_CSS + \
"background-color: #007bff;"
# Status bar styles
STATUS_CSS = "color: #333;" \
"font-size: 12px;" \
"font-weight: 800;"
# Input styles
INPUT_CSS = "background-color: #ddd;" \
"border: 1px solid #eee;" \
"border-radius: 0.4em;" \
"color: #333;" \
"font-size: 14px;"
# Checkbox styles
CHECKBOX_CSS = "color: #333;" \
"align: center;"
# Cells styles
CELL_CSS = "border: 1px solid #eee;"
DEAD_CSS = CELL_CSS + \
"background-color: #ddd;"
ALIVE_CSS = CELL_CSS + \
"background-color: #28A745;"
| [
"arsenosipan02work@gmail.com"
] | arsenosipan02work@gmail.com |
0083e93218f93976537335daf228c1432b37276d | 0f2b51f85685b8f165b05854bf657f918bafb976 | /NER_train_predict/bert.py | 9a396b7af665652b701661bde9f5ce664a9986f1 | [] | no_license | Zenodia/NLP_Bert_Pytorch_NER_task | dfade7086fb2a2ae101db43f13d551e56a5cbe24 | 087efbb86dd0e84203dd07a507551caa23689f3a | refs/heads/master | 2022-12-14T21:13:04.091027 | 2020-09-16T11:46:59 | 2020-09-16T11:46:59 | 296,013,848 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,560 | py | """BERT NER Inference."""
from __future__ import absolute_import, division, print_function
import json
import os
import torch
import torch.nn.functional as F
from nltk import word_tokenize
from pytorch_transformers import (BertConfig, BertForTokenClassification,
BertTokenizer)
class BertNer(BertForTokenClassification):
def forward(self, input_ids, token_type_ids=None, attention_mask=None, valid_ids=None):
sequence_output = self.bert(input_ids, token_type_ids, attention_mask, head_mask=None)[0]
batch_size,max_len,feat_dim = sequence_output.shape
valid_output = torch.zeros(batch_size,max_len,feat_dim,dtype=torch.float32,device='cuda' if torch.cuda.is_available() else 'cpu')
for i in range(batch_size):
jj = -1
for j in range(max_len):
if valid_ids[i][j].item() == 1:
jj += 1
valid_output[i][jj] = sequence_output[i][j]
sequence_output = self.dropout(valid_output)
logits = self.classifier(sequence_output)
return logits
class Ner:
def __init__(self,model_dir: str):
self.model , self.tokenizer, self.model_config = self.load_model(model_dir)
self.label_map = self.model_config["label_map"]
self.max_seq_length = self.model_config["max_seq_length"]
self.label_map = {int(k):v for k,v in self.label_map.items()}
self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.model = self.model.to(self.device)
self.model.eval()
def load_model(self, model_dir: str, model_config: str = "model_config.json"):
model_config = os.path.join(model_dir,model_config)
model_config = json.load(open(model_config))
model = BertNer.from_pretrained(model_dir)
tokenizer = BertTokenizer.from_pretrained(model_dir, do_lower_case=model_config["do_lower"])
return model, tokenizer, model_config
def tokenize(self, text: str):
""" tokenize input"""
words = word_tokenize(text)
tokens = []
valid_positions = []
for i,word in enumerate(words):
token = self.tokenizer.tokenize(word)
tokens.extend(token)
for i in range(len(token)):
if i == 0:
valid_positions.append(1)
else:
valid_positions.append(0)
return tokens, valid_positions
def preprocess(self, text: str):
""" preprocess """
tokens, valid_positions = self.tokenize(text)
## insert "[CLS]"
tokens.insert(0,"[CLS]")
valid_positions.insert(0,1)
## insert "[SEP]"
tokens.append("[SEP]")
valid_positions.append(1)
segment_ids = []
for i in range(len(tokens)):
segment_ids.append(0)
input_ids = self.tokenizer.convert_tokens_to_ids(tokens)
input_mask = [1] * len(input_ids)
while len(input_ids) < self.max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
valid_positions.append(0)
return input_ids,input_mask,segment_ids,valid_positions
def predict(self, text: str):
input_ids,input_mask,segment_ids,valid_ids = self.preprocess(text)
input_ids = torch.tensor([input_ids],dtype=torch.long,device=self.device)
input_mask = torch.tensor([input_mask],dtype=torch.long,device=self.device)
segment_ids = torch.tensor([segment_ids],dtype=torch.long,device=self.device)
valid_ids = torch.tensor([valid_ids],dtype=torch.long,device=self.device)
with torch.no_grad():
logits = self.model(input_ids, segment_ids, input_mask,valid_ids)
logits = F.softmax(logits,dim=2)
logits_label = torch.argmax(logits,dim=2)
logits_label = logits_label.detach().cpu().numpy().tolist()[0]
logits_confidence = [values[label].item() for values,label in zip(logits[0],logits_label)]
logits = []
pos = 0
for index,mask in enumerate(valid_ids[0]):
if index == 0:
continue
if mask == 1:
logits.append((logits_label[index-pos],logits_confidence[index-pos]))
else:
pos += 1
logits.pop()
labels = [(self.label_map[label],confidence) for label,confidence in logits]
words = word_tokenize(text)
assert len(labels) == len(words)
Person = []
Location = []
Organization = []
Miscelleneous = []
for word, (label, confidence) in zip(words, labels):
if label=="PER" :
Person.append(word)
elif label=="LOC" :
Location.append(word)
elif label=="ORG" :
Organization.append(word)
elif label=="MISC" :
Miscelleneous.append(word)
else:
output = None
output = []
for word, (label, confidence) in zip(words, labels):
if label == "PER":
output.append(' '.join(Person) + ": Person")
if label=="LOC":
output.append(' '.join(Location) + ": Location")
if label=="MISC":
output.append(' '.join(Miscelleneous) + ": Miscelleneous Entity")
if label=="ORG":
output.append(' '.join(Organization) + ": Organization")
return output
| [
"noreply@github.com"
] | noreply@github.com |
16d37fe91e6e6174ecc5ebf06d10063687980ee8 | 97e54e4b18c1d696926678f1e320b2fc9cef5436 | /jaraco/text/strip-prefix.py | 761717a9b9e1f837eeacf0e888822f6fad881361 | [
"MIT"
] | permissive | jaraco/jaraco.text | 8ff2d7d49b3af0ca5e98c1cb337562bde9d3ba72 | 460dc329b799b88adb32ea95435d3a9e03cbdc00 | refs/heads/main | 2023-09-04T06:57:23.624303 | 2023-07-30T01:01:42 | 2023-07-30T01:01:42 | 48,551,451 | 15 | 8 | MIT | 2023-07-30T14:52:20 | 2015-12-24T17:20:06 | Python | UTF-8 | Python | false | false | 412 | py | import sys
import autocommand
from jaraco.text import Stripper
def strip_prefix():
r"""
Strip any common prefix from stdin.
>>> import io, pytest
>>> getfixture('monkeypatch').setattr('sys.stdin', io.StringIO('abcdef\nabc123'))
>>> strip_prefix()
def
123
"""
sys.stdout.writelines(Stripper.strip_prefix(sys.stdin).lines)
autocommand.autocommand(__name__)(strip_prefix)
| [
"jaraco@jaraco.com"
] | jaraco@jaraco.com |
dc72573a696b1184ae2cf899bda0ecd956d49f9d | 0931b32140ba932b3ba02f5109a087c6c70a244d | /frappe/desk/desk_page.py | fc7281e06c18d9766c2efcb8f939fa6938c5c494 | [
"MIT"
] | permissive | cstkyrilos/frappe | b60ed4e95ce929c74c2fc46000080d10b343190e | 27d9306bc5924c11c2749503454cc6d11a8cc654 | refs/heads/main | 2023-03-23T10:35:42.732385 | 2021-03-22T21:55:58 | 2021-03-22T21:55:58 | 350,292,784 | 0 | 0 | MIT | 2021-03-22T10:01:08 | 2021-03-22T10:01:07 | null | UTF-8 | Python | false | false | 1,569 | py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.translate import send_translations
@frappe.whitelist()
def get(name):
"""
Return the :term:`doclist` of the `Page` specified by `name`
"""
page = frappe.get_doc('Page', name)
if page.is_permitted():
page.load_assets()
docs = frappe._dict(page.as_dict())
if getattr(page, '_dynamic_page', None):
docs['_dynamic_page'] = 1
return docs
else:
frappe.response['403'] = 1
raise frappe.PermissionError, 'No read permission for Page %s' % \
(page.title or name)
@frappe.whitelist(allow_guest=True)
def getpage():
"""
Load the page from `frappe.form` and send it via `frappe.response`
"""
page = frappe.form_dict.get('name')
doc = get(page)
# load translations
if frappe.lang != "en":
send_translations(frappe.get_lang_dict("page", page))
frappe.response.docs.append(doc)
def has_permission(page):
if frappe.session.user == "Administrator" or "System Manager" in frappe.get_roles():
return True
page_roles = [d.role for d in page.get("roles")]
if page_roles:
if frappe.session.user == "Guest" and "Guest" not in page_roles:
return False
elif not set(page_roles).intersection(set(frappe.get_roles())):
# check if roles match
return False
if not frappe.has_permission("Page", ptype="read", doc=page):
# check if there are any user_permissions
return False
else:
# hack for home pages! if no Has Roles, allow everyone to see!
return True
| [
"cst.kyrilos@gmail.com"
] | cst.kyrilos@gmail.com |
91ea1c1fcfcc6577bf717c2abd059bc968643776 | 5e84763c16bd6e6ef06cf7a129bb4bd29dd61ec5 | /blimgui/dist/pyglet/libs/darwin/cocoapy/runtime.py | b692ce130d04d7d7af0a3e1daa11e437a71c142c | [
"MIT"
] | permissive | juso40/bl2sdk_Mods | 8422a37ca9c2c2bbf231a2399cbcb84379b7e848 | 29f79c41cfb49ea5b1dd1bec559795727e868558 | refs/heads/master | 2023-08-15T02:28:38.142874 | 2023-07-22T21:48:01 | 2023-07-22T21:48:01 | 188,486,371 | 42 | 110 | MIT | 2022-11-20T09:47:56 | 2019-05-24T20:55:10 | Python | UTF-8 | Python | false | false | 51,751 | py | # objective-ctypes
#
# Copyright (c) 2011, Phillip Nguyen
# All rights reserved.
#
# 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.
# Neither the name of objective-ctypes nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# 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.
import sys
import platform
import struct
from ctypes import *
from ctypes import util
from .cocoatypes import *
__LP64__ = (8*struct.calcsize("P") == 64)
__i386__ = (platform.machine() == 'i386')
__arm64__ = (platform.machine() == 'arm64')
if sizeof(c_void_p) == 4:
c_ptrdiff_t = c_int32
elif sizeof(c_void_p) == 8:
c_ptrdiff_t = c_int64
######################################################################
lib = util.find_library('objc')
# Hack for compatibility with macOS > 11.0
if lib is None:
lib = '/usr/lib/libobjc.dylib'
objc = cdll.LoadLibrary(lib)
######################################################################
# BOOL class_addIvar(Class cls, const char *name, size_t size, uint8_t alignment, const char *types)
objc.class_addIvar.restype = c_bool
objc.class_addIvar.argtypes = [c_void_p, c_char_p, c_size_t, c_uint8, c_char_p]
# BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
objc.class_addMethod.restype = c_bool
# BOOL class_addProtocol(Class cls, Protocol *protocol)
objc.class_addProtocol.restype = c_bool
objc.class_addProtocol.argtypes = [c_void_p, c_void_p]
# BOOL class_conformsToProtocol(Class cls, Protocol *protocol)
objc.class_conformsToProtocol.restype = c_bool
objc.class_conformsToProtocol.argtypes = [c_void_p, c_void_p]
# Ivar * class_copyIvarList(Class cls, unsigned int *outCount)
# Returns an array of pointers of type Ivar describing instance variables.
# The array has *outCount pointers followed by a NULL terminator.
# You must free() the returned array.
objc.class_copyIvarList.restype = POINTER(c_void_p)
objc.class_copyIvarList.argtypes = [c_void_p, POINTER(c_uint)]
# Method * class_copyMethodList(Class cls, unsigned int *outCount)
# Returns an array of pointers of type Method describing instance methods.
# The array has *outCount pointers followed by a NULL terminator.
# You must free() the returned array.
objc.class_copyMethodList.restype = POINTER(c_void_p)
objc.class_copyMethodList.argtypes = [c_void_p, POINTER(c_uint)]
# objc_property_t * class_copyPropertyList(Class cls, unsigned int *outCount)
# Returns an array of pointers of type objc_property_t describing properties.
# The array has *outCount pointers followed by a NULL terminator.
# You must free() the returned array.
objc.class_copyPropertyList.restype = POINTER(c_void_p)
objc.class_copyPropertyList.argtypes = [c_void_p, POINTER(c_uint)]
# Protocol ** class_copyProtocolList(Class cls, unsigned int *outCount)
# Returns an array of pointers of type Protocol* describing protocols.
# The array has *outCount pointers followed by a NULL terminator.
# You must free() the returned array.
objc.class_copyProtocolList.restype = POINTER(c_void_p)
objc.class_copyProtocolList.argtypes = [c_void_p, POINTER(c_uint)]
# id class_createInstance(Class cls, size_t extraBytes)
objc.class_createInstance.restype = c_void_p
objc.class_createInstance.argtypes = [c_void_p, c_size_t]
# Method class_getClassMethod(Class aClass, SEL aSelector)
# Will also search superclass for implementations.
objc.class_getClassMethod.restype = c_void_p
objc.class_getClassMethod.argtypes = [c_void_p, c_void_p]
# Ivar class_getClassVariable(Class cls, const char* name)
objc.class_getClassVariable.restype = c_void_p
objc.class_getClassVariable.argtypes = [c_void_p, c_char_p]
# Method class_getInstanceMethod(Class aClass, SEL aSelector)
# Will also search superclass for implementations.
objc.class_getInstanceMethod.restype = c_void_p
objc.class_getInstanceMethod.argtypes = [c_void_p, c_void_p]
# size_t class_getInstanceSize(Class cls)
objc.class_getInstanceSize.restype = c_size_t
objc.class_getInstanceSize.argtypes = [c_void_p]
# Ivar class_getInstanceVariable(Class cls, const char* name)
objc.class_getInstanceVariable.restype = c_void_p
objc.class_getInstanceVariable.argtypes = [c_void_p, c_char_p]
# const char *class_getIvarLayout(Class cls)
objc.class_getIvarLayout.restype = c_char_p
objc.class_getIvarLayout.argtypes = [c_void_p]
# IMP class_getMethodImplementation(Class cls, SEL name)
objc.class_getMethodImplementation.restype = c_void_p
objc.class_getMethodImplementation.argtypes = [c_void_p, c_void_p]
# The function is marked as OBJC_ARM64_UNAVAILABLE.
if not __arm64__:
# IMP class_getMethodImplementation_stret(Class cls, SEL name)
objc.class_getMethodImplementation_stret.restype = c_void_p
objc.class_getMethodImplementation_stret.argtypes = [c_void_p, c_void_p]
# const char * class_getName(Class cls)
objc.class_getName.restype = c_char_p
objc.class_getName.argtypes = [c_void_p]
# objc_property_t class_getProperty(Class cls, const char *name)
objc.class_getProperty.restype = c_void_p
objc.class_getProperty.argtypes = [c_void_p, c_char_p]
# Class class_getSuperclass(Class cls)
objc.class_getSuperclass.restype = c_void_p
objc.class_getSuperclass.argtypes = [c_void_p]
# int class_getVersion(Class theClass)
objc.class_getVersion.restype = c_int
objc.class_getVersion.argtypes = [c_void_p]
# const char *class_getWeakIvarLayout(Class cls)
objc.class_getWeakIvarLayout.restype = c_char_p
objc.class_getWeakIvarLayout.argtypes = [c_void_p]
# BOOL class_isMetaClass(Class cls)
objc.class_isMetaClass.restype = c_bool
objc.class_isMetaClass.argtypes = [c_void_p]
# IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
objc.class_replaceMethod.restype = c_void_p
objc.class_replaceMethod.argtypes = [c_void_p, c_void_p, c_void_p, c_char_p]
# BOOL class_respondsToSelector(Class cls, SEL sel)
objc.class_respondsToSelector.restype = c_bool
objc.class_respondsToSelector.argtypes = [c_void_p, c_void_p]
# void class_setIvarLayout(Class cls, const char *layout)
objc.class_setIvarLayout.restype = None
objc.class_setIvarLayout.argtypes = [c_void_p, c_char_p]
# Class class_setSuperclass(Class cls, Class newSuper)
objc.class_setSuperclass.restype = c_void_p
objc.class_setSuperclass.argtypes = [c_void_p, c_void_p]
# void class_setVersion(Class theClass, int version)
objc.class_setVersion.restype = None
objc.class_setVersion.argtypes = [c_void_p, c_int]
# void class_setWeakIvarLayout(Class cls, const char *layout)
objc.class_setWeakIvarLayout.restype = None
objc.class_setWeakIvarLayout.argtypes = [c_void_p, c_char_p]
######################################################################
# const char * ivar_getName(Ivar ivar)
objc.ivar_getName.restype = c_char_p
objc.ivar_getName.argtypes = [c_void_p]
# ptrdiff_t ivar_getOffset(Ivar ivar)
objc.ivar_getOffset.restype = c_ptrdiff_t
objc.ivar_getOffset.argtypes = [c_void_p]
# const char * ivar_getTypeEncoding(Ivar ivar)
objc.ivar_getTypeEncoding.restype = c_char_p
objc.ivar_getTypeEncoding.argtypes = [c_void_p]
######################################################################
# char * method_copyArgumentType(Method method, unsigned int index)
# You must free() the returned string.
objc.method_copyArgumentType.restype = c_char_p
objc.method_copyArgumentType.argtypes = [c_void_p, c_uint]
# char * method_copyReturnType(Method method)
# You must free() the returned string.
objc.method_copyReturnType.restype = c_char_p
objc.method_copyReturnType.argtypes = [c_void_p]
# void method_exchangeImplementations(Method m1, Method m2)
objc.method_exchangeImplementations.restype = None
objc.method_exchangeImplementations.argtypes = [c_void_p, c_void_p]
# void method_getArgumentType(Method method, unsigned int index, char *dst, size_t dst_len)
# Functionally similar to strncpy(dst, parameter_type, dst_len).
objc.method_getArgumentType.restype = None
objc.method_getArgumentType.argtypes = [c_void_p, c_uint, c_char_p, c_size_t]
# IMP method_getImplementation(Method method)
objc.method_getImplementation.restype = c_void_p
objc.method_getImplementation.argtypes = [c_void_p]
# SEL method_getName(Method method)
objc.method_getName.restype = c_void_p
objc.method_getName.argtypes = [c_void_p]
# unsigned method_getNumberOfArguments(Method method)
objc.method_getNumberOfArguments.restype = c_uint
objc.method_getNumberOfArguments.argtypes = [c_void_p]
# void method_getReturnType(Method method, char *dst, size_t dst_len)
# Functionally similar to strncpy(dst, return_type, dst_len)
objc.method_getReturnType.restype = None
objc.method_getReturnType.argtypes = [c_void_p, c_char_p, c_size_t]
# const char * method_getTypeEncoding(Method method)
objc.method_getTypeEncoding.restype = c_char_p
objc.method_getTypeEncoding.argtypes = [c_void_p]
# IMP method_setImplementation(Method method, IMP imp)
objc.method_setImplementation.restype = c_void_p
objc.method_setImplementation.argtypes = [c_void_p, c_void_p]
######################################################################
# Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)
objc.objc_allocateClassPair.restype = c_void_p
objc.objc_allocateClassPair.argtypes = [c_void_p, c_char_p, c_size_t]
# Protocol **objc_copyProtocolList(unsigned int *outCount)
# Returns an array of *outcount pointers followed by NULL terminator.
# You must free() the array.
objc.objc_copyProtocolList.restype = POINTER(c_void_p)
objc.objc_copyProtocolList.argtypes = [POINTER(c_int)]
# id objc_getAssociatedObject(id object, void *key)
objc.objc_getAssociatedObject.restype = c_void_p
objc.objc_getAssociatedObject.argtypes = [c_void_p, c_void_p]
# id objc_getClass(const char *name)
objc.objc_getClass.restype = c_void_p
objc.objc_getClass.argtypes = [c_char_p]
# int objc_getClassList(Class *buffer, int bufferLen)
# Pass None for buffer to obtain just the total number of classes.
objc.objc_getClassList.restype = c_int
objc.objc_getClassList.argtypes = [c_void_p, c_int]
# id objc_getMetaClass(const char *name)
objc.objc_getMetaClass.restype = c_void_p
objc.objc_getMetaClass.argtypes = [c_char_p]
# Protocol *objc_getProtocol(const char *name)
objc.objc_getProtocol.restype = c_void_p
objc.objc_getProtocol.argtypes = [c_char_p]
# You should set return and argument types depending on context.
# id objc_msgSend(id theReceiver, SEL theSelector, ...)
# id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
# The function is marked as OBJC_ARM64_UNAVAILABLE.
if not __arm64__:
# void objc_msgSendSuper_stret(struct objc_super *super, SEL op, ...)
objc.objc_msgSendSuper_stret.restype = None
# double objc_msgSend_fpret(id self, SEL op, ...)
# objc.objc_msgSend_fpret.restype = c_double
# The function is marked as OBJC_ARM64_UNAVAILABLE.
if not __arm64__:
# void objc_msgSend_stret(void * stretAddr, id theReceiver, SEL theSelector, ...)
objc.objc_msgSend_stret.restype = None
# void objc_registerClassPair(Class cls)
objc.objc_registerClassPair.restype = None
objc.objc_registerClassPair.argtypes = [c_void_p]
# void objc_removeAssociatedObjects(id object)
objc.objc_removeAssociatedObjects.restype = None
objc.objc_removeAssociatedObjects.argtypes = [c_void_p]
# void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)
objc.objc_setAssociatedObject.restype = None
objc.objc_setAssociatedObject.argtypes = [c_void_p, c_void_p, c_void_p, c_int]
######################################################################
# id object_copy(id obj, size_t size)
objc.object_copy.restype = c_void_p
objc.object_copy.argtypes = [c_void_p, c_size_t]
# id object_dispose(id obj)
objc.object_dispose.restype = c_void_p
objc.object_dispose.argtypes = [c_void_p]
# Class object_getClass(id object)
objc.object_getClass.restype = c_void_p
objc.object_getClass.argtypes = [c_void_p]
# const char *object_getClassName(id obj)
objc.object_getClassName.restype = c_char_p
objc.object_getClassName.argtypes = [c_void_p]
# Ivar object_getInstanceVariable(id obj, const char *name, void **outValue)
objc.object_getInstanceVariable.restype = c_void_p
objc.object_getInstanceVariable.argtypes=[c_void_p, c_char_p, c_void_p]
# id object_getIvar(id object, Ivar ivar)
objc.object_getIvar.restype = c_void_p
objc.object_getIvar.argtypes = [c_void_p, c_void_p]
# Class object_setClass(id object, Class cls)
objc.object_setClass.restype = c_void_p
objc.object_setClass.argtypes = [c_void_p, c_void_p]
# Ivar object_setInstanceVariable(id obj, const char *name, void *value)
# Set argtypes based on the data type of the instance variable.
objc.object_setInstanceVariable.restype = c_void_p
# void object_setIvar(id object, Ivar ivar, id value)
objc.object_setIvar.restype = None
objc.object_setIvar.argtypes = [c_void_p, c_void_p, c_void_p]
######################################################################
# const char *property_getAttributes(objc_property_t property)
objc.property_getAttributes.restype = c_char_p
objc.property_getAttributes.argtypes = [c_void_p]
# const char *property_getName(objc_property_t property)
objc.property_getName.restype = c_char_p
objc.property_getName.argtypes = [c_void_p]
######################################################################
# BOOL protocol_conformsToProtocol(Protocol *proto, Protocol *other)
objc.protocol_conformsToProtocol.restype = c_bool
objc.protocol_conformsToProtocol.argtypes = [c_void_p, c_void_p]
class OBJC_METHOD_DESCRIPTION(Structure):
_fields_ = [ ("name", c_void_p), ("types", c_char_p) ]
# struct objc_method_description *protocol_copyMethodDescriptionList(Protocol *p, BOOL isRequiredMethod, BOOL isInstanceMethod, unsigned int *outCount)
# You must free() the returned array.
objc.protocol_copyMethodDescriptionList.restype = POINTER(OBJC_METHOD_DESCRIPTION)
objc.protocol_copyMethodDescriptionList.argtypes = [c_void_p, c_bool, c_bool, POINTER(c_uint)]
# objc_property_t * protocol_copyPropertyList(Protocol *protocol, unsigned int *outCount)
objc.protocol_copyPropertyList.restype = c_void_p
objc.protocol_copyPropertyList.argtypes = [c_void_p, POINTER(c_uint)]
# Protocol **protocol_copyProtocolList(Protocol *proto, unsigned int *outCount)
objc.protocol_copyProtocolList = POINTER(c_void_p)
objc.protocol_copyProtocolList.argtypes = [c_void_p, POINTER(c_uint)]
# struct objc_method_description protocol_getMethodDescription(Protocol *p, SEL aSel, BOOL isRequiredMethod, BOOL isInstanceMethod)
objc.protocol_getMethodDescription.restype = OBJC_METHOD_DESCRIPTION
objc.protocol_getMethodDescription.argtypes = [c_void_p, c_void_p, c_bool, c_bool]
# const char *protocol_getName(Protocol *p)
objc.protocol_getName.restype = c_char_p
objc.protocol_getName.argtypes = [c_void_p]
######################################################################
# const char* sel_getName(SEL aSelector)
objc.sel_getName.restype = c_char_p
objc.sel_getName.argtypes = [c_void_p]
# SEL sel_getUid(const char *str)
# Use sel_registerName instead.
# BOOL sel_isEqual(SEL lhs, SEL rhs)
objc.sel_isEqual.restype = c_bool
objc.sel_isEqual.argtypes = [c_void_p, c_void_p]
# SEL sel_registerName(const char *str)
objc.sel_registerName.restype = c_void_p
objc.sel_registerName.argtypes = [c_char_p]
######################################################################
def ensure_bytes(x):
if isinstance(x, bytes):
return x
return x.encode('ascii')
######################################################################
def get_selector(name):
return c_void_p(objc.sel_registerName(ensure_bytes(name)))
def get_class(name):
return c_void_p(objc.objc_getClass(ensure_bytes(name)))
def get_object_class(obj):
return c_void_p(objc.object_getClass(obj))
def get_metaclass(name):
return c_void_p(objc.objc_getMetaClass(ensure_bytes(name)))
def get_superclass_of_object(obj):
cls = c_void_p(objc.object_getClass(obj))
return c_void_p(objc.class_getSuperclass(cls))
# http://www.sealiesoftware.com/blog/archive/2008/10/30/objc_explain_objc_msgSend_stret.html
# http://www.x86-64.org/documentation/abi-0.99.pdf (pp.17-23)
# executive summary: on x86-64, who knows?
def x86_should_use_stret(restype):
"""Try to figure out when a return type will be passed on stack."""
if type(restype) != type(Structure):
return False
if not __LP64__ and sizeof(restype) <= 8:
return False
if __LP64__ and sizeof(restype) <= 16: # maybe? I don't know?
return False
return True
# http://www.sealiesoftware.com/blog/archive/2008/11/16/objc_explain_objc_msgSend_fpret.html
def should_use_fpret(restype):
"""Determine if objc_msgSend_fpret is required to return a floating point type."""
if not __i386__:
# Unneeded on non-intel processors
return False
if __LP64__ and restype == c_longdouble:
# Use only for long double on x86_64
return True
if not __LP64__ and restype in (c_float, c_double, c_longdouble):
return True
return False
# By default, assumes that restype is c_void_p
# and that all arguments are wrapped inside c_void_p.
# Use the restype and argtypes keyword arguments to
# change these values. restype should be a ctypes type
# and argtypes should be a list of ctypes types for
# the arguments of the message only.
def send_message(receiver, selName, *args, **kwargs):
if isinstance(receiver, str):
receiver = get_class(receiver)
selector = get_selector(selName)
restype = kwargs.get('restype', c_void_p)
#print 'send_message', receiver, selName, args, kwargs
argtypes = kwargs.get('argtypes', [])
# Choose the correct version of objc_msgSend based on return type.
if should_use_fpret(restype):
objc.objc_msgSend_fpret.restype = restype
objc.objc_msgSend_fpret.argtypes = [c_void_p, c_void_p] + argtypes
result = objc.objc_msgSend_fpret(receiver, selector, *args)
elif x86_should_use_stret(restype):
objc.objc_msgSend_stret.argtypes = [POINTER(restype), c_void_p, c_void_p] + argtypes
result = restype()
objc.objc_msgSend_stret(byref(result), receiver, selector, *args)
else:
objc.objc_msgSend.restype = restype
objc.objc_msgSend.argtypes = [c_void_p, c_void_p] + argtypes
result = objc.objc_msgSend(receiver, selector, *args)
if restype == c_void_p:
result = c_void_p(result)
return result
class OBJC_SUPER(Structure):
_fields_ = [ ('receiver', c_void_p), ('class', c_void_p) ]
OBJC_SUPER_PTR = POINTER(OBJC_SUPER)
# http://stackoverflow.com/questions/3095360/what-exactly-is-super-in-objective-c
#
# `superclass_name` is optional and can be used to force finding the superclass
# by name. It is used to circumvent a bug in which the superclass was resolved
# incorrectly which lead to an infinite recursion:
# https://github.com/pyglet/pyglet/issues/5
def send_super(receiver, selName, *args, superclass_name=None, **kwargs):
if hasattr(receiver, '_as_parameter_'):
receiver = receiver._as_parameter_
if superclass_name is None:
superclass = get_superclass_of_object(receiver)
else:
superclass = get_class(superclass_name)
super_struct = OBJC_SUPER(receiver, superclass)
selector = get_selector(selName)
restype = kwargs.get('restype', c_void_p)
argtypes = kwargs.get('argtypes', None)
objc.objc_msgSendSuper.restype = restype
if argtypes:
objc.objc_msgSendSuper.argtypes = [OBJC_SUPER_PTR, c_void_p] + argtypes
else:
objc.objc_msgSendSuper.argtypes = None
result = objc.objc_msgSendSuper(byref(super_struct), selector, *args)
if restype == c_void_p:
result = c_void_p(result)
return result
######################################################################
cfunctype_table = {}
def parse_type_encoding(encoding):
"""Takes a type encoding string and outputs a list of the separated type codes.
Currently does not handle unions or bitfields and strips out any field width
specifiers or type specifiers from the encoding. For Python 3.2+, encoding is
assumed to be a bytes object and not unicode.
Examples:
parse_type_encoding('^v16@0:8') --> ['^v', '@', ':']
parse_type_encoding('{CGSize=dd}40@0:8{CGSize=dd}16Q32') --> ['{CGSize=dd}', '@', ':', '{CGSize=dd}', 'Q']
"""
type_encodings = []
brace_count = 0 # number of unclosed curly braces
bracket_count = 0 # number of unclosed square brackets
typecode = b''
for c in encoding:
# In Python 3, c comes out as an integer in the range 0-255. In Python 2, c is a single character string.
# To fix the disparity, we convert c to a bytes object if necessary.
if isinstance(c, int):
c = bytes([c])
if c == b'{':
# Check if this marked the end of previous type code.
if typecode and typecode[-1:] != b'^' and brace_count == 0 and bracket_count == 0:
type_encodings.append(typecode)
typecode = b''
typecode += c
brace_count += 1
elif c == b'}':
typecode += c
brace_count -= 1
assert(brace_count >= 0)
elif c == b'[':
# Check if this marked the end of previous type code.
if typecode and typecode[-1:] != b'^' and brace_count == 0 and bracket_count == 0:
type_encodings.append(typecode)
typecode = b''
typecode += c
bracket_count += 1
elif c == b']':
typecode += c
bracket_count -= 1
assert(bracket_count >= 0)
elif brace_count or bracket_count:
# Anything encountered while inside braces or brackets gets stuck on.
typecode += c
elif c in b'0123456789':
# Ignore field width specifiers for now.
pass
elif c in b'rnNoORV':
# Also ignore type specifiers.
pass
elif c in b'^cislqCISLQfdBv*@#:b?':
if typecode and typecode[-1:] == b'^':
# Previous char was pointer specifier, so keep going.
typecode += c
else:
# Add previous type code to the list.
if typecode:
type_encodings.append(typecode)
# Start a new type code.
typecode = c
# Add the last type code to the list
if typecode:
type_encodings.append(typecode)
return type_encodings
# Limited to basic types and pointers to basic types.
# Does not try to handle arrays, arbitrary structs, unions, or bitfields.
# Assume that encoding is a bytes object and not unicode.
def cfunctype_for_encoding(encoding):
# Check if we've already created a CFUNCTYPE for this encoding.
# If so, then return the cached CFUNCTYPE.
if encoding in cfunctype_table:
return cfunctype_table[encoding]
# Otherwise, create a new CFUNCTYPE for the encoding.
typecodes = {b'c':c_char, b'i':c_int, b's':c_short, b'l':c_long, b'q':c_longlong,
b'C':c_ubyte, b'I':c_uint, b'S':c_ushort, b'L':c_ulong, b'Q':c_ulonglong,
b'f':c_float, b'd':c_double, b'B':c_bool, b'v':None, b'*':c_char_p,
b'@':c_void_p, b'#':c_void_p, b':':c_void_p, NSPointEncoding:NSPoint,
NSSizeEncoding:NSSize, NSRectEncoding:NSRect, NSRangeEncoding:NSRange,
PyObjectEncoding:py_object}
argtypes = []
for code in parse_type_encoding(encoding):
if code in typecodes:
argtypes.append(typecodes[code])
elif code[0:1] == b'^' and code[1:] in typecodes:
argtypes.append(POINTER(typecodes[code[1:]]))
else:
raise Exception('unknown type encoding: ' + code)
cfunctype = CFUNCTYPE(*argtypes)
# Cache the new CFUNCTYPE in the cfunctype_table.
# We do this mainly because it prevents the CFUNCTYPE
# from being garbage-collected while we need it.
cfunctype_table[encoding] = cfunctype
return cfunctype
######################################################################
# After calling create_subclass, you must first register
# it with register_subclass before you may use it.
# You can add new methods after the class is registered,
# but you cannot add any new ivars.
def create_subclass(superclass, name):
if isinstance(superclass, str):
superclass = get_class(superclass)
return c_void_p(objc.objc_allocateClassPair(superclass, ensure_bytes(name), 0))
def register_subclass(subclass):
objc.objc_registerClassPair(subclass)
# types is a string encoding the argument types of the method.
# The first type code of types is the return type (e.g. 'v' if void)
# The second type code must be '@' for id self.
# The third type code must be ':' for SEL cmd.
# Additional type codes are for types of other arguments if any.
def add_method(cls, selName, method, types):
type_encodings = parse_type_encoding(types)
assert(type_encodings[1] == b'@') # ensure id self typecode
assert(type_encodings[2] == b':') # ensure SEL cmd typecode
selector = get_selector(selName)
cfunctype = cfunctype_for_encoding(types)
imp = cfunctype(method)
objc.class_addMethod.argtypes = [c_void_p, c_void_p, cfunctype, c_char_p]
objc.class_addMethod(cls, selector, imp, types)
return imp
def add_ivar(cls, name, vartype):
return objc.class_addIvar(cls, ensure_bytes(name), sizeof(vartype), alignment(vartype), encoding_for_ctype(vartype))
def set_instance_variable(obj, varname, value, vartype):
objc.object_setInstanceVariable.argtypes = [c_void_p, c_char_p, vartype]
objc.object_setInstanceVariable(obj, ensure_bytes(varname), value)
def get_instance_variable(obj, varname, vartype):
variable = vartype()
objc.object_getInstanceVariable(obj, ensure_bytes(varname), byref(variable))
return variable.value
######################################################################
class ObjCMethod:
"""This represents an unbound Objective-C method (really an IMP)."""
# Note, need to map 'c' to c_byte rather than c_char, because otherwise
# ctypes converts the value into a one-character string which is generally
# not what we want at all, especially when the 'c' represents a bool var.
typecodes = {b'c':c_byte, b'i':c_int, b's':c_short, b'l':c_long, b'q':c_longlong,
b'C':c_ubyte, b'I':c_uint, b'S':c_ushort, b'L':c_ulong, b'Q':c_ulonglong,
b'f':c_float, b'd':c_double, b'B':c_bool, b'v':None, b'Vv':None, b'*':c_char_p,
b'@':c_void_p, b'#':c_void_p, b':':c_void_p, b'^v':c_void_p, b'?':c_void_p,
NSPointEncoding:NSPoint, NSSizeEncoding:NSSize, NSRectEncoding:NSRect,
NSRangeEncoding:NSRange,
PyObjectEncoding:py_object}
cfunctype_table = {}
def __init__(self, method):
"""Initialize with an Objective-C Method pointer. We then determine
the return type and argument type information of the method."""
self.selector = c_void_p(objc.method_getName(method))
self.name = objc.sel_getName(self.selector)
self.pyname = self.name.replace(b':', b'_')
self.encoding = objc.method_getTypeEncoding(method)
self.return_type = objc.method_copyReturnType(method)
self.nargs = objc.method_getNumberOfArguments(method)
self.imp = c_void_p(objc.method_getImplementation(method))
self.argument_types = []
for i in range(self.nargs):
buffer = c_buffer(512)
objc.method_getArgumentType(method, i, buffer, len(buffer))
self.argument_types.append(buffer.value)
# Get types for all the arguments.
try:
self.argtypes = [self.ctype_for_encoding(t) for t in self.argument_types]
except:
#print 'no argtypes encoding for %s (%s)' % (self.name, self.argument_types)
self.argtypes = None
# Get types for the return type.
try:
if self.return_type == b'@':
self.restype = ObjCInstance
elif self.return_type == b'#':
self.restype = ObjCClass
else:
self.restype = self.ctype_for_encoding(self.return_type)
except:
#print 'no restype encoding for %s (%s)' % (self.name, self.return_type)
self.restype = None
self.func = None
def ctype_for_encoding(self, encoding):
"""Return ctypes type for an encoded Objective-C type."""
if encoding in self.typecodes:
return self.typecodes[encoding]
elif encoding[0:1] == b'^' and encoding[1:] in self.typecodes:
return POINTER(self.typecodes[encoding[1:]])
elif encoding[0:1] == b'^' and encoding[1:] in [CGImageEncoding, NSZoneEncoding]:
# special cases
return c_void_p
elif encoding[0:1] == b'r' and encoding[1:] in self.typecodes:
# const decorator, don't care
return self.typecodes[encoding[1:]]
elif encoding[0:2] == b'r^' and encoding[2:] in self.typecodes:
# const pointer, also don't care
return POINTER(self.typecodes[encoding[2:]])
else:
raise Exception('unknown encoding for %s: %s' % (self.name, encoding))
def get_prototype(self):
"""Returns a ctypes CFUNCTYPE for the method."""
if self.restype == ObjCInstance or self.restype == ObjCClass:
# Some hacky stuff to get around ctypes issues on 64-bit. Can't let
# ctypes convert the return value itself, because it truncates the pointer
# along the way. So instead, we must do set the return type to c_void_p to
# ensure we get 64-bit addresses and then convert the return value manually.
self.prototype = CFUNCTYPE(c_void_p, *self.argtypes)
else:
self.prototype = CFUNCTYPE(self.restype, *self.argtypes)
return self.prototype
def __repr__(self):
return "<ObjCMethod: %s %s>" % (self.name, self.encoding)
def get_callable(self):
"""Returns a python-callable version of the method's IMP."""
if not self.func:
prototype = self.get_prototype()
self.func = cast(self.imp, prototype)
if self.restype == ObjCInstance or self.restype == ObjCClass:
self.func.restype = c_void_p
else:
self.func.restype = self.restype
self.func.argtypes = self.argtypes
return self.func
def __call__(self, objc_id, *args):
"""Call the method with the given id and arguments. You do not need
to pass in the selector as an argument since it will be automatically
provided."""
f = self.get_callable()
try:
result = f(objc_id, self.selector, *args)
# Convert result to python type if it is a instance or class pointer.
if self.restype == ObjCInstance:
result = ObjCInstance(result)
elif self.restype == ObjCClass:
result = ObjCClass(result)
return result
except ArgumentError as error:
# Add more useful info to argument error exceptions, then reraise.
error.args += ('selector = ' + str(self.name),
'argtypes =' + str(self.argtypes),
'encoding = ' + str(self.encoding))
raise
######################################################################
class ObjCBoundMethod:
"""This represents an Objective-C method (an IMP) which has been bound
to some id which will be passed as the first parameter to the method."""
def __init__(self, method, objc_id):
"""Initialize with a method and ObjCInstance or ObjCClass object."""
self.method = method
self.objc_id = objc_id
def __repr__(self):
return '<ObjCBoundMethod %s (%s)>' % (self.method.name, self.objc_id)
def __call__(self, *args):
"""Call the method with the given arguments."""
return self.method(self.objc_id, *args)
######################################################################
class ObjCClass:
"""Python wrapper for an Objective-C class."""
# We only create one Python object for each Objective-C class.
# Any future calls with the same class will return the previously
# created Python object. Note that these aren't weak references.
# After you create an ObjCClass, it will exist until the end of the
# program.
_registered_classes = {}
def __new__(cls, class_name_or_ptr):
"""Create a new ObjCClass instance or return a previously created
instance for the given Objective-C class. The argument may be either
the name of the class to retrieve, or a pointer to the class."""
# Determine name and ptr values from passed in argument.
if isinstance(class_name_or_ptr, str):
name = class_name_or_ptr
ptr = get_class(name)
else:
ptr = class_name_or_ptr
# Make sure that ptr value is wrapped in c_void_p object
# for safety when passing as ctypes argument.
if not isinstance(ptr, c_void_p):
ptr = c_void_p(ptr)
name = objc.class_getName(ptr)
# Check if we've already created a Python object for this class
# and if so, return it rather than making a new one.
if name in cls._registered_classes:
return cls._registered_classes[name]
# Otherwise create a new Python object and then initialize it.
objc_class = super(ObjCClass, cls).__new__(cls)
objc_class.ptr = ptr
objc_class.name = name
objc_class.instance_methods = {} # mapping of name -> instance method
objc_class.class_methods = {} # mapping of name -> class method
objc_class._as_parameter_ = ptr # for ctypes argument passing
# Store the new class in dictionary of registered classes.
cls._registered_classes[name] = objc_class
# Not sure this is necessary...
objc_class.cache_instance_methods()
objc_class.cache_class_methods()
return objc_class
def __repr__(self):
return "<ObjCClass: %s at %s>" % (self.name, str(self.ptr.value))
def cache_instance_methods(self):
"""Create and store python representations of all instance methods
implemented by this class (but does not find methods of superclass)."""
count = c_uint()
method_array = objc.class_copyMethodList(self.ptr, byref(count))
for i in range(count.value):
method = c_void_p(method_array[i])
objc_method = ObjCMethod(method)
self.instance_methods[objc_method.pyname] = objc_method
def cache_class_methods(self):
"""Create and store python representations of all class methods
implemented by this class (but does not find methods of superclass)."""
count = c_uint()
method_array = objc.class_copyMethodList(objc.object_getClass(self.ptr), byref(count))
for i in range(count.value):
method = c_void_p(method_array[i])
objc_method = ObjCMethod(method)
self.class_methods[objc_method.pyname] = objc_method
def get_instance_method(self, name):
"""Returns a python representation of the named instance method,
either by looking it up in the cached list of methods or by searching
for and creating a new method object."""
if name in self.instance_methods:
return self.instance_methods[name]
else:
# If method name isn't in the cached list, it might be a method of
# the superclass, so call class_getInstanceMethod to check.
selector = get_selector(name.replace(b'_', b':'))
method = c_void_p(objc.class_getInstanceMethod(self.ptr, selector))
if method.value:
objc_method = ObjCMethod(method)
self.instance_methods[name] = objc_method
return objc_method
return None
def get_class_method(self, name):
"""Returns a python representation of the named class method,
either by looking it up in the cached list of methods or by searching
for and creating a new method object."""
if name in self.class_methods:
return self.class_methods[name]
else:
# If method name isn't in the cached list, it might be a method of
# the superclass, so call class_getInstanceMethod to check.
selector = get_selector(name.replace(b'_', b':'))
method = c_void_p(objc.class_getClassMethod(self.ptr, selector))
if method.value:
objc_method = ObjCMethod(method)
self.class_methods[name] = objc_method
return objc_method
return None
def __getattr__(self, name):
"""Returns a callable method object with the given name."""
# If name refers to a class method, then return a callable object
# for the class method with self.ptr as hidden first parameter.
name = ensure_bytes(name)
method = self.get_class_method(name)
if method:
return ObjCBoundMethod(method, self.ptr)
# If name refers to an instance method, then simply return the method.
# The caller will need to supply an instance as the first parameter.
method = self.get_instance_method(name)
if method:
return method
# Otherwise, raise an exception.
raise AttributeError('ObjCClass %s has no attribute %s' % (self.name, name))
######################################################################
class ObjCInstance:
"""Python wrapper for an Objective-C instance."""
_cached_objects = {}
def __new__(cls, object_ptr):
"""Create a new ObjCInstance or return a previously created one
for the given object_ptr which should be an Objective-C id."""
# Make sure that object_ptr is wrapped in a c_void_p.
if not isinstance(object_ptr, c_void_p):
object_ptr = c_void_p(object_ptr)
# If given a nil pointer, return None.
if not object_ptr.value:
return None
# Check if we've already created an python ObjCInstance for this
# object_ptr id and if so, then return it. A single ObjCInstance will
# be created for any object pointer when it is first encountered.
# This same ObjCInstance will then persist until the object is
# deallocated.
if object_ptr.value in cls._cached_objects:
return cls._cached_objects[object_ptr.value]
# Otherwise, create a new ObjCInstance.
objc_instance = super(ObjCInstance, cls).__new__(cls)
objc_instance.ptr = object_ptr
objc_instance._as_parameter_ = object_ptr
# Determine class of this object.
class_ptr = c_void_p(objc.object_getClass(object_ptr))
objc_instance.objc_class = ObjCClass(class_ptr)
# Store new object in the dictionary of cached objects, keyed
# by the (integer) memory address pointed to by the object_ptr.
cls._cached_objects[object_ptr.value] = objc_instance
# Create a DeallocationObserver and associate it with this object.
# When the Objective-C object is deallocated, the observer will remove
# the ObjCInstance corresponding to the object from the cached objects
# dictionary, effectively destroying the ObjCInstance.
observer = send_message(send_message('DeallocationObserver', 'alloc'), 'initWithObject:', objc_instance)
objc.objc_setAssociatedObject(objc_instance, observer, observer, 0x301)
# The observer is retained by the object we associate it to. We release
# the observer now so that it will be deallocated when the associated
# object is deallocated.
send_message(observer, 'release')
return objc_instance
def __repr__(self):
if self.objc_class.name == b'NSCFString':
# Display contents of NSString objects
from .cocoalibs import cfstring_to_string
string = cfstring_to_string(self)
return "<ObjCInstance %#x: %s (%s) at %s>" % (id(self), self.objc_class.name, string, str(self.ptr.value))
return "<ObjCInstance %#x: %s at %s>" % (id(self), self.objc_class.name, str(self.ptr.value))
def __getattr__(self, name):
"""Returns a callable method object with the given name."""
# Search for named instance method in the class object and if it
# exists, return callable object with self as hidden argument.
# Note: you should give self and not self.ptr as a parameter to
# ObjCBoundMethod, so that it will be able to keep the ObjCInstance
# alive for chained calls like MyClass.alloc().init() where the
# object created by alloc() is not assigned to a variable.
name = ensure_bytes(name)
method = self.objc_class.get_instance_method(name)
if method:
return ObjCBoundMethod(method, self)
# Else, search for class method with given name in the class object.
# If it exists, return callable object with a pointer to the class
# as a hidden argument.
method = self.objc_class.get_class_method(name)
if method:
return ObjCBoundMethod(method, self.objc_class.ptr)
# Otherwise raise an exception.
raise AttributeError('ObjCInstance %s has no attribute %s' % (self.objc_class.name, name))
######################################################################
def convert_method_arguments(encoding, args):
"""Used by ObjCSubclass to convert Objective-C method arguments to
Python values before passing them on to the Python-defined method."""
new_args = []
arg_encodings = parse_type_encoding(encoding)[3:]
for e, a in zip(arg_encodings, args):
if e == b'@':
new_args.append(ObjCInstance(a))
elif e == b'#':
new_args.append(ObjCClass(a))
else:
new_args.append(a)
return new_args
# ObjCSubclass is used to define an Objective-C subclass of an existing
# class registered with the runtime. When you create an instance of
# ObjCSubclass, it registers the new subclass with the Objective-C
# runtime and creates a set of function decorators that you can use to
# add instance methods or class methods to the subclass.
#
# Typical usage would be to first create and register the subclass:
#
# MySubclass = ObjCSubclass('NSObject', 'MySubclassName')
#
# then add methods with:
#
# @MySubclass.method('v')
# def methodThatReturnsVoid(self):
# pass
#
# @MySubclass.method('Bi')
# def boolReturningMethodWithInt_(self, x):
# return True
#
# @MySubclass.classmethod('@')
# def classMethodThatReturnsId(self):
# return self
#
# It is probably a good idea to organize the code related to a single
# subclass by either putting it in its own module (note that you don't
# actually need to expose any of the method names or the ObjCSubclass)
# or by bundling it all up inside a python class definition, perhaps
# called MySubclassImplementation.
#
# It is also possible to add Objective-C ivars to the subclass, however
# if you do so, you must call the __init__ method with register=False,
# and then call the register method after the ivars have been added.
# But rather than creating the ivars in Objective-C land, it is easier
# to just define python-based instance variables in your subclass's init
# method.
#
# This class is used only to *define* the interface and implementation
# of an Objective-C subclass from python. It should not be used in
# any other way. If you want a python representation of the resulting
# class, create it with ObjCClass.
#
# Instances are created as a pointer to the objc object by using:
#
# myinstance = send_message('MySubclassName', 'alloc')
# myinstance = send_message(myinstance, 'init')
#
# or wrapped inside an ObjCInstance object by using:
#
# myclass = ObjCClass('MySubclassName')
# myinstance = myclass.alloc().init()
#
class ObjCSubclass:
"""Use this to create a subclass of an existing Objective-C class.
It consists primarily of function decorators which you use to add methods
to the subclass."""
def __init__(self, superclass, name, register=True):
self._imp_table = {}
self.name = name
self.objc_cls = create_subclass(superclass, name)
self._as_parameter_ = self.objc_cls
if register:
self.register()
def register(self):
"""Register the new class with the Objective-C runtime."""
objc.objc_registerClassPair(self.objc_cls)
# We can get the metaclass only after the class is registered.
self.objc_metaclass = get_metaclass(self.name)
def add_ivar(self, varname, vartype):
"""Add instance variable named varname to the subclass.
varname should be a string.
vartype is a ctypes type.
The class must be registered AFTER adding instance variables."""
return add_ivar(self.objc_cls, varname, vartype)
def add_method(self, method, name, encoding):
imp = add_method(self.objc_cls, name, method, encoding)
self._imp_table[name] = imp
# http://iphonedevelopment.blogspot.com/2008/08/dynamically-adding-class-objects.html
def add_class_method(self, method, name, encoding):
imp = add_method(self.objc_metaclass, name, method, encoding)
self._imp_table[name] = imp
def rawmethod(self, encoding):
"""Decorator for instance methods without any fancy shenanigans.
The function must have the signature f(self, cmd, *args)
where both self and cmd are just pointers to objc objects."""
# Add encodings for hidden self and cmd arguments.
encoding = ensure_bytes(encoding)
typecodes = parse_type_encoding(encoding)
typecodes.insert(1, b'@:')
encoding = b''.join(typecodes)
def decorator(f):
name = f.__name__.replace('_', ':')
self.add_method(f, name, encoding)
return f
return decorator
def method(self, encoding):
"""Function decorator for instance methods."""
# Add encodings for hidden self and cmd arguments.
encoding = ensure_bytes(encoding)
typecodes = parse_type_encoding(encoding)
typecodes.insert(1, b'@:')
encoding = b''.join(typecodes)
def decorator(f):
def objc_method(objc_self, objc_cmd, *args):
py_self = ObjCInstance(objc_self)
py_self.objc_cmd = objc_cmd
args = convert_method_arguments(encoding, args)
result = f(py_self, *args)
if isinstance(result, ObjCClass):
result = result.ptr.value
elif isinstance(result, ObjCInstance):
result = result.ptr.value
return result
name = f.__name__.replace('_', ':')
self.add_method(objc_method, name, encoding)
return objc_method
return decorator
def classmethod(self, encoding):
"""Function decorator for class methods."""
# Add encodings for hidden self and cmd arguments.
encoding = ensure_bytes(encoding)
typecodes = parse_type_encoding(encoding)
typecodes.insert(1, b'@:')
encoding = b''.join(typecodes)
def decorator(f):
def objc_class_method(objc_cls, objc_cmd, *args):
py_cls = ObjCClass(objc_cls)
py_cls.objc_cmd = objc_cmd
args = convert_method_arguments(encoding, args)
result = f(py_cls, *args)
if isinstance(result, ObjCClass):
result = result.ptr.value
elif isinstance(result, ObjCInstance):
result = result.ptr.value
return result
name = f.__name__.replace('_', ':')
self.add_class_method(objc_class_method, name, encoding)
return objc_class_method
return decorator
######################################################################
# Instances of DeallocationObserver are associated with every
# Objective-C object that gets wrapped inside an ObjCInstance.
# Their sole purpose is to watch for when the Objective-C object
# is deallocated, and then remove the object from the dictionary
# of cached ObjCInstance objects kept by the ObjCInstance class.
#
# The methods of the class defined below are decorated with
# rawmethod() instead of method() because DeallocationObservers
# are created inside of ObjCInstance's __new__ method and we have
# to be careful to not create another ObjCInstance here (which
# happens when the usual method decorator turns the self argument
# into an ObjCInstance), or else get trapped in an infinite recursion.
class DeallocationObserver_Implementation:
DeallocationObserver = ObjCSubclass('NSObject', 'DeallocationObserver', register=False)
DeallocationObserver.add_ivar('observed_object', c_void_p)
DeallocationObserver.register()
@DeallocationObserver.rawmethod('@@')
def initWithObject_(self, cmd, anObject):
self = send_super(self, 'init')
self = self.value
set_instance_variable(self, 'observed_object', anObject, c_void_p)
return self
@DeallocationObserver.rawmethod('v')
def dealloc(self, cmd):
anObject = get_instance_variable(self, 'observed_object', c_void_p)
ObjCInstance._cached_objects.pop(anObject, None)
send_super(self, 'dealloc')
@DeallocationObserver.rawmethod('v')
def finalize(self, cmd):
# Called instead of dealloc if using garbage collection.
# (which would have to be explicitly started with
# objc_startCollectorThread(), so probably not too much reason
# to have this here, but I guess it can't hurt.)
anObject = get_instance_variable(self, 'observed_object', c_void_p)
ObjCInstance._cached_objects.pop(anObject, None)
send_super(self, 'finalize')
| [
"justin.sostmann@googlemail.com"
] | justin.sostmann@googlemail.com |
a84a107c0e275202b4cbb1b877c37f3825b42b1d | 36cf4465f576b2a7a2648f71177333c199f84796 | /src/analysis/document_similarities.py | 6b92aa2c2afefd204b3c88ea62f38dba55efd079 | [] | no_license | stevenrouk/evolution-of-machine-learning | d0cd5f6535db876f97445d04a3ad78db27a82f03 | 3be74301ce425377ec7a2e7aeffb35a1764225ff | refs/heads/master | 2023-02-20T08:37:32.932015 | 2022-08-10T22:14:10 | 2022-08-10T22:14:10 | 215,085,244 | 2 | 1 | null | 2023-02-15T22:58:25 | 2019-10-14T15:54:48 | Jupyter Notebook | UTF-8 | Python | false | false | 353 | py | import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
def get_similar_doc_idxs_to_loadings(loadings, W):
sims = cosine_similarity(loadings, W)[0]
return np.argsort(sims)[::-1]
def get_similar_doc_idxs_to_tfidf(tfidf_vec, all_docs):
sims = cosine_similarity(tfidf_vec, all_docs)[0]
return np.argsort(sims)[::-1]
| [
"stevenrouk@gmail.com"
] | stevenrouk@gmail.com |
5fa9d6c34be022eb700f187f8a95d6366b9ee254 | a5ae57b44064e6bb2fa17b5e7a8e551ec278345f | /src/core/runtime/control_structure/block.py | 00143a8d061be0bc1fd9baa0369f77e4f6ebaa9d | [
"MIT"
] | permissive | thomasmf/nomenine | 5cfc06ecfbacd73938b3ab0c52a2ebd3a0349faf | ead48185b150fdc07a5019499511f696c5326d45 | refs/heads/master | 2021-01-10T02:35:06.465381 | 2015-11-11T10:00:57 | 2015-11-11T10:00:57 | 44,127,966 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,245 | py |
TEST( """ with ( function x1 [ . 40 ] ) [ x1 ] == 40 """ )
TEST( """ let x1 30 [ x1 * 10 ] == 300 """ )
TEST( """ use [ [ definition x 387 ] [ definition y 4123 ] [ function f [ x + 1000 ] ] ] [ f * ( y ) ] == 5718601 """ )
TEST( """ use [ [ definition TestFactory ( factory ( Integer ) [ : that + 10000 ] ) ] [ function f ( TestFactory ) [ : that ] ] ] [ f ( TestFactory 100 ) + 1 ] == 10101 """ )
ROOT_SCOPE_METHOD(
MC( ARG( CW( 'with' ), CG( 'ANY', 'scope' ), CG( 'LIST', 'phrase' ) ), """
$NOM( CONTEXT,
$CA(UNION_new( $LISTNEW(
nom_definition( $CA(WORD_new( "scope" )), PARAM_scope ),
nom_definition( $CA(WORD_new( "phrase" )), PARAM_phrase )
) )),
: that phrase evaluate ( union
( : that scope )
( : this )
)
) ;
""" ),
MC( ARG( CW( 'let' ), CG( 'WORD', 'name' ), CG( 'ANY', 'value' ), CG( 'LIST', 'phrase' ) ), """
$NOM( CONTEXT,
$CA(UNION_new( $LISTNEW(
nom_definition( $CA(WORD_new( "name" )), PARAM_name ),
nom_definition( $CA(WORD_new( "value" )), PARAM_value ),
nom_definition( $CA(WORD_new( "phrase" )), PARAM_phrase )
) )),
: this with ( definition ( : that name ) ( : that value ) ) ( : that phrase )
) ;
""" ),
MC( ARG( CW( 'block' ), CG( 'ANY', 'scope' ), CG( 'LIST', 'components' ) ), """
$NOM( CONTEXT,
$CA(UNION_new( $LISTNEW(
nom_definition( $CA(WORD_new( "scope" )), PARAM_scope ),
nom_definition( $CA(WORD_new( "components" )), PARAM_components )
) )),
if value [ : that components value ]
then [
let scope ( union ( : that scope ) ( value evaluate ( : that scope ) ) ) [
: this block ( scope ) ( : that components next )
]
]
else [
: that scope
]
) ;
""" ),
MC( ARG( CW( 'use' ), CG( 'LIST', 'components' ), CG( 'LIST', 'phrase' ) ), """
$NOM( CONTEXT,
$CA(UNION_new( $LISTNEW(
nom_definition( $CA(WORD_new( "components" )), PARAM_components ),
nom_definition( $CA(WORD_new( "phrase" )), PARAM_phrase )
) )),
: this with ( : this block ( : this ) ( : that components ) ) ( : that phrase )
) ;
""" )
)
| [
"thomas@metatools.org"
] | thomas@metatools.org |
e78a07d5a9ac0d6375bab50be733a669fac273ff | e5b6d2e79d6593587fa8f5854def9ebf4d47a9e1 | /djangocli/wsgi.py | 8e9c0ba06187289fb8d23d2abffc8b6bcf5721d6 | [] | no_license | redeyed-archive/DjangoSiteCheckerExample | 35756664f0b9667e151d4608c6ebd5d279523534 | e53b2fad15d2a768e75bc853c69113c0d54c2ed2 | refs/heads/master | 2023-03-17T06:22:46.129989 | 2019-02-17T05:48:43 | 2019-02-17T05:48:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 395 | py | """
WSGI config for djangocli project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangocli.settings')
application = get_wsgi_application()
| [
"unconfigured@null.spigotmc.org"
] | unconfigured@null.spigotmc.org |
39b0fd52bc50bd9b15dfb1bcdb7536b39cdacdc5 | 0abb03d472094ea9c2b3c672cba53b4d603b19dd | /ansible/plugins/modules/test1.py | de2bace0bbbea56e32b1bc8d2ecdb1939c8aaca0 | [
"Unlicense"
] | permissive | mamercad/sandbox | 29502faa7f7b5bdbb17bcf87fae7ec0a0cefa568 | 2e69094452a7e2ecbf6500bb658c94fbaba2395b | refs/heads/main | 2023-08-21T21:09:03.867299 | 2023-05-22T18:57:27 | 2023-05-22T18:57:27 | 280,487,343 | 0 | 0 | Unlicense | 2023-05-22T18:52:03 | 2020-07-17T17:35:17 | Python | UTF-8 | Python | false | false | 21 | py | test1
test
test
test
| [
"mamercad@gmail.com"
] | mamercad@gmail.com |
3d26d362ff03dbd5bd9189d208e4bcad515f2f2a | e5d04f7f5e67e186dcb78a256341c3ab3afe796d | /twidder/helper.py | 44cc176fb3c2a497f691b2e0e481b8ebcb5bf55b | [] | no_license | bavaria95/twidder | c7ce456d1dd6b4713553608534cd2d19b7f3b168 | 496ed5c2324ab07db36f4f3cfe22ef4dd471d37c | refs/heads/master | 2016-08-11T21:58:01.284283 | 2016-03-08T00:16:08 | 2016-03-08T00:16:08 | 51,746,949 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,325 | py | import os
import binascii
import json
import database_helper
import random
import hmac
import hashlib
import time
from flask_sockets import Sockets
# implementing Diffie-Hellman key exchange algorithm
# generator
g = 3
# divider
p = 17
def log(msg):
f = open('log.txt', 'a')
f.write(str(msg) + '\n')
f.close()
def compute_public_key():
y = random.randrange(50, 100)
public_key = g**y % p
return {'public_key': public_key, 'secret_variable': y}
def compute_secret_key(client_public, y):
return client_public**y % p
def is_legid(message, exp_hash, timestamp):
'''
checks whether received message is correct(expected and actual hash-sum match)
'''
actual_timestamp = int(time.time())
# if message is older than 10 seconds - drop it
if abs(actual_timestamp - timestamp) > 10:
return False
token = message['token']
secret_key = database_helper.storage.get_user_secret(token)
message_string = ''.join([message[x] for x in sorted(message.keys())])
message_string += str(timestamp)
actual_hash = hmac.new(str(secret_key),
message_string,
hashlib.sha1).hexdigest()
return exp_hash == actual_hash
# to store tokens and corresponded emails to it
class Storage():
def __init__(self):
self.d = {}
def add_user(self, token, email, secret):
if token in self.d:
raise 'Token is used.'
self.d[token] = {'email': email, 'secret': secret}
def remove_user(self, token):
self.d.pop(token, None)
def get_user_email(self, token):
res = self.d.get(token)
if res:
return res['email']
return None
def get_user_secret(self, token):
res = self.d.get(token)
if res:
return res['secret']
return None
def is_token_presented(self, token):
return token in self.d
def get_all_storage(self):
return self.d
def get_token_by_email(self, email):
res = []
for k,v in self.d.iteritems():
if v['email'] == email:
res.append(k)
return res
def remove_token_by_email(self, email):
for k,v in list(self.d.iteritems())[:]:
if v['email'] == email:
self.d.pop(k, None)
class SocketPool():
def __init__(self):
self.d = {}
def add_socket(self, email, sock):
self.d[email] = sock
def get_socket(self, email):
return self.d.get(email, None)
def is_socket_presented(self, email):
return email in self.d
def remove_socket(self, email):
return self.d.pop(email, None)
def get_all_sockets(self):
return self.d
def size(self):
return len(self.d)
def change_socket_by_email(self, email, sock):
self.d[email] = sock
class StatsInfo():
def __init__(self):
self.d = {}
def add_entry(self, token, sock):
self.d[token] = {'socket': sock, 'prev': {'all_users': None,
'online': None,
'posts': None,
'all_posts': None}}
def is_entry_presented(self, token):
return token in self.d
def get_entry(self, token):
return self.d.get(token, None)
def remove_entry(self, token):
return self.d.pop(token)
def get_all_entries(self):
return self.d
def notify_by_token(self, token, data):
'''
Also takes care about necessity of notifying
(sends nothing if nothing changed)
'''
if not token in self.d:
return
if self.d[token]['prev'] != data:
try:
self.d[token]['socket'].send(json.dumps(data))
self.d[token]['prev'] = data
except:
pass
def all_subscribers(self):
return self.d.keys()
def generate_random_token():
token_length = 36
return binascii.hexlify(os.urandom(token_length))
def allowed_file(filename):
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif', 'avi', 'mp4', 'mp3'])
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
| [
"bavaria95@gmail.com"
] | bavaria95@gmail.com |
12bde3b49a3da09feeaeba0f56b55e4a8f07c0de | 47d5fe99e3cb28d3e0aed9564b774889d3a3d1cc | /ask/ask/urls.py | 2f115fd2b1d7167cb3452f53e1af2107688aaaff | [] | no_license | EgrethName/Web | 5a19999342dcfba445ba1b4b963c2c01e283b2bd | 928dc006f8155e28cc16ef490d47a671053d7c27 | refs/heads/master | 2023-04-14T16:34:34.856734 | 2021-04-28T12:37:56 | 2021-04-28T12:37:56 | 327,976,788 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,103 | py | """ask URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, re_path
urlpatterns = [
re_path('qa/', include('qa.urls')),
re_path('admin/', admin.site.urls),
re_path('', include('qa.urls')),
re_path('login/', include('qa.urls')),
re_path('signup/', include('qa.urls')),
re_path('ask/', include('qa.urls')),
re_path(r'question/\d+/', include('qa.urls')),
re_path('popular/', include('qa.urls')),
re_path('new/', include('qa.urls')),
]
| [
"egreth@mail.ru"
] | egreth@mail.ru |
1f009db8fd1167365c68a8e8ac41c0e88857d046 | c219339c6f1818685cccd71a9ca88ecf0d9bfcf2 | /Module 8/demo22ex3/demo22ex3.py | 01743c4aa432d1b030ee9fc40f872bda5bbc2885 | [] | no_license | UmeshDeshmukh/DSP_Lab_ECE-GY_6183 | fc2b01e2a65ae16c243f7f747072ffaec689e179 | 7ad7988fcf7ac947dcb8a90c148938be008d7021 | refs/heads/main | 2023-05-08T17:05:44.054708 | 2021-06-02T04:34:25 | 2021-06-02T04:34:25 | 334,494,205 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,424 | py | # find_blue_in_image.py
# Detect pixels similar to a prescribed color.
# This can be done usg HSV color space.
import cv2
import numpy as np
img = cv2.imread('input_image.jpg', 1)
# 1 : import image in color
# Convert to different color space
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
print(type(img_hsv))
print(img_hsv.shape)
print(img_hsv.dtype)
green = np.uint8([[[0, 255, 0]]]) # 3D array
green_hsv = cv2.cvtColor(green, cv2.COLOR_BGR2HSV)
h = green_hsv[0,0,0]
print('Green in HSV color space:', green_hsv)
print('Hue = ', h) # see that h = 120
# lower = np.array([90, 50, 22])
# upper = np.array([180, 255, 90])
lower = np.array([h-50, 50, 50])
upper = np.array([h+50, 255, 255])
print('lower = ', lower)
print('upper = ', upper)
# quit()
# Determine binary mask
green_mask = cv2.inRange(img_hsv, lower, upper)
# Apply mask to color image
output = cv2.bitwise_and(img, img, mask = green_mask)
# Show images:
cv2.imshow('Original image', img)
cv2.imshow('Mask', green_mask)
cv2.imshow('Segmented image', output)
print('Switch to images. Then press any key to stop')
cv2.waitKey(0)
cv2.destroyAllWindows()
# Write the image to a file
# cv2.imwrite('tiger_mask.jpg', green_mask)
# cv2.imwrite('tiger_green.jpg', output)
cv2.imwrite('mask_image.jpg', green_mask)
cv2.imwrite('detected_pixels.jpg', output)
# Reference
# http://docs.opencv.org/3.2.0/df/d9d/tutorial_py_colorspaces.html
| [
"noreply@github.com"
] | noreply@github.com |
36c646e5fe820af4bb83f2371e13d24460aa2f1f | 29bae218ba2662d8c700b48f7f256298de08d9f2 | /env/bin/f2py | 493f3036cc4786365a324ee6baf2959080e2f80a | [] | no_license | bradyb/deepgraminterview | c4986cb9ff090eb89a119b61faab4845d24ca7c0 | f48a4c5a17ca62195656e5839f4e8b60e33d4cdc | refs/heads/main | 2023-07-05T05:47:37.931140 | 2021-08-11T06:00:55 | 2021-08-11T06:00:55 | 394,879,774 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 252 | #!/home/turist/interviews/deepgram/env/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from numpy.f2py.f2py2e import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"brady.ben12@gmail.com"
] | brady.ben12@gmail.com | |
2b3a01df19d821d47f7af67c938295d1d18bcc2e | 28922bb1e78165a6d6fd02a45eca4acbdf202cab | /0x0F-python-object_relational_mapping/relationship_state.py | 740f17ebad5cdfa3478b85d68f147f312fe9a214 | [] | no_license | dalejoroc11/holbertonschool-higher_level_programming | 03d261a59971421b42fc0def730cc43ad478d2cb | e3195595f3237df4f0f8f519888927f07e86d959 | refs/heads/master | 2022-12-23T13:32:21.378580 | 2020-09-23T00:30:09 | 2020-09-23T00:30:09 | 259,437,432 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 520 | py | #!/usr/bin/python3
# Class definition of a State and an instance relationship
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from relationship_city import Base, City
class State(Base):
"""Represents a state for database"""
__tablename__ = "states"
id = Column(Integer, primary_key=True)
name = Column(String(128), nullable=False)
cities = relationship("City", backref="state", cascade="all, delete")
| [
"diegorojas279@hotmail.com"
] | diegorojas279@hotmail.com |
303f9eed263c05da330921097549a5347a38de5e | 7f9f44689af2d52b4bc0384f934d74ce86fe7deb | /src/magic1.py | 7a18fd8bc1f41e7470ac0d05aaf44be6dfa5e52e | [] | no_license | Nuked88/excbot | af94c8f16e145288e7d5b812d2f15bc7d9c0acce | 9b3b70a345c3dba396d3f92bfabebec2fe70c516 | refs/heads/master | 2021-05-11T00:56:25.097351 | 2018-02-11T15:54:54 | 2018-02-11T15:54:54 | 118,316,939 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,283 | py | from __future__ import division
from itertools import count
import matplotlib.pyplot as plt
from numpy import linspace, loadtxt, ones, convolve
import numpy as np
import pandas as pd
import collections
from random import randint
from matplotlib import style
import pymongo
from pymongo import MongoClient
from pprint import pprint
#cdb = MongoClient('173.249.9.155', 27017)
cdb = MongoClient('localhost', 27017)
db = cdb.excbot
data = db.data2
score = db.score
maxRes=40000
sym = "ETHUSDT"
def way(array):
prevValue = 0
wWay=0
for a in array:
if a > prevValue:
wWay=wWay+1
else:
wWay=wWay-1
prevValue=a
return wWay
def getData():
datacount= data.aggregate([
{ "$match": { "sym": sym} },
{ "$project": {
"year": { "$year": '$date'},
"month": { "$month": '$date'},
"day": { "$dayOfMonth": '$date'},
"hour": { "$hour": '$date'},
"minute": { "$minute": '$date'},
"price": 1,
"date":1
}},
{
"$group": {
"_id": { "date":"$date"},
"price":{
"$avg": "$price"
}}
},
{
"$limit":maxRes
},
{ "$sort" : { '_id.date': 1 } }])
score=0
i=0
armonica=0
list1=[]
b=[]
for a in datacount:
if str(a["price"]) != 'None':
i=i+1
tarr=[]
#pprint(str(a["price"])+"-"+str(a["_id"]))
tarr.append(i)
tarr.append(a["price"])
tarr.append(a["_id"]["date"])
b.append(a["price"])
list1.append(tarr)
#list1['SunSpots'].append(a["price"])
armonica=float(armonica)+(1/float(a["price"]))
#PRINT DATE
pprint("Ultima data:")
pprint(list1)
#mi dice se va su o giù
res=(100*way(b))/maxRes
pprint("Guadagno/Perdita")
pprint(str(res)+"%")
#media armonica prezzi
pprint("Numero risultati:")
pprint(i)
armonica=i/float(armonica)
return [list1,armonica]
# 3. Lets define some use-case specific UDF(User Defined Functions)
def moving_average(data, window_size):
""" Computes moving average using discrete linear convolution of two one dimensional sequences.
Args:
-----
data (pandas.Series): independent variable
window_size (int): rolling window size
Returns:
--------
ndarray of linear convolution
References:
------------
[1] Wikipedia, "Convolution", http://en.wikipedia.org/wiki/Convolution.
[2] API Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html
"""
window = np.ones(int(window_size))/float(window_size)
return np.convolve(data, window, 'same')
def explain_anomalies(y, window_size, sigma=1.0):
""" Helps in exploring the anamolies using stationary standard deviation
Args:
-----
y (pandas.Series): independent variable
window_size (int): rolling window size
sigma (int): value for standard deviation
Returns:
--------
a dict (dict of 'standard_deviation': int, 'anomalies_dict': (index: value))
containing information about the points indentified as anomalies
"""
avg = moving_average(y, window_size).tolist()
residual = y - avg
# Calculate the variation in the distribution of the residual
std = np.std(residual)
return {'standard_deviation': round(std, 8),
'ad': collections.OrderedDict([(index, y_i) for
index, y_i, avg_i in zip(count(), y, avg)
if (y_i > avg_i + (sigma*std)) | (y_i < avg_i - (sigma*std))])}
def explain_anomalies_rolling_std(y, window_size, sigma=1.0):
""" Helps in exploring the anamolies using rolling standard deviation
Args:
-----
y (pandas.Series): independent variable
window_size (int): rolling window size
sigma (int): value for standard deviation
Returns:
--------
a dict (dict of 'standard_deviation': int, 'anomalies_dict': (index: value))
containing information about the points indentified as anomalies
"""
avg = moving_average(y, window_size)
avg_list = avg.tolist()
residual = y - avg
# Calculate the variation in the distribution of the residual
testing_std = pd.rolling_std(residual, window_size)
testing_std_as_df = pd.DataFrame(testing_std)
rolling_std = testing_std_as_df.replace(np.nan,
testing_std_as_df.ix[window_size - 1]).round(3).iloc[:,0].tolist()
std = np.std(residual)
return {'stationary standard_deviation': round(std, 3),
'anomalies_dict': collections.OrderedDict([(index, y_i)
for index, y_i, avg_i, rs_i in zip(count(),
y, avg_list, rolling_std)
if (y_i > avg_i + (sigma * rs_i)) | (y_i < avg_i - (sigma * rs_i))])}
# This function is repsonsible for displaying how the function performs on the given dataset.
def plot_results(x, y, window_size, sigma_value=1,
text_xlabel="X Axis", text_ylabel="Y Axis", applying_rolling_std=False):
""" Helps in generating the plot and flagging the anamolies.
Supports both moving and stationary standard deviation. Use the 'applying_rolling_std' to switch
between the two.
Args:
-----
x (pandas.Series): dependent variable
y (pandas.Series): independent variable
window_size (int): rolling window size
sigma_value (int): value for standard deviation
text_xlabel (str): label for annotating the X Axis
text_ylabel (str): label for annotatin the Y Axis
applying_rolling_std (boolean): True/False for using rolling vs stationary standard deviation
"""
#plt.figure(figsize=(15, 8))
#plt.plot(x, y, "k.")
#y_av = moving_average(y, window_size)
#plt.plot(x, y_av, color='green')
#plt.xlim(0, 600)
#plt.xlabel(text_xlabel)
#plt.ylabel(text_ylabel)
# Query for the anomalies and plot the same
events = {}
if applying_rolling_std:
events = explain_anomalies_rolling_std(y, window_size=window_size, sigma=sigma_value)
else:
events = explain_anomalies(y, window_size=window_size, sigma=sigma_value)
x_anomaly = np.fromiter(events['ad'].keys(), dtype=int, count=len(events['ad']))
y_anomaly = np.fromiter(events['ad'].values(), dtype=float,
count=len(events['ad']))
return events
def calcPer(old,new):
#http://www.marcolazzari.it/blog/2010/08/24/come-calcolare-le-percentuali-con-excel-o-con-calc/
diffP= (1-float(new)/old)* 100
return diffP
# 4. Lets play with the functions
data = getData()
data_as_frame = pd.DataFrame(data[0], columns=['Months', 'SunSpots','Date'])
data_as_frame.head()
pprint("Media Armonica:")
pprint(data[1])
x = data_as_frame['Months']
Y = data_as_frame['SunSpots']
# plot the results
anomaly=plot_results(x, y=Y, window_size=10, text_xlabel="Minutes", sigma_value=2,text_ylabel="No. of Sun spots")
pprint(anomaly)
final = anomaly['ad']
rev= list(final.items())[-2]
pprint("Ultimo spike:")
pprint(rev)
#getData()
| [
"nuked8@gmail.com"
] | nuked8@gmail.com |
1613cc4678e8069425e88c9c92f2e3f813b95770 | 7e3fbcd8c130c5f98e45f20cfebee1d4d9531503 | /SERE/catalogos/urls.py | 6ff633552962a16b06c656edb6ff70d2deff891e | [] | no_license | hmachuca22/sere | 3653cc17a9fe8814b0733af6af364bb7e43169ae | ae318004729bb76277422d264a4fef6cdb108daa | refs/heads/master | 2020-11-25T16:45:29.576663 | 2019-12-20T00:53:49 | 2019-12-20T00:53:49 | 228,761,298 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,247 | py | from django.urls import path
from catalogos.views import CategoriaView
from catalogos.views import CategoriaNew
from catalogos.views import CategoriaEdit
from catalogos.views import CategoriaDel
from catalogos.views import ProductoViewSINREGISTRO,ProductoNewSINREGISTRO,ProductoViewINTERNOS,ProductoNewINTERNOS,ProductoEditINTERNOS
from catalogos.views import SubCategoriaView,SubCategoriaNew,SubCategoriaEdit,SubCategoriaDel,ProductoView,ProductoNew,ProductoEdit,categoria_print,historial_list
urlpatterns = [
path('categorias', CategoriaView.as_view(), name='categoria_list'),
path('categorias/new', CategoriaNew.as_view(), name='categoria_new'),
path('categoria/edit/<int:pk>', CategoriaEdit.as_view(), name='categoria_edit'),
path('categoria/delete/<int:pk>', CategoriaDel.as_view(), name='categoria_delete'),
path('categoria/dprint', categoria_print, name='categoria_print'),
path('categoria/dprint/<int:pk>', categoria_print, name='categoria_print_one'),
path('subcategorias', SubCategoriaView.as_view(), name='subcategoria_list'),
path('subcategorias/new', SubCategoriaNew.as_view(), name='subcategoria_new'),
path('subcategoria/edit/<int:pk>', SubCategoriaEdit.as_view(), name='subcategoria_edit'),
path('subcategoria/delete/<int:pk>', SubCategoriaDel.as_view(), name='subcategoria_delete'),
path('productos', ProductoView.as_view(), name='producto_list'),
path('producto/new', ProductoNew.as_view(), name='producto_new'),
path('producto/edit/<int:pk>', ProductoEdit.as_view(), name='producto_edit'),
path('productos/internos', ProductoViewINTERNOS.as_view(), name='producto_list_internos'),
path('producto/new/internos', ProductoNewINTERNOS.as_view(), name='producto_new_internos'),
path('producto/edit/internos/<int:pk>', ProductoEditINTERNOS.as_view(), name='producto_edit_internos'),
path('productos/sinregistro', ProductoViewSINREGISTRO.as_view(), name='producto_list_sinregistro'),
path('producto/new/sinregistro', ProductoNewSINREGISTRO.as_view(), name='producto_new_sinregistro'),
path('producto/edit/sinregistro/<int:pk>', ProductoEdit.as_view(), name='producto_edit_sinregistro'),
path('historial', historial_list, name='historial_list'),
] | [
"hmachuca19@gmail.com"
] | hmachuca19@gmail.com |
6a62b0983738172fa91c493cf2ac540bc6800c3f | 5df58c0a5796092d621486bc42b0754daac9d36f | /flashcardproject/flashcardapp/tests.py | 92868e1695605be05d35615c9f21b7479931b497 | [] | no_license | mcnguyenvn/Flashcard_team02 | 4af7fc4de825461daffc501d07fd28e0a4a25263 | fcfd0dc9e4ab6d1da7f876ccc1197dca92254280 | refs/heads/master | 2022-09-18T20:59:12.736488 | 2012-05-22T01:39:32 | 2012-05-22T01:39:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 722 | py | from django.test import TestCase
from django.test.client import Client
class UserFunctionTest(TestCase):
def setUp(self):
self.client = Client()
def test_creatingflashcard(self):
response = self.client.login(username='demo', password='123456')
self.assertTrue(response)
data = {
'title' : 'test',
'description':'test creating flashcard',
'grade' : 'first',
'subject' : 'art',
'Prompt 01':'test01',
'Answer 01' : 'answer01',
'Prompt 02':'test',
'Answer 02' : 'answer01'
}
response = self.client.post('/create/', data)
self.assertEqual(response.status_code, 200) | [
"cuongnm92@hotmail.com.vn"
] | cuongnm92@hotmail.com.vn |
be751f1b34a9337ee7ddbdecf8faf42c9f798399 | 09445ee10edc71baf61c0e286e7a79531fb76ba0 | /main.py | a1c4a1a93221990ed28908ebd856b9136e778957 | [] | no_license | yonkshi/master_thesis | e8d40fc0bd41d937946406bd9d4073bdffcaa05b | 0309061e7b3770b669adf15031ad76a672e2c1e6 | refs/heads/master | 2020-04-24T15:33:31.187952 | 2019-03-29T13:24:05 | 2019-03-29T13:24:05 | 172,072,683 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,577 | py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
import random
import os
import datetime
from scipy.misc import imsave
from model import VAE
from data_manager import DataManager
tf.app.flags.DEFINE_integer("epoch_size", 2000, "epoch size")
tf.app.flags.DEFINE_integer("batch_size", 64, "batch size")
tf.app.flags.DEFINE_float("gamma", 1000.0, "gamma param for latent loss")
tf.app.flags.DEFINE_float("capacity_limit", 1000.0,
"encoding capacity limit param for latent loss")
tf.app.flags.DEFINE_integer("capacity_change_duration", 100000,
"encoding capacity change duration")
tf.app.flags.DEFINE_float("learning_rate", 5e-4, "learning rate")
tf.app.flags.DEFINE_string("checkpoint_dir", "checkpoints", "checkpoint directory")
tf.app.flags.DEFINE_string("log_file", "./log", "log file directory")
tf.app.flags.DEFINE_boolean("training", True, "training or not")
tf.app.flags.DEFINE_integer("input_width", 128, "input image pixel width")
tf.app.flags.DEFINE_integer("input_height", 128, "input image pixel height")
tf.app.flags.DEFINE_integer("input_channels", 3, "input image color channels (RGB default)")
tf.app.flags.DEFINE_integer("latent_dim", 256, "Dimension of latent space")
tf.app.flags.DEFINE_string("dataset", "Megaman", "log file directory")
flags = tf.app.flags.FLAGS
run_name = "gamma={0}, capacity_lim={1}, latent_dim={2}, input_dim={3}x{4}x{5}, dataset={6}, " \
"date={7}".format(flags.gamma,
flags.capacity_limit,
flags.latent_dim,
flags.input_width,
flags.input_height,
flags.input_channels,
flags.dataset,
datetime.datetime.now(),
)
run_logpath = os.path.join(flags.log_file, run_name)
run_checkpoint_path = os.path.join(flags.checkpoint_dir, run_name)
if not os.path.exists(run_logpath):
os.mkdir(run_logpath)
def train(sess,
model,
manager,
saver):
summary_writer = tf.summary.FileWriter(run_logpath, sess.graph)
n_samples = manager.sample_size
np.random.seed(1231)
reconstruct_check_images = manager.get_random_images(10)
indices = list(range(n_samples))
step = 0
# Training cycle
for epoch in range(flags.epoch_size):
print('\n===== EPOCH %d =====' % epoch)
# Shuffle image indices
random.shuffle(indices)
avg_cost = 0.0
total_batch = n_samples // flags.batch_size
print('>> Total Batch Size: %d' % total_batch)
# Loop over all batches
print('>> Training ', end='')
for i in range(total_batch):
# Generate image batch
print(".", end='')
batch_indices = indices[flags.batch_size * i: flags.batch_size * (i + 1)]
batch_xs = manager.get_images(batch_indices)
# Fit training using batch data
reconstr_loss, latent_loss, summary_str = model.partial_fit(sess, batch_xs, step)
summary_writer.add_summary(summary_str, step)
step += 1
# Image reconstruction check
print('')
print('>> Reconstruction check ... ', end='')
img_summary = reconstruct_check(sess, model, reconstruct_check_images)
print('Done')
# # Disentangle check
# print('>> Disentanglement check...', end='')
# disentangle_check(sess, model, manager)
# print('Done')
summary_writer.add_summary(img_summary, step)
# Save checkpoint
saver.save(sess, run_checkpoint_path + '/' + 'checkpoint', global_step=step)
def reconstruct_check(sess, model, images):
# Check image reconstruction
x_reconstruct, img_summary = model.reconstruct(sess, images)
if not os.path.exists("reconstr_img"):
os.mkdir("reconstr_img")
for i in range(len(images)):
print('>>>> Reconstructing image %d ' % i)
org_img = images[i].reshape([flags.input_width, flags.input_height, flags.input_channels])
org_img = org_img.astype(np.float32)
reconstr_img = x_reconstruct[i].reshape([flags.input_width, flags.input_height, flags.input_channels])
imsave("reconstr_img/org_{0}.png".format(i), org_img)
imsave("reconstr_img/reconstr_{0}.png".format(i), reconstr_img)
return img_summary
def disentangle_check(sess, model, manager, save_original=False):
'''
This code appears to be running disentanglement check (specified in the paper) with a preselected image.
So in my case, I am running with the preselected image 1337
:param sess:
:param model:
:param manager:
:param save_original:
:return:
'''
img = manager.get_image(1337)
if save_original:
imsave("original.png",
img.reshape([flags.input_width, flags.input_height, flags.input_channels]).astype(np.float32))
batch_xs = [img]
z_mean, z_log_sigma_sq = model.transform(sess, batch_xs)
z_sigma_sq = np.exp(z_log_sigma_sq)[0]
# Print variance
zss_str = ""
for i, zss in enumerate(z_sigma_sq):
str = "z{0}={1:.4f}".format(i, zss)
zss_str += str + ", "
# print(zss_str)
# Save disentangled images
z_m = z_mean[0]
n_z = 256 # Latent space dim
if not os.path.exists("disentangle_img"):
os.mkdir("disentangle_img")
for target_z_index in range(n_z):
for ri in range(n_z):
value = -3.0 + (6.0 / 9.0) * ri
z_mean2 = np.zeros((1, n_z))
for i in range(n_z):
if (i == target_z_index):
z_mean2[0][i] = value
else:
z_mean2[0][i] = z_m[i]
reconstr_img = model.generate(sess, z_mean2)
rimg = reconstr_img[0].reshape([flags.input_width, flags.input_height, flags.input_channels])
imsave("disentangle_img/check_z{0}_{1}.png".format(target_z_index, ri), rimg)
def load_checkpoints(sess):
saver = tf.train.Saver()
checkpoint = tf.train.get_checkpoint_state(run_checkpoint_path)
if checkpoint and checkpoint.model_checkpoint_path:
saver.restore(sess, checkpoint.model_checkpoint_path)
print("loaded checkpoint: {0}".format(checkpoint.model_checkpoint_path))
else:
print("Could not find old checkpoint")
if not os.path.exists(run_checkpoint_path):
os.mkdir(run_checkpoint_path)
return saver
def main(argv):
manager = DataManager()
manager.load()
sess = tf.Session()
model = VAE(
input_width=flags.input_width,
input_height=flags.input_height,
input_channels=flags.input_channels,
gamma=flags.gamma,
capacity_limit=flags.capacity_limit,
capacity_change_duration=flags.capacity_change_duration,
learning_rate=flags.learning_rate,
)
sess.run(tf.global_variables_initializer())
saver = load_checkpoints(sess)
if flags.training:
# Train
train(sess, model, manager, saver)
else:
reconstruct_check_images = manager.get_random_images(10)
# Image reconstruction check
reconstruct_check(sess, model, reconstruct_check_images)
# Disentangle check
disentangle_check(sess, model, manager)
if __name__ == '__main__':
tf.app.run()
| [
"nopctoday@gmail.com"
] | nopctoday@gmail.com |
97b2511118f4f47bd460d91c403d4e82b77fff9f | 316fef235cb8e446ea29f226418f0e9a79f2b2fa | /convex_hull/1405075_PlotScript.py | be4ac1ed76b699319c64322aa0eec8beceacc6f1 | [] | no_license | azmainadel/computational-geometry | a4a88719075bdb7759cf1cd3b3e94055cb316bc8 | ab0ef74d0d9557ca7f9dcfed82047d2ba421e032 | refs/heads/master | 2023-08-28T07:30:42.076334 | 2023-08-09T04:31:06 | 2023-08-09T04:31:06 | 253,682,150 | 3 | 1 | null | 2020-04-08T06:03:30 | 2020-04-07T03:56:39 | C++ | UTF-8 | Python | false | false | 602 | py | import matplotlib.pyplot as plt
p = []
q = []
with open('1405075_input1.txt') as f2:
next(f2)
for line in f2:
xC, yC = line.split()
p.append(xC)
q.append(yC)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.scatter(p, q, s=10, c='r')
for xy in zip(p,q):
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data')
plt.grid()
x = []
y = []
with open('1405075_output.txt') as f1:
for line in f1:
xC, yC = line.split()
x.append(xC)
y.append(yC)
plt.plot(x, y, linewidth=4)
plt.title("Convex Hull")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
| [
"azmainadel47@gmail.com"
] | azmainadel47@gmail.com |
5e32aa296d6c958b4c340ef0e125637e341d4fdf | 25e48619b6157be79a0cb3051f7b59af4e7a48bb | /main_name.py | 8d6bc8217700cfdc49b3b936482e765111907e08 | [] | no_license | Nana-Antwi/UVM-CS-21 | 8fdb2125f01820f063e7a2b3e40c4a0b3bd64c73 | 535b8e7efb61a0e4071766b4986e5d9b97952456 | refs/heads/master | 2020-04-17T09:29:27.027534 | 2019-01-18T19:19:18 | 2019-01-18T19:19:18 | 166,459,805 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 151 | py | #program that display personal information
def main():
print_my_name()
#function
def print_my_name():
print('Nana')
main():
| [
"noreply@github.com"
] | noreply@github.com |
2bc4f1ab2384a7e76f74641976a53715c495cc2a | b0c528e2650dec1ff011215537fc5ea536627966 | /main/urls.py | 58a80f586c83f786718a9f83bb105e9b11210f7e | [] | no_license | trinhgliedt/Python_Great_number_game | 9cb84a1bd95333df15140cc2e1c466d0911b7b19 | 8358c84012981b8dfaafb9017fc9a92450a98e7b | refs/heads/master | 2023-02-08T21:14:23.124896 | 2021-01-01T06:18:02 | 2021-01-01T06:18:02 | 325,926,745 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 135 | py | from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('result/', views.process_form),
] | [
"chuot2008@gmail.com"
] | chuot2008@gmail.com |
e8da4fa3f3886a0e95df838344b3c25934dc0c78 | 9d87541ce623eeb1a82987c62d8ddb293b21ecdf | /groups/migrations/0001_initial.py | 764aa2174250e12c8c9337223696ff50aea2e2b0 | [] | no_license | rajasbhadke/code.fun.do | 24e76785a2689d28b84b0b188346a39ba3b12834 | c61b5e5d6c6ed251d597e8df1c3e336c3f55a662 | refs/heads/master | 2021-09-19T05:58:32.543269 | 2018-07-24T06:01:11 | 2018-07-24T06:01:11 | 107,448,756 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,313 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-10-20 13:00
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Events',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('EventType', models.CharField(max_length=255)),
('description', models.CharField(max_length=255)),
('date', models.DateField()),
('time', models.TimeField()),
],
),
migrations.CreateModel(
name='Group',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, unique=True)),
('slug', models.SlugField(allow_unicode=True, unique=True)),
('description', models.TextField(blank=True, default='')),
('description_html', models.TextField(blank=True, default='', editable=False)),
],
options={
'ordering': ['name'],
},
),
migrations.CreateModel(
name='GroupMember',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='memberships', to='groups.Group')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_groups', to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='group',
name='members',
field=models.ManyToManyField(through='groups.GroupMember', to=settings.AUTH_USER_MODEL),
),
migrations.AlterUniqueTogether(
name='groupmember',
unique_together=set([('group', 'user')]),
),
]
| [
"rajasbhadke@gmail.com"
] | rajasbhadke@gmail.com |
96e52d0093401f85706495e10a173ccc42cff38e | 10571744731d20bbb463ae0559e1e5462319c2c3 | /ModelTesting/venv/Scripts/easy_install-3.7-script.py | 6e487f8ffbc499a22648a2dd081ce0e8a45cc5cd | [] | no_license | monsadan/MachineLearning | 6731c7a88e886525e31d47bc4e52e827f87af69a | c5d4eceb099a467cb5ae3bac6d039b9b4ccc2aff | refs/heads/master | 2022-11-05T23:15:08.634848 | 2020-08-26T22:57:01 | 2020-08-26T22:57:01 | 246,444,686 | 0 | 1 | null | 2022-10-06T19:11:06 | 2020-03-11T01:18:46 | null | UTF-8 | Python | false | false | 480 | py | #!C:\Users\dmmpc\Documents\GitHub\MachineLearning\ModelTesting\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install-3.7'
__requires__ = 'setuptools==40.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==40.8.0', 'console_scripts', 'easy_install-3.7')()
)
| [
"54322798+monsadan@users.noreply.github.com"
] | 54322798+monsadan@users.noreply.github.com |
e5e0ff738ca6d3556fc24b219daa7846f1e584f6 | e4d532362315fa21e9d403a5e04f27c5046c95cc | /app/core/migrations/0001_initial.py | 5c306375b4d4a859034f1000c1a32bcbe51eee15 | [
"MIT"
] | permissive | yvsreenivas/recipe-app-api | 722055d0abcd07a63f483c38ba6a3a419d55721e | 84c68edcbbc4060255589ea7666df76eed5fad53 | refs/heads/main | 2023-01-23T17:42:24.686340 | 2020-11-27T11:43:50 | 2020-11-27T11:43:50 | 297,965,550 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,709 | py | # Generated by Django 2.1.15 on 2020-11-26 09:24
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(max_length=255, unique=True)),
('name', models.CharField(max_length=255)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
| [
"yvsreenivas@yahoo.co.in"
] | yvsreenivas@yahoo.co.in |
f67df4a1e6f69b4ed8c0be1156e7f043268c888d | 5cf49cea129b36e7999bb5eed4a79a539dbc622c | /app/user/serializers.py | cd3b85465de2c1b98571250680297d34ea0c8124 | [
"MIT"
] | permissive | mydjangoprojects/recipe-app-api | 449674317f72b760b33d4e2bfc934b123b0c904b | 95f402e825b3bd22d1f2c63bf3de113e8c9044d7 | refs/heads/master | 2020-04-29T03:22:17.678663 | 2019-05-01T13:09:35 | 2019-05-01T13:09:35 | 175,806,784 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,696 | py | from django.contrib.auth import get_user_model, authenticate
from django.utils.translation import ugettext_lazy as _
from rest_auth.registration.serializers import \
RegisterSerializer as BaseRegisterSerializer
from rest_auth.serializers import LoginSerializer as BaseLoginSerializer
from allauth.account import app_settings as allauth_settings
from allauth.utils import email_address_exists
from allauth.account.adapter import get_adapter
from allauth.account.utils import setup_user_email
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
"""Serializer for the user object"""
class Meta:
model = get_user_model()
fields = ('email', 'password1', 'password2')
extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
def create(self, validated_data):
"""Create a new user with encrypted password and return it"""
return get_user_model().objects.create_user(**validated_data)
def update(self, instance, validated_data):
"""Update a user, setting the password correctly and return the user"""
password = validated_data.pop('password', None)
user = super().update(instance, validated_data)
if password:
user.set_password(password)
user.save()
return user
class AuthTokenSerializer(serializers.Serializer):
"""Serializer for the user authentication object"""
email = serializers.CharField()
password = serializers.CharField(
style={'input_type': 'password'},
trim_whitespace=False,
)
def validate(self, attrs):
"""Validate and authenticate the user"""
email = attrs.get('email')
password = attrs.get('password')
user = authenticate(
request=self.context.get('request'),
username=email,
password=password,
)
if not user:
msg = _('Unable to authenticate with provided credentials.')
raise serializers.ValidationError(msg, code='authentication')
attrs['user'] = user
return attrs
# Rest-Auth Override
class RegisterSerializer(BaseRegisterSerializer):
"""Serializer for register new User"""
username = None
email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
password1 = serializers.CharField(required=True, write_only=True)
password2 = serializers.CharField(required=True, write_only=True)
def validate_email(self, email):
email = get_adapter().clean_email(email)
if allauth_settings.UNIQUE_EMAIL:
if email and email_address_exists(email):
raise serializers.ValidationError(
_("A user is already registered with this e-mail address.")
)
return email
def validate_password1(self, password):
return get_adapter().clean_password(password)
def validate(self, data):
if data['password1'] != data['password2']:
raise serializers.ValidationError(
_("The two password fields didn't match."))
return data
def get_cleaned_data(self):
return {
'password1': self.validated_data.get('password1', ''),
'email': self.validated_data.get('email', ''),
}
def save(self, request):
adapter = get_adapter()
user = adapter.new_user(request)
self.cleaned_data = self.get_cleaned_data()
adapter.save_user(request, user, self)
setup_user_email(request, user, [])
return user
class LoginSerializer(BaseLoginSerializer):
# Removing username to use only email
username = None
| [
"psykepro@abv.bg"
] | psykepro@abv.bg |
5b2b9b5810a6117b1af4440eda79ec7c15ae4f0b | c537ab4ad9769454c3bc894ae56e650ce74e96a3 | /lesson_07/code/06.文件的读取.py | 466343210c431990d28681bba33847f92b12a646 | [] | no_license | ZhouYao0627/course_python | f8b940ddf0b71c0d62b8e6f13121b7bd1de8a11b | 8236a3e431d45fd8353c55c181b5d9f84b9d4757 | refs/heads/master | 2023-08-15T06:22:15.325444 | 2021-10-01T08:38:27 | 2021-10-01T08:38:27 | 412,095,996 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 964 | py | file_name = 'demo2 .txt'
try:
with open(file_name) as file_obj:
# 如果直接调用read()他会将文本文件的所有内容全部都读出来
# 对于较大的文件,不要直接调用read()
# help(file_obj.read())
# read()可以接受一个size作为参数,该参数用来指定要读取的字符的数量
# 默认值是-1,它会读取文件中的所有字符
# 可以为size指定一个值,这样read()会读取指定数量的字符
# 每一次的读取都是从上一次读取到的位置开始读取的
# 如果字符的数量小于size,则会读取剩余所有的
# content = file_obj.read(-1)
content = file_obj.read(6)
content = file_obj.read(6)
content = file_obj.read(6)
content = file_obj.read(6)
print(content)
print(len(content))
except FileNotFoundError:
print(f'{file_name} 文件不存在···')
| [
"1607435943@qq.com"
] | 1607435943@qq.com |
f77c214c3496e3927ac4f3539fc029b10bbe7302 | f6c41523b1f03f447a0ace4fd01ddf9d5ba85a24 | /getCountriesbyRegion.py | 1f5d81a6df742fab4ba97a8288ab2ecf7eda9c18 | [] | no_license | AdroitAnandAI/Automated-Reasoning-with-ML-Knowledge-Graph-and-Machine-Comprehension-with-AI | cc39d75c99700ace3fd0f94d97665547b57dc947 | 252448c9885e1d47daa30aec7113fa732326e03a | refs/heads/main | 2023-01-03T04:38:21.228788 | 2020-10-18T07:26:33 | 2020-10-18T07:26:33 | 305,045,678 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,665 | py | from grakn.client import GraknClient
with GraknClient(uri="localhost:48555") as client:
with client.session(keyspace = "globe") as session:
with session.transaction().read() as transaction:
query = [
'match $country isa country, has countryname $cname,' +
' has indepyear $iy, has region "Caribbean"; $iy > 1980; get $cname;'
]
# has indepyear $iy, has population $p, has surfacearea $sc; $sc > 10000; $p < 1000000; get $cname, $p, $sc;
print("\nQuery:\n", "\n".join(query))
query = "".join(query)
iterator = transaction.query(query)
#can also use compute max like this but will get only highest value.
# if you want to find country with maximum lifeexpectancy, then u need
# to execute 2 queries, first to compute max and
# then the above query to "== max"
#compute max of lifeexpectancy, in country;
countries = [[ans.get("cname")] for ans in iterator]
print(countries)
# result = [ answer.id for answer in answers ]
for country in countries:
print(str(country[0].value()))
# print(": " country[1].value())
# print("\nResult:\n", result)
# answers = [ans.get("city") for ans in iterator]
# print(answers)
# result = [ answer.id for answer in answers ]
# for answer in answers:
# print(answer.type().__getattribute__('cityname'))
# print(answer.type().label())
# print("\nResult:\n", result) | [
"noreply@github.com"
] | noreply@github.com |
01b2b94a2a0eedae0205ccea536b5edd468b7316 | 2ab6afdcc194efa65f6122ff4eb9c32843d1611b | /visualize.py | 6b7464a64706b0353a58e9255d1fb255955b8f9d | [] | no_license | liuliuOD/Data-Visualization | 641b98d8bffc98ee6a6ed010309ee9b752081dcf | ed8e20a61f1105ea2513a17bfd592c153daf9e7a | refs/heads/master | 2020-05-17T14:36:42.355886 | 2019-04-28T00:57:14 | 2019-04-28T00:57:14 | 183,768,823 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,009 | py | import matplotlib.pyplot as plt
class visualize () :
# def __init__ (self) :
def scatter (self, x, y, color = 'g', marker = 'o', size = 8) :
plt.scatter(x, y, c = color, marker = marker, s = size)
return self
# def plot (self, x, y, color = 'g') :
# plt.plot(x, y, color = color, marker = marker)
# return self
def show (self) :
plt.show()
return self
def draw (self) :
plt.draw()
return self
def pause (self, pauseZone = 0.1) :
plt.pause(pauseZone)
return self
def close (self, window = "all") :
plt.close(window)
return self
def interactive (self, turn = True) :
if turn :
plt.ion()
else :
plt.ioff()
return self
def clearWindow (self) :
plt.clf()
return self
def save (self, imgName = "test.png") :
plt.savefig(imgName)
return self
| [
"liuliugit@gmail.com"
] | liuliugit@gmail.com |
2e8acef5d561c60f976847083658fb070708a1dd | c18ee10367a6b8bd3efa20d3e5f1345f8a065a73 | /hw2/code/src/regression.py | 4ec54b283222b2d08f8387ee925f81550a819ae6 | [] | no_license | michaelwu756/CSM146 | 9f6bf604a20b20483d268a9ec2dfbb21731d2d4e | 46599acfa792e9dc68f40b956b7583c6f23c623b | refs/heads/master | 2021-05-12T03:33:56.246498 | 2018-03-16T11:40:02 | 2018-03-16T11:40:02 | 117,620,119 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,292 | py | #!/usr/bin/python
# This code was adapted from course material by Jenna Wiens (UMichigan).
# python libraries
import os
import math
# numpy libraries
import numpy as np
# matplotlib libraries
import matplotlib.pyplot as plt
######################################################################
# classes
######################################################################
class Data :
def __init__(self, X=None, y=None) :
"""
Data class.
Attributes
--------------------
X -- numpy array of shape (n,d), features
y -- numpy array of shape (n,), targets
"""
# n = number of examples, d = dimensionality
self.X = X
self.y = y
def load(self, filename) :
"""
Load csv file into X array of features and y array of labels.
Parameters
--------------------
filename -- string, filename
"""
# determine filename
dir = os.path.dirname('__file__')
f = os.path.join(dir, '..', 'data', filename)
# load data
with open(f, 'r') as fid :
data = np.loadtxt(fid, delimiter=",")
# separate features and labels
self.X = data[:,:-1]
self.y = data[:,-1]
def plot(self, name, **kwargs) :
"""Plot data."""
if 'color' not in kwargs :
kwargs['color'] = 'b'
plt.scatter(self.X, self.y, **kwargs)
plt.xlabel('x', fontsize = 16)
plt.ylabel('y', fontsize = 16)
if name==None:
plt.show()
else:
plt.savefig(name)
plt.clf()
# wrapper functions around Data class
def load_data(filename) :
data = Data()
data.load(filename)
return data
def plot_data(X, y, name=None, **kwargs) :
data = Data(X, y)
data.plot(name, **kwargs)
class PolynomialRegression() :
def __init__(self, m=1, reg_param=0) :
"""
Ordinary least squares regression.
Attributes
--------------------
coef_ -- numpy array of shape (d,)
estimated coefficients for the linear regression problem
m_ -- integer
order for polynomial regression
lambda_ -- float
regularization parameter
"""
self.coef_ = None
self.m_ = m
self.lambda_ = reg_param
def generate_polynomial_features(self, X) :
"""
Maps X to an mth degree feature vector e.g. [1, X, X^2, ..., X^m].
Parameters
--------------------
X -- numpy array of shape (n,1), features
Returns
--------------------
Phi -- numpy array of shape (n,(m+1)), mapped features
"""
n,d = X.shape
# part b: modify to create matrix for simple linear model
# part g: modify to create matrix for polynomial model
m = self.m_
Phi = np.zeros((n,m+1))
for i in range(0,n):
val=[1]
index=[(m+1)*i]
for j in range(0,m):
val.append(val[j]*X.flat[i])
index.append(index[j]+1)
np.put(Phi, index, val)
return Phi
def fit_GD(self, X, y, eta=None,
eps=0, tmax=10000, verbose=False) :
"""
Finds the coefficients of a {d-1}^th degree polynomial
that fits the data using least squares batch gradient descent.
Parameters
--------------------
X -- numpy array of shape (n,d), features
y -- numpy array of shape (n,), targets
eta -- float, step size
eps -- float, convergence criterion
tmax -- integer, maximum number of iterations
verbose -- boolean, for debugging purposes
Returns
--------------------
self -- an instance of self
"""
if self.lambda_ != 0 :
raise Exception("GD with regularization not implemented")
if verbose :
plt.subplot(1, 2, 2)
plt.xlabel('iteration')
plt.ylabel(r'$J(\theta)$')
plt.ion()
plt.show()
X = self.generate_polynomial_features(X) # map features
n,d = X.shape
eta_input = eta
self.coef_ = np.zeros(d) # coefficients
err_list = np.zeros((tmax,1)) # errors per iteration
# GD loop
for t in xrange(tmax) :
# part f: update step size
# change the default eta in the function signature to 'eta=None'
# and update the line below to your learning rate function
if eta_input is None :
eta = 1/float(1+t)
else :
eta = eta_input
# part d: update theta (self.coef_) using one step of GD
# hint: you can write simultaneously update all theta using vector math
# track error
# hint: you cannot use self.predict(...) to make the predictions
y_pred = np.zeros(n)
for i in range(0,n):
np.put(y_pred,i,np.dot(X[i],self.coef_))
self.coef_=self.coef_-2*eta*np.dot(y_pred-y,X)
err_list[t] = np.sum(np.power(y - y_pred, 2)) / float(n)
# stop?
if t > 0 and abs(err_list[t] - err_list[t-1]) <= eps :
break
# debugging
if verbose :
x = np.reshape(X[:,1], (n,1))
cost = self.cost(x,y)
plt.subplot(1, 2, 1)
plt.cla()
plot_data(x, y)
self.plot_regression()
plt.subplot(1, 2, 2)
plt.plot([t+1], [cost], 'bo')
plt.suptitle('iteration: %d, cost: %f' % (t+1, cost))
plt.draw()
plt.pause(0.05) # pause for 0.05 sec
print 'number of iterations: %d' % (t+1)
return self
def fit(self, X, y, l2regularize = None ) :
"""
Finds the coefficients of a {d-1}^th degree polynomial
that fits the data using the closed form solution.
Parameters
--------------------
X -- numpy array of shape (n,d), features
y -- numpy array of shape (n,), targets
l2regularize -- set to None for no regularization. set to positive double for L2 regularization
Returns
--------------------
self -- an instance of self
"""
X = self.generate_polynomial_features(X) # map features
# part e: implement closed-form solution
# hint: use np.dot(...) and np.linalg.pinv(...)
# be sure to update self.coef_ with your solution
self.coef_=np.dot(np.linalg.pinv(np.dot(X.T,X)),np.dot(X.T,y))
def predict(self, X) :
"""
Predict output for X.
Parameters
--------------------
X -- numpy array of shape (n,d), features
Returns
--------------------
y -- numpy array of shape (n,), predictions
"""
if self.coef_ is None :
raise Exception("Model not initialized. Perform a fit first.")
X = self.generate_polynomial_features(X) # map features
# part c: predict y
n,d = X.shape
y = np.zeros(n)
for i in range(0,n):
np.put(y,i,np.dot(X[i],self.coef_))
return y
def cost(self, X, y) :
"""
Calculates the objective function.
Parameters
--------------------
X -- numpy array of shape (n,d), features
y -- numpy array of shape (n,), targets
Returns
--------------------
cost -- float, objective J(theta)
"""
# part d: compute J(theta)
n,d = X.shape
y_pred=self.predict(X)
cost = 0
for i in range(0,n):
cost+=(y_pred.flat[i]-y.flat[i])**2
return cost
def rms_error(self, X, y) :
"""
Calculates the root mean square error.
Parameters
--------------------
X -- numpy array of shape (n,d), features
y -- numpy array of shape (n,), targets
Returns
--------------------
error -- float, RMSE
"""
# part h: compute RMSE
n,d = X.shape
error = math.sqrt(self.cost(X,y)/n)
return error
def plot_regression(self, xmin=0, xmax=1, n=50, **kwargs) :
"""Plot regression line."""
if 'color' not in kwargs :
kwargs['color'] = 'r'
if 'linestyle' not in kwargs :
kwargs['linestyle'] = '-'
X = np.reshape(np.linspace(0,1,n), (n,1))
y = self.predict(X)
plot_data(X, y, **kwargs)
plt.show()
######################################################################
# main
######################################################################
def main() :
# load data
train_data = load_data('regression_train.csv')
test_data = load_data('regression_test.csv')
# part a: main code for visualizations
print 'Visualizing data...'
#plot_data(train_data.X, train_data.y, 'trainData.pdf')
#plot_data(test_data.X, test_data.y, 'testData.pdf')
# parts b-f: main code for linear regression
print 'Investigating linear regression...'
import time
reg=PolynomialRegression(1)
eta=0.0001
print("eta="+str(eta))
start=time.time()
reg.fit_GD(train_data.X, train_data.y, eta)
end=time.time()
print("coefficients="+str(reg.coef_))
print("cost="+str(reg.cost(train_data.X, train_data.y)))
print("time="+str(end-start))
print("")
eta=0.001
print("eta="+str(eta))
start=time.time()
reg.fit_GD(train_data.X, train_data.y, eta)
end=time.time()
print("coefficients="+str(reg.coef_))
print("cost="+str(reg.cost(train_data.X, train_data.y)))
print("time="+str(end-start))
print("")
eta=0.01
print("eta="+str(eta))
start=time.time()
reg.fit_GD(train_data.X, train_data.y, eta)
end=time.time()
print("coefficients="+str(reg.coef_))
print("cost="+str(reg.cost(train_data.X, train_data.y)))
print("time="+str(end-start))
print("")
eta=0.0407
print("eta="+str(eta))
start=time.time()
reg.fit_GD(train_data.X, train_data.y, eta)
end=time.time()
print("coefficients="+str(reg.coef_))
print("cost="+str(reg.cost(train_data.X, train_data.y)))
print("time="+str(end-start))
print("")
print("eta=1/(1+k)")
start=time.time()
reg.fit_GD(train_data.X, train_data.y)
end=time.time()
print("coefficients="+str(reg.coef_))
print("cost="+str(reg.cost(train_data.X, train_data.y)))
print("time="+str(end-start))
print("")
print("Closed form fit")
start=time.time()
reg.fit(train_data.X, train_data.y)
end=time.time()
print("coefficients="+str(reg.coef_))
print("cost="+str(reg.cost(train_data.X, train_data.y)))
print("time="+str(end-start))
print("")
# parts g-i: main code for polynomial regression
print 'Investigating polynomial regression...'
mPlot=[]
trainRMSE=[]
testRMSE=[]
for m in range(0,11):
reg=PolynomialRegression(m)
reg.fit(train_data.X, train_data.y)
print("m="+str(m))
print("train RMSE="+str(reg.rms_error(train_data.X, train_data.y)))
print("test RMSE="+str(reg.rms_error(test_data.X, test_data.y)))
print("")
mPlot.append(m)
trainRMSE.append(reg.rms_error(train_data.X, train_data.y))
testRMSE.append(reg.rms_error(test_data.X, test_data.y))
#line1, =plt.plot(mPlot, trainRMSE, '-', label='Training RMSE')
#line2, =plt.plot(mPlot, testRMSE, '-', label='Testing RMSE')
#plt.axis('auto')
#plt.xlabel('m')
#plt.ylabel('Root Mean Squared Error')
#plt.legend(loc='best')
#plt.title('Errors for Polynomial Regression of Degree m')
#plt.savefig("polynomialRegression.pdf")
#plt.clf()
print "Done!"
if __name__ == "__main__" :
main()
| [
"cheeserules43@gmail.com"
] | cheeserules43@gmail.com |
270280b5e47a20fdb3e29373151542e0bac4ad1e | a1f63894e73369a4649be4cc792c407b671f9547 | /src/brown_drivers/irobot_create_2_1/src/irobot_create_2_1/srv/_Dock.py | 86383b2435da8ebdf3092f8c38b5a4851722a6f1 | [] | no_license | parksj92/rosie | 5b21329a4d14f2e21cebd71f85bae154d714ff6f | 8f8b70a2cdb351c9a8ae1dbcfd8e9f242c1c7e03 | refs/heads/master | 2020-06-04T12:55:28.007459 | 2015-05-06T19:57:54 | 2015-05-06T19:57:54 | 31,720,276 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,149 | py | """autogenerated by genpy from irobot_create_2_1/DockRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class DockRequest(genpy.Message):
_md5sum = "d41d8cd98f00b204e9800998ecf8427e"
_type = "irobot_create_2_1/DockRequest"
_has_header = False #flag to mark the presence of a Header object
_full_text = """
"""
__slots__ = []
_slot_types = []
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(DockRequest, self).__init__(*args, **kwds)
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
pass
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
pass
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
"""autogenerated by genpy from irobot_create_2_1/DockResponse.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class DockResponse(genpy.Message):
_md5sum = "358e233cde0c8a8bcfea4ce193f8fc15"
_type = "irobot_create_2_1/DockResponse"
_has_header = False #flag to mark the presence of a Header object
_full_text = """bool success
"""
__slots__ = ['success']
_slot_types = ['bool']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
success
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(DockResponse, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.success is None:
self.success = False
else:
self.success = False
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
buff.write(_struct_B.pack(self.success))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
start = end
end += 1
(self.success,) = _struct_B.unpack(str[start:end])
self.success = bool(self.success)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
buff.write(_struct_B.pack(self.success))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
start = end
end += 1
(self.success,) = _struct_B.unpack(str[start:end])
self.success = bool(self.success)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
_struct_B = struct.Struct("<B")
class Dock(object):
_type = 'irobot_create_2_1/Dock'
_md5sum = '358e233cde0c8a8bcfea4ce193f8fc15'
_request_class = DockRequest
_response_class = DockResponse
| [
"rbtying@aeturnalus.com"
] | rbtying@aeturnalus.com |
4c557ef7d1519e016f479c44b7cdfb3e045d59ab | 3681d5b2786f60dafdcac95fb2421307c0a59975 | /blogapp/blog/admin.py | 517dec69d08d243e68cb9ca116bd59ade671195f | [] | no_license | conectabell/Django_SimpleBlog | 45cd4e43bec87a4c435a7345618ca28a419149db | 498f5b5432ffc15be5adbd7b053ce92023430101 | refs/heads/master | 2021-01-09T05:53:30.002624 | 2017-04-23T23:32:47 | 2017-04-23T23:32:47 | 80,858,258 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 156 | py | from django.contrib import admin
#from django.db import models
from .models import Post
#admin.site.register(Rules, RulesAdmin)
admin.site.register(Post)
| [
"conectabell@gmail.com"
] | conectabell@gmail.com |
c118f02e997f6b98c12d016a62028a6e2795e9da | 30606e113697002f7a2a44a315d44796b428b944 | /src/neural_net_tests.py | 0ff0b44abfd150bcefd8474fe40e2fad66248ab6 | [
"MIT"
] | permissive | EoinM95/FYP | 2d0ac824e921bf45a502bbaba964a29c4be8a714 | 8b3bb73a0776dc65a8b577867d6a1d2f369fc7c5 | refs/heads/master | 2021-01-11T07:58:08.640167 | 2017-03-30T14:59:57 | 2017-03-30T14:59:57 | 72,131,784 | 1 | 0 | null | 2017-02-22T18:39:50 | 2016-10-27T17:27:49 | Python | UTF-8 | Python | false | false | 1,274 | py | """Tests for NeuralNetwork class"""
import unittest
import numpy as np
from neural_net import NeuralNetwork
class NeuralNetworkTests(unittest.TestCase):
"""Tests for NeuralNetwork class"""
def test_xor_gate(self):
"""Simulate XOR gate and ensure working"""
inputs = [[1.0, 1.0],
[1.0, 0.0],
[0.0, 1.0],
[0.0, 0.0]]
output_vector = [[0.0],
[1.0],
[1.0],
[0.0]]
inputs = np.array(inputs, dtype='float32')
output_vector = np.array(output_vector)
net = NeuralNetwork(inputs, output_vector)
net.train()
output = net.feed(np.array([[0, 1]], dtype='float32'))[0][0]
output = round(output, 3)
self.assertAlmostEqual(output, 1)
output = net.feed(np.array([[1, 0]], dtype='float32'))[0][0]
output = round(output, 3)
self.assertAlmostEqual(output, 1)
output = net.feed(np.array([[0, 0]], dtype='float32'))[0][0]
output = round(output, 3)
self.assertAlmostEqual(output, 0)
output = net.feed(np.array([[1, 1]], dtype='float32'))[0][0]
output = round(output, 3)
self.assertAlmostEqual(output, 0)
| [
"murphe43@tcd.ie"
] | murphe43@tcd.ie |
39d52659f57b9560c8b853368de4c568f3f77ca1 | 757d26801d42764be6d5368a5dbbe175f3ceeef4 | /venv/bin/mailmail | dcbd886bccad5d70e80dc0583034fcc2b0744ac4 | [] | no_license | luyuehm/scrapy_v1 | d1265eaad7836348be5911c06556ed23340d6de9 | 69da04ccfea06822f6bcd74f3abc3a44daabd300 | refs/heads/master | 2023-03-15T04:10:34.668307 | 2021-03-07T08:58:53 | 2021-03-07T08:58:53 | 346,115,989 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 267 | #!/Users/macbook/PycharmProjects/scrapy_v1/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from twisted.mail.scripts.mailmail import run
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(run())
| [
"macbook@macbookdeMacBook-Pro.local"
] | macbook@macbookdeMacBook-Pro.local | |
edf40036c2140cfcdf728abbeb3fcfcbf0fdae99 | caf8d5ee09ef4412cd0c14b6a479714e50c68c1e | /small.py | 3fbd8ffd9d98384e49ed26d60a07560960e4f135 | [
"MIT"
] | permissive | victorShawFan/distill_BERT_into_RNN-CNN | 0dde6e89c8df5d8a9edf74aa528448d6f3214494 | 0ecbb033d229a2cc4f611964fd249a8eafdd710f | refs/heads/main | 2023-05-24T03:32:24.500902 | 2021-06-13T09:30:49 | 2021-06-13T09:30:49 | 377,155,136 | 1 | 0 | MIT | 2021-06-15T12:28:51 | 2021-06-15T12:28:50 | null | UTF-8 | Python | false | false | 4,352 | py | import torch, numpy as np
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from keras.preprocessing import sequence
from utils import load_data
USE_CUDA = torch.cuda.is_available()
if USE_CUDA: torch.cuda.set_device(0)
LTensor = torch.cuda.LongTensor if USE_CUDA else torch.LongTensor
class RNN(nn.Module):
def __init__(self, x_dim, e_dim, h_dim, o_dim):
super(RNN, self).__init__()
self.h_dim = h_dim
self.dropout = nn.Dropout(0.2)
self.emb = nn.Embedding(x_dim, e_dim, padding_idx=0)
self.lstm = nn.LSTM(e_dim, h_dim, bidirectional=True, batch_first=True)
self.fc = nn.Linear(h_dim * 2, o_dim)
self.softmax = nn.Softmax(dim=1)
self.log_softmax = nn.LogSoftmax(dim=1)
def forward(self, x, lens):
embed = self.dropout(self.emb(x))
out, _ = self.lstm(embed)
hidden = self.fc(out[:, -1, :])
return self.softmax(hidden), self.log_softmax(hidden)
class CNN(nn.Module):
def __init__(self, x_dim, e_dim, h_dim, o_dim):
super(CNN, self).__init__()
self.emb = nn.Embedding(x_dim, e_dim, padding_idx=0)
self.dropout = nn.Dropout(0.2)
self.conv1 = nn.Conv2d(1, h_dim, (3, e_dim))
self.conv2 = nn.Conv2d(1, h_dim, (4, e_dim))
self.conv3 = nn.Conv2d(1, h_dim, (5, e_dim))
self.fc = nn.Linear(h_dim * 3, o_dim)
self.softmax = nn.Softmax(dim=1)
self.log_softmax = nn.LogSoftmax(dim=1)
def forward(self, x, lens):
embed = self.dropout(self.emb(x)).unsqueeze(1)
c1 = torch.relu(self.conv1(embed).squeeze(3))
p1 = torch.max_pool1d(c1, c1.size()[2]).squeeze(2)
c2 = torch.relu(self.conv2(embed).squeeze(3))
p2 = torch.max_pool1d(c2, c2.size()[2]).squeeze(2)
c3 = torch.relu(self.conv3(embed).squeeze(3))
p3 = torch.max_pool1d(c3, c3.size()[2]).squeeze(2)
pool = self.dropout(torch.cat((p1, p2, p3), 1))
hidden = self.fc(pool)
return self.softmax(hidden), self.log_softmax(hidden)
class Model(object):
def __init__(self, v_size):
self.model = None
self.b_size = 64
self.lr = 0.001
self.model = RNN(v_size, 256, 256, 2)
# self.model = CNN(v_size,256,128,2)
def train(self, x_tr, y_tr, l_tr, x_te, y_te, l_te, epochs=15):
assert self.model is not None
if USE_CUDA: self.model = self.model.cuda()
loss_func = nn.NLLLoss()
opt = optim.Adam(self.model.parameters(), lr=self.lr)
for epoch in range(epochs):
losses = []
accu = []
self.model.train()
for i in range(0, len(x_tr), self.b_size):
self.model.zero_grad()
bx = Variable(LTensor(x_tr[i:i + self.b_size]))
by = Variable(LTensor(y_tr[i:i + self.b_size]))
bl = Variable(LTensor(l_tr[i:i + self.b_size]))
_, py = self.model(bx, bl)
loss = loss_func(py, by)
loss.backward()
opt.step()
losses.append(loss.item())
self.model.eval()
with torch.no_grad():
for i in range(0, len(x_te), self.b_size):
bx = Variable(LTensor(x_te[i:i + self.b_size]))
by = Variable(LTensor(y_te[i:i + self.b_size]))
bl = Variable(LTensor(l_te[i:i + self.b_size]))
_, py = torch.max(self.model(Variable(LTensor(bx)), bl)[1], 1)
accu.append((py == by).float().mean().item())
print(np.mean(losses), np.mean(accu))
if __name__ == '__main__':
x_len = 50
# ----- ----- ----- ----- -----
# from keras.datasets import imdb
# v_size = 10000
# (x_tr,y_tr),(x_te,y_te) = imdb.load_data(num_words=v_size)
# ----- ----- ----- ----- -----
name = 'hotel' # clothing, fruit, hotel, pda, shampoo
(x_tr, y_tr, _), _, (x_te, y_te, _), v_size, _ = load_data(name)
l_tr = list(map(lambda x: min(len(x), x_len), x_tr))
l_te = list(map(lambda x: min(len(x), x_len), x_te))
x_tr = sequence.pad_sequences(x_tr, maxlen=x_len)
x_te = sequence.pad_sequences(x_te, maxlen=x_len)
clf = Model(v_size)
clf.train(x_tr, y_tr, l_tr, x_te, y_te, l_te)
| [
"luxuantao@126.com"
] | luxuantao@126.com |
83f87eada15ab8d5a659a10f018b7e6ffd3ba2ef | ca68dec0fa417f3276454cc27ed30066246947da | /stats.py | b250261d121b5c0d88c8c0fb2e7a03a2fa7cad1c | [] | no_license | jpanag1213/Project_stock | 0f431c6c83102957fe2617222c546c73a74435a7 | cbad6729850869d5fa53aab85f9812eebdfc5cad | refs/heads/master | 2020-04-19T08:59:24.160458 | 2019-04-11T08:15:34 | 2019-04-11T08:15:34 | 168,096,311 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 82,142 | py | # -*- coding: utf-8 -*-
"""
Created on 2019-02-23
to stats the order imbalance feature
#导出日线数据
@author: jiaxiong
"""
import numpy as np
import Data
import SignalTester
import pandas as pd
import os
import configparser
import time
from Utils import *
import matplotlib.pyplot as plt
import datetime
from numba import jit
from multiprocessing.dummy import Pool as mdP
from multiprocessing.pool import Pool as mpP
from functools import partial
class Stats(object):
def __init__(self, symbol, tradedate, quoteData,tradeData = None,futureData =None, outputpath = 'E://stats_test/'):
self.symbol = symbol
self.tradeDate = tradedate
if isinstance(quoteData,dict):
self.quoteData = quoteData
self.tradeData = tradeData
else:
self.quoteData = dict()
self.quoteData[symbol] = quoteData
self.tradeData = dict()
self.tradeData[symbol] = tradeData
self.outputpath = outputpath
self.futureData = futureData
if os.path.exists(outputpath) is False:
os.makedirs(outputpath)
if futureData == None:
self.columns =[
'exchangeCode', 'exchangeTime', 'latest', 'pre_close', 'open', 'high', 'low', 'upper_limit',
'lower_limit', 'status', 'tradeNos', 'tradeVolume', 'totalTurnover',
'bidPrice1', 'bidPrice2', 'bidPrice3', 'bidPrice4', 'bidPrice5', 'bidPrice6', 'bidPrice7',
'bidPrice8', 'bidPrice9', 'bidPrice10',
'askPrice1', 'askPrice2', 'askPrice3', 'askPrice4', 'askPrice5', 'askPrice6', 'askPrice7',
'askPrice8', 'askPrice9', 'askPrice10',
'bidVolume1', 'bidVolume2', 'bidVolume3', 'bidVolume4', 'bidVolume5', 'bidVolume6', 'bidVolume7',
'bidVolume8', 'bidVolume9', 'bidVolume10',
'askVolume1', 'askVolume2', 'askVolume3', 'askVolume4', 'askVolume5', 'askVolume6', 'askVolume7',
'askVolume8', 'askVolume9', 'askVolume10',
'total_bid_qty', 'total_ask_qty', 'weighted_avg_bid_price', 'weighted_avg_ask_price',
'iopv', 'yield_to_maturity']
else:
self.columns = [
'id', 'exchangeTime', 'latest', 'pre_close', 'settle','pre_settle','open', 'high', 'low','close', 'upper_limit',
'lower_limit', 'status', 'buy', 'tradeVolume', 'totalTurnover',
'bidPrice1', 'bidPrice2', 'bidPrice3', 'bidPrice4', 'bidPrice5',
'askPrice1', 'askPrice2', 'askPrice3', 'askPrice4', 'askPrice5',
'bidVolume1', 'bidVolume2', 'bidVolume3', 'bidVolume4', 'bidVolume5',
'askVolume1', 'askVolume2', 'askVolume3', 'askVolume4', 'askVolume5',
'open_interest','pre_open_interest', 'open_qty','close_qty']
def check_file(self,file,symbol = " "):
file.to_csv(self.outputpath+str(self.tradeDate)+'_'+symbol + '_checkquote.csv')
return 0
def Evaluation_times(self,tick = 30):
##监测前30分钟的因子值。订单结构等。
#定义:订单结构,因子设计等等。
#input quotedata tradedata
#output return?volatility?
eva_duration = 20 * tick
quoteData = self.quoteData[self.symbol[0]]
quoteData = pd.concat([quoteData.loc[datetime.datetime.strptime(str(self.tradeDate + ' 09:30:00'),'%Y%m%d %H:%M:%S'):datetime.datetime.strptime(str(self.tradeDate + ' 9:45:00'), '%Y%m%d %H:%M:%S'):],quoteData.loc[datetime.datetime.strptime(str(self.tradeDate + ' 13:00:00'),'%Y%m%d %H:%M:%S'):datetime.datetime.strptime(str(self.tradeDate + ' 13:15:00'), '%Y%m%d %H:%M:%S'):]])
columns = self.columns
stats.check_file(quoteData)
return 0
def lastNday(self,tradingday,tradingDates):
tradingDayFile ='./ref_data/TradingDay.csv'
tradingDays = pd.read_csv(tradingDayFile)
def opentime(self,symbol,closetime = ' 14:50:00'):
quoteData = self.quoteData[symbol]
quoteData.loc[:,'opentime'] = 0
quoteData.loc[datetime.datetime.strptime(str(self.tradeDate + ' 09:30:00'), '%Y%m%d %H:%M:%S'):datetime.datetime.strptime(str(self.tradeDate +closetime), '%Y%m%d %H:%M:%S'),'opentime'] = 1
quoteData.loc[
datetime.datetime.strptime(str(self.tradeDate + closetime), '%Y%m%d %H:%M:%S'):datetime.datetime.strptime(str(self.tradeDate + ' 14:57:00'), '%Y%m%d %H:%M:%S'), 'opentime'] =2
#stats.check_file(quoteData)
return quoteData
def time_cut(self,symbol,closetime = ' 14:50:00'):
quoteData = self.quoteData[symbol]
quoteData.loc[:,'opentime'] = 0
quoteData.loc[datetime.datetime.strptime(str(self.tradeDate + ' 09:30:03'), '%Y%m%d %H:%M:%S'):datetime.datetime.strptime(str(self.tradeDate +closetime), '%Y%m%d %H:%M:%S'),'opentime'] = 1
quoteData = quoteData.loc[datetime.datetime.strptime(str(self.tradeDate + ' 09:30:03'), '%Y%m%d %H:%M:%S'):datetime.datetime.strptime(str(self.tradeDate +closetime), '%Y%m%d %H:%M:%S'),:]
#stats.check_file(quoteData)
return quoteData
def quote_cut(self,quoteData,num = 10):
price_column_ask= list()
price_column_bid= list()
volunme_column_ask = list()
volunme_column_bid = list()
for Nos in range(1,num+1):
price_column_ask.append('askPrice'+ str(Nos))
volunme_column_ask.append('askVolume' + str(Nos))
for Nos in range(1,num+1):
price_column_bid.append('bidPrice' + str(Nos))
volunme_column_bid.append('bidVolume'+ str(Nos))
return quoteData.loc[:,price_column_ask],quoteData.loc[:,volunme_column_ask],quoteData.loc[:,price_column_bid],quoteData.loc[:,volunme_column_bid]
def responseFun(self,symbol):
quoteData = self.quoteData[symbol]
quoteD = pd.DataFrame()
return 0
def spread_width(self):
quotedata.loc[:,'bid_spread'] = quotedata.loc[:,'bidPrice1'] - quotedata.loc[:,'bidPrice10']
quotedata.loc[:, 'bid_weight'] =( (quotedata.loc[:,'bidPrice1'] - quotedata.loc[:,'weighted_avg_bid_price'])**2*(quotedata.loc[:,'bidVolume1'])
+(quotedata.loc[:, 'bidPrice2'] - quotedata.loc[:, 'weighted_avg_bid_price'])**2 * (quotedata.loc[:, 'bidVolume2'])
+(quotedata.loc[:, 'bidPrice3'] - quotedata.loc[:, 'weighted_avg_bid_price'])**2 * (quotedata.loc[:, 'bidVolume3'])
+(quotedata.loc[:, 'bidPrice4'] - quotedata.loc[:, 'weighted_avg_bid_price'])**2 * (quotedata.loc[:, 'bidVolume4'])
+(quotedata.loc[:, 'bidPrice5'] - quotedata.loc[:, 'weighted_avg_bid_price'])**2 * (quotedata.loc[:, 'bidVolume5'])
+(quotedata.loc[:, 'bidPrice6'] - quotedata.loc[:, 'weighted_avg_bid_price'])**2 * (quotedata.loc[:, 'bidVolume6'])
+(quotedata.loc[:, 'bidPrice7'] - quotedata.loc[:, 'weighted_avg_bid_price'])**2 * (quotedata.loc[:, 'bidVolume7'])
+(quotedata.loc[:, 'bidPrice8'] - quotedata.loc[:, 'weighted_avg_bid_price'])**2 * (quotedata.loc[:, 'bidVolume8'])
+(quotedata.loc[:, 'bidPrice9'] - quotedata.loc[:, 'weighted_avg_bid_price'])**2 * (quotedata.loc[:, 'bidVolume9'])
+(quotedata.loc[:, 'bidPrice10'] - quotedata.loc[:, 'weighted_avg_bid_price'])**2 * (quotedata.loc[:, 'bidVolume10']))/ (quotedata.loc[:, 'total_bid_qty'])
quotedata.loc[:, 'ask_weight'] = ((quotedata.loc[:,'askPrice1'] - quotedata.loc[:,'weighted_avg_ask_price'])**2*(quotedata.loc[:,'askVolume1'])
+(quotedata.loc[:, 'askPrice2'] - quotedata.loc[:, 'weighted_avg_ask_price'])**2 * (quotedata.loc[:, 'askVolume2'])
+(quotedata.loc[:, 'askPrice3'] - quotedata.loc[:, 'weighted_avg_ask_price'])**2 * (quotedata.loc[:, 'askVolume3'])
+(quotedata.loc[:, 'askPrice4'] - quotedata.loc[:, 'weighted_avg_ask_price'])**2 * (quotedata.loc[:, 'askVolume4'])
+(quotedata.loc[:, 'askPrice5'] - quotedata.loc[:, 'weighted_avg_ask_price'])**2 * (quotedata.loc[:, 'askVolume5'])
+(quotedata.loc[:, 'askPrice6'] - quotedata.loc[:, 'weighted_avg_ask_price'])**2 * (quotedata.loc[:, 'askVolume6'])
+(quotedata.loc[:, 'askPrice7'] - quotedata.loc[:, 'weighted_avg_ask_price'])**2 * (quotedata.loc[:, 'askVolume7'])
+(quotedata.loc[:, 'askPrice8'] - quotedata.loc[:, 'weighted_avg_ask_price'])**2 * (quotedata.loc[:, 'askVolume8'])
+(quotedata.loc[:, 'askPrice9'] - quotedata.loc[:, 'weighted_avg_ask_price'])**2 * (quotedata.loc[:, 'askVolume9'])
+(quotedata.loc[:, 'askPrice10'] - quotedata.loc[:, 'weighted_avg_ask_price'])**2 * (quotedata.loc[:, 'askVolume10']))/ (quotedata.loc[:, 'total_ask_qty'])
quotedata.loc[:,'weight_ratio'] = quotedata.loc[:, 'bid_weight']/quotedata.loc[:, 'ask_weight']
'''
quotedata.loc[:,'ratio_mean'] = quotedata.loc[:,'weight_ratio'].ewm(10).mean()
quotedata.loc[:,'ratio_std'] = quotedata.loc[:,'weight_ratio'].ewm(10).std()
positivePos = quotedata.loc[:,'weight_ratio'] > (quotedata.loc[:,'ratio_mean'] + 2*quotedata.loc[:,'ratio_std'])
negativePos = quotedata.loc[:,'weight_ratio'] < (quotedata.loc[:,'ratio_mean'] -2* quotedata.loc[:,'ratio_std'])
quotedata.loc[:,'signal'] = 0
quotedata.loc[positivePos,'signal'] = 1
quotedata.loc[negativePos,'signal'] = -1
'''
quotedata.loc[:,'ask_spread'] = quotedata.loc[:,'askPrice1'] -quotedata.loc[:,'askPrice10']
quotedata.loc[:,'spread'] = quotedata.loc[:,'askPrice1'] -quotedata.loc[:,'bidPrice1']
return 0
def morning_session(self,symbol):
opendata = stats.time_cut(symbol,closetime = ' 09:30:06')
base_price_ask,base_volume_ask = stats.rolling_dealer(opendata,num=10,name='ask')
base_price_bid,base_volume_bid = stats.rolling_dealer(opendata,num=10,name='bid')
quotedata = stats.time_cut(symbol, closetime=' 14:50:00')
quotedata = stats.rolling_dealer(quotedata,num=5,name='ask',base_price = base_price_ask,base_qty= base_volume_ask)
quotedata = stats.rolling_dealer(quotedata,num=5,name='bid',base_price = base_price_bid,base_qty= base_volume_bid)
quotedata.loc[:,'ret_bid'] = np.log(quotedata.loc[:,'bid_leftPrice'] / quotedata.loc[:, 'pre_close'])
quotedata.loc[:,'ret_ask'] = np.log(quotedata.loc[:,'ask_leftPrice'] / quotedata.loc[:, 'pre_close'])
quotedata.loc[:, 'open_ret'] = np.log(quotedata.loc[:, 'open'] / quotedata.loc[:, 'pre_close'])
stats.check_file(quotedata,symbol)
return quotedata
def rolling_dealer(self,quotedata,num = 10,name = 'ask',base_price = 0,base_qty = 0):
#统计开盘时的订单情况。
#计算开盘时刻,盘口之外的挂单情况。
total_qty_name = 'total_'+name+'_qty'
avg_price_name = 'weighted_avg_'+name+'_price'
temp = quotedata.loc[:, avg_price_name]*quotedata.loc[:, total_qty_name] - base_price *1*base_qty/2
temp2 = quotedata.loc[:, total_qty_name] -1* base_qty/2
for number in range(1,num+1):
price_name = name+'Price'+str(number)
Volume_name = name+'Volume'+str(number)
temp = temp -quotedata.loc[:,price_name]*quotedata.loc[:,Volume_name]
temp2 = temp2 -quotedata.loc[:,Volume_name]
quotedata.loc[:,name+'_leftPrice'] = temp/temp2
quotedata.loc[:, name + '_BasePrice'] = base_price
quotedata.loc[:,name+'_leftVolume'] = temp2
quotedata.loc[:,name+'_BaseVolume'] =base_qty*1/2
if base_price ==0:
return (temp/temp2).mean(),temp2.mean()
else:
return quotedata
def cancel_order(self,symbol):
quotedata = self.quoteData[symbol]
tradeData = self.tradeData[symbol]
quote_time = pd.to_datetime(quotedata.exchangeTime.values).values
quotedata.loc[:,'tradeVolume'] =quotedata.loc[:, 'tradeVolume'].diff()
quotedata.loc[:,'Turnover'] =quotedata.loc[:, 'totalTurnover'].diff()
quotedata.index = pd.to_datetime(quotedata.loc[:, 'exchangeTime'].values, format='%Y-%m-%d %H:%M:%S')
temp_1 = pd.to_datetime(tradeData.loc[:,' nTime'], format='%Y-%m-%d %H:%M:%S.%f')
qqq = temp_1[0].microsecond
bid_order = tradeData.loc[:, ' nBSFlag'] == 'B'
ask_order = tradeData.loc[:, ' nBSFlag'] == 'S'
can_order = tradeData.loc[:, ' nBSFlag'] == ' '
tradeData.loc[bid_order, 'numbs_flag'] = 1
tradeData.loc[ask_order, 'numbs_flag'] = -1
tradeData.loc[can_order, 'numbs_flag'] = 0
tradeData.loc[:, 'temp'] = tradeData.loc[:, ' nPrice']
#tradeData.loc[pos, 'temp'] = np.nan
tradeData.temp.fillna(method='ffill', inplace=True)
lastrep = list(tradeData.temp.values[:-1])
lastrep.insert(0, 0)
lastrep = np.asarray(lastrep)
tradeData_quote = pd.merge(quotedata.loc[:, ['bidPrice1', 'askPrice1','tradeVolume','Turnover']],tradeData, left_index=True,right_index=True, how='outer')
tradeData_quote['bidPrice1'].fillna(method='ffill', inplace=True)
tradeData_quote['askPrice1'].fillna(method='ffill', inplace=True)
# tradeData_quote.to_csv(self.dataSavePath + './' + str(self.tradeDate.date()) + signal + ' ' + symbol + '.csv')
ActiveBuy = (tradeData_quote.loc[:, 'numbs_flag'] == 1)
ActiveSell = (tradeData_quote.loc[:, 'numbs_flag'] == -1)
tradeData_quote.loc[ActiveBuy, 'abVolume'] = tradeData_quote.loc[ActiveBuy, ' nVolume']
tradeData_quote.loc[ActiveSell, 'asVolume'] = tradeData_quote.loc[ActiveSell, ' nVolume']
tradeData_quote.loc[ActiveBuy, 'abPrice'] = tradeData_quote.loc[ActiveBuy, ' nTurnover']
tradeData_quote.loc[ActiveSell, 'asPrice'] = tradeData_quote.loc[ActiveSell, ' nTurnover']
#stats.check_file(tradeData_quote)
temp_quote_time = np.asarray(list(quote_time))
Columns_ = ['abVolume', 'asVolume','abPrice', 'asPrice']
resample_tradeData = tradeData_quote.loc[:, Columns_].resample('1S', label='right', closed='right').sum()
resample_tradeData = resample_tradeData.cumsum()
resample_tradeData = resample_tradeData.loc[temp_quote_time, :]
r_tradeData = resample_tradeData.diff()
r_tradeData.loc[:, 'abPrice'] = r_tradeData.loc[:, 'abPrice'] / r_tradeData.loc[:, 'abVolume']
r_tradeData.loc[:, 'asPrice'] = r_tradeData.loc[:, 'asPrice']/ r_tradeData.loc[:, 'asVolume']
r_tradeData.loc[:, 'VWAP'] =(r_tradeData.loc[:, 'asPrice']+ r_tradeData.loc[:, 'asPrice'])/ (r_tradeData.loc[:, 'asVolume']+r_tradeData.loc[:, 'abVolume'])
r_tradeData.loc[:,'timecheck'] =quotedata.loc[:, 'exchangeTime']
#stats.check_file(r_tradeData)
#stats.check_file(r_tradeData)
'''
quote_order = pd.merge(self.quoteData[symbol].loc[:, ['midp', 'midp_10', 'spread']], r_tradeData, left_index=True,
right_index=True, how='left')
# .loc[:,'midp'] =self.quoteData[symbol].loc[:,'midp']
quote_order.to_csv(self.outputpath + './ quote_order.csv')
# self.quoteData[symbol].loc[:, ['midp', 'bidVolume1', 'askVolume1']].to_csv(self.outputpath + './ quote_o.csv')
'''
r_tradeData.loc[:,'diff'] = r_tradeData.loc[:, 'abVolume'] - r_tradeData.loc[:, 'asVolume']
r_tradeData.loc[:,'cum_diff'] = r_tradeData.loc[:,'diff'].cumsum()
return r_tradeData
def plot(self):
return 0
def price_filter(self):
symbol = self.symbol[0]
midp = self.quoteData[symbol].loc[:, 'midp']
quotedata = self.quoteData[symbol]
bid_Volume10 = (quotedata.loc[:, 'bidVolume1'] + quotedata.loc[:, 'bidVolume2'] + quotedata.loc[:,
'bidVolume3']) * 1 / 10
ask_Volume10 = (quotedata.loc[:, 'askVolume1'] + quotedata.loc[:, 'askVolume2'] + quotedata.loc[:,
'askVolume3']) * 1 / 10
bid_Volume10_2 = (quotedata.loc[:, 'bidVolume1'] + quotedata.loc[:, 'bidVolume2'])
ask_Volume10_2 = (quotedata.loc[:, 'askVolume1'] + quotedata.loc[:, 'askVolume2'])
bid_price = (bid_Volume10 < quotedata.loc[:, 'bidVolume1']) + 2 * (
(bid_Volume10 > quotedata.loc[:, 'bidVolume1']) & (bid_Volume10 < bid_Volume10_2))
ask_price = (ask_Volume10 < quotedata.loc[:, 'askVolume1']) + 2 * (
(ask_Volume10 > quotedata.loc[:, 'askVolume1']) & (ask_Volume10 < ask_Volume10_2))
quotedata.loc[:, 'bid_per10'] = quotedata.loc[:, 'bidPrice1']
quotedata.loc[:, 'ask_per10'] = quotedata.loc[:, 'askPrice1']
quotedata.loc[:, 'bid_vol10'] = quotedata.loc[:, 'bidVolume1']
quotedata.loc[:, 'ask_vol10'] = quotedata.loc[:, 'askVolume1']
quotedata.loc[bid_price == 2, 'bid_per10'] = quotedata.loc[bid_price == 2, 'bidPrice2']
quotedata.loc[bid_price == 0, 'bid_per10'] = quotedata.loc[bid_price == 0, 'bidPrice3']
quotedata.loc[ask_price == 2, 'ask_per10'] = quotedata.loc[ask_price == 2, 'askPrice2']
quotedata.loc[ask_price == 0, 'ask_per10'] = quotedata.loc[ask_price == 0, 'askPrice3']
quotedata.loc[quotedata.loc[:, 'ask_per10'] == 0, 'ask_per10'] = np.nan
quotedata.loc[quotedata.loc[:, 'bid_per10'] == 0, 'bid_per10'] = np.nan
quotedata.loc[bid_price == 2, 'bid_vol10'] = quotedata.loc[bid_price == 2, 'bidVolume2']
quotedata.loc[bid_price == 0, 'bid_vol10'] = quotedata.loc[bid_price == 0, 'bidVolume3']
quotedata.loc[ask_price == 2, 'ask_vol10'] = quotedata.loc[ask_price == 2, 'askVolume2']
quotedata.loc[ask_price == 0, 'ask_vol10'] = quotedata.loc[ask_price == 0, 'askVolume3']
midp_2 = (quotedata.loc[:, 'ask_per10'] * quotedata.loc[:, 'bid_vol10'] + quotedata.loc[:,
'bid_per10'] * quotedata.loc[:,
'ask_vol10']) / (
quotedata.loc[:, 'bid_vol10'] + quotedata.loc[:, 'ask_vol10'])
self.quoteData[symbol].loc[:, 'midp_2'] = midp_2
# midp = (quotedata.loc[:, 'askPrice1'] * quotedata.loc[:, 'bidVolume1'] + quotedata.loc[:, 'bidPrice1'] * quotedata.loc[:,'askVolume1']) / (quotedata.loc[:, 'bidVolume1'] + quotedata.loc[:, 'askVolume1'])
mean_midp = midp_2.rolling(20).mean()
Minute = 6
ewm_midp = mean_midp.ewm(6 * 20).mean()
fig, ax = plt.subplots(1, figsize=(20, 12), sharex=True)
mean_midp_ = midp.rolling(20).mean()
ewm_midp_ = mean_midp_.ewm(6 * 20).mean()
not_point = list()
kp1_point = list()
kp2_point = list()
kp_1 = 0
kp_2 = 0
id_1 = 0
id_2 = 0
count = 0
std_ = mean_midp.ewm(6 * 20).std()
# std = mean_midp.ewm(M2* T)
STATE_test = list()
kp_list = list()
for row in zip(ewm_midp, std_):
count = count + 1
i = row[0]
j = row[1]
if i is not np.nan:
if (kp_1 != 0) & (kp_2 != 0) & (kp_1 == kp_1) & (kp_2 == kp_2):
kp_diff = kp_1 - kp_2
if (kp_diff * (i - kp_2) < 0):
if ((abs(i - kp_2)) > 4 * j):
# print(id_2-id_1)
not_point.append(i)
kp_1 = kp_2
kp_2 = i
id_1 = id_2
id_2 = count
STATE_test.append(3)
else:
not_point.append(kp_2)
STATE_test.append(2)
else:
kp_2 = i
id_2 = count
not_point.append(kp_1)
STATE_test.append(1)
else:
not_point.append(np.nan)
kp_1 = i
kp_2 = i
id_1 = count
id_2 = count
STATE_test.append(0)
kp1_point.append(kp_1)
kp2_point.append(kp_2)
else:
not_point.append(np.nan)
kp1_point.append(np.nan)
kp2_point.append(np.nan)
STATE_test.append(np.nan)
self.quoteData[symbol].loc[:, 'ewm'] = ewm_midp_
self.quoteData[symbol].loc[:, 'filter_ewm'] = ewm_midp
self.quoteData[symbol].loc[:, 'not'] = not_point
# self.quoteData[symbol].loc[:,'kp_1'] = kp1_point
# self.quoteData[symbol].loc[:,'kp_2'] = kp2_point
self.quoteData[symbol].loc[:, 'std_'] = std_
# self.quoteData[symbol].loc[:,'std_'] = std_
# self.quoteData[symbol].loc[:,'state'] = STATE_test
self.quoteData[symbol].loc[:, 'upper_bound'] = self.quoteData[symbol].loc[:, 'not'] + 3 * \
self.quoteData[symbol].loc[:, 'std_']
self.quoteData[symbol].loc[:, 'lower_bound'] = self.quoteData[symbol].loc[:, 'not'] - 3 * \
self.quoteData[symbol].loc[:, 'std_']
# negativePos = (self.quoteData[symbol].loc[:,'ewm']> (self.quoteData[symbol].loc[:,'not'] +3*self.quoteData[symbol].loc[:,'std_']))&(self.quoteData[symbol].loc[:,'ewm'].shift(-1) <(self.quoteData[symbol].loc[:,'not'].shift(-1) + 3*self.quoteData[symbol].loc[:,'std_'].shift(-1)))
# negativePos = (self.quoteData[symbol].loc[:,'ewm'].shift(1) > (self.quoteData[symbol].loc[:,'not'].shift(1) +3*self.quoteData[symbol].loc[:,'std_'].shift(1) ))&(self.quoteData[symbol].loc[:,'ewm'] <(self.quoteData[symbol].loc[:,'not'] + 3*self.quoteData[symbol].loc[:,'std_']))
positivePos = (self.quoteData[symbol].loc[:, 'ewm'].shift(1) < (
self.quoteData[symbol].loc[:, 'not'].shift(1) + 3 * self.quoteData[symbol].loc[:,
'std_'].shift(1))) & (
self.quoteData[symbol].loc[:, 'ewm'] > (
self.quoteData[symbol].loc[:, 'not'] + 3 * self.quoteData[symbol].loc[:,
'std_']))
# positivePos = (self.quoteData[symbol].loc[:,'ewm']< (self.quoteData[symbol].loc[:,'not'] -3*self.quoteData[symbol].loc[:,'std_']))&(self.quoteData[symbol].loc[:,'ewm'].shift(-1)>(self.quoteData[symbol].loc[:,'not'].shift(-1) - 3*self.quoteData[symbol].loc[:,'std_'].shift(-1)))
# positivePos = (self.quoteData[symbol].loc[:,'ewm'].shift(1) < (self.quoteData[symbol].loc[:,'not'].shift(1) -3*self.quoteData[symbol].loc[:,'std_'].shift(1) ))&(self.quoteData[symbol].loc[:,'ewm']>(self.quoteData[symbol].loc[:,'not'] - 3*self.quoteData[symbol].loc[:,'std_']))
negativePos = (self.quoteData[symbol].loc[:, 'ewm'].shift(1) > (
self.quoteData[symbol].loc[:, 'not'].shift(1) - 3 * self.quoteData[symbol].loc[:,
'std_'].shift(1))) & (
self.quoteData[symbol].loc[:, 'ewm'] < (
self.quoteData[symbol].loc[:, 'not'] - 3 * self.quoteData[symbol].loc[:,
'std_']))
'''
y_value = list(midp.iloc[:])
yvalue =list(ewm_midp)
yvalue_3 = list(ewm_midp_)
ax.plot(yvalue,label = '1')
ax.plot(y_value,label = '2')
ax.plot(not_point, marker='^', c='red')
#plt.savefig(self.dataSavePath + '/'+ str(self.tradeDate.date()) +symbol +signal+ '.jpg')
'''
quotedata = self.quoteData[symbol]
stats.check_file(quotedata,symbol)
return 0
def obi_fixedprice(self,symbol):
'''
定义一个相对的量:
bv1 = 1
股 if bv1 < 主动卖量
意味着:盘口的量只要按1个tick内就很有可能被打掉了。 ##这个事情怎么衡量呢 或者说打掉的分布。
av1 = 1
股 if av1 < 主动买量
obi = log(bv / av)
去除obi过分大的情况
large_obi = abs(obi) > exp(2)(7.3
倍左右)
obi[large_obi] = 0 ##todo 这里可以修改 。这里我想可能设置的不够好。如果是0的话。也体现不了obi从-2到2变动的情况。
##备选方式1 obi[large_obi] = k * obi[large_obi] ,k<<1
初始化盘口量计数。last_obi
价格不变的情况下,计算obi_change = obi - last_obi ##这里有个计数的方式,表示跟踪N tick的 obi的变化。
midp变化的情况下,重置last_obi。
##这里有个trick,主要的原因在于当obi信号触发的时候,薄弱的盘口不稳定。导致midp的多次变化->last_obi重复出现->last_obi不一定可靠。
##不过有一点不变的是 厚单快被打掉的时候就进去了。
##厚单的情况仍然需要继续统计。
## 突然被打掉的情况是不清楚的。如下方的青岛港
'''
self.quoteData[symbol] = self.high_obi(symbol)
small_obi_bid = self.quoteData[symbol].loc[:, 'bidVolume1']<self.quoteData[symbol].loc[:, 'asVolume']
small_obi_ask = self.quoteData[symbol].loc[:, 'askVolume1']<self.quoteData[symbol].loc[:, 'abVolume']
self.quoteData[symbol].loc[small_obi_bid, 'bidVolume1'] = 1
self.quoteData[symbol].loc[small_obi_ask, 'askVolume1'] = 1
self.quoteData[symbol] .loc[:, 'obi'] = np.log(self.quoteData[symbol] .loc[:, 'bidVolume1']) - np.log(
self.quoteData[symbol] .loc[:, 'askVolume1'])
large_obi = np.abs(self.quoteData[symbol].loc[:,'obi']) > 2
self.quoteData[symbol].loc[large_obi, 'obi'] = 0
self.quoteData[symbol].loc[:, 'obi'] = np.log(self.quoteData[symbol].loc[:, 'bidVolume1']) - np.log(
self.quoteData[symbol].loc[:, 'askVolume1'])
# self.quoteData[symbol].loc[:, 'obi_' + str(window) + '_min'] = self.quoteData[symbol].loc[:,
# 'obi'].rolling(window * 60).mean()
self.quoteData[symbol].loc[:, 'obi_' + '_min'] = self.quoteData[symbol].loc[:, 'obi'].diff()
askPriceDiff = self.quoteData[symbol]['askPrice1'].diff()
bidPriceDiff = self.quoteData[symbol]['bidPrice1'].diff()
midPriceChange = self.quoteData[symbol]['midp'].diff()
self.quoteData[symbol].loc[:, 'priceChange'] = 1
self.quoteData[symbol].loc[midPriceChange == 0, 'priceChange'] = 0
obi_change_list = list()
last_obi = self.quoteData[symbol]['obi'].iloc[0]
tick_count = 0
row_count = 0
for row in zip(self.quoteData[symbol]['priceChange'], self.quoteData[symbol]['obi']):
priceStatus = row[0]
obi = row[1]
if (priceStatus == 1) or np.isnan(priceStatus):
tick_count = 0
last_obi = obi
else:
last_obi = self.quoteData[symbol]['obi'].iloc[row_count - tick_count]
tick_count = tick_count + 1
row_count = row_count + 1
obi_change = obi - last_obi
obi_change_list.append(obi_change)
self.quoteData[symbol].loc[:, 'obi'] = obi_change_list
return self.quoteData[symbol]
def volume_change(self,symbol):
#检测对应价格的变动量以及变动率。记录变动时间等等。这个后面有个更好更快的版本了。可以删去。
quotedata = stats.time_cut(symbol)
askPrice1 = quotedata.loc[:,'askPrice2']
bidPrice1 = quotedata.loc[:,'bidPrice2']
askVolume1 = quotedata.loc[:,'askVolume2']
bidVolume1 = quotedata.loc[:,'bidVolume2']
Time = quotedata.loc[:, 'exchangeTime']
MAX_PRICE_VOLUME_ASK = dict()
MAX_PRICE_VOLUME_BID = dict()
for row in zip(askPrice1,bidPrice1,askVolume1,bidVolume1,Time):
ap1 = row[0]
bp1 = row[1]
av1 = row[2]
bv1 = row[3]
time = row[4]
key_ask = list(MAX_PRICE_VOLUME_ASK.keys())
key_bid = list(MAX_PRICE_VOLUME_BID.keys())
if ap1 in key_ask:
MAX_PRICE_VOLUME_ASK[ap1][1] =(av1 -MAX_PRICE_VOLUME_ASK[ap1][0])
MAX_PRICE_VOLUME_ASK[ap1][0] = av1
MAX_PRICE_VOLUME_ASK[ap1][2] = MAX_PRICE_VOLUME_ASK[ap1][1]/(av1+1)
MAX_PRICE_VOLUME_ASK[ap1][4] = MAX_PRICE_VOLUME_ASK[ap1][4] + 1
if MAX_PRICE_VOLUME_ASK[ap1][2] > 0.5:
MAX_PRICE_VOLUME_ASK[ap1][3] = MAX_PRICE_VOLUME_ASK[ap1][3]+1
MAX_PRICE_VOLUME_ASK[ap1][5] = time
else:
MAX_PRICE_VOLUME_ASK[ap1] = [av1,0,0,0,0,time]
if bp1 in key_bid:
MAX_PRICE_VOLUME_BID[bp1][0] = max(bv1,MAX_PRICE_VOLUME_BID[bp1][0])
if MAX_PRICE_VOLUME_BID[bp1][0] == bv1:
MAX_PRICE_VOLUME_BID[bp1][1] = time
else:
MAX_PRICE_VOLUME_BID[bp1] = [bv1 ,time]
if bp1 in key_bid:
MAX_PRICE_VOLUME_BID[bp1][1] =(bv1 -MAX_PRICE_VOLUME_BID[bp1][0])
MAX_PRICE_VOLUME_BID[bp1][0] = bv1
MAX_PRICE_VOLUME_BID[bp1][2] = MAX_PRICE_VOLUME_BID[bp1][1]/(bv1+1)
MAX_PRICE_VOLUME_BID[bp1][4] = MAX_PRICE_VOLUME_BID[bp1][4] + 1
if MAX_PRICE_VOLUME_BID[bp1][2] > 0.5:
MAX_PRICE_VOLUME_BID[bp1][3] = MAX_PRICE_VOLUME_BID[bp1][3]+1
MAX_PRICE_VOLUME_ASK[bp1][5] = time
else:
MAX_PRICE_VOLUME_BID[bp1] = [av1,0,0,0,0,time]
ask_df = pd.DataFrame.from_dict(MAX_PRICE_VOLUME_ASK,orient='index',columns = ['volume_ask','diff_v_ask','diff_r_ask','diff_t_ask','diff_l_ask','time_ask'])
bid_df = pd.DataFrame.from_dict(MAX_PRICE_VOLUME_BID,orient='index',columns = ['volume_bid','diff_v_bid','diff_r_bid','diff_t_bid','diff_l_bid','time_bid'])
df = pd.merge(ask_df,bid_df,left_index=True,right_index= True,how = 'outer')
return df
def large_order(self,symbol,price = 5.9, closetime=' 14:50:00'):
'''
检测某一个价位当天的情况。
##用于检测有无单一大挂单。可能是虚假单。
包括所在当前tick盘口位置(location) bid是负号,ask是正号,
交易量(nvolume,从tradeorder接入) 对应该price的交易数目
加单量(add_cancel) 正的表示加单 负的表示撤单
加单绝对值(add_cancel_abs)
订单变化量(order diff)
##todo 和order变化不同的是 这里去除了交易量的影响来计算。
###按每个价格计算一次也太慢了
例子:20190409的青岛港 601298.SH price = 10.85
10.85这个价位出现bp10到bp1到转变到ap4,以第117行为例:
买单减少116手,交易是165手,那么新增订单是49手
再以123行为例
此时价格是卖3,卖单增加138手,交易数是108手,那么实际在10.85新增下单数目是246手。
'''
window = 50
quotedata = stats.time_cut(symbol,closetime=closetime )
Price_form = dict()
price_ask,volume_ask,price_bid,volume_bid = stats.quote_cut(quotedata)
quote_index = quotedata.index
price_quote = price_ask.loc[:,:] ==price
ask_cum_quote = 11 - pd.DataFrame(price_quote.cumsum(axis=1).sum(axis = 1),columns = ['location'])
ask_cum_quote.loc[ ask_cum_quote.loc[:,'location'] == 11,'location'] = 0
volume_ask.columns = price_ask.columns
price_quote = pd.DataFrame(price_quote,dtype=int)
vol_ask = price_quote*volume_ask
vol_ask = vol_ask.sum(axis = 1)
vol_ask = pd.DataFrame(vol_ask,columns = ['order'])
price_quote = price_bid.loc[:,:] ==price
volume_bid.columns = price_bid.columns
bid_cum_quote = -(11 - pd.DataFrame(price_quote.cumsum(axis=1).sum(axis=1), columns=['location']))
bid_cum_quote.loc[bid_cum_quote.loc[:, 'location'] == -11, 'location'] = 0
price_quote = pd.DataFrame(price_quote,dtype=int)
vol_bid = price_quote*volume_bid
vol_bid = -1*vol_bid.sum(axis = 1)
vol_bid = pd.DataFrame(vol_bid,columns = ['order'])
vol = vol_ask+vol_bid
inorderbook = vol.loc[:,'order']==0
vol.loc[inorderbook,:] = np.nan
vol.fillna(method='ffill', inplace=True)
vol_diff = vol.loc[:,'order'].diff()
vol.loc[:, 'order_diff'] = vol_diff
vol.loc[:, 'location'] = bid_cum_quote+ ask_cum_quote
tv = quotedata.loc[:,'tradeVolume'].diff()
#vol.loc[:,'tv'] = tv
tradedata_price= stats.tradeorder(symbol,quotedata,price = price)
vol.loc[:,'nVolume'] = tradedata_price.loc[:,' nVolume']
vol.loc[:, 'nVolume'] = vol.loc[:,'nVolume'].fillna(0)
vol.loc[:,'pre_order'] = vol.loc[:,'order']-vol.loc[:, 'order_diff']
tempPositive = vol.loc[:,'pre_order'] >0
tempNegative = vol.loc[:,'pre_order'] <0
vol.loc[:,'temp'] = 0
vol.loc[tempPositive,'temp'] = vol.loc[tempPositive, 'order_diff']
vol.loc[tempNegative,'temp'] = -1*vol.loc[tempNegative, 'order_diff']
vol.loc[:,'add_cancel'] =vol.loc[:,'temp'] +vol.loc[:,'nVolume']
vol.loc[:,'add_cancel_abs'] =vol.loc[:,'add_cancel'].abs()
diff_where = np.sign(vol.loc[:, 'order']).diff() !=0
last_time = (list(vol.loc[diff_where,:].index)[-1])
return vol#max(vol.loc[last_time:,'add_cancel_abs'])
def tradeorder(self,symbol,quotedata,price = 6.25):
'''
tradeorder
给定价格
输出当前以该价格交易的交易量。
### todo 这里没有识别是买单卖单。这个重要吗? (可以仔细思考下)
'''
tradeData = self.tradeData[symbol]
#print(tradeData.columns)
price_loc = tradeData.loc[:,' nPrice'] == price
tradeData_loc = tradeData.loc[price_loc,:]
temp_quote_time = quotedata.index
tradeData_ = tradeData_loc.resample('1S').sum()
tradeData_ = tradeData_.cumsum()
#print(tradeData_)
#stats.check_file(pd.DataFrame(tradeData_))
try:
tradeData_ = tradeData_.loc[temp_quote_time, :]
r_tradeData = tradeData_.diff()
return r_tradeData
except:
print('AError')
return tradeData_
def high_obi(self,symbol):
'''
##接入large_order_count(self,quotedata,large_margin_buy,large_margin_sell,num = 10)
定义量阈值,认为这是大单:
比如
N个tick的主动买量:abVolume: active
Buy
volume
N个tick的主动卖量:asVolume: active
Sell
volume
以askVolume
卖盘为例,如果买的交易量很小,那么一个小的挂单可以“卡住”价格。
如果
存在大于abVolume的量,返回满足条件的最大askPrice,Max_ask_price, 以及对应的askVolume, Max_ask_volume, 若无
则返回askPrice = np.nan
askVolume = 0
对应asVolume
和bid盘
有
Min_bid_volume, Min_bid_price
###
因子:
如果Min_bid_volume == 0 & Max_ask_volume != 0 = > bid侧无“大单”,ask侧有一个或以上的“大单”
## todo 这里涉及到交易量的预测,预期一个大单的出现可能是一个方向?
## todo 上面考虑的因子其实和obi有点违背,obi本身有设计到吃掉大单的行为,上面的因子是一种“远离”大单的行为。
'''
quotedata = self.quoteData[symbol]
tradeData = self.cancel_order(symbol)
tradeData.loc[:, 'cum_buy'] =tradeData.loc[:, 'abVolume'].rolling(10).sum()
tradeData.loc[:, 'cum_sell'] =tradeData.loc[:, 'asVolume'].rolling(10).sum()
quotedata.loc[:,'obi'] = np.log(quotedata.loc[:,'askVolume1'] /quotedata.loc[:,'bidVolume1'])
#quotedata.loc[:, 'tv'] = quotedata.loc[:,'tradeVolume'].diff(10)
volume_bid, volume_ask,bid_loc,ask_loc = self.large_order_count(quotedata,tradeData.loc[:, 'cum_buy'],tradeData.loc[:, 'cum_sell'],num= 10 )
vb = list()
va = list()
pb = list()
pb = list()
quotedata.loc[:,'large_bid'] = volume_bid
quotedata.loc[:,'large_ask'] = volume_ask
#quotedata.loc[large_ask,'large_ask'] = quotedata.loc[large_ask,'askPrice1']
#quotedata.loc[:,'large_bid'].fillna(method='ffill', inplace=True)
#quotedata.loc[:,'large_ask'].fillna(method='ffill', inplace=True)
quotedata.loc[:,'large_width'] = quotedata.loc[:,'large_ask'] - quotedata.loc[:,'large_bid']
'''
for row in zip(quotedata.index ,volume_bid,volume_ask):
times = str(row[0])[10:]
print(times)
bp = row[1]
ap = row[2]
bid_max.append(stats.large_order(symbol,bp,times))
ask_max.append(stats.large_order(symbol,ap,times))
'''
#quotedata.loc[:,'bid_max'] = bid_max
#quotedata.loc[:,'ask_max'] = ask_max
quotedata.loc[:,'bid_loc'] = bid_loc
quotedata.loc[:,'ask_loc'] = ask_loc
quotedata.loc[:,'abVolume'] = tradeData.loc[:, 'abVolume']
quotedata.loc[:,'asVolume'] = tradeData.loc[:, 'asVolume']
return quotedata
def large_order_count(self,quotedata,large_margin_buy,large_margin_sell,num = 10):
###large_order_count
###用于统计大于某个阈值large_margin_buy(ask volume)/large_margin_sell(bid volume)的最小/大价格
###num :默认统计档数
###
###待优化效率
price_ask, volume_ask, price_bid, volume_bid = self.quote_cut(quotedata,num = num)
bid_ = (volume_bid).apply(lambda x : x - np.asarray(large_margin_sell))> 0
bid_ = pd.DataFrame(bid_,dtype= int)
price_bid.columns = bid_.columns
bid_ = price_bid *bid_
volume_zero = bid_ ==0
bid_[volume_zero] = np.nan
bid_ = bid_.max(axis =1)
bid_loc = (price_bid).apply(lambda x : x == np.asarray(bid_))
bid_loc = pd.DataFrame(bid_loc,columns=volume_bid.columns,dtype= int)
bid_loc =( bid_loc * volume_bid ).sum(axis=1)
#zero_bid_loc = bid_loc ==0
#bid_loc[zero_bid_loc] = np.nan
ask_ = (volume_ask).apply(lambda x : x - np.asarray(large_margin_buy))> 0
ask_ = pd.DataFrame(ask_,dtype= int)
#volume_loc = (volume_bid).apply(lambda x: x == np.asarray(large_margin_buy))
price_ask.columns = ask_.columns
ask_ = price_ask *ask_
volume_zero = ask_ ==0
ask_[volume_zero] = np.nan
ask_ = ask_.min(axis =1)
ask_loc = (price_ask).apply(lambda x : x == np.asarray(ask_))
ask_loc = pd.DataFrame(ask_loc,columns=volume_ask.columns,dtype= int)
ask_loc =( ask_loc * volume_ask ).sum(axis=1)
#zero_ask_loc = ask_loc ==0
#ask_loc[~zero_ask_loc] = np.nan
#bid_.fillna(method='ffill', inplace=True)
#ask_.fillna(method='ffill', inplace=True)
#bid_loc.fillna(method='ffill', inplace=True)
#ask_loc.fillna(method='ffill', inplace=True)
return bid_,ask_,bid_loc,ask_loc
def point_monitor(self, symbol, point_list):
###链接过滤后的序列化处理,类似于分钟数据的采样后的策略
### todo 如果有合适的key point 序列,可以考虑他们之间的统计性质 类似分钟数据下的策略构造。
### 建议用作统计两个或多个key point 之间的性质。而不仅仅是一个信号过滤器。
quotedata = self.quoteData[symbol]
tradeData = self.cancel_order(symbol)
quotedata.loc[:, 'kp'] = point_list
positivePos = quotedata.loc[:, 'kp'] == 1
negativePos = quotedata.loc[:, 'kp'] == -1
quotedata.loc[~positivePos & ~negativePos, 'kp'] = np.nan
quotedata.loc[:, 'kp'].fillna(method='ffill', inplace=True)
quotedata.loc[:, 'kp_diff'] = quotedata.loc[:, 'kp'].diff()
quotedata.loc[:, 'asVolume_cum'] = quotedata.loc[:, 'asVolume'].cumsum()
quotedata.loc[:, 'abVolume_cum'] = quotedata.loc[:, 'abVolume'].cumsum()
tick_count = 0
row_count = 0
last_as = quotedata.loc[:, 'asVolume_cum'].iloc[0]
last_ab = quotedata.loc[:, 'abVolume_cum'].iloc[0]
cum_as = list()
cum_ab = list()
midp_change = list()
last_mid = quotedata.loc[:, 'midp'].iloc[0]
for row in zip(quotedata.loc[:, 'asVolume_cum'], quotedata.loc[:, 'abVolume_cum'], quotedata.loc[:, 'kp_diff'],quotedata.loc[:, 'midp']):
ak = row[0]
ab = row[1]
kp = row[2]
midp = row[3]
if (kp != 0):
tick_count = 0
last_as = ak
last_ab = ab
last_mid = midp
else:
last_as = quotedata.loc[:, 'asVolume_cum'].iloc[row_count - tick_count]
last_ab = quotedata.loc[:, 'abVolume_cum'].iloc[row_count - tick_count]
last_mid= quotedata.loc[:, 'midp'].iloc[row_count - tick_count]
tick_count = tick_count+1
#print(last_as)
row_count = row_count + 1
as_change = ak - last_as
ab_change = ab - last_ab
mid_change = midp - last_mid
cum_as.append( ak - last_as)
cum_ab.append( ab - last_ab)
midp_change.append(mid_change)
quotedata.loc[:, 'midp_change'] = midp_change
quotedata.loc[:, 'cum_as'] = cum_as
quotedata.loc[:, 'cum_ab'] = cum_ab
quotedata.loc[:, 'ab_as'] = quotedata.loc[:, 'cum_ab'] -quotedata.loc[:, 'cum_as']
tick_count = 0
row_count = 0
grad = 0
vol_cum = 0
pri_cum = 0
vm = list()
vs= list()
for row in zip(quotedata.loc[:, 'ab_as'],quotedata.loc[:, 'midp_change'], quotedata.loc[:, 'kp'], quotedata.loc[:, 'kp_diff']):
volume_change = row[0]
price_change = row[1]
key_point = row[2]
kp = row[3]
if (kp!= 0):
grad = 0
tick_count = 0
vol_mean = 0
vol_std = 0
else:
vol_mean = quotedata.loc[:, 'midp_change'].iloc[(row_count - tick_count):row_count].mean()
vol_std = quotedata.loc[:, 'midp_change'].iloc[(row_count - tick_count):row_count].std()
tick_count = tick_count + 1
row_count = row_count + 1
vm.append(vol_mean)
vs.append(vol_std)
quotedata.loc[:, 'vm'] = vm
quotedata.loc[:, 'vs'] = vs
return quotedata
def volume_imbalance_bar(self,symbol):
### vol imbalance bar
### 采样的一种方式
#tradeData = self.tradeData
T = 50
a = 1
exp_para = 10
trade_list = self.cancel_order(symbol)
count = 0
pre_bar = 0
pre_bar_list = list()
theta_bar_list = list()
bar_label = list()
temp_list = list()
count_list = list()
std_list = list()
theta_bar = 0
pre_bar_std = 0
#trade_list.loc[:, 'abVolume'] = np.exp(trade_list.loc[:,'abVolume'] /1000 )
#trade_list.loc[:, 'asVolume'] = np.exp(trade_list.loc[:,'asVolume'] /1000)
for row in zip(trade_list.loc[:,'abVolume'],trade_list.loc[:,'asVolume']):
buy_volume = row[0]
sell_volume = row[1]
if np.isnan(buy_volume):
buy_volume = 0
if np.isnan(sell_volume):
sell_volume = 0
if count < T:
pre_bar = pre_bar + buy_volume - sell_volume
bar_label.append(0)
else:
theta_bar = theta_bar +buy_volume - sell_volume
if ((theta_bar)- (pre_bar) )>a * pre_bar_std:
bar_label.append(1)
temp_list.append(theta_bar)
pre_bar_df = (pd.DataFrame(temp_list))
pre_bar_df_ewm = (pre_bar_df.ewm(exp_para).mean())
theta_bar = 0.0
if pre_bar_df_ewm.shape[0]>1:
pre_bar_std = (pre_bar_df.ewm(exp_para).std()).iloc[-1,0]
else:
pre_bar_std = 0
#print(pre_bar_df_ewm.iloc[-1,0])
pre_bar = pre_bar_df_ewm.iloc[-1,0]
##print(theta_bar)
#theta_bar = 0.0
elif ((theta_bar)- (pre_bar) )<-a* pre_bar_std:
bar_label.append(-1)
theta_bar = 0.0
temp_list.append(theta_bar)
pre_bar_df = (pd.DataFrame(temp_list))
pre_bar_df_ewm = (pre_bar_df.ewm(exp_para).mean())
if pre_bar_df_ewm.shape[0]>1:
pre_bar_std = (pre_bar_df.ewm(exp_para).std()).iloc[-1,0]
else:
pre_bar_std = 0
#print(pre_bar_df_ewm.iloc[-1,0])
pre_bar = pre_bar_df_ewm.iloc[-1,0]
else:
bar_label.append(0)
count = count + 1
std_list.append(pre_bar_std)
pre_bar_list.append(pre_bar)
theta_bar_list.append(theta_bar)
count_list.append(count)
trade_list.loc[:, 'pre_bar_list'] = pre_bar_list
trade_list.loc[:, 'theta_bar_list'] = theta_bar_list
trade_list.loc[:, 'bar_label'] = bar_label
trade_list.loc[:, 'count_list'] = count_list
trade_list.loc[:, 'pre_bar_std'] = std_list
return trade_list
def response_fun(self,symbol):
quotedata = self.time_cut(symbol)
quotedata = quotedata[~quotedata.index.duplicated(keep='first')]
tradeData = self.tradeData[symbol]
quote_time = pd.to_datetime(quotedata.exchangeTime.values).values
quotedata.loc[:, 'tradeVolume'] = quotedata.loc[:, 'tradeVolume'].diff()
quotedata.loc[:, 'Turnover'] = quotedata.loc[:, 'totalTurnover'].diff()
quotedata.loc[:,'VWAP'] = quotedata.loc[:,'Turnover'] / quotedata.loc[:, 'tradeVolume']
quotedata.loc[:,'spd'] = quotedata.loc[:, 'askPrice1'] - quotedata.loc[:, 'bidPrice1']
quotedata.loc[quotedata.loc[:,'spd'] == 0 , 'spd'] = 0.01
bid_order = tradeData.loc[:, ' nBSFlag'] == 'B'
ask_order = tradeData.loc[:, ' nBSFlag'] == 'S'
can_order = tradeData.loc[:, ' nBSFlag'] == ' '
tradeData.loc[bid_order, 'numbs_flag'] = 1
tradeData.loc[ask_order, 'numbs_flag'] = -1
tradeData.loc[can_order, 'numbs_flag'] = 0
temp_quote_time = np.asarray(list(quote_time))
tradeData.loc[:, 'temp'] = tradeData.loc[:, ' nPrice']
# tradeData.loc[pos, 'temp'] = np.nan
tradeData.temp.fillna(method='ffill', inplace=True)
lastrep = list(tradeData.temp.values[:-1])
lastrep.insert(0, 0)
lastrep = np.asarray(lastrep)
tradeData_quote = pd.merge(quotedata.loc[:, ['spd', 'tradeVolume', 'Turnover']], tradeData,
left_index=True, right_index=True, how='outer')
tradeData_quote.loc[:, 'spd'].fillna(method='ffill', inplace=True)
#ActiveBuy = (tradeData_quote.loc[:, 'numbs_flag'] == 1)
#ActiveSell = (tradeData_quote.loc[:, 'numbs_flag'] == -1)
# tradeData_quote.loc[ActiveBuy, 'abVolume'] = tradeData_quote.loc[ActiveBuy, ' nVolume']
#tradeData_quote.loc[ActiveSell, 'asVolume'] = tradeData_quote.loc[ActiveSell, ' nVolume']
#tradeData_quote.loc[ActiveBuy, 'abPrice'] = tradeData_quote.loc[ActiveBuy, ' nTurnover']
l_dict = dict()
for l in range(1,301,10):
#quotedata.loc[:, 'VWAP_l'] = quotedata.loc[:, 'VWAP'].shift(-l)
tradeData_quote.loc[:, 'VWAP_l'] = np.nan
tradeData_quote.loc[temp_quote_time,'VWAP_l'] = quotedata.loc[:, 'VWAP'].shift(-l)
tradeData_quote.loc[:,'VWAP_l'].fillna(method='ffill', inplace=True)
tradeData_quote.loc[:, 'rsp_func'] = tradeData_quote.loc[:, ' nVolume']* (- tradeData_quote.loc[:, ' nPrice'] + tradeData_quote.loc[:, 'VWAP_l']) *tradeData_quote.loc[:, 'numbs_flag'] / tradeData_quote.loc[:, 'spd']
#print(np.nanmean(tradeData_quote.loc[:, 'rsp_func'])/np.nanmean(tradeData_quote.loc[:, ' nVolume']))
l_dict[l] = np.nanmean(tradeData_quote.loc[:, 'rsp_func'])/np.nanmean(tradeData_quote.loc[:, ' nVolume'])
'''
temp_quote_time = np.asarray(list(quote_time))
Columns_ = ['Rp_func']
resample_tradeData = tradeData_quote.loc[:, Columns_].resample('1S', label='right', closed='right').mean()
resample_tradeData = resample_tradeData.cumsum()
resample_tradeData = resample_tradeData.loc[temp_quote_time, :]
r_tradeData = resample_tradeData.diff()
'''
'''
r_tradeData.loc[:, 'abPrice'] = r_tradeData.loc[:, 'abPrice'] / r_tradeData.loc[:, 'abVolume']
r_tradeData.loc[:, 'asPrice'] = r_tradeData.loc[:, 'asPrice'] / r_tradeData.loc[:, 'asVolume']
r_tradeData.loc[:, 'timecheck'] = quotedata.loc[:, 'exchangeTime']
'''
# stats.check_file(r_tradeData)
# stats.check_file(r_tradeData)
'''
quote_order = pd.merge(self.quoteData[symbol].loc[:, ['midp', 'midp_10', 'spread']], r_tradeData, left_index=True,
right_index=True, how='left')
# .loc[:,'midp'] =self.quoteData[symbol].loc[:,'midp']
quote_order.to_csv(self.outputpath + './ quote_order.csv')
# self.quoteData[symbol].loc[:, ['midp', 'bidVolume1', 'askVolume1']].to_csv(self.outputpath + './ quote_o.csv')
'''
#r_tradeData.loc[:, 'diff'] = r_tradeData.loc[:, 'abVolume'] - r_tradeData.loc[:, 'asVolume']
#r_tradeData.loc[:, 'cum_diff'] = r_tradeData.loc[:, 'diff'].cumsum()
#print(l_dict)
return l_dict
def price_concat(self,price_ask,price_bid):
## 统计当天出现的所有价格
ask_column = price_ask.columns
bid_column = price_bid.columns
price_list = list()
price_ = list()
for column in zip(ask_column,bid_column):
ask = column[0]
bid = column[1]
price_list.append (pd.Series(price_ask.loc[:,ask]).unique())
price_list.append(pd.Series(price_bid.loc[:,bid]).unique())
price_.append(list(price_ask.loc[:,ask]))
price_.append(list(price_bid.loc[:,bid]))
price_concat = [x for j in price_ for x in j]
price_ = pd.DataFrame(pd.Series(price_concat).unique(),columns=['today_price'])
return price_
def price_volume_fun(self,symbol):
'''
dataframe test:算出每个tick下的对应价格的volume,并放在一个以time 为index,price 为column 的dataframe内
对于该tick前未出现过的价位,其对应的volume 为nan,若出现,则对应的volume 为最新出现的volume,
为了区分bid和ask,其中askVolume 为正 volume,bidVolume 为负volume
在bp10 到ap10之间的价位,若不出现在盘口,则记为0,因为被吃掉了
计算每一个tick之间的订单变化情况:
order_change = diff(test)
计算posChange :正向变化总和 正向变化包括:ask方加单 ask方吃bid单,bid方撤单
posChange = (order_change*((order_change> 0 ).astype(int))).sum(axis = 1)
计算negChange :负向变化总和 负向变化包括:bid方加单 bid方吃ask单,ask方撤单
negChange = (order_change*((order_change<0).astype(int))).sum(axis = 1)
计算净变化totalchange和绝对变化abschange
totalchange = posChange - negchange
abschange = posChange + negchange
观测 20 tick内的一致性:
consistence = quotedata.loc[:, 'TOTALchange'].rolling(20).sum() / quotedata.loc[:, 'abs_change'].rolling(20).sum()
假如consistence 绝对高的情况下,totalchange占abschange的比重很大,那么意味着poschange 或者negchange其中一个相对很小。这里使用滚动均值方差来表示绝对高,参数为2
posMark = consistence > consistence_mean + 2 * consistence_std ##过高,一致poschange,ask方一致增强,表示卖信号
negMark = consistence < consistence_mean - 2 * consistence_std ##过低,一致negchange,bid方一致增强,表示买信号
'''
quotedata =self.quoteData[symbol]
quotedata = quotedata[~quotedata.index.duplicated(keep='first')]
#print(quotedata.index.duplicated(keep='first'))
price_ask, volume_ask, price_bid, volume_bid = self.quote_cut(quotedata,num= 10)
## price_today 当日的所有的价格序列。
len_time = len(quotedata.index)
count = 0
dict_ = [dict() for i in range(len_time) ]
volume_ask.columns = price_ask.columns
volume_bid.columns = price_bid.columns
dict_ask = self.dict_merge(price_ask.to_dict('index'),volume_ask.to_dict('index'))
dict_bid = self.dict_merge(price_bid.to_dict('index'),volume_bid.to_dict('index'))
pool = mdP(4)
zip_list = zip(dict_,dict_ask.items(), dict_bid.items())
test =pool.map(self.volume_loading, zip_list)
pool.close()
pool.join()
test = pd.DataFrame(test,index = price_ask.index)
test.fillna(method = 'ffill',inplace = True)
order_change = test.diff()
quotedata.loc[:,'posChange'] = (order_change*((order_change> 0 ).astype(int))).sum(axis = 1)
quotedata.loc[:,'negChange'] = (order_change*((order_change<0).astype(int))).sum(axis = 1)
quotedata.loc[:,'tradeVol'] = quotedata.loc[:,'tradeVolume'].diff()*1
quotedata.loc[:, 'TOTALchange'] = (quotedata.loc[:,'posChange'] + quotedata.loc[:,'negChange'])
quotedata.loc[:, 'abs_change'] =( abs(quotedata.loc[:,'posChange']) + abs(quotedata.loc[:,'negChange']))
over_vol = quotedata.loc[:, 'tradeVol']>= quotedata.loc[:, 'abs_change'] /2
quotedata.loc[:,'over_vol'] = 0
quotedata.loc[over_vol,'over_vol'] =1
quotedata.loc[:, 'cum_over_vol'] = (quotedata.loc[:,'over_vol']* quotedata.loc[:, 'tradeVol']).cumsum()
quotedata.loc[:, 'cum_over_vol_diff'] = quotedata.loc[:,'tradeVolume'] - quotedata.loc[:, 'cum_over_vol']
quotedata.loc[:, 'consistence'] = quotedata.loc[:, 'TOTALchange'].rolling(20).mean() / quotedata.loc[:, 'abs_change'].rolling(20).mean()
quotedata.loc[:,'consistence_mean'] = quotedata.loc[:, 'consistence'].rolling(20).mean()
quotedata.loc[:,'consistence_std'] = quotedata.loc[:, 'consistence'].rolling(20).std()
posMark =(quotedata.loc[:, 'consistence']> quotedata.loc[:,'consistence_mean']+2*quotedata.loc[:,'consistence_std'])#&((quotedata.loc[:, 'consistence']< quotedata.loc[:,'consistence_mean']+3*quotedata.loc[:,'consistence_std']))
negMark =(quotedata.loc[:, 'consistence']< quotedata.loc[:,'consistence_mean']-2*quotedata.loc[:,'consistence_std'])#&(quotedata.loc[:, 'consistence']> quotedata.loc[:,'consistence_mean']-3*quotedata.loc[:,'consistence_std'])
quotedata.loc[:,'upper_'] = quotedata.loc[:,'consistence_mean']+2*quotedata.loc[:,'consistence_std']
quotedata.loc[:,'lower_'] = quotedata.loc[:,'consistence_mean']-2*quotedata.loc[:,'consistence_std']
#negMark = quotedata.loc[:,'posChange'] > av_sum
#posMark = quotedata.loc[:,'negChange'] <- bv_sum
quotedata.loc[posMark, 'marker'] = 1
quotedata.loc[negMark, 'marker'] = -1
quotedata.loc[(~posMark) & (~negMark), 'marker'] =0
#quotedata.loc[:,'change_cum'] = quotedata.loc[:, 'TOTALchange'] .cumsum()
'''
key_point = quotedata.loc[:, 'marker'] !=0
quotedata_kp = quotedata.loc[key_point, :]
quotedata_kp.loc[:,'tc_change'] = quotedata_kp.loc[:,'change_cum'].diff()
quotedata_kp.loc[:,'tv_change'] = quotedata_kp.loc[:,'tradeVolume'].diff()
#quotedata.loc[:, 'consistence_diff'] = quotedata.loc[:, 'consistence_5'] - quotedata.loc[:, 'consistence_20']
para_matrix = pd.DataFrame()
para_matrix.loc[:,'midp'] =quotedata.loc[:,'midp']
para_matrix.loc[:,'posChange'] =quotedata.loc[:,'posChange']
para_matrix.loc[:,'negChange'] =quotedata.loc[:,'negChange']
para_matrix.loc[:,'price_shift_20'] = para_matrix.loc[:,'midp'].shift(20)
para_matrix.loc[:,'price_shift_50'] = para_matrix.loc[:,'midp'].shift(50)
para_matrix.loc[:,'price_diff_20'] = para_matrix.loc[:,'midp'] - para_matrix.loc[:,'price_shift_20']
para_matrix.loc[:,'price_diff_50'] = para_matrix.loc[:,'midp'] - para_matrix.loc[:,'price_shift_50']
large_change = abs(para_matrix.loc[:,'price_diff_20'])> para_matrix.loc[:,'midp'].iloc[0]*15/10000 + 0.01
para_matrix = para_matrix.loc[large_change,:]
'''
return quotedata
def price_volume_fun3(self,symbol):
'''
dataframe test:算出每个tick下的对应价格的volume,并放在一个以time 为index,price 为column 的dataframe内
对于该tick前未出现过的价位,其对应的volume 为nan,若出现,则对应的volume 为最新出现的volume,
为了区分bid和ask,其中askVolume 为正 volume,bidVolume 为负volume
在bp10 到ap10之间的价位,若不出现在盘口,则记为0,因为被吃掉了
计算每一个tick之间的订单变化情况:
order_change = diff(test)
计算posChange :正向变化总和 正向变化包括:ask方加单 ask方吃bid单,bid方撤单
posChange = (order_change*((order_change> 0 ).astype(int))).sum(axis = 1)
计算negChange :负向变化总和 负向变化包括:bid方加单 bid方吃ask单,ask方撤单
negChange = (order_change*((order_change<0).astype(int))).sum(axis = 1)
计算净变化totalchange和绝对变化abschange
totalchange = posChange - negchange
abschange = posChange + negchange
观测 20 tick内的一致性:
consistence = quotedata.loc[:, 'TOTALchange'].rolling(20).sum() / quotedata.loc[:, 'abs_change'].rolling(20).sum()
假如consistence 绝对高的情况下,totalchange占abschange的比重很大,那么意味着poschange 或者negchange其中一个相对很小。这里使用滚动均值方差来表示绝对高,参数为2
posMark = consistence > consistence_mean + 2 * consistence_std ##过高,一致poschange,ask方一致增强,表示卖信号
negMark = consistence < consistence_mean - 2 * consistence_std ##过低,一致negchange,bid方一致增强,表示买信号
'''
quotedata =self.quoteData[symbol]
quotedata = quotedata[~quotedata.index.duplicated(keep='first')]
#print(quotedata.index.duplicated(keep='first'))
price_ask, volume_ask, price_bid, volume_bid = self.quote_cut(quotedata,num= 10)
## price_today 当日的所有的价格序列。
len_time = len(quotedata.index)
count = 0
dict_ = [dict() for i in range(len_time) ]
volume_ask.columns = price_ask.columns
volume_bid.columns = price_bid.columns
dict_ask = self.dict_merge(price_ask.to_dict('index'),volume_ask.to_dict('index'))
dict_bid = self.dict_merge(price_bid.to_dict('index'),volume_bid.to_dict('index'))
pool = mdP(4)
zip_list = zip(dict_,dict_ask.items(), dict_bid.items())
test =pool.map(self.volume_loading, zip_list)
pool.close()
pool.join()
test = pd.DataFrame(test,index = price_ask.index)
test.fillna(method = 'ffill',inplace = True)
order_change = test.diff()
quotedata.loc[:,'posChange'] = (order_change*((order_change> 0 ).astype(int))).sum(axis = 1)
quotedata.loc[:,'negChange'] = (order_change*((order_change<0).astype(int))).sum(axis = 1)
quotedata.loc[:,'tradeVol'] = quotedata.loc[:,'tradeVolume'].diff()*1
quotedata.loc[:, 'TOTALchange'] = (quotedata.loc[:,'posChange'] + quotedata.loc[:,'negChange'])
quotedata.loc[:, 'abs_change'] =( abs(quotedata.loc[:,'posChange']) + abs(quotedata.loc[:,'negChange']))
over_vol = quotedata.loc[:, 'tradeVol']>= quotedata.loc[:, 'abs_change'] /2
quotedata.loc[:,'over_vol'] = 0
quotedata.loc[over_vol,'over_vol'] =1
quotedata.loc[:, 'cum_over_vol'] = (quotedata.loc[:,'over_vol']* quotedata.loc[:, 'tradeVol']).cumsum()
quotedata.loc[:, 'cum_over_vol_diff'] = quotedata.loc[:,'tradeVolume'] - quotedata.loc[:, 'cum_over_vol']
quotedata.loc[:, 'consistence'] = quotedata.loc[:, 'TOTALchange'].rolling(20).sum() / quotedata.loc[:, 'abs_change'].rolling(20).sum()
quotedata.loc[:, 'consistence'] = quotedata.loc[:, 'consistence'].ewm(20).mean()
quotedata.loc[:,'consistence_mean'] = quotedata.loc[:, 'consistence'].rolling(20).mean()
quotedata.loc[:,'consistence_std'] = quotedata.loc[:, 'consistence'].rolling(20).std()
quotedata.loc[:, 'regular'] = 0
quotedata.loc[quotedata.loc[:,'consistence_mean']>quotedata.loc[:,'consistence_std'], 'regular'] = 0.5
quotedata.loc[quotedata.loc[:,'consistence_mean']<-quotedata.loc[:,'consistence_std'], 'regular'] = -0.5
posMark =(quotedata.loc[:, 'consistence']> quotedata.loc[:,'consistence_mean']+(2-quotedata.loc[:, 'regular'])*quotedata.loc[:,'consistence_std'])#&((quotedata.loc[:, 'consistence']< quotedata.loc[:,'consistence_mean']+3*quotedata.loc[:,'consistence_std']))
negMark =(quotedata.loc[:, 'consistence']< quotedata.loc[:,'consistence_mean']-(2+quotedata.loc[:, 'regular'])*quotedata.loc[:,'consistence_std'])#&(quotedata.loc[:, 'consistence']> quotedata.loc[:,'consistence_mean']-3*quotedata.loc[:,'consistence_std'])
quotedata.loc[:,'upper_'] = quotedata.loc[:,'consistence_mean']+(2+quotedata.loc[:, 'regular'])*quotedata.loc[:,'consistence_std']
quotedata.loc[:,'lower_'] = quotedata.loc[:,'consistence_mean']-(2-quotedata.loc[:, 'regular'])*quotedata.loc[:,'consistence_std']
#negMark = quotedata.loc[:,'posChange'] > av_sum
#posMark = quotedata.loc[:,'negChange'] <- bv_sum
quotedata.loc[posMark, 'marker'] = 1
quotedata.loc[negMark, 'marker'] = -1
quotedata.loc[(~posMark) & (~negMark), 'marker'] =0
quotedata.loc[:,'change_cum'] = quotedata.loc[:, 'TOTALchange'] .cumsum()
'''
key_point = quotedata.loc[:, 'marker'] !=0
quotedata_kp = quotedata.loc[key_point, :]
quotedata_kp.loc[:,'tc_change'] = quotedata_kp.loc[:,'change_cum'].diff()
quotedata_kp.loc[:,'tv_change'] = quotedata_kp.loc[:,'tradeVolume'].diff()
#quotedata.loc[:, 'consistence_diff'] = quotedata.loc[:, 'consistence_5'] - quotedata.loc[:, 'consistence_20']
para_matrix = pd.DataFrame()
para_matrix.loc[:,'midp'] =quotedata.loc[:,'midp']
para_matrix.loc[:,'posChange'] =quotedata.loc[:,'posChange']
para_matrix.loc[:,'negChange'] =quotedata.loc[:,'negChange']
para_matrix.loc[:,'price_shift_20'] = para_matrix.loc[:,'midp'].shift(20)
para_matrix.loc[:,'price_shift_50'] = para_matrix.loc[:,'midp'].shift(50)
para_matrix.loc[:,'price_diff_20'] = para_matrix.loc[:,'midp'] - para_matrix.loc[:,'price_shift_20']
para_matrix.loc[:,'price_diff_50'] = para_matrix.loc[:,'midp'] - para_matrix.loc[:,'price_shift_50']
large_change = abs(para_matrix.loc[:,'price_diff_20'])> para_matrix.loc[:,'midp'].iloc[0]*15/10000 + 0.01
para_matrix = para_matrix.loc[large_change,:]
'''
return quotedata
def dict_merge(self,dict1,dict2):
for k in dict1.keys():
if k in dict2:
temp = dict()
for i in dict1[k].keys():
temp[(dict1[k][i])] = dict2[k][i]
dict1[k] = temp
return dict1
def volume_loading(self,row):
dict_y = row[0]
dict_ask = row[1][1]
dict_bid = row[2][1]
bid_nonzero = [k for k in dict_bid.keys() if k >0]
ask_nonzero = [k for k in dict_ask.keys() if k >0]
ask_max_volume =max(dict_ask.values())
#print(ask_max_volume)
bid_max_volume =max(dict_bid.values())
if len(bid_nonzero)>0:
lower_bound = min(bid_nonzero)
upper_bound = max(ask_nonzero)
price_range = np.linspace(lower_bound,upper_bound,num =round((upper_bound - lower_bound)/0.01) + 1).round(2)
for price in price_range:
if price in dict_ask.keys():
#dict_y[price] = dict_ask[price]/np.log(ask_max_volume+1)
dict_y[price] = dict_ask[price]
elif price in dict_bid.keys():
#dict_y[price] = -dict_bid[price]/ np.log(bid_max_volume+1)
dict_y[price] = - dict_bid[price]
else:
dict_y[price] = 0
else:
dict_y[0] = 0
return dict_y
def flow_detect(self,symbol):
### 检测流动性用 公式 Spread_k = 2 * (Dk-MK)/MK
quotedata = self.quoteData[symbol]
tradeData = self.tradeData[symbol]
quotedata.loc[:,'midp'] =(quotedata.loc[:,'bidPrice1'] * quotedata.loc[:,'askVolume1'] + quotedata.loc[:,'bidVolume1'] * quotedata.loc[:,'askPrice1'] ) / (quotedata.loc[:,'bidVolume1']+ quotedata.loc[:,'askVolume1'] )
quote_time = pd.to_datetime(quotedata.exchangeTime.values).values
quotedata.loc[:, 'tradeVolume'] = quotedata.loc[:, 'tradeVolume'].diff()
quotedata.loc[:, 'Turnover'] = quotedata.loc[:, 'totalTurnover'].diff()
quotedata.index = pd.to_datetime(quotedata.loc[:, 'exchangeTime'].values, format='%Y-%m-%d %H:%M:%S')
temp_1 = pd.to_datetime(tradeData.loc[:, ' nTime'], format='%Y-%m-%d %H:%M:%S.%f')
qqq = temp_1[0].microsecond
bid_order = tradeData.loc[:, ' nBSFlag'] == 'B'
ask_order = tradeData.loc[:, ' nBSFlag'] == 'S'
can_order = tradeData.loc[:, ' nBSFlag'] == ' '
tradeData.loc[bid_order, 'numbs_flag'] = 1
tradeData.loc[ask_order, 'numbs_flag'] = -1
tradeData.loc[can_order, 'numbs_flag'] = 0
cancel_order = tradeData.loc[:, ' nPrice'] == 0
tradeData.loc[:, 'temp'] = tradeData.loc[:, ' nPrice']
# tradeData.loc[pos, 'temp'] = np.nan
tradeData.temp.fillna(method='ffill', inplace=True)
lastrep = list(tradeData.temp.values[:-1])
lastrep.insert(0, 0)
lastrep = np.asarray(lastrep)
tradeData_quote = pd.merge(quotedata.loc[:, [ 'bidPrice1', 'askPrice1','midp', 'tradeVolume', 'Turnover']], tradeData,
left_index=True, right_index=True, how='outer')
tradeData_quote['midp'].fillna(method='ffill', inplace=True)
tradeData_quote['askPrice1'].fillna(method='ffill', inplace=True)
tradeData_quote['bidPrice1'].fillna(method='ffill', inplace=True)
# tradeData_quote.to_csv(self.dataSavePath + './' + str(self.tradeDate.date()) + signal + ' ' + symbol + '.csv')
ActiveBuy = (tradeData_quote.loc[:, 'numbs_flag'] == 1)
ActiveSell = (tradeData_quote.loc[:, 'numbs_flag'] == -1)
tradeData_quote.loc[ActiveBuy, 'abVolume'] = tradeData_quote.loc[ActiveBuy, ' nVolume']
tradeData_quote.loc[ActiveSell, 'asVolume'] = tradeData_quote.loc[ActiveSell, ' nVolume']
tradeData_quote.loc[ActiveBuy, 'abPrice'] = (tradeData_quote.loc[ActiveBuy, ' nTurnover'] - tradeData_quote.loc[ActiveBuy, ' nVolume']* tradeData_quote.loc[ActiveBuy, 'bidPrice1'])
tradeData_quote.loc[ActiveSell, 'asPrice'] = (tradeData_quote.loc[ActiveSell, ' nTurnover'] - tradeData_quote.loc[ActiveSell, ' nVolume']*tradeData_quote.loc[ActiveSell, 'askPrice1'])*-1
# stats.check_file(tradeData_quote)
temp_quote_time = np.asarray(list(quote_time))
Columns_ = ['abVolume', 'asVolume', 'abPrice', 'asPrice']
resample_tradeData = tradeData_quote.loc[:, Columns_].resample('1S', label='right', closed='right').sum()
resample_tradeData = resample_tradeData.cumsum()
resample_tradeData = resample_tradeData.loc[temp_quote_time, :]
r_tradeData = resample_tradeData.diff()
r_tradeData.loc[:, 'abSpread'] = r_tradeData.loc[:, 'abPrice'] / r_tradeData.loc[:, 'abVolume']
r_tradeData.loc[:, 'asSpread'] = r_tradeData.loc[:, 'asPrice'] / r_tradeData.loc[:, 'asVolume']
r_tradeData.loc[:, 'timecheck'] = quotedata.loc[:, 'exchangeTime']
# stats.check_file(r_tradeData)
# stats.check_file(r_tradeData)
'''
quote_order = pd.merge(self.quoteData[symbol].loc[:, ['midp', 'midp_10', 'spread']], r_tradeData, left_index=True,
right_index=True, how='left')
# .loc[:,'midp'] =self.quoteData[symbol].loc[:,'midp']
quote_order.to_csv(self.outputpath + './ quote_order.csv')
# self.quoteData[symbol].loc[:, ['midp', 'bidVolume1', 'askVolume1']].to_csv(self.outputpath + './ quote_o.csv')
'''
r_tradeData.loc[:, 'diff'] = r_tradeData.loc[:, 'abVolume'] - r_tradeData.loc[:, 'asVolume']
r_tradeData.loc[:, 'cum_diff'] = r_tradeData.loc[:, 'diff'].cumsum()
return r_tradeData
def PV_summary(self,symbol):
quotedata = self.price_volume_fun(symbol)
quotedata_2 = self.high_obi(symbol)
#quotedata_3 = self.obi_fixedprice(symbol)
quotedata_2 = quotedata_2[~quotedata_2.index.duplicated(keep='first')]
#quotedata_3 = quotedata_3[~quotedata_3.index.duplicated(keep='first')]
quotedata.loc[:,'large_bid'] = quotedata_2.loc[:,'large_bid']
quotedata.loc[:,'large_ask'] = quotedata_2.loc[:,'large_ask']
quotedata.loc[:,'bid_loc'] = quotedata_2.loc[:,'bid_loc']
quotedata.loc[:,'ask_loc'] = quotedata_2.loc[:,'ask_loc']
quotedata.loc[:,'obi'] = quotedata_2.loc[:,'obi']
quotedata.loc[:,'spread'] =quotedata.loc[:,'askPrice1'] - quotedata.loc[:,'bidPrice1']
negativePos =(quotedata.loc[:, 'marker'] == 1)&(quotedata.loc[:,'bid_loc']==0)& (quotedata.loc[:,'ask_loc']!=0)
positivePos = (quotedata.loc[:, 'marker'] == -1)&(quotedata.loc[:,'ask_loc']==0)& (quotedata.loc[:,'bid_loc']!=0)
quotedata.loc[negativePos,'signal_'] = -1
quotedata.loc[positivePos,'signal_'] = 1
quotedata.loc[(~positivePos) & (~negativePos),'signal_'] = 0
return quotedata
def vol_detect(self, symbol):
###算一算突破成功率?
###
quotedata = self.price_volume_fun(symbol)
tradeData = self.cancel_order(symbol)
tradeData.loc[:,'up_down'] =0
tradeData.loc[tradeData.loc[:,'diff'] <0,'up_down'] =-1
tradeData.loc[tradeData.loc[:,'diff'] >0,'up_down'] =1
tradeData.loc[:,'up_down_mean_long'] = tradeData.loc[:,'up_down'].rolling(30).mean()
tradeData.loc[:,'up_down_std_long'] = tradeData.loc[:,'up_down_mean_long'].rolling(30).std()
tradeData.loc[:,'up_down_mean_short'] = tradeData.loc[:,'up_down'].rolling(10).mean()
tradeData.loc[:,'up_down_std_short'] = tradeData.loc[:,'up_down_mean_short'].rolling(10).std()
return tradeData
def ProcessOrderInfo(self, sampleData, orderType = ' nBidOrder'):
#整合订单信息
##todo 可以考察一个订单被吃掉以后的情况用作验证想法( 可以结合到订单的分析,注意情况)
"""
This function is used to aggregate the orderInfo
:param orderInfo: the groupby object which is group by the bidorder or askorder
:return:整合得到以下信息:主动报单方向,主动报单量,主动成交量,被动成交量,撤单量,主动报单金额,主动成交金额,被动成交金额
撤单金额,主动报单价格
"""
# activeBuy = sampleData.groupby([orderType, ' nBSFlag'])
# activeBuyTime = activeBuy.first().loc[:, [' nTime']]
# activeBuyPrice= activeBuy.last().loc[:, [' nPrice']]
# activeBuy = pd.concat([activeBuy.sum().loc[:, [' nVolume', ' nTurnover']], activeBuyTime, activeBuyPrice], 1) # here, sort by level = 2 due to that level = 2 is the time index level, first two levels is order and bs flag
activeBuy = sampleData.groupby([orderType, ' nBSFlag']).agg({' nVolume': 'sum', ' nTurnover': 'sum', ' nTime': 'first', ' nPrice': 'last'}) # use agg can apply different type of
if orderType == ' nBidOrder':
orderDirection = 'B'
otherSideDirection = 'S'
else:
orderDirection = 'S'
otherSideDirection = 'B'
# start = time.time()
# activeBuy = activeBuy.sort_values(' nTime')
# activeBuy = activeBuy.reset_index()
# activeBuy.index = pd.to_datetime(pd.Series(map(lambda stime: self.tradeDate + str(stime),
# activeBuy.loc[:, ' nTime'])), format='%Y%m%d%H%M%S%f')
# activeBuy.index = list(map(lambda stime: datetime.datetime.strptime(self.tradeDate + str(stime), '%Y%m%d%H%M%S%f'),
# activeBuy.loc[:, ' nTime']))
# activeBuyB = activeBuy.loc[activeBuy.loc[:, ' nBSFlag'] == orderDirection, [orderType, ' nPrice', ' nVolume', ' nTurnover']] # which is the part of active buying
# activeBuyB.columns = ['order', 'auctionPrice', 'activeVolume', 'activeTurnover']
# activeBuyS = activeBuy.loc[activeBuy.loc[:, ' nBSFlag'] == otherSideDirection, [orderType, ' nPrice', ' nVolume', ' nTurnover']] # which is the part of active buying
# activeBuyS.columns = ['order', 'tradePrice', 'passiveVolume', 'passiveTurnover']
# activeBuyC = activeBuy.loc[activeBuy.loc[:, ' nBSFlag'] == ' ', [orderType, ' nVolume']] # which is the part of active buying and cancel
# activeBuyC.columns = ['order', 'cancelVolume']
# activeBuy = pd.merge(activeBuyB, activeBuyS, on='order', sort=False, how='left')
# activeBuy = pd.merge(activeBuy, activeBuyC, on='order', sort=False, how='left')
# activeBuy.index = activeBuyB.index
# end = time.time()
# start = time.time()
activeBuyB = activeBuy.iloc[activeBuy.index.get_level_values(' nBSFlag') == orderDirection]
if activeBuyB.shape[0] == 0:
return None
activeBuyB.columns = ['activeVolume', 'activeTurnover', ' nTime', 'auctionPrice']
activeBuyS = activeBuy.iloc[activeBuy.index.get_level_values(' nBSFlag') == otherSideDirection]
activeBuyS.columns = ['passiveVolume', 'passiveTurnover', ' nTime', 'tradePrice']
activeBuyC = activeBuy.iloc[activeBuy.index.get_level_values(' nBSFlag') == ' '].loc[:, [' nVolume', ' nTime']]
activeBuyC.columns = ['cancelVolume', ' nTime']
activeBuy = pd.merge(activeBuyB.reset_index(), activeBuyS.loc[:,['passiveVolume', 'passiveTurnover', 'tradePrice']].reset_index(), on=orderType, sort=False, how='left')
activeBuy = pd.merge(activeBuy, activeBuyC.loc[:, 'cancelVolume'].reset_index(), on=orderType, sort=False, how='left')
activeBuy.index = pd.to_datetime(activeBuy.loc[:, ' nTime'])
# end = time.time()
# print(end - start,' s')
activeBuy = activeBuy.rename(columns = {orderType:'order'})
activeBuy = activeBuy.loc[:, ['order', 'auctionVolume', 'auctionPrice', 'auctionTurnover',
'activeVolume', 'activeTurnover', 'passiveVolume', 'passiveTurnover', 'cancelVolume']].fillna(0)
activeBuy.loc[:, 'auctionVolume'] = activeBuy.loc[:, 'activeVolume'] + activeBuy.loc[:, 'passiveVolume'] + activeBuy.loc[:, 'cancelVolume']
activeBuy.loc[:, 'auctionTurnover'] = activeBuy.loc[:, 'auctionPrice'] * activeBuy.loc[:, 'auctionVolume'] / 100
activeBuy.loc[:, 'orderDirection'] = orderDirection
return activeBuy.loc[:, ['order', 'orderDirection', 'auctionVolume', 'auctionPrice', 'auctionTurnover',
'activeVolume', 'activeTurnover', 'passiveVolume', 'passiveTurnover', 'cancelVolume']]
def run(self,symbol):
print(symbol)
t1 = time.time()
#quotedata = stats.zaopan_stats(symbol)
#stats.cancel_order(symbol)
#stats.price_filter()
price_situation =pd.DataFrame.from_dict(self.response_fun(symbol),orient='index')
t2 = time.time()
#self.check_file(price_situation)
#price_situation
#price_situation = stats.high_obi(symbol,' 14:55:00')
#self.check_file(price_situation,symbol = symbol)
#t3 = time.time()
#print('cal time:'+str(t2-t1))
#print('writing time:'+str(t3-t2))
return price_situation
if __name__ == '__main__':
"""
test the class
['2019-01-02', '2019-01-03', '2019-01-04', '2019-01-07', '2019-01-08', '2019-01-09', '2019-01-10', '2019-01-11', '2019-01-14',
'2019-01-15', '2019-01-16', '2019-01-17', '2019-01-18', '2019-01-21', '2019-01-22', '2019-01-23', '2019-01-24', '2019-01-25',
'2019-01-28', '2019-01-29', '2019-01-30', '2019-01-31', '2019-02-01', '2019-02-11', '2019-02-12', '2019-02-13', '2019-02-14',
'2019-02-15', '2019-02-18', '2019-02-19', '2019-02-20', '2019-02-21', '2019-02-22', '2019-02-25', '2019-02-26', '2019-02-27',
'2019-02-28', '2019-03-01', '2019-03-04', '2019-03-05', '2019-03-06', '2019-03-07', '2019-03-08', '2019-03-11', '2019-03-12',
'2019-03-13', '2019-03-14', '2019-03-15', '2019-03-18', '2019-03-19', '2019-03-20', '2019-03-21', '2019-03-22', '2019-03-25',
'2019-03-26', '2019-03-27', '2019-03-28', '2019-03-29', '2019-04-01', '2019-04-02', '2019-04-03', '2019-04-04', '2019-04-08',
'2019-04-09', '2019-04-10']
"""
# data = Data('E:/personalfiles/to_zhixiong/to_zhixiong/level2_data_with_factor_added','600030.SH','20170516')
dataPath = '//192.168.0.145/data/stock/wind'
## /sh201707d/sh_20170703
t1 = time.time()
tradeDate = '20190410'
symbols_path = 'D:/SignalTest/SignalTest/ref_data/sh50.csv'
symbol_list = pd.read_csv(symbols_path)
symbols = symbol_list.loc[:,'secucode']
print(symbols)
symbols = ['600366.SH']
tradingDay = ['20190102', '20190103', '20190104', '20190107', '20190108', '20190109', '20190110',
'20190111', '20190114', '20190115', '20190116', '20190117', '20190118', '20190121',
'20190122', '20190123', '20190124', '20190125', '20190128', '20190129', '20190130',
'20190131', '20190201', '20190211', '20190212', '20190213', '20190214', '20190215',
'20190218', '20190219', '20190220', '20190221', '20190222', '20190225', '20190226',
'20190227',
'20190228', '20190301', '20190304', '20190305', '20190306', '20190307', '20190308',
'20190311',
'20190312', '20190314', '20190315', '20190318', '20190319', '20190320', '20190321',
'20190322',
'20190325',]
'''
'20190326', '20190328', '20190329', '20190401', '20190402', '20190403',
'20190404',
'20190408', '20190409']
'''
# price_situation =self.ProcessOrderInfo(data.tradeData[symbol],orderType = ' nAskOrder')
t2 = time.time()
stats_df = pd.DataFrame()
for tradeDate in tradingDay:
print(tradeDate)
data = Data.Data(dataPath,symbols, tradeDate,'' ,dataReadType= 'gzip', RAWDATA = 'True')
stats = Stats(symbols,tradeDate,data.quoteData,data.tradeData)
temp = stats.run(symbols[0])
stats_df.loc[:, tradeDate] = temp[0]
#print(data.tradeData[symbols[0]])
#file_ = stats_df.loc[:,tradeDate] = temp
stats.check_file(stats_df)
'''
q = pd.DataFrame()
multi_pool = mpP(4)
multi_pool.map(stats.run,symbols)
multi_pool.close()
multi_pool.join()
'''
t3 = time.time()
print('total:' + str(t3 - t2))
print('readData_time:' + str(t2 - t1))
#
print('Test end')
| [
"jpanag@163.com"
] | jpanag@163.com |
a554fe02fd9428bee0aa30e20f5fc252b6d25627 | d4f19cbcd4179b84069dcc588edc970fe30909c0 | /supervisors_commands/add_user.py | 707ed49ad48becef19fc21862d2dd4ffd959cd35 | [] | no_license | chypppre/opvs_bot | d77d7aa1d104d51fcc9d53e22207dfbaa1332d32 | e6e1c784d32747ff98d783cd60b6ac6f1155cf44 | refs/heads/master | 2020-09-14T12:30:52.774310 | 2019-12-02T09:40:33 | 2019-12-02T09:40:33 | 222,877,939 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,334 | py | import sqlite3
from telebot import types
from misc import DB_DIR, CHATS_ID
def add_to_tempo(uid, last_name, first_name, department):
"""Добавить во временную таблицу в БД"""
db = sqlite3.connect(DB_DIR)
cursor = db.cursor()
check_sql = "SELECT uid FROM tempo WHERE uid={}".format(uid)
cursor.execute(check_sql)
if len(cursor.fetchall()) == 1:
add_sql = "UPDATE tempo SET uid={}, last_name='{}', first_name='{}', department={}".format(
uid, last_name, first_name, department)
else:
add_sql = "INSERT INTO tempo VALUES ({}, '{}', '{}', {})".format(uid, last_name, first_name, department)
cursor.execute(add_sql)
db.commit()
def send_add_request(bot, uid):
"""Отправить запрос с данными в бота"""
kbrd = types.InlineKeyboardMarkup()
uc_btn = types.InlineKeyboardButton(text="КЭ", callback_data="add_uc")
uc_helper_btn = types.InlineKeyboardButton(text="Пом.КЭ", callback_data="add_uc_helper")
uc_super_btn = types.InlineKeyboardButton(text="Супер.КЭ", callback_data="add_uc_super")
#kb_btn = types.InlineKeyboardButton(text="КБухглатерия", callback_data="add_kb")
#kb_helper_btn = types.InlineKeyboardButton(text="Пом.КБухглатерия", callback_data="add_kb_helper")
#kb_super_btn = types.InlineKeyboardButton(text="Супер.КБухглатерия", callback_data="add_kb_super")
#elba_btn = types.InlineKeyboardButton(text="Эльба", callback_data="add_elba")
#elba_helper_btn = types.InlineKeyboardButton(text="Пом.Эльба", callback_data="add_elba_helper")
#elba_super_btn = types.InlineKeyboardButton(text="Супер.Эльба", callback_data="add_elba_super")
# fms_btn = types.InlineKeyboardButton(text="ФМС", callback_data="add_fms")
# fms_helper_btn = types.InlineKeyboardButton(text="Пом.ФМС", callback_data="add_fms_helper")
# fms_super_btn = types.InlineKeyboardButton(text="Супер.ФМС", callback_data="add_fms_super")
intern_btn = types.InlineKeyboardButton(text="Стажер", callback_data="add_intern")
mentor_btn = types.InlineKeyboardButton(text="Наставник", callback_data="add_intern_helper")
oo_btn = types.InlineKeyboardButton(text="ОО", callback_data="add_oo")
pip_btn = types.InlineKeyboardButton(text="ПиП", callback_data="add_pip")
decline_btn = types.InlineKeyboardButton(text="Отклонить", callback_data="decline")
db = sqlite3.connect(DB_DIR)
cursor = db.cursor()
sql = "SELECT uid, last_name, first_name, department FROM tempo WHERE uid={}".format(uid)
cursor.execute(sql)
data = cursor.fetchall()[0]
uid, last_name, first_name, department= data[0], data[1], data[2], data[3]
if department in [1,3]:
chat_id = CHATS_ID[0]
kbrd.row(uc_btn, uc_helper_btn, uc_super_btn)
kbrd.row(intern_btn, mentor_btn)
kbrd.row(oo_btn, pip_btn)
elif department == 5:
chat_id = CHATS_ID[6]
kbrd.row(kb_btn, kb_helper_btn, kb_super_btn)
elif department == 6:
chat_id = CHATS_ID[7]
kbrd.row(elba_btn, elba_helper_btn, elba_super_btn)
kbrd.row(decline_btn)
full_name = "{} {}".format(
last_name,
first_name)
text_for_admins = "{} просит добавить его в бота.\nUID = {}.".format(
full_name,
uid)
bot.send_message(
chat_id=chat_id,
text=text_for_admins,
reply_markup=kbrd)
def add_user(bot, call):
"""Добавить юзера согласно нажатой кнопки"""
text = call.message.text
text = text.split(" ")
cons_last_name, cons_first_name, uid = text[0], text[1], text[-1]
cons_full_name = "{} {}".format(cons_last_name, cons_first_name)
db = sqlite3.connect(DB_DIR)
cursor = db.cursor()
try:
if call.data == "add_uc":
sql = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, 1, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql)
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Врн, ххх опенспейс'.")
elif call.data == "add_kb":
sql = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, {}, '{}', '{}')""".format(uid, department, cons_last_name, cons_first_name)
cursor.execute(sql)
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Врн, ххх опенспейс'.")
elif call.data == "add_elba":
sql = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, {}, '{}', '{}')""".format(uid, department, cons_last_name, cons_first_name)
cursor.execute(sql)
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Врн, ххх опенспейс'.")
# elif call.data == "add_fms":
# sql = """INSERT INTO staff (uid, department, last_name, first_name)
# VALUES ({}, 2, '{}', '{}')""".format(uid, last_name, first_name)
elif call.data == "add_intern":
sql = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, 3, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql)
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Набор дд.мм ххх кабинет'.")
elif call.data == "add_uc_helper":
try:
sql = """INSERT INTO helpers (uid, department, last_name, first_name)
VALUES ({}, 1, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql)
sql2 = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, 1, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql2)
except:
pass
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Врн, ххх опенспейс' и "\
"Установить помогаторский адрес Врн, ххх опенспейс'.")
elif call.data == "add_kb_helper":
try:
sql = """INSERT INTO helpers (uid, department, last_name, first_name)
VALUES ({}, {}, '{}', '{}')""".format(uid, department, cons_last_name, cons_first_name)
cursor.execute(sql)
sql2 = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, {}, '{}', '{}')""".format(uid, department, cons_last_name, cons_first_name)
cursor.execute(sql2)
except:
pass
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Врн, ххх опенспейс' и "\
"Установить помогаторский адрес Врн, ххх опенспейс'.")
elif call.data == "add_elba_helper":
try:
sql = """INSERT INTO helpers (uid, department, last_name, first_name)
VALUES ({}, {}, '{}', '{}')""".format(uid, department, cons_last_name, cons_first_name)
cursor.execute(sql)
sql2 = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, {}, '{}', '{}')""".format(uid, department, cons_last_name, cons_first_name)
cursor.execute(sql2)
except:
pass
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Врн, ххх опенспейс' и "\
"Установить помогаторский адрес Врн, ххх опенспейс'.")
# elif call.data == "add_fms_helper":
# sql = """INSERT INTO helpers (uid, department, last_name, first_name)
# VALUES ({}, 2, '{}', '{}')""".format(uid, last_name, first_name)
# cursor.execute(sql)
# sql2 = """INSERT INTO staff (uid, department, last_name, first_name)
# VALUES ({}, 2, '{}', '{}')""".format(uid, last_name, first_name)
# cursor.execute(sql2)
elif call.data == "add_intern_helper":
try:
sql2 = """INSERT INTO helpers (uid, department, last_name, first_name)
VALUES ({}, 3, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql2)
sql = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, 1, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql)
except:
pass
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Врн, ххх опенспейс' и "\
"Установить помогаторский адрес Врн, ххх опенспейс'.")
elif call.data == "add_uc_super":
try:
sql = """INSERT INTO supers (uid, department, last_name, first_name)
VALUES ({}, 1, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql)
sql2 = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, 1, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql2)
except:
pass
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Врн, ххх опенспейс' и "\
"Установить помогаторский адрес Врн, ххх опенспейс'.")
elif call.data == "add_kb_super":
try:
sql = """INSERT INTO supers (uid, department, last_name, first_name)
VALUES ({}, {}}, '{}', '{}')""".format(uid, department, cons_last_name, cons_first_name)
cursor.execute(sql)
sql2 = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, 1, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql2)
except:
pass
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Врн, ххх опенспейс' и "\
"Установить помогаторский адрес Врн, ххх опенспейс'.")
elif call.data == "add_elba_super":
try:
sql = """INSERT INTO supers (uid, department, last_name, first_name)
VALUES ({}, {}, '{}', '{}')""".format(uid, department, cons_last_name, cons_first_name)
cursor.execute(sql)
sql2 = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, 1, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql2)
except:
pass
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Врн, ххх опенспейс' и "\
"Установить помогаторский адрес Врн, ххх опенспейс'.")
# elif call.data == "add_fms_super":
# sql = """INSERT INTO supers (uid, department, last_name, first_name)
# VALUES ({}, 2, '{}', '{}')""".format(uid, last_name, first_name)
elif call.data == "add_oo":
sql = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, 4, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql)
bot.send_message(
chat_id=uid,
text="Тебя добавили. Для налача работы напиши боту 'Установить адрес Врн, ххх опенспейс'.")
elif call.data == "add_pip":
sql = """INSERT INTO staff (uid, department, last_name, first_name)
VALUES ({}, 5, '{}', '{}')""".format(uid, cons_last_name, cons_first_name)
cursor.execute(sql)
except Exception as e:
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text="Скорее всего пользователь уже добавлен, но вот ошибка\n{}".format(e))
who_sql = "SELECT last_name, first_name FROM supers WHERE uid={}".format(call.from_user.id)
cursor.execute(who_sql)
resp = cursor.fetchall()[0]
responser_full_name = "{} {} (@{})".format(resp[0], resp[1], call.from_user.username)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text="{} успешно добавлен супервизором {}!".format(
cons_full_name,
responser_full_name))
delete_sql = "DELETE FROM tempo WHERE uid={}".format(uid)
cursor.execute(delete_sql)
db.commit()
cursor.close()
db.close()
| [
"noreply@github.com"
] | noreply@github.com |
c9ee8812a25fefe8c101523fb066299ab9ab3dd6 | 92c8737a6c4b967fd43885b97626ef25deb3e983 | /Burgers/burgers.py | f2feb0fa28ccaed55811dd23b18373c044983697 | [] | no_license | JMLipsmeyer/SA-PINNs | 42d53ffc3c3383dd6bbaea113303696e65348ea5 | a180801354e7db02bdda41f9c433008387a1c2f7 | refs/heads/master | 2022-12-27T18:45:35.179715 | 2020-10-12T18:51:08 | 2020-10-12T18:51:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,219 | py | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import time
import scipy.io
import math
import matplotlib.gridspec as gridspec
from plotting import newfig
from mpl_toolkits.axes_grid1 import make_axes_locatable
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras import layers, activations
from scipy.interpolate import griddata
from eager_lbfgs import lbfgs, Struct
from pyDOE import lhs
layer_sizes = [2, 20, 20, 20, 20, 20, 20, 20, 20, 1]
sizes_w = []
sizes_b = []
for i, width in enumerate(layer_sizes):
if i != 1:
sizes_w.append(int(width * layer_sizes[1]))
sizes_b.append(int(width if i != 0 else layer_sizes[1]))
def set_weights(model, w, sizes_w, sizes_b):
for i, layer in enumerate(model.layers[0:]):
start_weights = sum(sizes_w[:i]) + sum(sizes_b[:i])
end_weights = sum(sizes_w[:i+1]) + sum(sizes_b[:i])
weights = w[start_weights:end_weights]
w_div = int(sizes_w[i] / sizes_b[i])
weights = tf.reshape(weights, [w_div, sizes_b[i]])
biases = w[end_weights:end_weights + sizes_b[i]]
weights_biases = [weights, biases]
layer.set_weights(weights_biases)
def get_weights(model):
w = []
for layer in model.layers[0:]:
weights_biases = layer.get_weights()
weights = weights_biases[0].flatten()
biases = weights_biases[1]
w.extend(weights)
w.extend(biases)
w = tf.convert_to_tensor(w)
return w
def neural_net(layer_sizes):
model = Sequential()
model.add(layers.InputLayer(input_shape=(layer_sizes[0],)))
for width in layer_sizes[1:-1]:
model.add(layers.Dense(
width, activation=tf.nn.tanh,
kernel_initializer="glorot_normal"))
model.add(layers.Dense(
layer_sizes[-1], activation=None,
kernel_initializer="glorot_normal"))
return model
u_model = neural_net(layer_sizes)
u_model.summary()
def loss(x_f_batch, t_f_batch,
x0, t0, u0, x_lb,
t_lb, x_ub, t_ub, col_weights, u_weights):
f_u_pred = f_model(x_f_batch, t_f_batch)
u0_pred = u_model(tf.concat([x0, t0],1))
u_lb_pred, _ = u_x_model(x_lb, t_lb)
u_ub_pred, _ = u_x_model(x_ub, t_ub)
mse_0_u = tf.reduce_mean(tf.square(u_weights*(u0 - u0_pred)))
mse_b_u = tf.reduce_mean(tf.square(u_lb_pred - 0)) + \
tf.reduce_mean(tf.square(u_ub_pred - 0)) #since ub/lb is 0
mse_f_u = tf.reduce_mean(tf.square(col_weights*f_u_pred))
return mse_0_u + mse_b_u + mse_f_u , mse_0_u, mse_f_u
def f_model(x, t):
# keep track of our gradients
with tf.GradientTape(persistent=True) as tape:
tape.watch(x)
tape.watch(t)
u = u_model(tf.concat([x, t],1))
u_x = tape.gradient(u, x)
u_xx = tape.gradient(u_x, x)
u_t = tape.gradient(u, t)
del tape
#hsq = (u**2 + v**2)
f_u = u_t + u*u_x - (0.01/tf.constant(math.pi))*u_xx
#f_v = v_t - .5*u_xx - hsq*u
return f_u
def u_x_model(x, t):
with tf.GradientTape(persistent=True) as tape:
tape.watch(x)
tape.watch(t)
X = tf.concat([x,t],1)
u = u_model(X)
u_x = tape.gradient(u, x)
del tape
return u, u_x
def fit(x_f, t_f, x0, t0, u0, x_lb, t_lb, x_ub, t_ub, col_weights, u_weights, tf_iter, newton_iter):
# Built in support for mini-batch, set to N_f (i.e. full batch) by default
batch_sz = N_f
n_batches = N_f // batch_sz
start_time = time.time()
tf_optimizer = tf.keras.optimizers.Adam(lr = 0.005, beta_1=.90)
tf_optimizer_coll = tf.keras.optimizers.Adam(lr = 0.005, beta_1=.90)
tf_optimizer_u = tf.keras.optimizers.Adam(lr = 0.005, beta_1=.90)
print("starting Adam training")
for epoch in range(tf_iter):
for i in range(n_batches):
x0_batch = x0#[i*batch_sz:(i*batch_sz + batch_sz),]
t0_batch = t0#[i*batch_sz:(i*batch_sz + batch_sz),]
u0_batch = u0#[i*batch_sz:(i*batch_sz + batch_sz),]
x_f_batch = x_f[i*batch_sz:(i*batch_sz + batch_sz),]
t_f_batch = t_f[i*batch_sz:(i*batch_sz + batch_sz),]
with tf.GradientTape(persistent=True) as tape:
loss_value, mse_0, mse_f = loss(x_f_batch, t_f_batch, x0_batch, t0_batch, u0_batch, x_lb, t_lb, x_ub, t_ub, col_weights, u_weights)
grads = tape.gradient(loss_value, u_model.trainable_variables)
grads_col = tape.gradient(loss_value, col_weights)
grads_u = tape.gradient(loss_value, u_weights)
tf_optimizer.apply_gradients(zip(grads, u_model.trainable_variables))
tf_optimizer_coll.apply_gradients(zip([-grads_col], [col_weights]))
tf_optimizer_u.apply_gradients(zip([-grads_u], [u_weights]))
del tape
if epoch % 10 == 0:
elapsed = time.time() - start_time
print('It: %d, Time: %.2f' % (epoch, elapsed))
tf.print(f"mse_0: {mse_0} mse_f: {mse_f} total loss: {loss_value}")
start_time = time.time()
print(col_weights)
#l-bfgs-b optimization
print("Starting L-BFGS training")
loss_and_flat_grad = get_loss_and_flat_grad(x_f_batch, t_f_batch, x0_batch, t0_batch, u0_batch, x_lb, t_lb, x_ub, t_ub, col_weights, u_weights)
lbfgs(loss_and_flat_grad,
get_weights(u_model),
Struct(), maxIter=newton_iter, learningRate=0.8)
# L-BFGS implementation from https://github.com/pierremtb/PINNs-TF2.0
def get_loss_and_flat_grad(x_f_batch, t_f_batch, x0_batch, t0_batch, u0_batch, x_lb, t_lb, x_ub, t_ub, col_weights, u_weights):
def loss_and_flat_grad(w):
with tf.GradientTape() as tape:
set_weights(u_model, w, sizes_w, sizes_b)
loss_value, _, _ = loss(x_f_batch, t_f_batch, x0_batch, t0_batch, u0_batch, x_lb, t_lb, x_ub, t_ub, col_weights, u_weights)
grad = tape.gradient(loss_value, u_model.trainable_variables)
grad_flat = []
for g in grad:
grad_flat.append(tf.reshape(g, [-1]))
grad_flat = tf.concat(grad_flat, 0)
#print(loss_value, grad_flat)
return loss_value, grad_flat
return loss_and_flat_grad
def predict(X_star):
X_star = tf.convert_to_tensor(X_star, dtype=tf.float32)
u_star, _ = u_x_model(X_star[:,0:1],
X_star[:,1:2])
f_u_star = f_model(X_star[:,0:1],
X_star[:,1:2])
return u_star.numpy(), f_u_star.numpy()
lb = np.array([-1.0]) #x upper boundary
ub = np.array([1.0]) #x lower boundary
N0 = 100
N_b = 25 #25 per upper and lower boundary, so 50 total
N_f = 10000
col_weights = tf.Variable(tf.random.uniform([N_f, 1]))
u_weights = tf.Variable(100*tf.random.uniform([N0, 1]))
#load data, from Raissi et. al
data = scipy.io.loadmat('burgers_shock.mat')
t = data['t'].flatten()[:,None]
x = data['x'].flatten()[:,None]
Exact = data['usol']
Exact_u = np.real(Exact)
#grab random points off the initial condition
idx_x = np.random.choice(x.shape[0], N0, replace=False)
x0 = x[idx_x,:]
u0 = Exact_u[idx_x,0:1]
idx_t = np.random.choice(t.shape[0], N_b, replace=False)
tb = t[idx_t,:]
# Sample collocation points via LHS
X_f = lb + (ub-lb)*lhs(2, N_f)
x_f = tf.convert_to_tensor(X_f[:,0:1], dtype=tf.float32)
t_f = tf.convert_to_tensor(np.abs(X_f[:,1:2]), dtype=tf.float32)
#generate point vectors for training
X0 = np.concatenate((x0, 0*x0), 1) # (x0, 0)
X_lb = np.concatenate((0*tb + lb[0], tb), 1) # (lb[0], tb)
X_ub = np.concatenate((0*tb + ub[0], tb), 1) # (ub[0], tb)
#seperate point vectors
x0 = X0[:,0:1]
t0 = X0[:,1:2]
x_lb = tf.convert_to_tensor(X_lb[:,0:1], dtype=tf.float32)
t_lb = tf.convert_to_tensor(X_lb[:,1:2], dtype=tf.float32)
x_ub = tf.convert_to_tensor(X_ub[:,0:1], dtype=tf.float32)
t_ub = tf.convert_to_tensor(X_ub[:,1:2], dtype=tf.float32)
# Begin training, modify 10000/10000 for varying levels of adam/L-BFGS respectively
fit(x_f, t_f, x0, t0, u0, x_lb, t_lb, x_ub, t_ub, col_weights, u_weights, tf_iter = 10000, newton_iter = 10000)
#generate mesh to find U0-pred for the whole domain
X, T = np.meshgrid(x,t)
X_star = np.hstack((X.flatten()[:,None], T.flatten()[:,None]))
u_star = Exact_u.T.flatten()[:,None]
lb = np.array([-1.0, 0.0])
ub = np.array([1.0, 1])
# Get preds
u_pred, f_u_pred = predict(X_star)
#find L2 error
error_u = np.linalg.norm(u_star-u_pred,2)/np.linalg.norm(u_star,2)
print('Error u: %e' % (error_u))
U_pred = griddata(X_star, u_pred.flatten(), (X, T), method='cubic')
FU_pred = griddata(X_star, f_u_pred.flatten(), (X, T), method='cubic')
#plotting script in the style of Raissi et al
######################################################################
############################# Plotting ###############################
######################################################################
X0 = np.concatenate((x0, 0*x0), 1) # (x0, 0)
X_lb = np.concatenate((0*tb + lb[0], tb), 1) # (lb[0], tb)
X_ub = np.concatenate((0*tb + ub[0], tb), 1) # (ub[0], tb)
X_u_train = np.vstack([X0, X_lb, X_ub])
fig, ax = newfig(1.3, 1.0)
ax.axis('off')
####### Row 0: h(t,x) ##################
gs0 = gridspec.GridSpec(1, 2)
gs0.update(top=1-0.06, bottom=1-1/3, left=0.15, right=0.85, wspace=0)
ax = plt.subplot(gs0[:, :])
h = ax.imshow(U_pred.T, interpolation='nearest', cmap='YlGnBu',
extent=[lb[1], ub[1], lb[0], ub[0]],
origin='lower', aspect='auto')
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
fig.colorbar(h, cax=cax)
line = np.linspace(x.min(), x.max(), 2)[:,None]
ax.plot(t[25]*np.ones((2,1)), line, 'k--', linewidth = 1)
ax.plot(t[50]*np.ones((2,1)), line, 'k--', linewidth = 1)
ax.plot(t[75]*np.ones((2,1)), line, 'k--', linewidth = 1)
ax.set_xlabel('$t$')
ax.set_ylabel('$x$')
leg = ax.legend(frameon=False, loc = 'best')
# plt.setp(leg.get_texts(), color='w')
ax.set_title('$u(t,x)$', fontsize = 10)
####### Row 1: h(t,x) slices ##################
gs1 = gridspec.GridSpec(1, 3)
gs1.update(top=1-1/3, bottom=0, left=0.1, right=0.9, wspace=0.5)
ax = plt.subplot(gs1[0, 0])
ax.plot(x,Exact_u[:,25], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,U_pred[25,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.set_title('$t = %.2f$' % (t[25]), fontsize = 10)
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax = plt.subplot(gs1[0, 1])
ax.plot(x,Exact_u[:,50], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,U_pred[50,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax.set_title('$t = %.2f$' % (t[50]), fontsize = 10)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.3), ncol=5, frameon=False)
ax = plt.subplot(gs1[0, 2])
ax.plot(x,Exact_u[:,75], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,U_pred[75,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax.set_title('$t = %.2f$' % (t[75]), fontsize = 10)
#show u_pred across domain
fig, ax = plt.subplots()
ec = plt.imshow(U_pred.T, interpolation='nearest', cmap='rainbow',
extent=[0.0, 1.0, -1.0, 1.0],
origin='lower', aspect='auto')
ax.autoscale_view()
ax.set_xlabel('$t$')
ax.set_ylabel('$x$')
cbar = plt.colorbar(ec)
cbar.set_label('$u(x,t)$')
plt.title("Predicted $u(x,t)$",fontdict = {'fontsize': 14})
plt.show()
# Show F_U_pred across domain, should be close to 0
fig, ax = plt.subplots()
ec = plt.imshow(FU_pred.T, interpolation='nearest', cmap='rainbow',
extent=[0.0, math.pi/2, -5.0, 5.0],
origin='lower', aspect='auto')
ax.autoscale_view()
ax.set_xlabel('$x$')
ax.set_ylabel('$t$')
cbar = plt.colorbar(ec)
cbar.set_label('$\overline{f}_u$ prediction')
plt.show()
# collocation point weights
plt.scatter(t_f, x_f, c = col_weights.numpy(), s = col_weights.numpy()/5)
plt.show()
| [
"levimcclenny@tamu.edu"
] | levimcclenny@tamu.edu |
c9a91552c1b8f4b8a2ff609676b81cd11cf08ead | 48df99f4358be7a51becd3d685e1ec825d295ba4 | /dentalstate/models.py | 36c642462ac4cabb367d2fe592fdd0be94d557a6 | [
"Apache-2.0"
] | permissive | kuyesu/tscharts | 21d2aedeea4aad3b126defaa1703f60f44f14de6 | 9ed4e4bb0a6d296e1156afca5b55d0f71dfb894b | refs/heads/master | 2023-06-03T04:50:15.282855 | 2021-06-12T19:50:51 | 2021-06-12T19:50:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,258 | py | #(C) Copyright Syd Logan 2020
#(C) Copyright Thousand Smiles Foundation 2020
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#
#You may obtain a copy of the License at
#http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
from __future__ import unicode_literals
from django.db import models
from patient.models import Patient
from clinic.models import Clinic
from dentalcdt.models import DentalCDT
class DentalState(models.Model):
clinic = models.ForeignKey(Clinic)
patient = models.ForeignKey(Patient)
username = models.CharField(max_length=64, default = "") # user supplied name
time = models.DateTimeField(auto_now=True)
'''
tooth location is relative to location (top or bottom). Zero
indicates the treatment applies to whole mouth (and location
is ignored
'''
tooth = models.IntegerField(default = 0)
DENTAL_LOCATION_TOP = 't'
DENTAL_LOCATION_BOTTOM = 'b'
DENTAL_LOCATION_CHOICES = ((DENTAL_LOCATION_TOP, "top"), (DENTAL_LOCATION_BOTTOM, "bottom"))
location = models.CharField(max_length = 1, choices = DENTAL_LOCATION_CHOICES, default = DENTAL_LOCATION_TOP)
code = models.ForeignKey(DentalCDT)
DENTAL_STATE_NONE = 'n'
DENTAL_STATE_UNTREATED = 'u'
DENTAL_STATE_TREATED = 't'
DENTAL_STATE_OTHER = 'o'
DENTAL_STATE_MISSING = 'm'
DENTAL_STATE_CHOICES = ((DENTAL_STATE_MISSING, "missing"), (DENTAL_STATE_NONE, "none"), (DENTAL_STATE_UNTREATED, "untreated"), (DENTAL_STATE_TREATED, "treated"), (DENTAL_STATE_OTHER, "other"))
state = models.CharField(max_length = 1, choices = DENTAL_STATE_CHOICES, default = DENTAL_STATE_NONE)
DENTAL_SURFACE_NONE = 'n'
DENTAL_SURFACE_BUCCAL = 'b'
DENTAL_SURFACE_LINGUAL = 'u'
DENTAL_SURFACE_MESIAL = 'm'
DENTAL_SURFACE_OCCLUSAL = 'c'
DENTAL_SURFACE_LABIAL = 'a'
DENTAL_SURFACE_INCISAL = 'i'
DENTAL_SURFACE_WHOLE_MOUTH_OR_VISIT = 'w'
DENTAL_SURFACE_OTHER = 'o'
DENTAL_SURFACE_CHOICES = ((DENTAL_SURFACE_NONE, "none"), (DENTAL_SURFACE_BUCCAL, "buccal"), (DENTAL_SURFACE_LINGUAL, "lingual"), (DENTAL_SURFACE_MESIAL, "mesial"), (DENTAL_SURFACE_OCCLUSAL, 'occlusal'), (DENTAL_SURFACE_LABIAL, 'labial'), (DENTAL_SURFACE_INCISAL, 'incisal'), (DENTAL_SURFACE_WHOLE_MOUTH_OR_VISIT, 'whole_mouth_or_visit'), (DENTAL_SURFACE_OTHER, 'other'))
# here we define a charfield as a string to hold a set of surfaces
# this won't work with forms, but since we are just a REST API, doesn't
# matter much. The DENTAL_STATE_CHOICES tuple will be useful as we
# serialize/unserialize values between the client and the model. We
# could also have done this as an integer bitmask, but a string of chars
# facilitates debugging.
surface = models.CharField(max_length = 10, choices = DENTAL_SURFACE_CHOICES, default = DENTAL_SURFACE_NONE)
comment = models.TextField(default = "")
| [
"slogan621@gmail.com"
] | slogan621@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.