seq_id
string
text
string
repo_name
string
sub_path
string
file_name
string
file_ext
string
file_size_in_byte
int64
program_lang
string
lang
string
doc_type
string
stars
int64
dataset
string
pt
string
api
list
36028935609
import jwt from .models.models import * # get_permissions def get_permissions(user_id): # check role user = User.query.get(user_id) role = user.role # If role is true then user is admin if role: # get all user created lists user_owned_lists_query = List.query.filter(List.creator_id == user_id).all() user_owned_lists = [ str(lst.id) for lst in user_owned_lists_query ] # get all cards on user lists or cards he created user_lists_cards_query = Cards.query.filter(Cards.list_id.in_(user_owned_lists)).all() user_lists_cards = [ str(crd.id) for crd in user_lists_cards_query ] all_user_cards_query = Cards.query.filter(Cards.creator_id == user_id).all() all_user_cards = [ str(crd.id) for crd in all_user_cards_query ] all_user_cards += user_lists_cards # get all user created comments or comments in his cards or cards in own lists user_own_comments_query = Comments.query.filter(Comments.creator_id == user_id).all() user_own_comments = [ str(cmnt.id) for cmnt in user_own_comments_query ] user_cards_comments_query = Comments.query.filter(Comments.card_id.in_(user_lists_cards)).all() user_cards_comments = [ str(cmnt.id) for cmnt in user_cards_comments_query ] all_user_comments = user_own_comments + user_cards_comments # get all user created replies or replies in his cards or cards in own lists all_user_replies_query = Replies.query.filter(Replies.comment_id.in_(all_user_comments)).all() all_user_replies = [ str(rply.id) for rply in all_user_replies_query ] # create payload payload = { 'user_id': user_id, 'role': 'Admin', 'permissions': { 'get_all_lists': 'All', 'create_list': 'All', 'update_list': user_owned_lists, 'delete_list': user_owned_lists, 'get_list': 'All', 'assign_member_list': user_owned_lists, 'revoke_member_list': user_owned_lists, 'get_all_users': 'All', 'create_card': 'All', 'update_card': all_user_cards, 'delete_card': all_user_cards, 'get_card': 'All', 'create_comment': 'All', 'update_comment': all_user_comments, 'delete_comment': all_user_comments, 'get_comment': 'All', 'create_replies': 'All', 'update_replies': all_user_replies, 'delete_replies': all_user_replies, 'get_replies': 'All', } } secret = 'Irithm task is awesome' algo = "HS256" # encode a jwt encoded_jwt = jwt.encode(payload, secret, algorithm=algo) return encoded_jwt # if role is False the user is a member else: # get all lists assigned to the user user_assigned_lists_query = UserLists.query.filter(UserLists.user_id == user_id).all() user_assigned_lists = [str(lst.list_id) for lst in user_assigned_lists_query] # get all cards on user lists and cards he created in his assigned lists all_user_view_cards_query = Cards.query.filter(Cards.list_id.in_(user_assigned_lists)).all() all_user_view_cards = [str(crd.id) for crd in all_user_view_cards_query] all_user_created_cards_query = Cards.query.filter(Cards.creator_id == user_id).all() all_user_created_cards = [str(crd.id) for crd in all_user_created_cards_query] # get all user created comments and comments in his cards in assigned lists all_user_view_comments_query = Comments.query.filter(Comments.card_id.in_(all_user_view_cards)).all() all_user_view_comments = [str(cmnt.id) for cmnt in all_user_view_comments_query] all_user_created_comments_query = Comments.query.filter(Comments.creator_id == user_id).all() all_user_created_comments = [str(cmnt.id) for cmnt in all_user_created_comments_query] # get all user created replies or replies in his cards or cards in own lists all_user_view_replies_query = Replies.query.filter(Replies.comment_id.in_(all_user_view_comments)).all() all_user_view_replies = [str(rply.id) for rply in all_user_view_replies_query] all_user_created_replies_query = Replies.query.filter(Replies.creator_id == user_id).all() all_user_created_replies = [ str(rply.id) for rply in all_user_created_replies_query ] # create payload payload = { 'user_id': user_id, 'role': 'Member', 'permissions': { 'get_all_lists': False, 'create_list': False, 'update_list': False, 'delete_list': False, 'get_list': user_assigned_lists, 'get_all_users': False, 'assign_member_list': False, 'revoke_member_list': False, 'create_card': user_assigned_lists, 'update_card': all_user_created_cards, 'delete_card': all_user_created_cards, 'get_card': user_assigned_lists, 'create_comment': all_user_view_cards, 'update_comment': all_user_created_comments, 'delete_comment': all_user_created_comments, 'get_comment': all_user_view_cards, 'create_replies': all_user_view_comments, 'update_replies': all_user_created_replies, 'delete_replies': all_user_created_replies, 'get_replies': all_user_view_comments, } } secret = 'Irithm task is awesome' algo = "HS256" # encode a jwt encoded_jwt = jwt.encode(payload, secret, algorithm=algo) return encoded_jwt # check_permissions def check_permissions(token, permission, entity_id): # Decode a JWT secret = 'Irithm task is awesome' algo = 'HS256' payload = jwt.decode(token, secret, algorithms=algo, verify=True) if 'permissions' in payload: if payload['permissions'][permission]: if payload['permissions'][permission] == 'All': return True elif str(entity_id) in payload['permissions'][permission]: return True else: raise AuthError({ 'code': 'invalid_id', 'description': 'Authorization to this entity is forbidden.' }, 401) else: raise AuthError({ 'code': 'permission_access_forbidden', 'description': 'Access to this entity is forbidden.' }, 401) else: raise AuthError({ 'code': 'invalid_permission', 'description': 'Permission not granted.' }, 401) # authorization error class class AuthError(Exception): def __init__(self, error, status_code): self.error = error self.status_code = status_code
mfragab5890/Irithim-python-flask
src/auth.py
auth.py
py
7,106
python
en
code
0
github-code
36
[ { "api_name": "jwt.encode", "line_number": 67, "usage_type": "call" }, { "api_name": "jwt.encode", "line_number": 127, "usage_type": "call" }, { "api_name": "jwt.decode", "line_number": 136, "usage_type": "call" } ]
17520933988
# coding:utf-8 import unittest import ddt import os import requests from common import base_api from common import readexcel from common import writeexcel from common.readexcel import ExcelUtil curpath = os.path.dirname(os.path.realpath(__file__)) textxlsx = os.path.join(curpath,"demo_api.xlsx") report_path = os.path.join(os.path.dirname(curpath),"report") reportxlsx = os.path.join(report_path,"result.xlsx") testdata = readexcel.ExcelUtil(textxlsx,sheetName="Sheet1").dict_data() @ddt.ddt class Test_api(unittest.TestCase): @classmethod def setUpClass(cls): cls.s = requests.session() writeexcel.copy_excel(textxlsx,reportxlsx) @ddt.data(*testdata) def test_api(self,data): res = base_api.send_requests(self.s,data) base_api.wirte_result(res,filename=reportxlsx) check = data["checkpoint"] print(u"检查点->:%s"%check) res_text = res['text'] print(u"返回实际结果->:%s"%res_text) self.assertTrue(check in res_text) if __name__ == "__main__": unittest.main()
fangjiantan/PostTest
Testcase/test_api.py
test_api.py
py
1,065
python
en
code
0
github-code
36
[ { "api_name": "os.path.dirname", "line_number": 11, "usage_type": "call" }, { "api_name": "os.path", "line_number": 11, "usage_type": "attribute" }, { "api_name": "os.path.realpath", "line_number": 11, "usage_type": "call" }, { "api_name": "os.path.join", "lin...
6672720656
import torch import torch.nn as nn from torch.autograd import Variable import torchvision.datasets as dset import torchvision.transforms as transforms import torch.nn.functional as F import torch.optim as optim import numpy as np from sklearn.manifold import TSNE import matplotlib.pyplot as plt import torch.nn.functional as F from torch.autograd import Function from model import encoder, predictor from LoadData import DATASET import sys from torch.utils.data import Dataset, DataLoader from collections import defaultdict ''' dataset : infograph, quickdraw, real, sketch ''' cuda = torch.cuda.is_available() device = torch.device('cuda' if cuda else 'cpu') #print('cuda = ', cuda) BATCH_SIZE = 256 EP = 50 class ToRGB(object): def __init__(self): pass def __call__(self, sample): sample = sample.convert('RGB') return sample mean = np.array([0.5, 0.5, 0.5]) std = np.array([0.5, 0.5, 0.5]) transform = transforms.Compose([ ToRGB(), transforms.Resize((32, 32)), transforms.ToTensor(), transforms.Normalize(mean, std) ]) if __name__ == '__main__': argument = sys.argv[1:] source_domain = argument[:-1] target_domain = argument[-1] N = len(source_domain) # dataloader source_dataloader_list = [] source_clf = {} extractor = encoder().to(device) extractor_optim = optim.Adam(extractor.parameters(), lr=3e-4) for source in source_domain: print(source) if source == 'svhn': dataset = dset.SVHN(root='./dataset/svhn/', download=True, transform=transform) elif source == 'mnist': dataset = dset.MNIST('./dataset/mnist', train=True, download=True, transform=transform) else: print(source) dataset = DATASET(source, 'train') dataset = DataLoader(dataset, batch_size = BATCH_SIZE, shuffle=True) source_dataloader_list.append(dataset) # c1 : for target # c2 : for source source_clf[source] = {} source_clf[source]['c1'] = predictor().to(device) source_clf[source]['c2'] = predictor().to(device) source_clf[source]['optim'] = optim.Adam(list(source_clf[source]['c1'].parameters()) + list(source_clf[source]['c2'].parameters()), lr=3e-4, weight_decay=0.0005) if target_domain == 'svhn': target_dataset = dset.SVHN(root='./dataset/svhn/', download=True, transform=transform) elif target_domain == 'mnist': target_dataset = dset.MNIST('./dataset/mnist', train=True, download=True, transform=transform) else: target_dataset = DATASET(target_domain, 'train') target_dataloader = DataLoader(target_dataset, batch_size=BATCH_SIZE, shuffle=True) loss_extractor = nn.CrossEntropyLoss() for ep in range(EP): print(ep+1) extractor.train() source_ac = {} for source in source_domain: source_clf[source]['c1'] = source_clf[source]['c1'].train() source_clf[source]['c2'] = source_clf[source]['c2'].train() source_ac[source] = defaultdict(int) for batch_index, (src_batch, tar_batch) in enumerate(zip(zip(*source_dataloader_list), target_dataloader)): src_len = len(src_batch) loss_cls = 0 # train extractor and source clssifier for index, batch in enumerate(src_batch): x, y = batch x = x.to(device) y = y.to(device) y = y.view(-1) feature = extractor(x) pred1 = source_clf[source_domain[index]]['c1'](feature) pred2 = source_clf[source_domain[index]]['c2'](feature) source_ac[source_domain[index]]['c1'] += torch.sum(torch.max(pred1, dim=1)[1] == y).item() source_ac[source_domain[index]]['c2'] += torch.sum(torch.max(pred2, dim=1)[1] == y).item() loss_cls += loss_extractor(pred1, y) + loss_extractor(pred2, y) if batch_index % 5 == 0: for source in source_domain: print(source) print('c1 : [%.8f]' % (source_ac[source]['c1']/(batch_index+1)/BATCH_SIZE)) print('c2 : [%.8f]' % (source_ac[source]['c2']/(batch_index+1)/BATCH_SIZE)) print('\n') #extractor_optim.zero_grad() #for index, source in enumerate(source_domain): # source_clf[source_domain[index]]['optim'].zero_grad() #loss_cls.backward(retain_graph=True) #extractor_optim.step() #for index, source in enumerate(source_domain): # source_clf[source]['optim'].step() # source_clf[source]['optim'].zero_grad() #extractor_optim.zero_grad() m1_loss = 0 m2_loss = 0 for k in range(1, 3): for i_index, batch in enumerate(src_batch): x, y = batch x = x.to(device) y = y.to(device) y = y.view(-1) tar_x, _ = tar_batch tar_x = tar_x.to(device) src_feature = extractor(x) tar_feature = extractor(tar_x) e_src = torch.mean(src_feature**k, dim=0) e_tar = torch.mean(tar_feature**k, dim=0) m1_dist = e_src.dist(e_tar) m1_loss += m1_dist for j_index, other_batch in enumerate(src_batch[i_index:]): other_x, other_y = other_batch other_x = other_x.to(device) other_y = other_y.to(device) other_y = other_y.view(-1) other_feature = extractor(other_x) e_other = torch.mean(other_feature**k, dim=0) m2_dist = e_src.dist(e_other) m2_loss += m2_dist loss_m = 0.5 * (m1_loss/N + m2_loss/N/(N-1)*2) loss = loss_cls if batch_index % 5 == 0: print('[%d]/[%d]' % (batch_index, len(target_dataloader))) print('class loss : [%.5f]' % (loss_cls)) print('msd loss : [%.5f]' % (loss_m)) extractor_optim.zero_grad() for source in source_domain: source_clf[source]['optim'].zero_grad() loss.backward(retain_graph=True) extractor_optim.step() for source in source_domain: source_clf[source]['optim'].step() source_clf[source]['optim'].zero_grad() extractor_optim.zero_grad() tar_x , _ = tar_batch tar_x = tar_x.to(device) tar_feature = extractor(tar_x) loss = 0 for index, batch in enumerate(src_batch): x, y = batch x = x.to(device) y = y.to(device) y = y.view(-1) feature = extractor(x) pred1 = source_clf[source_domain[index]]['c1'](feature) pred2 = source_clf[source_domain[index]]['c2'](feature) clf_loss = loss_extractor(pred1, y) + loss_extractor(pred2, y) pred_c1 = source_clf[source_domain[index]]['c1'](tar_feature) pred_c2 = source_clf[source_domain[index]]['c2'](tar_feature) discrepency_loss = torch.mean(torch.sum(abs(F.softmax(pred_c1, dim=1) - F.softmax(pred_c2, dim=1)), dim=1)) loss += clf_loss - discrepency_loss loss.backward(retain_graph=True) for source in source_domain: source_clf[source]['optim'].zero_grad() source_clf[source]['optim'].step() source_clf[source]['optim'].zero_grad() extractor_optim.zero_grad() discrepency_loss = 0 for index, _ in enumerate(src_batch): pred_c1 = source_clf[source_domain[index]]['c1'](tar_feature) pred_c2 = source_clf[source_domain[index]]['c2'](tar_feature) discrepency_loss += torch.mean(torch.sum(abs(F.softmax(pred_c1, dim=1) - F.softmax(pred_c2, dim=1)), dim=1)) extractor_optim.zero_grad() discrepency_loss.backward(retain_graph=True) extractor_optim.step() extractor_optim.zero_grad() for source in source_domain: source_clf[source]['optim'].zero_grad() if batch_index % 5 == 0: print('Discrepency Loss : [%.4f]' % (discrepency_loss)) extractor.eval() for source in source_domain: source_clf[source]['c1'] = source_clf[source]['c1'].eval() source_clf[source]['c2'] = source_clf[source]['c2'].eval() source_ac = {} if target_domain == 'svhn': eval_loader = dset.SVHN(root='./dataset/svhn/', download=True, transform=transform) elif target_domain == 'mnist': eval_loader = dset.MNIST('./dataset/mnist', train=True, download=True, transform=transform) else: eval_loader = DATASET(target_domain, 'train') eval_loader = DataLoader(eval_loader, batch_size=BATCH_SIZE, shuffle=True) for source in source_domain: source_ac[source] = defaultdict(int) fianl_ac = 0 with torch.no_grad(): for index, batch in enumerate(eval_loader): x, y = batch x = x.to(device) y = y.to(device) y = y.view(-1) feature = extractor(x) final_pred = 1 for source in source_domain: pred1 = source_clf[source]['c1'](feature) pred2 = source_clf[source]['c2'](feature) if isinstance(final_pred, int): final_pred = F.softmax(pred1, dim=1) + F.softmax(pred2, dim=1) else: final_pred += F.softmax(pred1, dim=1) + F.softmax(pred2, dim=1) source_ac[source]['c1'] += np.sum(np.argmax(pred1.cpu().detach().numpy(), axis=1) == y.cpu().detach().numpy()) source_ac[source]['c2'] += np.sum(np.argmax(pred2.cpu().detach().numpy(), axis=1) == y.cpu().detach().numpy()) fianl_ac += np.sum(np.argmax(final_pred.cpu().detach().numpy(), axis=1) == y.cpu().detach().numpy()) for source in source_domain: print('Current Source : ', source) print('Accuray for c1 : [%.4f]' % (source_ac[source]['c1']/BATCH_SIZE/len(eval_loader))) print('Accuray for c2 : [%.4f]' % (source_ac[source]['c2']/BATCH_SIZE/len(eval_loader))) print('Combine Ac : [%.4f]' % (fianl_ac/BATCH_SIZE/len(eval_loader))) torch.save(extractor.state_dict(), './model/extractor'+'_'+str(ep)+'.pth') for source in source_domain: torch.save(source_clf[source]['c1'].state_dict(), './model/'+source+'_c1_'+str(ep)+'.pth') torch.save(source_clf[source]['c2'].state_dict(), './model/'+source+'_c2_'+str(ep)+'.pth')
PRCinguhou/domain-adaptation
train.py
train.py
py
9,439
python
en
code
2
github-code
36
[ { "api_name": "torch.cuda.is_available", "line_number": 23, "usage_type": "call" }, { "api_name": "torch.cuda", "line_number": 23, "usage_type": "attribute" }, { "api_name": "torch.device", "line_number": 24, "usage_type": "call" }, { "api_name": "numpy.array", ...
25446749830
""" Run correlation analysis asking if lucidity during the dream task influenced reported wakeup time. """ from pathlib import Path import matplotlib.pyplot as plt import numpy as np import pingouin as pg import utils ################################################################################ # SETUP ################################################################################ wakeup_col = "Wakeup" lucidity_col = "Task_lucid" wakeup_label = "Time between task and awakening" lucidity_label = "Lucidity while performing the task" # Load custom plotting settings. utils.load_matplotlib_settings() # Choose filepaths. config = utils.load_config() root_dir = Path(config["root_directory"]) export_path_plot = root_dir / "derivatives" / "wakeup_lucidity-plot.png" export_path_desc = root_dir / "derivatives" / "wakeup_lucidity-desc.tsv" export_path_stat = root_dir / "derivatives" / "wakeup_lucidity-stat.tsv" # Load data. df, meta = utils.load_raw(trim=True) # Reduce to only wakeup task conditions. df = df.query("Condition != 'Clench'") # Ensure values are floats. df[wakeup_col] = df[wakeup_col].astype(float) df[lucidity_col] = df[lucidity_col].astype(float) ################################################################################ # STATISTICS ################################################################################ # Get descriptives. desc = df[[wakeup_col, lucidity_col]].describe().T.rename_axis("variable") # Run correlation. x = df[lucidity_col].to_numpy() y = df[wakeup_col].to_numpy() stat = pg.corr(x, y, method="kendall") ################################################################################ # PLOTTING ################################################################################ # Get regression line predictor. coef = np.polyfit(x, y, 1) poly1d_func = np.poly1d(coef) # Grab ticks and labels from the sidecar file. xticks, xticklabels = zip(*meta[wakeup_col]["Levels"].items()) xticks = list(map(int, xticks)) yticks, yticklabels = zip(*meta[lucidity_col]["Levels"].items()) yticks = list(map(int, yticks)) # Open figure. fig, ax = plt.subplots(figsize=(2.4, 2.4)) # Draw dots and regression line. ax.plot(x, y, "ko", ms=5, alpha=0.2) ax.plot(x, poly1d_func(x), "-k") # Aesthetics. ax.set_xticks(xticks) ax.set_yticks(yticks) ax.set_xlabel(lucidity_label) ax.set_ylabel(wakeup_label) ax.grid(True, axis="both") ax.set_aspect("equal") ax.margins(0.1) ax.tick_params(direction="out", axis="both", which="both", top=False, right=False) ################################################################################ # EXPORT ################################################################################ desc.to_csv(export_path_desc, na_rep="n/a", sep="\t") stat.to_csv(export_path_stat, index_label="method", na_rep="n/a", sep="\t") plt.savefig(export_path_plot) plt.savefig(export_path_plot.with_suffix(".pdf")) plt.savefig(export_path_plot.with_suffix(".svg"))
remrama/wakeup
wakeup_lucidity.py
wakeup_lucidity.py
py
2,944
python
en
code
0
github-code
36
[ { "api_name": "utils.load_matplotlib_settings", "line_number": 24, "usage_type": "call" }, { "api_name": "utils.load_config", "line_number": 27, "usage_type": "call" }, { "api_name": "pathlib.Path", "line_number": 28, "usage_type": "call" }, { "api_name": "utils.l...
43221995512
# 1 from selenium import webdriver from math import log, sin browser = webdriver.Chrome() # Открыть страницу http://suninjuly.github.io/get_attribute.html browser.get('http://suninjuly.github.io/get_attribute.html') # Найти на ней элемент-картинку/ Взять у этого элемента значение атрибута valuex valuex = browser.find_element_by_css_selector('[id = "treasure"]').get_attribute('valuex') # Посчитать математическую функцию от x, Ввести ответ в текстовое поле. browser.find_element_by_id('answer').send_keys(str(log(abs(12 * sin(int(valuex)))))) # Отметить checkbox "Подтверждаю, что являюсь роботом". Выбрать radiobutton "Роботы рулят!". Нажать на кнопку Отправить. for selector in ['#robotCheckbox', '#robotsRule', '.btn.btn-default']: browser.find_element_by_css_selector(selector).click() # 2 import math import time from selenium import webdriver browser = webdriver.Chrome() try: browser.get("http://suninjuly.github.io/get_attribute.html") x = browser.find_element_by_id('treasure').get_attribute("valuex") y = str(math.log(abs(12*math.sin(int(x))))) browser.find_element_by_id('answer').send_keys(y) browser.find_element_by_id('robotCheckbox').click() browser.find_element_by_id('robotsRule').click() browser.find_element_by_css_selector("button.btn").click() finally: time.sleep(5) browser.quit() # 3 from selenium import webdriver import math link = 'http://suninjuly.github.io/get_attribute.html' def calc(x): ''' Функция возращает результат формулы :param x: :return: ''' return str(math.log(abs(12 * math.sin(int(x))))) driver = webdriver.Chrome() driver.get(link) # Находим значение аттрибута valuex элемента "сундук" x = driver.find_element_by_css_selector('#treasure').get_attribute('valuex') y = calc(x) # Передаем в поле ввода результат вычисления функции driver.find_element_by_css_selector('#answer').send_keys(y) # Кликаем чекбокс "Подтверждаю, что являюсь роботом" driver.find_element_by_css_selector('#robotCheckbox').click() # Кликаем radio "Роботы рулят" driver.find_element_by_css_selector('#robotsRule').click() # Нажимаем кнопку "Отправить" driver.find_element_by_css_selector('button.btn').click()
Rzktype/StepikPythonCourses
Module 2/lesson2-1_step7_anotherDecisions.py
lesson2-1_step7_anotherDecisions.py
py
2,614
python
ru
code
0
github-code
36
[ { "api_name": "selenium.webdriver.Chrome", "line_number": 5, "usage_type": "call" }, { "api_name": "selenium.webdriver", "line_number": 5, "usage_type": "name" }, { "api_name": "math.log", "line_number": 14, "usage_type": "call" }, { "api_name": "math.sin", "l...
7289309011
import networkx as nx import json import matplotlib.pyplot as plt import sys from collections import defaultdict from networkx.algorithms import bipartite import numpy as np import mmsbm import time import pickle def parse_reviews(review_file, business_ids): user_ids = [] reviews = defaultdict(list) stars = {} i = 0 with open(review_file, "r") as f: for line in f: j = json.loads(line) business_id = j["business_id"] if business_id in business_ids: user_id = j["user_id"] user_ids.append(user_id) reviews[user_id].append(business_id) stars[(user_id, business_id)] = j["stars"] i += 1 items = [] for key in reviews: for val in reviews[key]: items.append((key, val)) print(len(user_ids)) return items, user_ids, reviews, stars def parse_reviews_training(review_file, business_ids): user_ids = [] reviews = defaultdict(list) stars = {} i = 0 with open(review_file, "r") as f: for line in f: j = json.loads(line) business_id = j["business_id"] if business_id in business_ids: user_id = j["user_id"] user_ids.append(user_id) reviews[user_id].append(business_id) stars[(user_id, business_id)] = j["stars"] i += 1 items = [] for key in reviews: for val in reviews[key]: items.append((key, val)) ## shuffle items rand_items = np.random.permutation(items) ## make train and test sets training_items = rand_items[:int(len(rand_items)*.80)] test_items = rand_items[int(len(rand_items)*.80):] u_set = set(user_ids) training_set = set() for edge in training_items: training_set.add(edge[0]) training_set.add(edge[1]) training_set.intersection_update(u_set) test_set = set() for edge in test_items: test_set.add(edge[0]) test_set.add(edge[1]) test_set.intersection_update(u_set) b_set = set(business_ids.keys()) b_training_set = set() for edge in training_items: b_training_set.add(edge[0]) b_training_set.add(edge[1]) b_training_set.intersection_update(b_set) print(len(b_training_set),len(b_set)) return items, user_ids, reviews, stars, training_items, test_items, list(training_set), list(test_set), list(b_training_set) def parse_businesses(business_file): business_ids = {} i = 0 with open(business_file, "r") as f: for line in f: j = json.loads(line) #if i < 100 and j["city"] == "Las Vegas" and "Food" in j["categories"]: if j["city"] == "Las Vegas" and "Food" in j["categories"]: business_ids[j["business_id"]] = 0 i += 1 return business_ids def main(): try: review_file = sys.argv[1] business_file = sys.argv[2] except IndexError as e: print("Must provide input file.") sys.exit(-1) business_ids = parse_businesses(business_file) #items, user_ids, reviews, stars, training_items, test_items, training_ids, test_ids, training_business_ids= parse_reviews_training(review_file, business_ids) items, user_ids, reviews, stars = parse_reviews(review_file, business_ids) rating = np.zeros(5) print(len(stars)) for key in stars: rating[stars[key]-1] += 1 print(rating) ''' b = nx.Graph() b.add_nodes_from(user_ids, bipartite=0) b.add_nodes_from(business_ids.keys(), bipartite=1) b.add_edges_from(items) print(len(user_ids), len(business_ids), len(items)) for node in b.nodes(): if ''' ''' b = nx.Graph() b.add_nodes_from(training_ids, bipartite=0) b.add_nodes_from(training_business_ids, bipartite=1) b.add_edges_from(training_items) ''' b0 = 0 b1 = 0 for node in b.nodes(): b.node[node]['eta-theta'] = np.random.dirichlet(np.ones(10),1)[0] if b.node[node]['bipartite'] == 0: b0 += 1 if b.node[node]['bipartite'] == 1: b1 += 1 print(b0,b1,b0+b1,len(b.nodes())) p = np.full((5,10,10), 0.2) ## (r,k,l) for k in range(10): for l in range(10): vector = np.random.dirichlet(np.ones(5),1)[0] for r in range(5): p[r,k,l] = vector[r] #for edge in b.edges(): # print(stars[mmsbm.order_edge(b,edge)]) #for r in range(5): # print(p[r]) pickle.dump(items,open("items.p","wb")) pickle.dump(business_ids,open("business_ids.p","wb")) ''' pickle.dump(user_ids.p,open("user_ids.p","wb")) pickle.dump(stars,open("reviews.p","wb")) pickle.dump(stars,open("stars.p","wb")) pickle.dump(stars,open("training_items.p","wb")) pickle.dump(stars,open("test_items.p","wb")) pickle.dump(stars,open("training_ids.p","wb")) pickle.dump(stars,open("test_ids.p","wb")) pickle.dump(stars,open("pOG.p","wb")) pickle.dump(stars,open("bOG.p","wb")) for i in range(1,26): t1 = time.time() mmsbm.update(b,p,stars) t2 = time.time() print(t2-t1) print(b.node['LDfEWQRx2_Ijv_GyD38Abg']['eta-theta']) if i%5 == 0: pickle.dump(b,open("b80_"+str(i)+".p","wb")) pickle.dump(p,open("p80_"+str(i)+".p","wb")) ''' #print(b.nodes(data=True)) #for r in range(5): # print(p[r]) ''' count = 0 nodes = nx.get_node_attributes(b,'bipartite') print(nodes) for att in nodes: if nodes[att] == 0:# print(att)# == 1: count += 1 G.node[ ''' #print(count) #print(stars[('ajxohdcsKhRGFlEvHZDyTw', 'PSMJesRmIDmust2MUw7aQA')]) # nx.draw(b) # plt.show() #print(len(user_ids)) if __name__ == "__main__": main()
jonnymags/Networks-project
yelp.py
yelp.py
py
5,362
python
en
code
0
github-code
36
[ { "api_name": "collections.defaultdict", "line_number": 14, "usage_type": "call" }, { "api_name": "json.loads", "line_number": 20, "usage_type": "call" }, { "api_name": "collections.defaultdict", "line_number": 40, "usage_type": "call" }, { "api_name": "json.loads...
26626836853
import astropy.units as u from astropy.coordinates.sky_coordinate import SkyCoord from astropy.units import Quantity from astropy.table import Table from scipy import stats from matplotlib.colors import LogNorm import matplotlib.pyplot as plt import astropy.coordinates as asc import numpy as np import random import csv import os contour = np.genfromtxt("Data/OB-Katz-contour-0.1.dat", names = True, dtype=None) contour_id = contour['source_id'] readresults = Table.read("Data/OB-Katz.fits",format='fits') results = np.array(readresults) matches = np.array([]) j=0 for i in range(len(contour_id)): not_found = True while not_found: if contour_id[i]==results['source_id'][j]: matches = np.append(matches,j) not_found = False else: j+=1 newresults = np.append(results[int(matches[0])],results[int(matches[1])]) k = 2 while k <= len(matches)-1: newresults = np.append(newresults,results[int(matches[k])]) k+=1 results = newresults distances = 1000/results['parallax'] #Convert coordinates to galactic and then to cartesian. coordinates_ICRS = asc.SkyCoord(ra=results['ra']*u.degree, dec=results['dec']*u.degree, distance=distances*u.pc, pm_ra_cosdec=results['pmra']*u.mas/u.yr, pm_dec=results['pmdec']*u.mas/u.yr, frame='icrs', obstime='J2015.5') #coordinates_ICRS = asc.ICRS(ra=results['ra']*u.degree, dec=results['dec']*u.degree, distance=distances*u.pc, pm_ra_cosdec=results['pmra']*u.mas/u.yr, pm_dec=results['pmdec']*u.mas/u.yr) coordinates_galactic = coordinates_ICRS.galactic #coordinates_galactic = asc.SkyCoord(l=results['l']*u.degree, b=results['b']*u.degree, distance=distances*u.pc, pm_ra_cosdec=results['pmra']*u.mas/u.yr, pm_dec=results['pmdec']*u.mas/u.yr, radial_velocity=results['radial_velocity']*u.km/u.s, frame='galactic', obstime='J2015.5') #coordinates_galactic = asc.SkyCoord(l=results['l']*u.degree, b=results['b']*u.degree, distance=distances*u.pc, frame='galactic', obstime='J2015.5') coordinates_cartesian = np.column_stack((coordinates_galactic.cartesian.x.value, coordinates_galactic.cartesian.y.value, coordinates_galactic.cartesian.z.value)) x = coordinates_cartesian[:,0]#.filled(0) y = coordinates_cartesian[:,1]#.filled(0) z = coordinates_cartesian[:,2]#.filled(0) #counts,xbins,ybins,image = plt.hist2d(distances*(4.74 * 10**-3)*results['pmra'],distances*(4.74 * 10**-3)*results['pmdec'],bins=60,normed=True,norm=LogNorm(), cmap = 'Blues') #counts,xbins,ybins,image = plt.hist2d(results['pmra'],results['pmdec'],bins=40,normed=True,norm=LogNorm(),cmap = 'Blues') hb = plt.hexbin(distances*(4.74 * 10**-3)*results['pmra'], distances*(4.74 * 10**-3)*results['pmdec'], extent=(-50,50,-50,50), gridsize=80, bins='log', cmap = 'Blues') #hb = plt.hexbin(results['pmra'], results['pmdec'], gridsize=80, extent=(-50,50,-50,50), bins='log', cmap = 'Blues') plt.colorbar() #plt.contour(counts.transpose(), extent=[xbins.min(),xbins.max(),ybins.min(),ybins.max()], colors='k', linewidth=0.01), levels = [0.001]) #plt.text(-0.1, 10.0, 'Gaia DR1') plt.xlim(-50,50) plt.ylim(-50,50) plt.xlabel(r'$V_{Tra} \ (km/s)$') plt.ylabel(r'$V_{Tdec} \ (km/s)$') #plt.xlabel(r'$\mu_{ra} \ (mas/yr)$') #plt.ylabel(r'$\mu_{dec} \ (mas/yr)$') #plt.savefig('Proper-Motion-Katz-contour-0.1.png') plt.savefig('Tangential-Velocites-Katz-Contour-0.1.png')
spacer730/Gaia_research
Overdensities-Propermotion-Graph.py
Overdensities-Propermotion-Graph.py
py
3,287
python
en
code
0
github-code
36
[ { "api_name": "numpy.genfromtxt", "line_number": 14, "usage_type": "call" }, { "api_name": "astropy.table.Table.read", "line_number": 17, "usage_type": "call" }, { "api_name": "astropy.table.Table", "line_number": 17, "usage_type": "name" }, { "api_name": "numpy.a...
12954890166
#!/usr/bin/env python import os import re import sys import json import random import argparse from checks import cors from checks import cookie from core.requester import requester from core.colors import red, green, white, info, bad, end parser = argparse.ArgumentParser() parser.add_argument('-u', '--url', help='url', dest='url') parser.add_argument('--json', help='json output', dest='jsonOutput', action='store_true') args = parser.parse_args() def banner(): newText = '' text = '''\n\t{ meta v0.1-beta }\n''' for char in text: if char != ' ': newText += (random.choice([green, white]) + char + end) else: newText += char print (newText) with open(sys.path[0] + '/db/headers.json') as file: database = json.load(file) def information(headers): result = {} for header, value in headers.items(): if header in database.keys(): result[header] = database[header]['description'] return result def missing(headers): result = {} for header in database: if database[header]['security'] == 'yes': if header not in headers: result[header] = database[header]['description'] return result def misconfiguration(headers): result = {} if 'Access-Control-Allow-Origin' in headers: result['Access-Control-Allow-Origin'] = cors.check(args.url) if 'Set-Cookie' in headers: result['Set-Cookie'] = cookie.check(headers['Set-Cookie']) elif 'Cookie' in headers: result['Cookie'] = cookie.check(headers['Cookie']) return result headers = {} if args.url: headers = requester(args.url).headers else: banner() print ('%s No data to act upon.' % bad) quit() if not args.jsonOutput: banner() if headers: headerInformation = information(headers) missingHeaders = missing(headers) misconfiguration = misconfiguration(headers) if args.jsonOutput: jsoned = {} jsoned['information'] = headerInformation jsoned['missing'] = missingHeaders jsoned['misconfigurations'] = misconfiguration sys.stdout.write(json.dumps(jsoned, indent=4)) else: if headerInformation: print ('%s Header information\n' % info) print (json.dumps(headerInformation, indent=4)) if missingHeaders: print ('\n%s Missing Headers\n' % bad) print (json.dumps(missingHeaders, indent=4)) if missingHeaders: print ('\n%s Mis-configurations\n' % bad) print (json.dumps(misconfiguration, indent=4))
s0md3v/meta
meta.py
meta.py
py
2,604
python
en
code
37
github-code
36
[ { "api_name": "argparse.ArgumentParser", "line_number": 14, "usage_type": "call" }, { "api_name": "random.choice", "line_number": 24, "usage_type": "call" }, { "api_name": "core.colors.green", "line_number": 24, "usage_type": "name" }, { "api_name": "core.colors.w...
33210794674
from enum import Enum from typing import List import numpy as np import torch from nemo import logging from nemo.backends.pytorch.nm import DataLayerNM from nemo.core.neural_types import * __all__ = ['MultiDataLayer', 'DataCombination'] class DataCombination(Enum): CROSSPRODUCT = 1 ZIP = 2 class MultiDataLayer(DataLayerNM): def __init__( self, data_layers: List[DataLayerNM], batch_size: int, shuffle: bool = False, combination_mode: DataCombination = DataCombination.CROSSPRODUCT, port_names: List[str] = None, ): """ data_layers: (list) of DataLayerNM objects batch_size: (int) batchsize when the underlying dataset is loaded combination_mode: (DataCombination) defines how to combine the datasets. shuffle: (bool) whether underlying multi dataset should be shuffled in each epoch port_names: List(str) user can override all port names if specified """ super().__init__() self._data_layers = data_layers self._batch_size = batch_size self._shuffle = shuffle self._combination_mode = combination_mode self._port_names = port_names self._dataset = MultiDataset( datasets=[dl.dataset for dl in self._data_layers], combination_mode=combination_mode ) self._ports = dict() if self._port_names: i = 0 for dl in self._data_layers: for _, port_type in dl.output_ports.items(): self._ports[self._port_names[i]] = port_type i += 1 else: for dl_idx, dl in enumerate(self._data_layers): for port_name, port_type in dl.output_ports.items(): if port_name in self._ports: logging.warning(f"name collision {port_name}, will rename") self._ports[f"{port_name}_{dl_idx}"] = port_type else: self._ports[port_name] = port_type @property def output_ports(self): """Return: dict Returns union of all individual data_layer output ports In case of name collision, resolve by renaming """ return self._ports def __len__(self): return len(self._dataset) @property def dataset(self): return self._dataset @property def data_iterator(self): return None class MultiDataset(torch.utils.data.Dataset): def __init__( self, datasets: List[torch.utils.data.Dataset], combination_mode: DataCombination = DataCombination.CROSSPRODUCT, ): """ Datasets: list of torch.utils.data.Dataset objects. combination_mode: DataCombination, defines how to combine the datasets, Options are [DataCombination.CROSSPRODUCT, DataCombination.ZIP]. """ self.datasets = datasets self.combination_mode = combination_mode if self.combination_mode == DataCombination.CROSSPRODUCT: self.len = np.prod([len(d) for d in self.datasets]) elif self.combination_mode == DataCombination.ZIP: ds_lens = [len(d) for d in self.datasets] self.len = np.min(ds_lens) if len(set(ds_lens)) != 1: raise ValueError("datasets do not have equal lengths.") else: raise ValueError("combination_mode unknown") def __getitem__(self, i): """ Returns list [x1, x2, ...xn] where x1 \in D1, x2 \in D2, ..., xn \in Dn """ return [x for d in self.datasets for x in d[i % len(d)]] def __len__(self): """ Returns length of this dataset (int). In case of DataCombination.CROSSPRODUCT this would be prod(len(d) for d in self.datasets). In case of DataCombination.ZIP this would be min(len(d) for d in self.datasets) given that all datasets have same length. """ return self.len
cppxaxa/ICAN.ShapeShifter
ICAN.ShapeShifter.Worker/nemo/backends/pytorch/common/multi_data.py
multi_data.py
py
4,014
python
en
code
0
github-code
36
[ { "api_name": "enum.Enum", "line_number": 14, "usage_type": "name" }, { "api_name": "nemo.backends.pytorch.nm.DataLayerNM", "line_number": 19, "usage_type": "name" }, { "api_name": "typing.List", "line_number": 22, "usage_type": "name" }, { "api_name": "nemo.backe...
18132978929
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import numpy as np import re import matplotlib.pyplot as plt import keras from tensorflow import keras from keras.layers import Dense, SimpleRNN, Input, Embedding from keras.models import Sequential from keras.optimizers import Adam from keras.preprocessing.text import Tokenizer, text_to_word_sequence from keras.utils import to_categorical class WordsPredict: '''RNN для прогнозирования следующего слова в тексте. Для обучающей выборки мы из текста будем выделять слова целиком, а набор уникальных слов будет составлять наш словарь, размер которого будет определяться переменной max_words_count_in_dict, затем каждое слово будет кодироваться OneHot-вектором в соответствии с его номером в словаре, переменная inp_words будет содержать количество слов на основе которых будет строиться прогноз следующего слова''' def load_text(self): '''Метод для загрузки текста из ПК''' with open('/home/andrey/Machine_Learning/ML_practice/datasets/text_for_rnn/texsts_samples.txt', 'r', encoding='utf-8') as my_text: text = my_text.read() text = text.replace('\ufeff', '') # убираем первый невидимый символ return text def prepearing_data(self): '''Метод разбивки текста на отдельные слова с помощью Tokenizer, указывая, что у нас будет 20000 наиболее часто встречающихся слов в тексте, а остальные будут просто отброены сетью и она наних не будет обучаться, парметр filters удаляет все лишние символы из нашего текста, lower переврдит текст в нижний регистр, split - мы будем разбивать слова по пробелу, char_level=False потому что будем разбивать текст по словам, а не по символам.''' # указываем сколько максимум слов может быть у нас в словаре: max_words_count_in_dict = 2000 # создаем токенайзер tokenizer = Tokenizer(num_words=max_words_count_in_dict, filters='!-"-#$%amp;()*+,-./:;<=>?@[\\]^_`{|}~\t\n\r', lower=True, split=' ', char_level=False) # далее пропускаем наш текст через токенайзер (текст берем из метода load_data), # чтобы придать каждому слову свое число tokenizer.fit_on_texts(self.load_text()) # просмотр того, что у нас получается (для примера): # my_dict = list(tokenizer.word_counts.items()) # print(my_dict[:10]) # далее мы преобразовываем текст в последовательность чисел в соответствии # с полученным словарем, т.е. мы берем каждое отдельное слова в тексте # и на место этого слова ставим то число(индекс), которое соответствует этому слову: data = tokenizer.texts_to_sequences([self.load_text()]) # далее преобразуем эту последовательность в OneHotEncoding-векторы (0 и 1): # result = to_categorical(data[0], num_classes=max_words_count_in_dict) result=np.array(data[0]) # далее на основе коллекции result мы формируем 3-мерный тензор, # который у нас должен быть в обучающей выборке # Мы будем брать первые 3 слова и далее прогнозировать следующее слово, # потом мы смещаемся на 1 элемент вперед и повторяем операцию. input_words = 3 n = result.shape[0] - input_words # т.к. мы прогнозируем по трем словам четвертое # создаем тренировочную выборку: train = np.array([result[i:i + input_words] for i in range(n)]) # строим целевую выборку: target = to_categorical(result[input_words:], num_classes=max_words_count_in_dict) return train, target, input_words, n, max_words_count_in_dict, tokenizer def __init__(self): train, target, input_words, n, max_words_count_in_dict, tokenizer = self.prepearing_data() self.model = keras.Sequential([ Embedding(max_words_count_in_dict,512,input_length=input_words), SimpleRNN(256, activation='tanh'), Dense(max_words_count_in_dict, activation='softmax') ]) self.model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) self.history=self.model.fit(train, target, batch_size=32, epochs=100, validation_split=0.2) def CreateText(self, text, len_text=10): '''Метод для составления текста''' # текст пользователя, который он вводит result = text tokenizer = self.prepearing_data()[5] input_words = self.prepearing_data()[2] max_words_in_dict = self.prepearing_data()[4] # преобразовываем слова в последовательность чисел в тексте data = tokenizer.texts_to_sequences([text])[0] for i in range(len_text): # формируем слова на основе которых делаем прогноз следующего слова: # преобразовываем коллекцию data в векторы OneHotEncoding с 0 и 1: # OHE_vectors = to_categorical(data[i:i + input_words], num_classes=max_words_in_dict) # # создаем формат коллекции, которая подходит для подачи на RNN # collection = OHE_vectors.reshape(1, input_words, max_words_in_dict) #на вход НС будем подавать тензор из цифр digits = data[i:i + input_words] collection = np.expand_dims(digits, axis=0) # затем пропускаем эту коллекцию слов через нашу обученную модель: predict_words = self.model.predict(collection) # выбираем индекс с максимальным значением из коллекции слов predict_words: get_index = predict_words.argmax(axis=1)[0] # добавляем это слово в последовательность слов в тексте data data.append(get_index) # далее преобразовываем индекс обратно в слово и добавляем к тексту пользователя: result += ' ' + tokenizer.index_word[get_index] return result def MakePhrase(self,user_text,tex_length=10): result=user_text tokenizer = self.prepearing_data()[5] input_words = self.prepearing_data()[2] max_words_in_dict = self.prepearing_data()[4] data=tokenizer.texts_to_sequences([user_text])[0] for i in range(tex_length): # x=to_categorical(data[i:i+input_words],num_classes=max_words_in_dict) # inp=x.reshape(1,input_words,max_words_in_dict) #создаем список уже из индексов, а не из OHE-векторов digs_list=data[i:i+input_words] #добавляем ось input_collection=np.expand_dims(digs_list, axis=0) #делаем предсказание по обученной модели prediction=self.model.predict(input_collection) #ыбираем максимальное значение index=prediction.argmax(axis=1)[0] #добавляем в текст пользователя data.append(index) result+=' '+tokenizer.index_word[index] return result def show_acc_loss_during_learn_graphics(self): '''Выведем графики точности и потерь при обучении RNN''' acc = self.history.history['accuracy'] val_acc = self.history.history['val_accuracy'] loss = self.history.history['loss'] val_loss = self.history.history['val_loss'] epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() user = WordsPredict() print(user.MakePhrase('я люблю виски')) user.show_acc_loss_during_learn_graphics()
Sautenko-Andrey/ML_practice
RNN_words_predict.py
RNN_words_predict.py
py
9,910
python
ru
code
0
github-code
36
[ { "api_name": "os.environ", "line_number": 3, "usage_type": "attribute" }, { "api_name": "keras.preprocessing.text.Tokenizer", "line_number": 48, "usage_type": "call" }, { "api_name": "numpy.array", "line_number": 67, "usage_type": "call" }, { "api_name": "numpy.a...
25014074159
from collections import defaultdict import yaml import json def redial_config(path,data_type): def _entity_kg_process(opt, SELF_LOOP_ID=185): edge_list = [] # [(entity, entity, relation)] for entity in range(opt['n_entity']): if str(entity) not in opt['entity_kg']: continue edge_list.append((entity, entity, SELF_LOOP_ID)) # add self loop for tail_and_relation in opt['entity_kg'][str(entity)]: if entity != tail_and_relation[1] and tail_and_relation[0] != SELF_LOOP_ID: edge_list.append((entity, tail_and_relation[1], tail_and_relation[0])) edge_list.append((tail_and_relation[1], entity, tail_and_relation[0])) relation_cnt, relation2id, edges, entities = defaultdict(int), dict(), set(), set() for h, t, r in edge_list: relation_cnt[r] += 1 for h, t, r in edge_list: if relation_cnt[r] > 1000: if r not in relation2id: relation2id[r] = len(relation2id) edges.add((h, t, relation2id[r])) entities.add(opt['id2entity'][h]) entities.add(opt['id2entity'][t]) return { 'edge': list(edges), 'n_relation': len(relation2id), 'entity': list(entities) } def _word_kg_process(opt): edges = set() # {(entity, entity)} entities = set() with open(opt['word_kg'],'r') as f: for line in f: kg = line.strip().split('\t') entities.add(kg[1].split('/')[0]) entities.add(kg[2].split('/')[0]) e0 = opt['word2id'][kg[1].split('/')[0]] e1 = opt['word2id'][kg[2].split('/')[0]] edges.add((e0, e1)) edges.add((e1, e0)) # edge_set = [[co[0] for co in list(edges)], [co[1] for co in list(edges)]] return { 'edge': list(edges), 'entity': list(entities) } config_dict = dict() with open(path, 'r', encoding='utf-8') as f: config_dict.update(yaml.safe_load(f.read())) with open(config_dict[data_type]['movie_ids_path'],'r') as f: movie_ids = json.load(f) config_dict['movie_ids'] = movie_ids with open(config_dict[data_type]['entity2id_path'],'r') as f: entity2id = json.load(f) with open(config_dict[data_type]['entity_kg_path'],'r') as f: entity_kg = json.load(f) with open(config_dict[data_type]['token2id_path'],'r') as f: token2id = json.load(f) with open(config_dict[data_type]['word2id_path'],'r') as f: word2id = json.load(f) config_dict['graph'] = {} config_dict['graph']['word_kg'] = config_dict[data_type]['concept_kg_path'] config_dict['graph']['entity2id'] = entity2id config_dict['graph']['token2id'] = token2id config_dict['graph']['word2id'] = word2id config_dict['graph']['entity_kg'] = entity_kg config_dict['graph']['id2entity'] = {idx: entity for entity, idx in entity2id.items()} config_dict['graph']['n_entity'] = max(entity2id.values()) + 1 config_dict['graph']['n_word'] = max(word2id.values()) + 1 entity_kg_dict = _entity_kg_process(config_dict['graph']) word_kg_dict = _word_kg_process(config_dict['graph']) config_dict['graph']['entity_kg'] = entity_kg_dict config_dict['graph']['word_kg'] = word_kg_dict return config_dict
Oran-Ac/LOT-CRS
src/utils/config.py
config.py
py
3,493
python
en
code
1
github-code
36
[ { "api_name": "collections.defaultdict", "line_number": 16, "usage_type": "call" }, { "api_name": "yaml.safe_load", "line_number": 50, "usage_type": "call" }, { "api_name": "json.load", "line_number": 52, "usage_type": "call" }, { "api_name": "json.load", "lin...
17811464587
import boto3 from pprint import pprint import time aws_console=boto3.session.Session() ec2_console=aws_console.resource('ec2', region_name='us-east-1') # #ec2_console.start_instances(instance_id=['i-06186ed7e182cc28b']) # response=ec2_console.describe_instances(InstanceIds=['i-06186ed7e182cc28b']) # #pprint(response) # #print(response['Reservations']) # for each_iteam in (response['Reservations']): # print("########################") # pprint(each_iteam) my_inst=ec2_console.Instance("i-06186ed7e182cc28b") print("Starting given instance") my_inst.start() while True: my_inst_obj=ec2_console.Instance("i-06186ed7e182cc28b") print(f"The current state of ec2: {my_inst_obj.state['Name']}") if my_inst_obj.state['Name'] == "running": break print("Wating instance to be up") time.sleep(5) print("instance is up and running")
SachinPitale/AWS_Lambda
05-waiters/01-ec2-status.py
01-ec2-status.py
py
868
python
en
code
0
github-code
36
[ { "api_name": "boto3.session.Session", "line_number": 6, "usage_type": "call" }, { "api_name": "boto3.session", "line_number": 6, "usage_type": "attribute" }, { "api_name": "time.sleep", "line_number": 27, "usage_type": "call" } ]
11194223295
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Use this to execute the differential kinematics controller in our kinecontrol paper. ''' from __future__ import print_function import Sofa import math import sys, os import time import logging import datetime import numpy as np from utils import * from config import * from matplotlib import pyplot as plt import matplotlib.gridspec as gridspec logger = logging.getLogger(__name__) # generate sinusoid trajectory for head t, x = gen_sinusoid(amp=.8, freq=2, phase=30, interval=[0.1, 1, 0.01]) # https://www.sofa-framework.org/community/forum/topic/get-the-position-value-from-a-mechanicalobject-point-in-python/ def moveRestPos(rest_pos, pose): str_out = ' ' dx, dy, dz = pose for i in range(0,len(rest_pos)) : str_out= str_out + ' ' + str(rest_pos[i][0]+dx) str_out= str_out + ' ' + str(rest_pos[i][1]+dy) str_out= str_out + ' ' + str(rest_pos[i][2]+dz) return str_out def rotateRestPos(rest_pos,rx,centerPosY,centerPosZ): str_out = ' ' for i in xrange(0,len(rest_pos)) : newRestPosY = (rest_pos[i][1] - centerPosY)*math.cos(rx) - (rest_pos[i][2] - centerPosZ)*math.sin(rx) + centerPosY newRestPosZ = (rest_pos[i][1] - centerPosY)*math.sin(rx) + (rest_pos[i][2] - centerPosZ)*math.cos(rx) + centerPosZ str_out= str_out + ' ' + str(rest_pos[i][0]) str_out= str_out + ' ' + str(newRestPosY) str_out= str_out + ' ' + str(newRestPosZ) return str_out class controller(Sofa.PythonScriptController): ''' For examples, see: + Keyboard Control: - https://github.com/lakehanne/sofa/blob/master/examples/Tutorials/StepByStep/Dentistry_Python/keyboardControl.py + Parallel and SSH Launcher: - https://github.com/lakehanne/sofa/blob/master/tools/sofa-launcher/launcher.py + OneParticle: - https://github.com/lakehanne/sofa/blob/master/tools/sofa-launcher/example.py ''' def initGraph(self, root): self.move_dist = move_dist #(0, .40, 0) self.growth_rate = growth_rate #.5 #was .05 self.max_pressure = max_pressure #100 # was 15 # controls if IABs should continue to be inflated in a open-loop setting self.is_inflated = True self.deltaTime = root.findData('dt').value # print('deltaTime ', self.deltaTime, type(self.deltaTime)) self._fig = plt.figure() self._gs = gridspec.GridSpec(1,1) # rows cols self.traj_plotter = HeadTrajPlotter(self._fig, self._gs[0]) # subplot in gridspec self.patient = root.getChild('patient') self.patient_dofs = self.patient.getObject('patient_dofs') pat_rest_pose = self.patient_dofs.findData('rest_position').value self.thresholds = thresholds self.first_iter = True self.root = root logger.debug('patient initial pose {}'.format(thresholds['patient_trans'])) # get base IABs self.base_neck_left = root.getChild('base_neck_left') self.base_neck_right = root.getChild('base_neck_right') self.base_skull_left = root.getChild('base_skull_left') self.base_skull_right = root.getChild('base_skull_right') # get side IABs self.side_fore_left = root.getChild('side_fore_left') self.side_chin_left = root.getChild('side_chin_left') self.side_fore_right = root.getChild('side_fore_right') self.side_chin_right = root.getChild('side_chin_right') # obtain associated dofs and cavity dofs self.base_neck_left_dofs = self.get_dome_dofs(self.base_neck_left) self.base_neck_right_dofs = self.get_dome_dofs(self.base_neck_right) self.base_skull_left_dofs = self.get_dome_dofs(self.base_skull_left) self.base_skull_right_dofs = self.get_dome_dofs(self.base_skull_right) self.is_chart_updated = False # use this to track the x, y and z positions of the patient over time self._x, self._y, self._z = [], [], [] # visualization display_chart(self.run_traj_plotter) # plt.ioff() # plt.show() # io self._pat_dofs_filename = patient_dofs_filename self.max_vals = 0 # maximum positional values in the patient # domes' mechanical states def get_dome_dofs(self, node): 'dof name shall be in the form patient or base_neck etc' dh_dofs = node.getObject('dh_dofs') # dome head # dh_collis_dofs = node.getObject('dh_collis_dofs') # cavity cav_node = node.getChild('DomeCavity') cav_dofs = cav_node.getObject('dome_cav_dofs') pressure_constraint = cav_node.getObject('SurfacePressureConstraint') # pressure_constraint_collis = node.getChild('dome_cav_collis_dofs') # dome cover back cover_node = node.getChild('DomeCover') cover_dofs = cover_node.getObject('dome_cover_dofs') # cover collis node cover_collis_node = node.getChild('DomeCoverCollis') cover_collis_dofs = cover_collis_node.getObject('dome_cover_collis_dofs') return Bundle(dict(dh_dofs=dh_dofs, cav_dofs=cav_dofs, pressure_constraint=pressure_constraint, # cavity cover_dofs=cover_dofs, cover_collis_dofs=cover_collis_dofs)) def bwdInitGraph(self,node): # find the position at the end of the shape (which has the biggest x coordinate) # Positions = self.patient_dofs.findData('position').value Positions = self.patient_dofs.position#.value max_x, max_y, max_z = 0, 0, 0 max_idx_x, max_idx_y, max_idx_z = 0, 0, 0 for i in range(len(Positions)): if Positions[i][0] > max_x: max_idx_x = i max_x = Positions[i][0] if Positions[i][1] > max_y: max_idx_y = i max_y = Positions[i][1] if Positions[i][2] > max_z: max_idx_z = i max_z = Positions[i][2] # max_ids = Bundle(dict(max_idx_x=max_idx_x, max_idx_y=max_idx_y, max_idx_z=max_idx_z, position=Positions)) self.max_vals = Bundle(dict(max_x=max_x, max_y=max_y, max_z=max_z)) # print('max x,y,z indices: {}, {}, {}'.format(max_idx_x, max_idx_y, max_idx_z)) print('patient positions [x,y,z] {}, {}, {}'.format(max_x, max_y, max_z)) return 0 def run_traj_plotter(self): if self.is_chart_updated: self.traj_plotter.update(self.data) # time.sleep(.11) self.is_chart_updated = False def update_head_pose(self): rest_pose = self.patient_dofs.findData('rest_position').value # rest pose is a lisrt x, y, z = [t[0] for t in rest_pose], [t[1] for t in rest_pose], [t[2] for t in rest_pose] # use 2-norm of x, y, and z self.data = np.linalg.norm(np.c_[x, y, z], axis=0) self.is_chart_updated = True def onBeginAnimationStep(self, deltaTime): self.deltaTime += deltaTime # repopulate each iab at each time step self.base_neck_left = self.root.getChild('base_neck_left') self.base_neck_right = self.root.getChild('base_neck_right') self.base_skull_left = self.root.getChild('base_skull_left') self.base_skull_right = self.root.getChild('base_skull_right') # get side IABs self.side_fore_left = self.root.getChild('side_fore_left') self.side_chin_left = self.root.getChild('side_chin_left') self.side_fore_right = self.root.getChild('side_fore_right') self.side_chin_right = self.root.getChild('side_chin_right') # obtain associated dofs and cavity dofs self.base_neck_left_dofs = self.get_dome_dofs(self.base_neck_left) self.base_neck_right_dofs = self.get_dome_dofs(self.base_neck_right) self.base_skull_left_dofs = self.get_dome_dofs(self.base_skull_left) self.base_skull_right_dofs = self.get_dome_dofs(self.base_skull_right) # self.patient = self.root.getChild('patient') self.patient_dofs = self.patient.getObject('patient_dofs') if self.first_iter: rest_pat_pose = np.array([self.max_vals.max_x, self.max_vals.max_y, self.max_vals.max_z]) self.thresholds['patient_trans'] = rest_pat_pose self.thresholds['patient_trans'][0] += 100 self.thresholds['patient_trans'][1] += 100 self.thresholds['patient_trans'][2] += 100 self.thresholds.update(self.thresholds) logger.debug('rest_pat_pose: {}, '.format(rest_pat_pose)) self.first_iter = False curr_pat_pose = np.array([self.max_vals.max_x, self.max_vals.max_y, self.max_vals.max_z]) if curr_pat_pose[0]<self.thresholds['patient_trans'][0]: # not up to desired z pose = (self.growth_rate, 0, 0) test1 = moveRestPos(self.patient_dofs.findData('rest_position').value, pose) self.patient_dofs.findData('rest_position').value = test1 self.patient_dofs.position = test1 self._x.append(self.max_vals.max_x) # not up to desired z # if curr_pat_pose[2]>=self.thresholds['patient_trans'][2] and \ # curr_pat_pose[1]<self.thresholds['patient_trans'][1]: # logger.warning('moving along y now') # pose = (0.0, self.growth_rate, 0.0) # test1 = moveRestPos(self.patient_dofs.position, pose) # # self.patient_dofs.findData('rest_position').value = test1 # self.patient_dofs.position = test1 # self._y.append(self.max_vals.max_y) # if curr_pat_pose[2]>=self.thresholds['patient_trans'][2] and \ # curr_pat_pose[1]>=self.thresholds['patient_trans'][1] and \ # curr_pat_pose[0]<self.thresholds['patient_trans'][0]: # logger.warning(' moving along x now') # pose = (self.growth_rate, 0.0, 0.0) # test1 = moveRestPos(self.patient_dofs.position, pose) # # self.patient_dofs.findData('rest_position').value = test1 # self.patient_dofs.position = test1 # self._x.append(self.max_vals.max_x) # pose = (0, 0, self.growth_rate) # self._x.append(self.max_vals.max_x) # self._y.append(self.max_vals.max_y) # self._z.append(self.max_vals.max_z) # save what you got and end simulation #curr_pat_pose[2]>=self.thresholds['patient_trans'][2] and \ #curr_pat_pose[1]>=self.thresholds['patient_trans'][1] and \ if curr_pat_pose[0]>=self.thresholds['patient_trans'][0]: stab_val= self._x[-1] for i in range(len(self._x)*4): self._x.append(stab_val) with open(self._pat_dofs_filename, 'a') as foo: arr_to_save = np.array([self._x]) np.savetxt(foo, arr_to_save, delimiter=' ', fmt='%1.4e') # with open(self._pat_dofs_filename+'_ref.txt', 'a') as foo: # np.savetxt(foo, self.thresholds['patient_trans'], delimiter=' ', fmt='%1.4e') self.root.getRootContext().animate = False # os._exit() return 0; def onEndAnimationStep(self, deltaTime): sys.stdout.flush() #access the 'position' state vector pat_poses = self.patient_dofs.findData('position').value self.bwdInitGraph(self.root) return 0; def onLoaded(self, node): return 0; def reset(self): ## Please feel free to add an example for a simple usage in /home/lex/catkin_ws/src/superchicko/sofa/python/xml_2_scn.py return 0; def onMouseButtonMiddle(self, mouseX,mouseY,isPressed): # usage e.g. if isPressed : print("Control+Middle mouse button pressed at position "+str(mouseX)+", "+str(mouseY)) return 0; def onScriptEvent(self, senderNode, eventName,data): ## Please feel free to add an example for a simple usage in /home/lex/catkin_ws/src/superchicko/sofa/python/xml_2_scn.py return 0; def onMouseButtonRight(self, mouseX,mouseY,isPressed): ## usage e.g. if isPressed : print("Control+Right mouse button pressed at position "+str(mouseX)+", "+str(mouseY)) return 0; def onMouseButtonLeft(self, mouseX,mouseY,isPressed): ## usage e.g. if isPressed : print("Control+Left mouse button pressed at position "+str(mouseX)+", "+str(mouseY)) return 0;
robotsorcerer/superchicko
sofa/python/kinecontrol/diff_kine_controller.py
diff_kine_controller.py
py
11,135
python
en
code
0
github-code
36
[ { "api_name": "logging.getLogger", "line_number": 22, "usage_type": "call" }, { "api_name": "math.cos", "line_number": 40, "usage_type": "call" }, { "api_name": "math.sin", "line_number": 40, "usage_type": "call" }, { "api_name": "math.sin", "line_number": 41,...
8472917150
#!/usr/bin/python3 ## ## import os,sys,re import requests import time # Global variables BASE_URL = "https://api.thousandeyes.com" USERNAME = "your_username" PASSWORD = "your_password" API_TOKEN = None def get_api_token(): global API_TOKEN auth_endpoint = BASE_URL + "/v6/auth/login" data = { "username": USERNAME, "password": PASSWORD } try: response = requests.post(auth_endpoint, json=data) response.raise_for_status() token = response.json().get("token") if token: API_TOKEN = token print("New API token obtained.") else: print("Failed to obtain API token.") except requests.exceptions.RequestException as e: print("Error occurred during API token retrieval:", e) def revoke_api_token(): global API_TOKEN if API_TOKEN: revoke_endpoint = BASE_URL + "/v6/auth/logout" headers = { "Authorization": "Bearer " + API_TOKEN } try: response = requests.post(revoke_endpoint, headers=headers) response.raise_for_status() print("API token revoked.") API_TOKEN = None except requests.exceptions.RequestException as e: print("API token revocation failed:", e) def test_api_token(): if API_TOKEN: test_endpoint = BASE_URL + "/v6/account" headers = { "Authorization": "Bearer " + API_TOKEN } try: response = requests.get(test_endpoint, headers=headers) response.raise_for_status() print("API token is still valid.") except requests.exceptions.RequestException as e: print("API token test failed:", e) get_api_token() else: print("API token is not available. Please obtain a new token.") def main(): while True: test_api_token() time.sleep(300) # Sleep for 5 minutes (300 seconds) revoke_api_token() get_api_token() test_api_token() time.sleep(120) # Sleep for 2 minutes (120 seconds) if __name__ == "__main__": get_api_token() main() ## ## ## ## In this updated script, I've added two additional functions: ## ## revoke_api_token(): Revokes the current API token by making a POST request to the /auth/logout endpoint. ## main(): The main function now includes the revocation process. After testing the API token every 5 minutes, it revokes the token, obtains a new one, and tests the new token again. ##
babywyrm/sysadmin
pyth3/api/check_revoke_.py
check_revoke_.py
py
2,547
python
en
code
10
github-code
36
[ { "api_name": "requests.post", "line_number": 26, "usage_type": "call" }, { "api_name": "requests.exceptions", "line_number": 34, "usage_type": "attribute" }, { "api_name": "requests.post", "line_number": 47, "usage_type": "call" }, { "api_name": "requests.excepti...
3650201755
import random from users import users from random import randrange from datetime import timedelta,datetime #LEVEL TIMESTAMP METHOD API STATUS USERID def random_date(start= datetime.now()-timedelta(days=120), end=datetime.now()): """ This function will return a random datetime between two datetime objects. """ delta = end - start int_delta = (delta.days * 24 * 60 * 60) + delta.seconds random_second = randrange(int_delta) return str(start + timedelta(seconds=random_second)) api_list = [ '/api/cart','/api/order','/api/products/{0}/coupons','/api/users/profile','/api/login','/api/logout' ] status_codes = [ 500,200,202,400,404,301,308,401,403,405,408,409,502 ] method = ['GET', 'POST', 'DELETE','PUT'] statuscodelength = len(status_codes) - 1 apilistlength = len(api_list) - 1 userslength = len(users) - 1 methodlength=len(method) - 1 logs = [] for i in range(0,500000): randomuser=users[random.randint(0,userslength)] randomstatus=status_codes[random.randint(0,statuscodelength)] randomapi=api_list[random.randint(0,apilistlength)] randommethod=method[random.randint(0,methodlength)] if randomapi == '/api/products/{0}/coupons': randomapi = '/api/products/{0}/coupons'.format(random.randint(1000,200000)) if randomstatus in [200,202]: randomloglevel='INFO' elif randomstatus in [400,404,301,308,401,403,405,408,409]: randomloglevel='WARNING' else: randomloglevel='ERROR' logrow='{0} {1} {2} {3} {4} {5}'.format(randomloglevel,random_date(),randommethod,randomapi,randomstatus,randomuser['id']) logs.append(logrow) with open('server.log', 'w') as f: for line in logs: f.write(f"{line}\n")
Prashantpx-17237/Datahub
datascripts/serverlog.py
serverlog.py
py
1,666
python
en
code
0
github-code
36
[ { "api_name": "datetime.datetime.now", "line_number": 8, "usage_type": "call" }, { "api_name": "datetime.datetime", "line_number": 8, "usage_type": "name" }, { "api_name": "datetime.timedelta", "line_number": 8, "usage_type": "call" }, { "api_name": "random.randra...
8128484100
import electra_class from transformers import ElectraForQuestionAnswering, ElectraTokenizer model_name = "ahotrod/electra_large_discriminator_squad2_512" model = ElectraForQuestionAnswering.from_pretrained(model_name) tokenizer = ElectraTokenizer.from_pretrained(model_name) while(True): context = input("Enter Target Filename for BERT:\n") if context == "exit": break if context[:13] != "MinecraftWiki/": context = "MinecraftWiki/" + context if context[-4:] != ".txt": context += ".txt" while(True): query = input("JARVIS online. What would you like to know?\n") if query == "exit": break answer, score = electra_class.answerfromwebpage(query, context, model, tokenizer) print("Answer: " + answer)
gale2307/Jarvis
electra_test.py
electra_test.py
py
754
python
en
code
1
github-code
36
[ { "api_name": "transformers.ElectraForQuestionAnswering.from_pretrained", "line_number": 5, "usage_type": "call" }, { "api_name": "transformers.ElectraForQuestionAnswering", "line_number": 5, "usage_type": "name" }, { "api_name": "transformers.ElectraTokenizer.from_pretrained", ...
27668133159
import os from PIL import Image def resize_image(path, new_path, width, height, crop_center=True): '''Image resizing and saving to new path''' original_image = Image.open(path) image = original_image if not crop_center else crop_center_image( original_image) new_image = image.resize((width, height)) full_path = os.path.join(new_path, 'icon') new_image.save("{}-{}.{}".format(full_path, str(width), 'png')) def crop_center_image(image, new_width=None, new_height=None): '''Crop the center of an image''' width, height = image.size # Get dimensions if (new_width is None or new_height is None): if width >= height: # landscape crop new_width, new_height = height, height else: # portrait crop new_width, new_height = width, width left = (width - new_width) / 2 top = (height - new_height) / 2 right = (width + new_width) / 2 bottom = (height + new_height) / 2 image = image.crop((left, top, right, bottom)) return image def generate_icons(image, path, sizes=(32, 57, 76, 96, 128, 228)): for size in sizes: resize_image(image, path, size, size)
jonathanrodriguezs/image-resizer
image_resizer.py
image_resizer.py
py
1,177
python
en
code
0
github-code
36
[ { "api_name": "PIL.Image.open", "line_number": 7, "usage_type": "call" }, { "api_name": "PIL.Image", "line_number": 7, "usage_type": "name" }, { "api_name": "os.path.join", "line_number": 11, "usage_type": "call" }, { "api_name": "os.path", "line_number": 11, ...
20324223182
from pymongo import MongoClient def get_db(database): """ A quick way to get MongoDb Client link """ clientmg=MongoClient() db=clientmg[database] return db db=get_db("foundation") plist=db.process.find({},{"price":1,"qtt":2}) for p in plist: ttlamt=float(float(p["price"])*float(p["qtt"])) db.process.update({"_id":p["_id"]},{"$set":{"ttlamt":ttlamt}},upsert=True)
raynardj/terminus
major/mongo/pricefloat.py
pricefloat.py
py
372
python
en
code
0
github-code
36
[ { "api_name": "pymongo.MongoClient", "line_number": 6, "usage_type": "call" } ]
22811929801
from flask import Flask, render_template from gevent.pywsgi import WSGIServer from strategy_thread import StrategyThread import atexit from apscheduler.schedulers.background import BackgroundScheduler from copy import deepcopy import time import pandas as pd ########################################################### ### Static Variables ########################################################### cols = ["Ticker", "Direction", "Status", "State", "Last Update", "Candle Size", "Avg Filled Price", "Take Profit Price", "Soft Stop Price", "Initiated Time", "Execution Time", "Execution Logic", "Drawdown", "Run Up", "Trade Length", "Quantity", "Filled Position"] app = Flask(__name__) ########################################################### ### UI Events ########################################################### def get_table(): if len(strat.strategy.manager.trades) == 0: return pd.DataFrame(columns=cols).to_html() start = time.time() trades = [] for ticker in strat.strategy.manager.trades: trades.append(strat.strategy.manager.trades[ticker].simple_view()) df = pd.DataFrame(trades) df = df[cols] df.sort_values('Status', inplace=True) return df.to_html(classes=["table", "table-hover", "thead-dark"]) def get_health(): colors = ["#14ba14", "#ede91a", "#ef1010"] ## 2103, 2104, 2108 manager_data_code = strat.strategy.manager.last_data_code manager_color = min(manager_data_code - 2104, 1) manager_color = colors[manager_color] ## 2105, 2106, 2107 scanner_data_code = strat.strategy.scanner.last_data_code scanner_color = scanner_data_code - 2106 scanner_color = colors[scanner_color] colors = [colors[-1], colors[0]] api_code = int(strat.strategy.manager.isConnected() & strat.strategy.scanner.isConnected()) api_color = colors[api_code] return { "manager" : manager_color, "scanner" : scanner_color, "api" : api_color } @app.after_request def after_request(response): response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, public, max-age=0" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response @app.route('/') def dashboard(): ## Positions position_table = get_table() ## System Health system_health = get_health() return render_template("index.html", position_table = position_table, system_health = system_health) if __name__ == '__main__': try: strat = StrategyThread(num_periods = 50, short_num_periods = 20, time_period = 5) strat.start() http_server = WSGIServer(('0.0.0.0', 9095), app) http_server.serve_forever() except Exception as e: print('EEE', e) strat.on_close() strat.join() finally: strat.on_close() strat.join()
zQuantz/Logma
ibapi/ui/retrace.py
retrace.py
py
2,714
python
en
code
0
github-code
36
[ { "api_name": "flask.Flask", "line_number": 22, "usage_type": "call" }, { "api_name": "pandas.DataFrame", "line_number": 30, "usage_type": "call" }, { "api_name": "time.time", "line_number": 32, "usage_type": "call" }, { "api_name": "pandas.DataFrame", "line_n...
22767714265
import sys import random import numpy as np import networkx as nx import matplotlib.pyplot as plt ################################################################################################################################## ################################################################################################################################## ### CÁLCULO DE DISTANCIAS ENTRE DOS ELEMENTOS DE UNA REJILLA CUADRADA BIDIMENSIONAL DOTADA DE CONDICIONTES DE FRONTERA PERIÓDICAS def calc_dist(loc1, loc2, longitud): distx = loc1[0] - loc2[0] disty = loc1[1] - loc2[1] dist1 = (distx ** 2 + disty ** 2) ** (1 / 2) dist2 = ((distx - longitud) ** 2 + disty ** 2) ** (1 / 2) dist3 = ((distx + longitud) ** 2 + disty ** 2) ** (1 / 2) dist4 = (distx ** 2 + (disty - longitud) ** 2) ** (1 / 2) dist5 = (distx ** 2 + (disty + longitud) ** 2) ** (1 / 2) dist6 = ((distx + longitud) ** 2 + (disty + longitud) ** 2) ** (1 / 2) dist7 = ((distx - longitud) ** 2 + (disty + longitud) ** 2) ** (1 / 2) dist8 = ((distx - longitud) ** 2 + (disty - longitud) ** 2) ** (1 / 2) dist9 = ((distx + longitud) ** 2 + (disty - longitud) ** 2) ** (1 / 2) lista_distancias = [dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9] distancia = min(lista_distancias) return distancia ### INICIACIÓN DE GRÁFICA PARA SISTEMA CML def ini_graf(longitud): grafica = nx.Graph() # Definición de nodos num_sitios = longitud ** 2 for sitio in range(num_sitios): grafica.add_node(sitio, u = random.uniform(-1, 1)) # Definición de bordes lista_edges = [] for sitio1 in range(num_sitios): for sitio2 in range(num_sitios): if sitio2 == sitio1: continue coord1 = (sitio1 % longitud, sitio1 // longitud) coord2 = (sitio2 % longitud, sitio2 // longitud) distancia = calc_dist(coord1, coord2, longitud) lista_edges.append((sitio1, sitio2, {'path_distance': distancia})) grafica.add_edges_from(lista_edges) return grafica ### CÁLCULO DE PRIMEROS VECINOS DE UN NODO EN UNA GRÁFICA CON BORDES DOTADOS DE ATRIBUTOS EQUIVALENTES A LAS DISTANCIAS ENTRE LOS SITIOS QUE LOS DEFINEN def primeros_vecinos(grafica, nodo): # Lista de posibles distancias lista_dist = [] for vec1, datos1 in grafica.adj[nodo].items(): for keys1, dists1 in datos1.items(): lista_dist.append(dists1) min_dist = min(lista_dist) # Lista de sitios a distancia mínima (primeros vecinos) lista_1v = [] for vec2, datos2 in grafica.adj[nodo].items(): for keys2, dists2 in datos2.items(): if dists2 == min_dist: lista_1v.append(vec2) return lista_1v ### MAPEO PHI def phi(valor_t): if -1 <= valor_t < -1 / 3.: valor_tt = (-3 * valor_t) - 2 elif -1 / 3. <= valor_t < 1 / 3.: valor_tt = 3 * valor_t elif 1 / 3. <= valor_t <= 1: valor_tt = (-3 * valor_t) + 2 return valor_tt ### EVOLUCIÓN TEMPORAL DE LA GRÁFICA def ev_temp(num_iter, trans, x0, g_acople, grafica, lista_1vecinos, guardar): print('INICIO DE EVOLUCION TEMPORAL') lista_sitios = list(grafica.nodes()) tenth_progress = int(num_iter / 10) # Guardar evolución de 'u' if guardar == True: arr_promtemp = np.zeros((num_iter - trans)) for iteracion1 in range(num_iter): if iteracion1 % tenth_progress == 0: print('*') # Gráfica auxiliar con valores de 'u' de siguiente iteración grafica_holder1 = nx.Graph() for sitio1a in lista_sitios: grafica_holder1.add_node(sitio1a, u = 0) sum1vec1 = 0 for vecino1 in lista_1vecinos[sitio1a][1]: dif_u1 = phi(grafica.nodes[vecino1]['u']) - phi(grafica.nodes[sitio1a]['u']) sum1vec1 = sum1vec1 + dif_u1 grafica_holder1.nodes[sitio1a]['u'] = phi(grafica.nodes[sitio1a]['u']) + g_acople * sum1vec1 # Actualización de gráfica "original" for sitio1b in lista_sitios: grafica.nodes[sitio1b]['u'] = grafica_holder1.nodes[sitio1b]['u'] if iteracion1 <= trans - 1: continue arr_promtemp[iteracion1 - trans] = grafica.nodes[x0]['u'] print('FIN DE EVOLUCION TEMPORAL') return grafica, arr_promtemp # Sin guardar evolución de 'u' else: for iteracion2 in range(num_iter): if iteracion2 % tenth_progress == 0: print('*') # Gráfica auxiliar grafica_holder2 = nx.Graph() for sitio2a in lista_sitios: grafica_holder2.add_node(sitio2a, u = 0) sum1vec2 = 0 for vecino2 in lista_1vecinos[sitio2a][1]: dif_u2 = phi(grafica.nodes[vecino2]['u']) - phi(grafica.nodes[sitio2a]['u']) sum1vec2 = sum1vec2 + dif_u2 grafica_holder2.nodes[sitio2a]['u'] = phi(grafica.nodes[sitio2a]['u']) + g_acople * sum1vec2 # Actualización de gráfica for sitio2b in lista_sitios: grafica.nodes[sitio2b]['u'] = grafica_holder2.nodes[sitio2b]['u'] print('FIN DE EVOLUCION TEMPORAL') return grafica ################################################################################################################################## ################################################################################################################################## ### DEFINICIÓN DE PARÁMETROS DE SIMULACIÓN # Selección aleatoria de semilla s = random.randrange(sys.maxsize) # Definición de otros parámetros L = int(input('Ingresa la longitud de la rejilla CML (entero): ')) g = float(input('Ingresa la constante de acoplamiento (real positivo con tres decimales): ')) N_iter = int(input('Ingresa el total de iteraciones (entero): ')) transient = int(input('Ingresa el valor de transient (entero): ')) site_x0 = int(random.randrange(0,int(L**2),1)) N_ensembles = int(input('Ingresa el total de sistemas que conforman el ensamble (entero): ')) ### GENERACIÓN DE GRÁFICA Y LISTA CON PRIMEROS VECINOS # Iniciación de generador de números aleatorios random.seed(s) # Definición de gráfica y lista con primeros vecinos lattice = ini_graf(L) list_1neighbors = [] for site in range(L**2): list1v = primeros_vecinos(lattice, site) list_1neighbors.append((site, list1v)) print(lattice.nodes[15]['u']) print(type(lattice.nodes[15]['u'])) ### DISTRIBUCIÓN DE VARIABLE 'U' EN UN SITIO PARTICULAR TRAS MÚLTIPLES ITERACIONES, CONSIDERANDO UN SISTEMA safe_timeavg = True lattice, arr_timeavg = ev_temp(N_iter, transient, site_x0, g, lattice, list_1neighbors, safe_timeavg) fname_timeavg = 'tesis_Egolf_ergodicidad_L%(length)i_g%(coupling).3f_Niter%(iterations).3e_trans%(trans).3e_seed%(seed)i_site%(site)i_timeavg.txt' dict_fname_timeavg = {'length': L, 'coupling': g, 'iterations': N_iter, 'trans': transient, 'site': site_x0, 'seed': s} np.savetxt(fname_timeavg % dict_fname_timeavg, arr_timeavg) print('Evolución de sistema completada') # Distribución de variable 'u' en un sitio particular tras múltiples iteraciones, considerando un ensamble safe_ensembleavg = True arr_ensembleavg = np.zeros((N_ensembles, (N_iter - transient))) for sys in range(N_ensembles): lattice = ini_graf(L) lattice, arr_ensemble_holder = ev_temp(N_iter, transient, site_x0, g, lattice, list_1neighbors, safe_ensembleavg) arr_ensembleavg[sys] = arr_ensemble_holder arr_ensembleavg = arr_ensembleavg.flatten() fname_ensavg = 'tesis_Egolf_ergodicidad_L%(length)i_g%(coupling).3f_Niter%(iterations).3e_trans%(trans).3e_seed%(seed)i_site%(site)i_Nens%(ens)i_ensavg.txt' dict_fname_ensavg = {'length': L, 'coupling': g, 'iterations': N_iter, 'trans': transient, 'site': site_x0, 'ens': N_ensembles, 'seed': s} np.savetxt(fname_ensavg % dict_fname_ensavg, arr_ensembleavg) print('Evolución de ensamble completada') # Iniciación de rejilla CML para prueba de self-averaging L2 = int(2*L) lattice2 = ini_graf(L2) list_1neighbors2 = [] for site2 in range(L2**2): list1v2 = primeros_vecinos(lattice2, site2) list_1neighbors2.append((site2, list1v2)) # Distribución de variable 'u' en un sistema a un tiempo fijo safe_selfavg = False lattice2 = ev_temp(N_iter, transient, site_x0, g, lattice2, list_1neighbors2, safe_selfavg) arr_selfavg = np.zeros(L2**2) for site in range(L2**2): arr_selfavg[site] = lattice2.nodes[site]['u'] fname_selfavg = 'tesis_Egolf_ergodicidad_L%(length)i_g%(coupling).3f_Niter%(iterations).3e_trans%(trans).3e_seed%(seed)i_selfavg.txt' dict_fname_selfavg = {'length': L, 'coupling': g, 'iterations': N_iter, 'trans': transient, 'seed': s} np.savetxt(fname_selfavg % dict_fname_selfavg, arr_selfavg) print('Prueba de self-averaging completada') # Gráfica con resultados de ergodicidad y self-averaging plt.figure(1) fig1, (ax1A, ax1B, ax1C) = plt.subplots(nrows = 1, ncols = 3, figsize = (30,10)) plt.tight_layout(pad=4, h_pad=4, w_pad=6) hist_time, bins_time = np.histogram(arr_timeavg, range = (-1, 1)) hist_ens, bins_ens = np.histogram(arr_ensembleavg, range = (-1, 1)) hist_self, bins_self = np.histogram(arr_selfavg, range = (-1,1)) ax1A.hist(bins_time[:-1], bins_time, weights = hist_time, density = True) ax1A.set_title('Distribución de ' + r'$u_{\vec{x}_{0}}^{t}$' + ' con un sistema de %(lo)i x %(lo)i sitios ' % {'lo': L} + r'$(\vec{x}_{0} = %(siteref)i) $' % {'siteref': site_x0}, size=16) ax1A.set_ylabel('dP(u)', size=15) ax1A.set_xlabel('u', size=15) for tick in ax1A.xaxis.get_major_ticks(): tick.label.set_fontsize(14) for tick in ax1A.yaxis.get_major_ticks(): tick.label.set_fontsize(14) ax1B.hist(bins_ens[:-1], bins_ens, weights = hist_ens, density = True) ax1B.set_title('Distribución de ' + r'$u_{\vec{x}_{0}}^{t}$' + ' con un ensamble de %(Nens)i sistemas de %(lo)i x %(lo)i sitios' % {'Nens': N_ensembles, 'lo': L}, size=16) ax1B.set_ylabel('dP(u)', size=15) ax1B.set_xlabel('u', size=15) for tick in ax1B.xaxis.get_major_ticks(): tick.label.set_fontsize(14) for tick in ax1B.yaxis.get_major_ticks(): tick.label.set_fontsize(14) ax1C.hist(bins_self[:-1], bins_self, weights = hist_self, density = True) ax1C.set_title('Distribución de ' + r'$u_{\vec{x}}^{t_{0}}$' + ' sobre un sistema de %(lo)i x %(lo)i sitios ' % {'lo': L2} + r'$(t_{0} = %(tiempo).2e) $' % {'tiempo': N_iter}, size=16) ax1C.set_ylabel('dP(u)', size=15) ax1C.set_xlabel('u', size=15) for tick in ax1C.xaxis.get_major_ticks(): tick.label.set_fontsize(14) for tick in ax1C.yaxis.get_major_ticks(): tick.label.set_fontsize(14) imgname = 'tesis_Egolf_ergodicidad_L%(length)i_g%(coupling).3f_Niter%(iterations).3e_trans%(trans).3e_seed%(seed)i_site%(site)i_Nens%(ens)i_Graph.png' dict_imgname = {'length': L, 'coupling': g, 'iterations': N_iter, 'trans': transient, 'site': site_x0, 'ens': N_ensembles, 'seed': s} plt.savefig(imgname % dict_imgname) print('Programa concluido')
maal22/Tesis_Licenciatura
tesis_Egolf_ergodicidad4_2.py
tesis_Egolf_ergodicidad4_2.py
py
10,416
python
es
code
0
github-code
36
[ { "api_name": "networkx.Graph", "line_number": 29, "usage_type": "call" }, { "api_name": "random.uniform", "line_number": 33, "usage_type": "call" }, { "api_name": "numpy.zeros", "line_number": 80, "usage_type": "call" }, { "api_name": "networkx.Graph", "line_...
7228924054
import json import logging import os from uuid import uuid4 from sqlalchemy import and_ from log import Msg from helper import Now, model_to_dict, Http_error, value, check_schema from .model import Event from user.controller import get_profile def add(data, username, db_session): logging.info(Msg.START) required_data = ['action', 'target', 'entity_name', 'entity_id'] check_schema(required_data, data.keys()) logging.debug(Msg.SCHEMA_CHECKED) model_instance = Event() model_instance.creator = username model_instance.id = str(uuid4()) model_instance.creation_date = Now() model_instance.target = data.get('target') model_instance.action = data.get('action') model_instance.entity_id = data.get('entity_id') model_instance.entity_name = data.get('entity_name') model_instance.seen = False logging.debug(Msg.DATA_ADDITION + " || Data :" + json.dumps(data)) db_session.add(model_instance) logging.debug(Msg.DB_ADD) logging.info(Msg.END) return model_instance def get_events(data, db_session, username): if data.get('time') is None: data['time'] = Now() if data.get('count_number') is None: data['count_number'] = 50 final_result = [] logging.debug(Msg.GET_ALL_REQUEST + 'Events...') logging.info(Msg.START + 'getting events for user = {}'.format(username)) logging.debug(Msg.MODEL_GETTING) if data.get('scroll') == 'down': result = db_session.query(Event).filter(and_(Event.target == username, Event.creation_date < data.get( 'time'))).order_by( Event.creation_date.desc()).limit(data.get('count_number')).all() else: result = db_session.query(Event).filter(and_(Event.target == username, Event.creation_date > data.get( 'time'))).order_by( Event.creation_date.desc()).limit(data.get('count_number')).all() for event in result: event.seen = True event_creator = get_profile(event.creator, db_session) creator = model_to_dict(event_creator) del creator['password'] new_event = model_to_dict(event) new_event['creator'] = creator final_result.append(new_event) logging.debug(Msg.GET_SUCCESS) logging.info(Msg.END) return final_result def get_new_events(db_session, data, username): logging.info(Msg.START) required = ['scroll'] check_schema(required, data.keys()) if data.get('time') is None: data['time'] = Now() if data.get('count_number') is None: data['count_number'] = 50 logging.debug(Msg.GET_ALL_REQUEST + 'new unread Events...') if data.get('scroll') == 'down': result = db_session.query(Event).filter( and_(Event.target == username, Event.seen == False)).filter( Event.creation_date < data.get('time')).order_by( Event.creation_date.desc()).limit(data.get('count_number')).all() else: result = db_session.query(Event).filter( and_(Event.target == username, Event.seen == False)).filter( Event.creation_date > data.get('time')).order_by( Event.creation_date.desc()).limit(data.get('count_number')).all() logging.debug(Msg.GET_SUCCESS) logging.info(Msg.END) return result def get_new_events_count(db_session, username): logging.info(Msg.START) logging.debug(Msg.GET_ALL_REQUEST + 'the count of unread Events...') result = db_session.query(Event).filter( and_(Event.target == username, Event.seen == False)).count() logging.debug(Msg.GET_SUCCESS) logging.info(Msg.END) return {'count': int(result)}
nsmseifi/Bellezza
event/controller.py
controller.py
py
3,930
python
en
code
0
github-code
36
[ { "api_name": "logging.info", "line_number": 15, "usage_type": "call" }, { "api_name": "log.Msg.START", "line_number": 15, "usage_type": "attribute" }, { "api_name": "log.Msg", "line_number": 15, "usage_type": "name" }, { "api_name": "helper.check_schema", "li...
20052535936
from __future__ import print_function import matplotlib.pylab as plt import Layer1.NLSVC as svm import Layer1.learnerV2a as l import Layer1.RLLSVM as rlvm #import Layer1.SVMLearner as svm #import Layer1.RecurrentSVM as rsvm #import Layer1.Poly_Learner as pl #import Layer1.MLP_Learner as mlp import numpy as np from Layer2.AccountV2 import Account as acc if __name__ == "__main__": #setup #receive info final_out = list() for j in range(1): for i in range(10): #print("Now in iteration: "+str(i),end='\r') #make up default values num_learner = 1 learners = list() learner = l.Learner(0.1, 0.1, 0.001, 1, 23) learner.threshold = 2 #learner = svm.Learner() #learner = rsvm.Learner(adaption=0.32,transactionCost=1.5) #learner = nlsvm.Learner() #learner = pl.Learner(j,200) #learner = mlp.Learner(layers=2,mode='returns',n_itr=3) #learner = rlvm.Learner() account = acc("EURUSD",1000,0,0,0,2000) val_watch = list() val_watch.append(account.total_account_value()) #learner = l.Learner(0.02,0.3,1,0.95,10) #numbers = (np.sin(np.linspace(0, np.pi*8, 201))/3)+np.linspace(0,1,201)*0.5 numbers = (np.sin(np.linspace(0, np.pi*8, 20001))/3)+0.5 #numbers = (np.linspace(0,np.pi*8, 201)) #numbers = np.multiply(np.sin(np.linspace(0,np.pi*8,201))+1,np.linspace(0,np.pi*8,201)*1.01) #numbers = np.sin(np.linspace(0, np.pi*4, 201))+1 for i in range(len(numbers)): numbers[i]+= np.random.normal(0,0.03,1) pnumbers = numbers[:20000] preds = list() #execution loop for i in range(1): for i in range(len(numbers)-1): learner.predict(numbers[i],numbers[i+1]) #learner.stopLearning() for i in range(len(numbers)-1): account.update(1/numbers[i], numbers[i],i) prediction = learner.predict(numbers[i],numbers[i+1]) val_watch.append(account.total_account_value()) if(prediction < 0): account.execute('long') else: account.execute('short') # assert isinstance(prediction, float) preds.append(prediction) final_out.append(account.total_account_value()) print("------------------------------------------------------------------") print("Iteration:"+str(j)) print("Maximum was: "+str(np.amax(final_out))+" with recurrence: "+str(np.argmax(final_out))) print("Mean final profit: "+ str(np.mean(final_out))) print("With variance: " + str(np.std(final_out)**2)) fig1 = plt.figure() ax1 = fig1.add_subplot(111) ax1.plot(np.linspace(0, np.pi*8,20000), pnumbers) ax1.plot(np.linspace(0, np.pi*8,20000), preds) fig2 = plt.figure() ax2 = fig2.add_subplot(111) ax2.plot(range(len(val_watch)),val_watch) plt.xlabel('time in price-updates') plt.ylabel('total account value') plt.axis('tight') plt.show()
MLRichter/AutoBuffett
layer1_testScript.py
layer1_testScript.py
py
3,264
python
en
code
8
github-code
36
[ { "api_name": "Layer1.learnerV2a.Learner", "line_number": 27, "usage_type": "call" }, { "api_name": "Layer1.learnerV2a", "line_number": 27, "usage_type": "name" }, { "api_name": "Layer2.AccountV2.Account", "line_number": 35, "usage_type": "call" }, { "api_name": "...
24500666134
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Helper functions and classes.""" from typing import Callable, Iterable, List, Mapping, Tuple, Type import string import functools _registry = dict() _printable = set(string.printable) class MultiMethod: """ Representation of an overloaded method. Takes in the name of a function and allows for registering various signatures with different types. When an instance of this class is called, the appropriated function is called based on the types of the given arguments. From a tutorial written by Guido van Rossum. Please see https://www.artima.com/weblogs/viewpost.jsp?thread=101605 Parameters ---------- name: str Name of the function """ def __init__(self, name): self.name = name self.typemap = dict() def __call__(self, *args): types = tuple(arg.__class__ for arg in args) function = self.typemap.get(types) if function is None: raise TypeError("No match for overloaded function.") return function(*args) def register(self, types: Tuple[Type, ...], function: Callable) -> None: """ Register a new function signature. Parameters ---------- types: tuple of classes Types of the arguments for the function. function: callable To be called when arguments types match ``types``. Raises ------ TypeError If the given ``types`` is already registered to a function. """ if types in self.typemap: raise TypeError(f"Duplicate registration of function {self.name}") self.typemap[types] = function def multimethod(*types: Type) -> Callable: """ Function decorator for supporting method overloading. Based on an article written by Guido van Rossum (see https://www.artima.com/weblogs/viewpost.jsp?thread=101605). Best way to see its usage is by example. Examples -------- >>> from glo.helpers import multimethod >>> @multimethod(int, int) ... def my_func(a, b): ... return a * b ... >>> @multimethod(int, int, str) ... def my_func(a, b, s): ... return s.format(my_func(a, b)) ... >>> my_func(5, 6) 30 >>> my_func(5, 6, "The result is: {}") 'The result is: 30' """ def register(function): name = function.__name__ multi = _registry.get(name) if multi is None: multi = _registry[name] = MultiMethod(name) multi.register(types, function) return multi return register def prep_ascii_str(s_in: str) -> str: """ Takes in a string and prepares it for parsing. In this method we convert the string to all lowercase and remove any characters that aren't supported by the ASCII character set. Parameters ---------- s_in: str Input string to prep. Returns ------- str Prepped version of the input ``s_in``. Examples -------- >>> from glo.helpers import prep_ascii_str >>> prep_ascii_str("25 Ounces") '25 ounces' >>> prep_ascii_str("some\x05string. with\x15 funny characters") 'somestring. with funny characters' >>> prep_ascii_str(" some string with whitespace ") 'some string with whitespace' """ as_ascii = "".join(filter(lambda x: x in _printable, s_in)) return as_ascii.strip().lower() def remove_substrings(s_in: str, subs: Iterable[str]) -> str: """ Remove list of substrings from a given input string. Parameters ---------- s_in: str String to remove substrings from. subs: iterable of str List of substrings to remove from the input string. Will be removed in the order they are iterated over. Returns ------- str Input string with all substrings found in given substring list removed. Examples -------- >>> from glo.helpers import remove_substrings >>> remove_substrings("test1 test2 test3", ["test1", "test3"]) 'test2' >>> remove_substrings("TEST1 TEST2 TEST3", ["test1", "test3"]) 'TEST1 TEST2 TEST3' >>> remove_substrings("hey there", ["y there", "hey"]) 'he' """ return functools.reduce( lambda string, substring: string.replace(substring, "").strip(), subs, s_in, ) def split_in_list(in_list: Iterable[str], split_on: str) -> List[str]: """ Return flattened list of split input strings. Let's say that there are a bunch of strings that we want to split on a certain character, but want the results of the splits to be returned in a 1D array, rather than a 2D array: ```python >>> # instead of this: >>> l_in = ["test1 test2", "test3 test4"] >>> [s.split(" ") for s in l_in] [['test1', 'test2'], ['test3', 'test4']] >>> # we have this: >>> from glo.helpers import split_in_list >>> split_in_list(l_in, " ") ['test1', 'test2', 'test3', 'test4'] ``` Parameters ---------- l_in: iterable of str List of input strings to split. split_in: str String holding the substring that each input string will be split on. Returns ------- list of str Flattened list containing results from the splits Examples -------- >>> from glo.helpers import split_in_list >>> split_in_list(["hey this", "is a sentence."], " ") ['hey', 'this', 'is', 'a', 'sentence.'] >>> split_in_list(["and then, he said: ", "wait, what's that?"], ", ") ['and then', 'he said:', 'wait', "what's that?"] """ return functools.reduce( lambda results, next_str: results + [sub.strip() for sub in next_str.split(split_on)], in_list, list(), ) def contains_substring(s_in: str, subs: Iterable[str]) -> bool: """ Determine if any of the given substrings is in the given string. Parameters ---------- s_in: str Input string to check for given substrings. subs: iterable of str Substrings to check for in str Examples -------- >>> from glo.helpers import contains_substring >>> contains_substring("this is a test", ["hey", "there"]) False >>> contains_substring("this is another test", ["test", "hey", "there"]) True >>> contains_substring("this is another test", ["this", "is", "another"]) True >>> contains_substring("THIS IS ANOTHER TEST", ["this", "is", "another"]) False """ return any(sub_str in s_in for sub_str in subs) def replace_multiple_substrings(s_in: str, subs: Mapping[str, str]) -> str: """ Replace multiple substrings within the given input string. The order in which the replacements occur cannot be guaranteed. Parameters ---------- s_in: str Input string to make the substitutions in. sub: mapping of str to str Keys in this dict are substrings to replace, with each values being the string the key should be replaced with. Examples -------- >>> from glo.helpers import replace_multiple_substrings >>> replace_multiple_substrings("a test", {"a": "hey", "test": "there"}) 'hey there' >>> replace_multiple_substrings("12546", {"5": "3", "6": "321"}) '1234321' """ return functools.reduce( lambda result, next_sub: result.replace(*next_sub), subs.items(), s_in )
learnitall/glo
glo/helpers.py
helpers.py
py
7,497
python
en
code
0
github-code
36
[ { "api_name": "string.printable", "line_number": 10, "usage_type": "attribute" }, { "api_name": "typing.Tuple", "line_number": 42, "usage_type": "name" }, { "api_name": "typing.Type", "line_number": 42, "usage_type": "name" }, { "api_name": "typing.Callable", ...
7535863812
from django.test import TestCase, Client, tag from djangoplicity.media.models import Video @tag('frontpage') class TestFrontPageApp(TestCase): fixtures = ['test/pages', 'test/media', 'test/announcements', 'test/releases', 'test/highlights'] def setUp(self): self.client = Client() def test_homepage(self): youtube_only_html = '<div class="youtube-wrapper"><div id="youtube-player"></div></div>' homepage_sections = ['What\'s New', 'ESA/Hubble Facebook', 'Subscribe to Hubble News'] # first hubblecast with use_youtube = True response = self.client.get('/') for section in homepage_sections: self.assertContains(response, section) self.assertContains(response, youtube_only_html, html=True) # first hubblecast with use_youtube = False Video.objects.update(use_youtube=False) response = self.client.get('/') self.assertNotContains(response, youtube_only_html, html=True)
esawebb/esawebb
webb/frontpage/tests.py
tests.py
py
990
python
en
code
0
github-code
36
[ { "api_name": "django.test.TestCase", "line_number": 6, "usage_type": "name" }, { "api_name": "django.test.Client", "line_number": 10, "usage_type": "call" }, { "api_name": "djangoplicity.media.models.Video.objects.update", "line_number": 25, "usage_type": "call" }, {...
17884436215
# -*- encoding: utf-8 -*- """ 说明:由于之前帮助按钮模式做的效果不是很理想,目前计划是做一个新的模块作为临时结局方案 """ import webbrowser class helpLinkEngine(object): def __init__(self): self.url_dict = { "dataio_sample_showhelp":'导入其他数据分析软件的工作表?sort_id=3265627' } def openHelp(self, tag = ""): if tag in self.url_dict: url = "https://gitee.com/py2cn/pyminer/wikis/" + self.url_dict[tag] webbrowser.open(url) else: from PySide2.QtWidgets import QMessageBox QMessageBox.warning(None, '警告', '当前模块暂无帮助文档!', QMessageBox.Ok) helpLink = helpLinkEngine()
pyminer/pyminer
pyminer/packages/pm_helpLinkEngine/helpLinkEngine.py
helpLinkEngine.py
py
754
python
zh
code
77
github-code
36
[ { "api_name": "webbrowser.open", "line_number": 16, "usage_type": "call" }, { "api_name": "PySide2.QtWidgets.QMessageBox.warning", "line_number": 19, "usage_type": "call" }, { "api_name": "PySide2.QtWidgets.QMessageBox", "line_number": 19, "usage_type": "name" }, { ...
29378709444
from flask import Blueprint, request, session from database.service.location import Location as LocationSvc from database.service.user import User as UserSvc from database.service.device import Device as DeviceSvc from database.service.property import Property as PropertySvc from database.service.exceptions import NoRecordError ''' MQTT interface ''' import paho.mqtt.client as mqtt import json # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, rc): print("Connected with result code " + str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("record/#") client.on_message = on_message import re record_insert_regex = re.compile("record\/(\w+)\/(\w+)\/(\w+)") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): topic = msg.topic payload = msg.payload.decode('utf8') matched = record_insert_regex.match(topic) print(payload) json_payload = json.loads(payload) if matched: username = matched.group(1) location_name = matched.group(2) device_name = matched.group(3) print("MQTT received. Topic: " + username + " " + location_name +" " + device_name + " Payload: " + str(payload)) # Get user id try: password = json_payload["password"] user = UserSvc.verify(username, password) user_id = user.id print("User ID: " + str(user_id)) except NoRecordError as error: print(error) return # Usually username password mismatch except Exception as error: print(error) return # Get location, deices ids try: location = LocationSvc.get(user_id, name=location_name) device = DeviceSvc.get(user_id, name=device_name) print("Location ID: " + str(location.id)) print("Device ID: " + str(device.id)) except NoRecordError as error: print(error) return # No record # Not put data in there try: print("content: " + str(json_payload["content"])) PropertySvc.save_record_dict(device.id, location.id, json_payload["content"]) except Exception as error: print(error) return return mqtt_client = mqtt.Client() mqtt_client.on_connect = on_connect try: mqtt_client.connect(host='127.0.0.1', port=1883, keepalive=60) except: print('Failed to connect to the server') exit() else: print('Connection Success!') print('MQTT connection is being ready...') mqtt_client.loop_start()
Wolfie-Home/webserver2
wolfie_home/api_mqtt.py
api_mqtt.py
py
2,763
python
en
code
6
github-code
36
[ { "api_name": "re.compile", "line_number": 23, "usage_type": "call" }, { "api_name": "json.loads", "line_number": 31, "usage_type": "call" }, { "api_name": "database.service.user.User.verify", "line_number": 40, "usage_type": "call" }, { "api_name": "database.serv...
4397820007
import os from shutil import copyfile from unittest.mock import patch, Mock import pytest from ow import migrate class TestMigrateUnit(object): def test_includeme(self): config = Mock() migrate.includeme(config) config.scan.assert_called_with('ow.migrate') @patch('ow.migrate.run_migrations') def test_closer_wrapper_ok(self, run): closer = Mock() env = dict( registry=Mock(settings={}), root_factory=Mock(__module__='mytest'), request=1, root=2, closer=closer) migrate.closer_wrapper(env) run.assert_called_with(1, 2, 'mytest.migrations') assert closer.called @patch('ow.migrate.closer_wrapper') @patch('ow.migrate.prepare') def test_application_created_ok(self, prepare, wrap): event = Mock() migrate.application_created(event) assert prepare.called assert wrap.called @patch('ow.migrate.output') def test_command_line_no_conf(self, pr): ret = migrate.command_line_main(['test.py']) assert ret == 1 assert pr.called @patch('ow.migrate.closer_wrapper') @patch('ow.migrate.bootstrap') def test_command_line_no(self, bs, wrap): ret = migrate.command_line_main(['test.py', 'dev.ini']) assert ret == 0 assert bs.called assert wrap.called @patch('ow.migrate.commit') @patch('ow.migrate.get_connection') def test_reset_version(self, pget_connection, pcommit): zodb = {} pget_connection.return_value.root.return_value = zodb migrate.reset_version('myrequest', 25) assert zodb == {'database_version': 25} pcommit.asert_called_with() def cleanup(): """ Clean up pyc files generated while running the following test suite """ migrations = os.path.join(os.path.dirname(__file__), 'migrations') for f in os.listdir(migrations): if '.pyc' in f or 'fail' in f or f == '3.py': os.remove(os.path.join(migrations, f)) class mocked_get_connection(object): """ This is a class we can use to mock pyramid_zodbconn.get_connection() (see test_run_migrations) """ def __init__(self, versions=0): self.versions = versions def root(self): return {'database_version': self.versions} class TestsMigrate(object): package_name = 'ow.tests.migrations' ini_path = os.path.join(os.path.dirname(__file__), 'migrations') def test_get_indexes_ok(self): indexes = migrate.get_indexes(self.package_name) assert isinstance(indexes, list) assert len(indexes) == 2 def test_get_indexes_fail(self): migrate.get_indexes(self.package_name) with pytest.raises(ImportError): migrate.get_indexes('nonexistent.module.migrations') def test_get_indexes_invalid(self): # Create a new migration file with an invalid name, so the get_indexes # will raise a ValueError exception copyfile(os.path.join(os.path.dirname(__file__), 'migrations/1.py'), os.path.join(os.path.dirname(__file__), 'migrations/fail.py')) indexes = migrate.get_indexes(self.package_name) assert isinstance(indexes, list) assert len(indexes) == 2 def test_get_max_in_max_cache(self): with patch.dict(migrate.MAX_CACHE, {self.package_name: 10}): max_version = migrate.get_max(self.package_name) assert max_version == 10 def test_get_max(self): max_version = migrate.get_max(self.package_name) assert max_version == 2 def test_version(self): # instead of a real ZODB root, we do use a simple dict here, # it should be enough for what need to test. root = {} root = migrate.set_version(root, 10) assert root['database_version'] == 10 def test_max_version(self): # instead of a real ZODB root, we do use a simple dict here, # it should be enough for what need to test. root = {} root = migrate.set_max_version(root, self.package_name) assert root['database_version'] == 2 @patch('ow.migrate.get_connection') @patch('ow.tests.migrations.1.output') @patch('ow.tests.migrations.2.output') def test_run_all_migrations(self, pr2, pr1, gc): """ Test that all migrations apply """ gc.return_value = mocked_get_connection() migrate.run_migrations(None, {}, self.package_name) cleanup() assert pr1.called assert pr2.called @patch('ow.migrate.get_connection') def test_run_no_migrations(self, gc): """ Test that there are no more migrations to apply """ gc.return_value = mocked_get_connection(versions=2) migrate.run_migrations(None, {}, self.package_name) @patch('ow.migrate.get_connection') @patch('ow.tests.migrations.1.output') @patch('ow.tests.migrations.2.output') def test_run_invalid_migrations(self, pr2, pr1, gc): """ Test what happens if a migration does not contains the proper migrate method """ invalid_migration = open(os.path.join(os.path.dirname(__file__), 'migrations/3.py'), 'w') invalid_migration.write('# This is an empty migration, just for tests') invalid_migration.write('def no_migrate_method_here():') invalid_migration.write(' print "Nothing to see here!"') invalid_migration.close() gc.return_value = mocked_get_connection(versions=0) migrate.run_migrations(None, {}, self.package_name) cleanup() assert pr1.called assert pr2.called
openworkouts/OpenWorkouts
ow/tests/test_migrate.py
test_migrate.py
py
5,768
python
en
code
5
github-code
36
[ { "api_name": "unittest.mock.Mock", "line_number": 12, "usage_type": "call" }, { "api_name": "ow.migrate.includeme", "line_number": 13, "usage_type": "call" }, { "api_name": "ow.migrate", "line_number": 13, "usage_type": "name" }, { "api_name": "unittest.mock.Mock...
31320163241
import pandas as pd import pymongo from .metacritic_scrape import scrape_game_page from .pandas_functions import clean_df from selenium.webdriver import Firefox import random import time mc = pymongo.MongoClient() db =mc['game_recommender'] reviews_coll = db['reviews'] games=db['games'] #omc=pymongo.MongoClient() #cb = omc['ps4_game_data'] #games = cb['games'] def flatten_game_dict(game_dict): """Take a dictionary of dictionaries & flatten it""" for (game_id, user_score_dict) in game_dict.items(): for (user_id, score) in user_score_dict.items(): yield {'game_id': game_id, 'user_id': user_id, 'score': score} def store_all_users(coll=games): """Take raw_html from a game's user review page, and store the game, username, & score as an entry in reviews collection""" games_dict={} df = pd.DataFrame(list(coll.find())) #df =clean_df(df=df) game_titles = list(df.title) browser=Firefox() for game in game_titles: result= scrape_game_page(title=game, browser=browser) if not result: continue games_dict[game] = result existing_game_reviews=set((r['game_id'], r['user_id']) for r in reviews_coll.find()) flattened=flatten_game_dict(game_dict=games_dict) for review in flattened: game_id = review['game_id'] user_id = review['user_id'] if (game_id, user_id) not in existing_game_reviews: reviews_coll.insert_one(review) def make_preference_df(db=reviews_coll): """Go from all entries in reviews collection, to pandas dataframe""" df=pd.DataFrame(list(db.find())) """Set of unique user & game IDs""" users=set(df['user_id']) games=set(df['game_id']) """Zipping a number to each unique user & game ID""" game_id_lookup = dict(zip(games, range(len(games)))) user_id_lookup = dict(zip(users, range(len(users)))) df['game_number']=df['game_id'].apply(game_id_lookup.get) df['user_number']=df['user_id'].apply(user_id_lookup.get) #df=df.pivot(index='user_number', columns='game_number', values='score' ) return df
loeschn/Video-Game-Recommender
Notebooks/notebook_src/make_preference_matrix.py
make_preference_matrix.py
py
2,145
python
en
code
0
github-code
36
[ { "api_name": "pymongo.MongoClient", "line_number": 9, "usage_type": "call" }, { "api_name": "pandas.DataFrame", "line_number": 29, "usage_type": "call" }, { "api_name": "selenium.webdriver.Firefox", "line_number": 33, "usage_type": "call" }, { "api_name": "metacr...
8651855944
import time from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.select import Select from selenium.webdriver.support.wait import WebDriverWait service_obj = Service("C:/Users/PUJA/chromedriver") driver = webdriver.Chrome(service=service_obj) driver.implicitly_wait(5) expectedlist=['Cucumber - 1 Kg', 'Raspberry - 1/4 Kg', 'Strawberry - 1/4 Kg'] driver.get("https://rahulshettyacademy.com/seleniumPractise/#/") driver.find_element(By.CSS_SELECTOR,".search-keyword").send_keys("ber") time.sleep(2) #product_list: actuallist=[] productlist= driver.find_elements(By.XPATH,"//div/h4") for product in productlist: actuallist.append(product.text) print(actuallist) assert actuallist == expectedlist count = driver.find_elements(By.XPATH,"//div[@class='products']/div") print(len(count)) assert len(count)>0 #Chaining of web element for c in count: c.find_element(By.XPATH,"div/button").click() driver.find_element(By.XPATH,"//img[@alt='Cart']").click() driver.find_element(By.XPATH,"//button[text()='PROCEED TO CHECKOUT']").click() #sum _validation sum=0 rates= driver.find_elements(By.XPATH,"//tr/td[5]/p") for rate in rates: sum= sum+int(rate.text) print(sum) totalamount= int(driver.find_element(By.CSS_SELECTOR,".totAmt").text) assert sum == totalamount driver.find_element(By.CSS_SELECTOR,".promoCode").send_keys("rahulshettyacademy") driver.find_element(By.CLASS_NAME,"promoBtn").click() wait= WebDriverWait(driver,5) wait.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR,".promoInfo"))) print(driver.find_element(By.CLASS_NAME,"promoInfo").text) discountedamount= float(driver.find_element(By.CLASS_NAME,"discountAmt").text) print(discountedamount) assert totalamount>discountedamount driver.find_element(By.XPATH,"//button[text()='Place Order']").click() dropdown= Select(driver.find_element(By.XPATH,"//div/select")) dropdown.select_by_value("India") driver.find_element(By.CSS_SELECTOR,".chkAgree").click() driver.find_element(By.XPATH,"//button[text()='Proceed']").click()
PCPuja/FirstGit
Waits.py
Waits.py
py
2,198
python
en
code
0
github-code
36
[ { "api_name": "selenium.webdriver.chrome.service.Service", "line_number": 10, "usage_type": "call" }, { "api_name": "selenium.webdriver.Chrome", "line_number": 11, "usage_type": "call" }, { "api_name": "selenium.webdriver", "line_number": 11, "usage_type": "name" }, {...
41797269228
from django.core.management.base import BaseCommand from django.conf import settings import requests import json import telebot from telebot import types from crypton.models import Profile from preferences import preferences bot = telebot.TeleBot(settings.TOKEN) coins = { 'BTC': ['btc', 'bitcoin', 'биткоин'], 'ETH': ['eth', 'ethereum', 'эфириум'], 'DOGE': ['doge', 'dogecoin', 'догикоин'] } class Command(BaseCommand): help = 'Telegram Bot' def handle(self, *args, **options): bot.polling(none_stop=True) def exchange(crypto): url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest' headers = { "X-CMC_PRO_API_KEY": settings.COINMARKETCAP_API_KEY, "Accept": "application/json" } parameters = { 'symbol': crypto } session = requests.Session() session.headers.update(headers) data = session.get(url, params=parameters) results = (json.loads(data.text)).get('data') return results[f'{crypto}']['quote']['USD']['price'] @bot.message_handler(commands=['start']) def send_welcome(message): bot.send_message(message.chat.id, preferences.BotPreferences.welcome, reply_markup=choice_crypto()) chat_id = message.chat.id Profile.objects.get_or_create( tg_id=chat_id, defaults={ 'tg_username': message.from_user.username, 'tg_firstname': message.from_user.first_name, 'tg_lastname': message.from_user.last_name, } ) @bot.message_handler(content_types=["text"]) def send_anytext(message): text = message.text.lower() chat_id = message.chat.id for key, val in coins.items(): if text in val: bot.send_message(chat_id, exchange(key), reply_markup=choice_crypto()) break else: bot.send_message(chat_id, preferences.BotPreferences.error_message, reply_markup=choice_crypto()) def choice_crypto(): markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True) btc = types.KeyboardButton(preferences.BotPreferences.btc) eth = types.KeyboardButton(preferences.BotPreferences.eth) doge = types.KeyboardButton(preferences.BotPreferences.doge) markup.add(btc, eth, doge) return markup
iterweb/test_bot
crypton/management/commands/tg_bot.py
tg_bot.py
py
2,340
python
en
code
0
github-code
36
[ { "api_name": "telebot.TeleBot", "line_number": 13, "usage_type": "call" }, { "api_name": "django.conf.settings.TOKEN", "line_number": 13, "usage_type": "attribute" }, { "api_name": "django.conf.settings", "line_number": 13, "usage_type": "name" }, { "api_name": "...
42305321529
import sqlite3 import DepartmentStudentAmounts as dsa Database = sqlite3.connect('Identities') items = Database.cursor() """class used to validate the adding none year group specific items Attributes ----------- private Attributes ---> name item ---> average ---> department """ class validate_adding_item_none_yeargroup_specfic: name_item_length_max = 25 name_item_length_mini = 3 average_upper_bound = 6 average_lower_bound = 1 total_students = 0 DefaultStockAlertValue = 0 def __init__(self, name_item, average, department): self.name_item = name_item self.average = average self.department = department # Method is used to check the user inputs def check(self): if validate_adding_item_none_yeargroup_specfic.name_item_length_mini < len(self.name_item) <= validate_adding_item_none_yeargroup_specfic.name_item_length_max and validate_adding_item_none_yeargroup_specfic.average_lower_bound <= self.average < validate_adding_item_none_yeargroup_specfic.average_upper_bound: return True else: return False # Method is used to perform claculation about the amount that should be inputted into the database def calculations(self): # Loops through the dictonary calculating the total amount of students for i in dsa.StudentAmounts: value = dsa.StudentAmounts[i][self.department] # Adds the value to the total students class variable self.total_students += value return self.total_students # Method is used to perform the final calcultaion abou the amount that would be inputted to the database def final_calc(self): TotalStudents = self.calculations() CurrentAmount = TotalStudents * self.average MinimumAmount = round((CurrentAmount * 0.1), 0) return CurrentAmount, MinimumAmount # Method is used to check if the item already exsists in the database def checkItem_exsist(self): previous = self.check() if previous: items.execute("SELECT * FROM None_yeargroup_specific WHERE Name_item=?", (self.name_item,)) item = items.fetchone() Database.commit() if item is not None: return True else: return False else: return True # Method is used to input the item to the database def inputItem(self): previous = self.checkItem_exsist() if previous is False: CalculationResults = self.final_calc() CurrentAmount = CalculationResults[0] MinimumAmount = CalculationResults[1] items.execute("INSERT INTO None_yeargroup_specific VALUES (?, ?, ?, ?, ?)", (self.name_item, CurrentAmount, MinimumAmount, self.department, validate_adding_item_none_yeargroup_specfic.DefaultStockAlertValue)) result = Database.commit() if result is not None: return False else: return True else: return False """Subclass used to validate entries Subclass ( valdidate_adding_yeargroup_specfic ) inherites from Superclass ( validate_adding_item_none_yeargroup_specfic ) subclass superclass validate_adding_item_none_yeargroup_specfic -----> valdidate_adding_yeargroup_specfic Attributes ----------- ---> year group + the inherted attributes """ class valdidate_adding_yeargroup_specfic(validate_adding_item_none_yeargroup_specfic): def __init__(self, name_item, average, department, yeargroup): super().__init__(name_item, average, department) self.yeargroup = yeargroup # Polyphorism may be able to be used on this method by overriding it. def calculation(self): amount_students = dsa.StudentAmounts["Year " + self.yeargroup][self.department] result = self.average * amount_students Minimum_amount = round(result * 0.3) return result, Minimum_amount # Polyphorism used on this method by overriding it. def checkItem_exsist(self): previous = self.check() print(previous) if previous: items.execute("SELECT * FROM year_group_specific WHERE Name_item=? AND year_group=?", (self.name_item, self.yeargroup)) result = Database.commit() if result is not None: return True else: return False else: return False # The method check would be called first if True connect to year group specific database and determine if the item exsist or not. # Polyphorism is used here to input the item. (Overidding) def inputItem(self): previous = self.checkItem_exsist() if previous is False: # return tuple (result, minmum amount) result = self.calculation() MinimumAmount = result[1] CurrentAmount = result[0] items.execute("INSERT INTO year_group_specific VALUES (?, ?, ?, ?, ?, ?)", (self.name_item, CurrentAmount, MinimumAmount, self.department, self.yeargroup, validate_adding_item_none_yeargroup_specfic.DefaultStockAlertValue, )) result = Database.commit() if result is not None: return False else: return True else: return False
newton124/code
AddingItem.py
AddingItem.py
py
5,597
python
en
code
0
github-code
36
[ { "api_name": "sqlite3.connect", "line_number": 4, "usage_type": "call" }, { "api_name": "DepartmentStudentAmounts.StudentAmounts", "line_number": 49, "usage_type": "attribute" }, { "api_name": "DepartmentStudentAmounts.StudentAmounts", "line_number": 50, "usage_type": "a...
9194439636
# coding: utf-8 """ Lightly API Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@lightly.ai Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from lightly.openapi_generated.swagger_client.configuration import Configuration class JobStatusData(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'id': 'MongoObjectID', 'status': 'JobState', 'meta': 'JobStatusMeta', 'wait_time_till_next_poll': 'int', 'created_at': 'Timestamp', 'finished_at': 'Timestamp', 'error': 'str', 'result': 'JobStatusDataResult' } attribute_map = { 'id': 'id', 'status': 'status', 'meta': 'meta', 'wait_time_till_next_poll': 'waitTimeTillNextPoll', 'created_at': 'createdAt', 'finished_at': 'finishedAt', 'error': 'error', 'result': 'result' } def __init__(self, id=None, status=None, meta=None, wait_time_till_next_poll=None, created_at=None, finished_at=None, error=None, result=None, _configuration=None): # noqa: E501 """JobStatusData - a model defined in Swagger""" # noqa: E501 if _configuration is None: _configuration = Configuration() self._configuration = _configuration self._id = None self._status = None self._meta = None self._wait_time_till_next_poll = None self._created_at = None self._finished_at = None self._error = None self._result = None self.discriminator = None self.id = id self.status = status if meta is not None: self.meta = meta self.wait_time_till_next_poll = wait_time_till_next_poll self.created_at = created_at if finished_at is not None: self.finished_at = finished_at if error is not None: self.error = error if result is not None: self.result = result @property def id(self): """Gets the id of this JobStatusData. # noqa: E501 :return: The id of this JobStatusData. # noqa: E501 :rtype: MongoObjectID """ return self._id @id.setter def id(self, id): """Sets the id of this JobStatusData. :param id: The id of this JobStatusData. # noqa: E501 :type: MongoObjectID """ if self._configuration.client_side_validation and id is None: raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 self._id = id @property def status(self): """Gets the status of this JobStatusData. # noqa: E501 :return: The status of this JobStatusData. # noqa: E501 :rtype: JobState """ return self._status @status.setter def status(self, status): """Sets the status of this JobStatusData. :param status: The status of this JobStatusData. # noqa: E501 :type: JobState """ if self._configuration.client_side_validation and status is None: raise ValueError("Invalid value for `status`, must not be `None`") # noqa: E501 self._status = status @property def meta(self): """Gets the meta of this JobStatusData. # noqa: E501 :return: The meta of this JobStatusData. # noqa: E501 :rtype: JobStatusMeta """ return self._meta @meta.setter def meta(self, meta): """Sets the meta of this JobStatusData. :param meta: The meta of this JobStatusData. # noqa: E501 :type: JobStatusMeta """ self._meta = meta @property def wait_time_till_next_poll(self): """Gets the wait_time_till_next_poll of this JobStatusData. # noqa: E501 The time in seconds the client should wait before doing the next poll. # noqa: E501 :return: The wait_time_till_next_poll of this JobStatusData. # noqa: E501 :rtype: int """ return self._wait_time_till_next_poll @wait_time_till_next_poll.setter def wait_time_till_next_poll(self, wait_time_till_next_poll): """Sets the wait_time_till_next_poll of this JobStatusData. The time in seconds the client should wait before doing the next poll. # noqa: E501 :param wait_time_till_next_poll: The wait_time_till_next_poll of this JobStatusData. # noqa: E501 :type: int """ if self._configuration.client_side_validation and wait_time_till_next_poll is None: raise ValueError("Invalid value for `wait_time_till_next_poll`, must not be `None`") # noqa: E501 self._wait_time_till_next_poll = wait_time_till_next_poll @property def created_at(self): """Gets the created_at of this JobStatusData. # noqa: E501 :return: The created_at of this JobStatusData. # noqa: E501 :rtype: Timestamp """ return self._created_at @created_at.setter def created_at(self, created_at): """Sets the created_at of this JobStatusData. :param created_at: The created_at of this JobStatusData. # noqa: E501 :type: Timestamp """ if self._configuration.client_side_validation and created_at is None: raise ValueError("Invalid value for `created_at`, must not be `None`") # noqa: E501 self._created_at = created_at @property def finished_at(self): """Gets the finished_at of this JobStatusData. # noqa: E501 :return: The finished_at of this JobStatusData. # noqa: E501 :rtype: Timestamp """ return self._finished_at @finished_at.setter def finished_at(self, finished_at): """Sets the finished_at of this JobStatusData. :param finished_at: The finished_at of this JobStatusData. # noqa: E501 :type: Timestamp """ self._finished_at = finished_at @property def error(self): """Gets the error of this JobStatusData. # noqa: E501 :return: The error of this JobStatusData. # noqa: E501 :rtype: str """ return self._error @error.setter def error(self, error): """Sets the error of this JobStatusData. :param error: The error of this JobStatusData. # noqa: E501 :type: str """ self._error = error @property def result(self): """Gets the result of this JobStatusData. # noqa: E501 :return: The result of this JobStatusData. # noqa: E501 :rtype: JobStatusDataResult """ return self._result @result.setter def result(self, result): """Sets the result of this JobStatusData. :param result: The result of this JobStatusData. # noqa: E501 :type: JobStatusDataResult """ self._result = result def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(JobStatusData, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, JobStatusData): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, JobStatusData): return True return self.to_dict() != other.to_dict()
tibe97/thesis-self-supervised-learning
lightly/openapi_generated/swagger_client/models/job_status_data.py
job_status_data.py
py
9,149
python
en
code
2
github-code
36
[ { "api_name": "lightly.openapi_generated.swagger_client.configuration.Configuration", "line_number": 60, "usage_type": "call" }, { "api_name": "six.iteritems", "line_number": 268, "usage_type": "call" }, { "api_name": "pprint.pformat", "line_number": 293, "usage_type": "c...
28224836636
import random from string import ascii_letters from typing import Any, Generator def data_stream_gen( total_length: int | None = None, element_length: int = 100 ) -> Generator[str, None, None]: if total_length is None: total_length == float("inf") idx = 0 while idx < total_length: element = "" for el_length in range(element_length): element += random.choice(ascii_letters) yield element idx += 1 def n_th_data(data_gen: Generator[str, None, None], idx: int) -> str: for i in range(idx + 1): element = next(data_gen) return element def solution(big_stream: Any) -> Any: random_element = None for idx, element in enumerate(big_stream): if idx == 0: random_element = element elif random.randint(1, idx + 1) == 1: # prob of 1 in n random_element = element return random_element TOTAL_LENGTH = 1_000_000 ELEMENT_LENGTH = 100 data = data_stream_gen(TOTAL_LENGTH, ELEMENT_LENGTH) element_idx = random.randint(0, TOTAL_LENGTH) print(n_th_data(data, element_idx))
HomayoonAlimohammadi/Training
DailyProblem/2_7_2022.py
2_7_2022.py
py
1,104
python
en
code
2
github-code
36
[ { "api_name": "random.choice", "line_number": 15, "usage_type": "call" }, { "api_name": "string.ascii_letters", "line_number": 15, "usage_type": "argument" }, { "api_name": "typing.Generator", "line_number": 8, "usage_type": "name" }, { "api_name": "typing.Generat...
44392387615
import falcon from routes.user import UserRoutes from routes.workspace import WorkspaceRoutes from routes.display import DisplayRoutes from routes.token import TokenRoutes from routes.scene import SceneRoutes from routes.slide import SlideRoutes from falcon.http_status import HTTPStatus class HandleCORS(object): def process_request(self, req, resp): resp.set_header('Access-Control-Allow-Origin', '*') resp.set_header('Access-Control-Allow-Methods', '*') resp.set_header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization') resp.set_header('Access-Control-Max-Age', 1728000) # 20 days if req.method == 'OPTIONS': raise HTTPStatus(falcon.HTTP_200, body='\n') app = falcon.API(middleware=[HandleCORS()]) userRoutes = UserRoutes() workspaceRoutes = WorkspaceRoutes() displayRoutes = DisplayRoutes() tokenRoutes = TokenRoutes() sceneRoutes = SceneRoutes() slideRoutes = SlideRoutes() app.add_route('/user', userRoutes) app.add_route('/user/register', userRoutes, suffix='register') app.add_route('/user/login', userRoutes, suffix='login') app.add_route('/user/forgot', userRoutes, suffix='forgot') app.add_route('/user/reset', userRoutes, suffix='reset') app.add_route('/token', tokenRoutes) app.add_route('/workspaces', workspaceRoutes) app.add_route('/workspaces/{workspaceId}', workspaceRoutes) app.add_route('/workspaces/{workspaceId}/users/{userId}', userRoutes, suffix='giveaccess') app.add_route('/workspaces/{workspaceId}/scenes', sceneRoutes) app.add_route('/workspaces/{workspaceId}/scenes/{sceneId}', sceneRoutes, suffix='withSceneId') app.add_route('/workspaces/{workspaceId}/slides', slideRoutes) app.add_route('/workspaces/{workspaceId}/slides/{slideId}', slideRoutes, suffix='withSlideId') app.add_route('/workspaces/{workspaceId}/displays', displayRoutes) app.add_route('/workspaces/{workspaceId}/displays/{displayId}', displayRoutes, suffix='withDisplayId')
Silassales/Displayly
backend/main.py
main.py
py
1,942
python
en
code
0
github-code
36
[ { "api_name": "falcon.http_status.HTTPStatus", "line_number": 17, "usage_type": "call" }, { "api_name": "falcon.HTTP_200", "line_number": 17, "usage_type": "attribute" }, { "api_name": "falcon.API", "line_number": 20, "usage_type": "call" }, { "api_name": "routes....
13404192861
import warnings, logging, os, sys warnings.filterwarnings('ignore',category=FutureWarning) logging.disable(logging.WARNING) os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import json import tensorflow as tf from utils import * from arguments import get_args_many args = get_args_many() MDIR = args.MDIR n2d_layers = 61 n2d_filters = 64 window2d = 3 wmin = 0.8 ns = 21 # load network weights in RAM w,b,beta_,gamma_ = load_weights(args.MDIR) # # network # config = tf.ConfigProto( gpu_options = tf.GPUOptions(allow_growth=True) ) activation = tf.nn.elu conv1d = tf.layers.conv1d conv2d = tf.layers.conv2d with tf.Graph().as_default(): with tf.name_scope('input'): ncol = tf.placeholder(dtype=tf.int32, shape=()) nrow = tf.placeholder(dtype=tf.int32, shape=()) msa = tf.placeholder(dtype=tf.uint8, shape=(None,None)) # # collect features # msa1hot = tf.one_hot(msa, ns, dtype=tf.float32) weights = reweight(msa1hot, wmin) # 1D features f1d_seq = msa1hot[0,:,:20] f1d_pssm = msa2pssm(msa1hot, weights) f1d = tf.concat(values=[f1d_seq, f1d_pssm], axis=1) f1d = tf.expand_dims(f1d, axis=0) f1d = tf.reshape(f1d, [1,ncol,42]) # 2D features f2d_dca = tf.cond(nrow>1, lambda: fast_dca(msa1hot, weights), lambda: tf.zeros([ncol,ncol,442], tf.float32)) f2d_dca = tf.expand_dims(f2d_dca, axis=0) f2d = tf.concat([tf.tile(f1d[:,:,None,:], [1,1,ncol,1]), tf.tile(f1d[:,None,:,:], [1,ncol,1,1]), f2d_dca], axis=-1) f2d = tf.reshape(f2d, [1,ncol,ncol,442+2*42]) # # 2D network # # store ensemble of networks in separate branches layers2d = [[] for _ in range(len(w))] preds = [[] for _ in range(4)] Activation = tf.nn.elu for i in range(len(w)): layers2d[i].append(Conv2d(f2d,w[i][0],b[i][0])) layers2d[i].append(InstanceNorm(layers2d[i][-1],beta_[i][0],gamma_[i][0])) layers2d[i].append(Activation(layers2d[i][-1])) # resnet idx = 1 dilation = 1 for _ in range(n2d_layers): layers2d[i].append(Conv2d(layers2d[i][-1],w[i][idx],b[i][idx],dilation)) layers2d[i].append(InstanceNorm(layers2d[i][-1],beta_[i][idx],gamma_[i][idx])) layers2d[i].append(Activation(layers2d[i][-1])) idx += 1 layers2d[i].append(Conv2d(layers2d[i][-1],w[i][idx],b[i][idx],dilation)) layers2d[i].append(InstanceNorm(layers2d[i][-1],beta_[i][idx],gamma_[i][idx])) layers2d[i].append(Activation(layers2d[i][-1] + layers2d[i][-6])) idx += 1 dilation *= 2 if dilation > 16: dilation = 1 # probabilities for theta and phi preds[0].append(tf.nn.softmax(Conv2d(layers2d[i][-1],w[i][123],b[i][123]))[0]) preds[1].append(tf.nn.softmax(Conv2d(layers2d[i][-1],w[i][124],b[i][124]))[0]) # symmetrize layers2d[i].append(0.5*(layers2d[i][-1]+tf.transpose(layers2d[i][-1],perm=[0,2,1,3]))) # probabilities for dist and omega preds[2].append(tf.nn.softmax(Conv2d(layers2d[i][-1],w[i][125],b[i][125]))[0]) preds[3].append(tf.nn.softmax(Conv2d(layers2d[i][-1],w[i][127],b[i][127]))[0]) #preds[4].append(tf.nn.softmax(Conv2d(layers2d[i][-1],w[i][126],b[i][126]))[0]) # average over all branches prob_theta = tf.reduce_mean(tf.stack(preds[0]),axis=0) prob_phi = tf.reduce_mean(tf.stack(preds[1]),axis=0) prob_dist = tf.reduce_mean(tf.stack(preds[2]),axis=0) prob_omega = tf.reduce_mean(tf.stack(preds[3]),axis=0) with tf.Session(config=config) as sess: # loop over all A3M files in the imput folder for filename in os.listdir(args.ALNDIR): if not filename.endswith(".a3m"): continue # parse & predict a3m = parse_a3m(args.ALNDIR + '/' + filename) print("processing:", filename) pd, pt, pp, po = sess.run([prob_dist, prob_theta, prob_phi, prob_omega], feed_dict = {msa : a3m, ncol : a3m.shape[1], nrow : a3m.shape[0] }) # save distograms & anglegrams npz_file = args.NPZDIR + '/' + filename[:-3] + 'npz' np.savez_compressed(npz_file, dist=pd, omega=po, theta=pt, phi=pp)
gjoni/trRosetta
network/predict_many.py
predict_many.py
py
4,388
python
en
code
192
github-code
36
[ { "api_name": "warnings.filterwarnings", "line_number": 2, "usage_type": "call" }, { "api_name": "logging.disable", "line_number": 3, "usage_type": "call" }, { "api_name": "logging.WARNING", "line_number": 3, "usage_type": "attribute" }, { "api_name": "os.environ"...
21203385181
from pyramid_promosite.models import ( DBSession, Page, ) from pyramid.view import view_config @view_config(route_name='admin', renderer='admin/index.jinja2', permission="authenticated") def admin(request): pages = DBSession.query(Page).filter(Page.orign_page_id == 0).\ order_by(Page.position).all() return dict(pages=pages)
uralbash/pyramid_promosite
pyramid_promosite/views/admin.py
admin.py
py
386
python
en
code
12
github-code
36
[ { "api_name": "pyramid_promosite.models.DBSession.query", "line_number": 12, "usage_type": "call" }, { "api_name": "pyramid_promosite.models.Page", "line_number": 12, "usage_type": "argument" }, { "api_name": "pyramid_promosite.models.DBSession", "line_number": 12, "usage...
35919702620
import difflib import redis from pymongo import MongoClient, ASCENDING client = MongoClient('mongodb+srv://Alex:goit123@utcluster.zrkwr.mongodb.net/myFirstDatabase?retryWrites=true&w=majority') def command_assistant(): commands = ['add', 'show', 'delete', 'show_all', 'exit', 'update'] # list of commands r = redis.StrictRedis(host='localhost', port=6379, db=0) while True: command = str(input('Enter command:\n>>> ')).lower().strip() if not command in commands: # prediction logic if r.get(command): # checking cache print(f"(Cache)Perhaps you mean {(r.get(command)).decode('utf-8')}") ans = str(input("Answer (Y/N): ")).lower() if ans == "n": print("Command input error, try again") continue elif ans == "y": variant = r.get(command).decode('utf-8') break else: variant = str(difflib.get_close_matches(command, commands, cutoff=0.1, n=1))[2:-2] # prediction realisation print(f"Perhaps you mean {variant}") answer = str(input("Answer (Y/N): ")).lower() if answer == "n": print("Command input error, try again") continue elif answer == "y": r.set(command, variant) break else: variant = command break return variant if __name__ == '__main__': with client: db = client.myfirst_mongoDB print(f'{" "*20}*** Welcome to Personal assistant Contact book DB edition!***') print("Commands:\n - add;\n - show;\n - show_all;\n - delete;\n - update;\n - exit\n") while True: try: answer = command_assistant() except (ConnectionRefusedError, redis.exceptions.ConnectionError, ConnectionError) as Error: print("Error! Connection problems to Redis. App is working without command prediction") answer = str(input('Enter command:\n>>> ')).lower().strip() if answer == 'add': name = input('Enter name: ') if db.ContactBook.find_one({'name': name}): print(f"The record with name '{name}' is already exist. Try another name or update the one") continue phone = input('Enter phone: ') email = input('Enter email: ') db.ContactBook.insert_one({'name': name, 'email': email, 'phone': phone}) print('New record successfully added') continue elif answer == 'show_all': for rec in db.ContactBook.find(): print(f'name = {rec["name"]}, phone = {rec["phone"]}, email = {rec["email"]}') continue elif answer == 'delete': name = input('Enter name: ') if db.ContactBook.find_one({'name': name}): db.ContactBook.delete_one({'name': name}) print(f'Record with name "{name}" has been successfully deleted') continue else: print("There is no such record in DB") continue elif answer == 'show': name = input('Enter name: ') result = db.ContactBook.find_one({'name': name}) if result: print(f'name = {result["name"]}, phone = {result["phone"]}, email = {result["email"]}') else: print("There is no such record in DB") continue elif answer == 'update': name = input('Enter name: ') if db.ContactBook.find_one({'name': name}): print("The record exists in DB. Enter a new data:") phone = input('Enter phone: ') email = input('Enter email: ') db.ContactBook.update_one({'name': name},{'$set':{'name': name, 'email': email, 'phone': phone}}) print(f'Record "{name}" has been successfully updated') continue else: print("There is no such record in DB. Try another command") continue elif answer == 'exit': break else: print("Command input error. Try correct command again") continue print("Good bye!")
AlexUtchenko/goit-python
WEB10/PA_Mongo_Redis.py
PA_Mongo_Redis.py
py
4,755
python
en
code
0
github-code
36
[ { "api_name": "pymongo.MongoClient", "line_number": 6, "usage_type": "call" }, { "api_name": "redis.StrictRedis", "line_number": 10, "usage_type": "call" }, { "api_name": "difflib.get_close_matches", "line_number": 24, "usage_type": "call" }, { "api_name": "redis....
39989734557
#%% import os from transformers import pipeline, AutoTokenizer def EvalModel(modelname, input_words, author_name=None, out_lines_number=None, temperature=None): model = os.path.join("models", modelname) tokenizer = AutoTokenizer.from_pretrained("GroNLP/gpt2-small-italian") pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) result = pipe(input_words)[0]['generated_text'].replace(" .", ".") return result
AndPazzaglia/xEleonora2
utils/EvalModel.py
EvalModel.py
py
444
python
en
code
0
github-code
36
[ { "api_name": "os.path.join", "line_number": 6, "usage_type": "call" }, { "api_name": "os.path", "line_number": 6, "usage_type": "attribute" }, { "api_name": "transformers.AutoTokenizer.from_pretrained", "line_number": 7, "usage_type": "call" }, { "api_name": "tra...
72201720423
import argparse import transformers from transformers import AutoModel, AutoTokenizer import numpy as np import torch import logging from pathlib import Path from os.path import exists import os import pandas as pd from tqdm import tqdm from datasets import load_dataset from transformers import AutoTokenizer, DataCollatorWithPadding, AutoModelForSequenceClassification, TrainingArguments, Trainer import csv, json import evaluate from datasets import Dataset from captum.influence import TracInCP, TracInCPFast, TracInCPFastRandProj from sklearn.metrics import auc, roc_curve from torch import tensor from transformers.pipelines import TextClassificationPipeline from captum.attr import LayerIntegratedGradients, TokenReferenceBase, visualization import matplotlib.pyplot as plt import jsonlines labelToModelLogitIndex = { "Negative": 0, "Positive": 1, } colsToRemove = { "imdb": [ "text" ] } labelTag = { "imdb": "label" } parser = argparse.ArgumentParser() parser.add_argument( "-info", action="store_true", help="Boolean flag to enable info mode" ) parser.add_argument( "-log", "--logFile", type=str, help="Path to file to print logging information", default=None ) parser.add_argument( "-cacheDir", help="Path to cache location for Huggingface", default="/scratch/general/vast/u1419542/huggingface_cache/" ) parser.add_argument( "-dataset", choices = [ "imdb", ], default="imdb", ) parser.add_argument( "-numEpochs", type=int, help="Number of epochs to train model for", default=1 ) parser.add_argument( "-batchSize", type=int, help="Batch size of dataloader", default=16 ) parser.add_argument( "-learningRate", type=float, help="Learning rate for optimizer", default=2e-5 ) parser.add_argument( "-weightDecay", type=float, help="Weight Decay for optimizer", default=0.01 ) parser.add_argument( "-model", help="Path to model to use", default="microsoft/deberta-v3-large" ) parser.add_argument( "-out", "--output_dir", help="Path to output directory where trained model is to be saved", required=True ) parser.add_argument( '-seed', type=int, help='Random seed', default=13 ) parser.add_argument( "-do_train", action="store_true", help="Boolean flag to train model" ) parser.add_argument( "-do_predict", action="store_true", help="Boolean flag to make predictions" ) parser.add_argument( "-cpu", "--use_cpu", action="store_true", help="Boolean flag to use cpu only" ) #--------------------------------------------------------------------------- def checkIfExists(path, isDir=False, createIfNotExists=False): if isDir and not path.endswith("/"): raise ValueError("Directory path should end with '/'") pathExists = exists(path) if not pathExists: if createIfNotExists: os.makedirs(path) else: raise ValueError(f"{path} is an invalid path!") if not isDir: filePath = Path(path) if not filePath.is_file(): raise ValueError(f"{path} is not a file!") #--------------------------------------------------------------------------- def checkFile(fileName, fileExtension=None): if fileExtension: if not fileName.endswith(fileExtension): raise ValueError(f"[checkFile] {fileName} does not have expected file extension {fileExtension}!") file_exists = exists(fileName) if not file_exists: raise RuntimeError(f"[checkFile] {fileName} is an invalid file path!") path = Path(fileName) if not path.is_file(): raise RuntimeError(f"[checkFile] {fileName} is not a file!") #--------------------------------------------------------------------------- class ComputeMetrics: def __init__(self, metricName="accuracy"): self.metricName = metricName self.metric = evaluate.load(metricName) def __call__(self, evalPreds): predictions, labels = evalPreds predictions = np.argmax(predictions, axis=1) return self.metric.compute(predictions=predictions, references=labels) #--------------------------------------------------------------------------- class Tokenize: def __init__(self, tokenizer, dataset): self.tokenizer = tokenizer self.dataset = dataset def __call__(self, example): # return self.tokenizer(inputToPrompt(example, self.dataset), truncation=True) return self.tokenizer(example["text"], truncation=True) #--------------------------------------------------------------------------- def inputToPrompt(instance, dataset): if dataset == "imdb": inpPrompt = "Review: {review}\nWhat is the sentiment of the review: negative or positive?".format( review=instance["text"] ) else: raise ValueError("[inputToPrompt] {} not supported!".format(dataset)) return inpPrompt #--------------------------------------------------------------------------- def writeFile(data, fileName): if fileName.endswith(".csv"): with open(fileName, 'w', newline='') as f: writer = csv.DictWriter(f, data[0].keys()) writer.writeheader() writer.writerows(data) elif fileName.endswith(".json"): with open(fileName, "w") as f: json.dump(data, f) elif fileName.endswith(".jsonl"): with open(fileName, "w") as f: for instance in data: f.write(json.dumps(instance)) f.write("\n") else: raise ValueError("[readFile] {} has unrecognized file extension!".format(fileName)) #--------------------------------------------------------------------------- def collateBatch(batch): return zip(*batch) #--------------------------------------------------------------------------- def createDataLoader(ds, batchSize, collateFn=collateBatch): return torch.utils.data.DataLoader( ds, batch_size=batchSize, num_workers=0, shuffle=True, collate_fn=collateFn, ) # --------------------------------------------------------------------------- class DeBertaWrapper(torch.nn.Module): def __init__(self, model, device="cpu"): super(DeBertaWrapper, self).__init__() self.model = model self.device = device self.model.to(device) def __call__(self, *inputs): inputs = torch.tensor(inputs, device=self.device).squeeze() return torch.tensor(self.model(inputs)["logits"]) # return self.model(*inputs) def children(self): return self.model.children() # --------------------------------------------------------------------------- def main(): args = parser.parse_args() np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) if args.logFile: checkFile(args.logFile) logging.basicConfig(filename=args.logFile, filemode='w', level=logging.INFO) elif args.info: logging.basicConfig(filemode='w', level=logging.INFO) else: # logging.basicConfig(filemode='w', level=logging.ERROR) logging.basicConfig(filemode='w', level=logging.INFO) if torch.cuda.is_available() and not args.use_cpu: logging.info("Using GPU: cuda") device = "cuda" else: logging.info("Using CPU") device = "cpu" if args.batchSize <= 0: raise ValueError("[main] Batch Size has to be a positive number!") data = load_dataset(args.dataset, cache_dir=args.cacheDir) data = data.shuffle(seed=args.seed) if "train" not in data.keys(): raise RuntimeError("[main] No train split found in {} dataset!".format(args.dataset)) if "test" not in data.keys(): raise RuntimeError("[main] No test split found in {} dataset!".format(args.dataset)) data["train"] = data["train"].select(np.random.choice(len(data["train"]), 10)) data["test"] = data["test"].select(np.random.choice(len(data["test"]), 2)) tokenizer = AutoTokenizer.from_pretrained(args.model) model = AutoModelForSequenceClassification.from_pretrained(args.model, num_labels=len(labelToModelLogitIndex)) model.to(device) tokenizedDatasets = data.map(Tokenize(tokenizer, args.dataset), batched=True, remove_columns=colsToRemove[args.dataset]) tokenizedDatasets = tokenizedDatasets.rename_column(labelTag[args.dataset], "labels") dataCollator = DataCollatorWithPadding(tokenizer=tokenizer, padding="max_length", max_length=1024) if args.do_train or args.do_predict: trainingArgs = TrainingArguments( output_dir=args.output_dir, num_train_epochs=args.numEpochs, learning_rate=args.learningRate, weight_decay=args.weightDecay, per_device_train_batch_size=args.batchSize, per_device_eval_batch_size=args.batchSize, evaluation_strategy="steps", save_strategy="steps", save_steps=50, eval_steps=50, save_total_limit=100, metric_for_best_model="accuracy", load_best_model_at_end=True, bf16=True, gradient_accumulation_steps=4, gradient_checkpointing=True ) trainer = Trainer( model, trainingArgs, train_dataset=tokenizedDatasets["train"], eval_dataset=tokenizedDatasets["test"], data_collator=dataCollator, tokenizer=tokenizer, compute_metrics=ComputeMetrics("accuracy") ) if args.do_train: #Train the model trainer.train() if args.do_predict: #Sample 10 mispredictions randomly predictions = trainer.predict(tokenizedDatasets["test"]) preds = np.argmax(predictions.predictions, axis=-1) incorrectInds = np.where(~np.equal(preds, tokenizedDatasets["test"]["labels"]))[0] assert len(incorrectInds) >= 10 testData = data["test"] testData = testData.add_column("predicted", preds) if args.dataset == "imdb": testData = testData.rename_column("text", "review") allData = Dataset.from_dict(testData[incorrectInds]) sampledData = Dataset.from_dict(testData[np.random.choice(incorrectInds, 10, replace=False)]) allData.to_json("mispredictions.jsonl", orient="records", lines=True) sampledData.to_json("mispredictions_10.jsonl", orient="records", lines=True) #Finding most influential training examples for test examples # clf = transformers.pipeline("text-classification", # model=model, # tokenizer=tokenizer, # device=device # ) # modelCheckpoints = list(os.walk(args.output_dir))[0][1] # extrChkpt = lambda path: int(path.split("-")[-1]) # sorted(modelCheckpoints, key=extrChkpt) # appendOutputDirPath = lambda path: args.output_dir + "/" + path # modelCheckpoints = list(map(appendOutputDirPath, modelCheckpoints)) # model = ExplainableTransformerPipeline(modelCheckpoints[-1], clf, device) # checkpoints_load_func = lambda _, path: ExplainableTransformerPipeline(path, clf, device) checkpoints_load_func = lambda _, path: DeBertaWrapper(AutoModelForSequenceClassification.from_pretrained(path, num_labels=len(labelToModelLogitIndex)), device) model = DeBertaWrapper(model, device) # #Generate train data in the format TracInCPFast expects # trainDataLoader = createDataLoader(tokenizedDatasets["train"], args.batchSize, dataCollator) # #Generate test data in the format TracInCPFast expects # testDataLoader = createDataLoader(tokenizedDatasets["test"], args.batchSize, dataCollator) tokenizedDatasets["train"] = tokenizedDatasets["train"].map(dataCollator) tokenizedDatasets["test"] = tokenizedDatasets["test"].map(dataCollator) tracin_cp_fast = TracInCPFast( model=model, final_fc_layer=list(model.children())[-1], train_dataset=( tokenizedDatasets["train"]["input_ids"], torch.tensor(tokenizedDatasets["train"]["labels"], device=device), ), # train_dataset=tokenizedDatasets["train"], # train_dataset=trainDataLoader, # checkpoints=modelCheckpoints, checkpoints=args.output_dir, checkpoints_load_func=checkpoints_load_func, loss_fn=torch.nn.CrossEntropyLoss(reduction="sum"), batch_size=1, vectorize=False, ) k = 10 proponents_indices, proponents_influence_scores = tracin_cp_fast.influence( # testDataLoader, ( tokenizedDatasets["test"]["input_ids"], torch.tensor(tokenizedDatasets["test"]["labels"], device=device), ), k=k, proponents=True, show_progress=True, ) opponents_indices, opponents_influence_scores = tracin_cp_fast.influence( # testDataLoader, ( tokenizedDatasets["test"]["input_ids"], torch.tensor(tokenizedDatasets["test"]["labels"], device=device), ), k=k, proponents=False, show_progress=True, ) print(proponents_indices) print(opponents_indices) #--------------------------------------------------------------------------- if __name__ == "__main__": main()
RishanthRajendhran/influenceFunctions
model.py
model.py
py
13,479
python
en
code
0
github-code
36
[ { "api_name": "argparse.ArgumentParser", "line_number": 42, "usage_type": "call" }, { "api_name": "os.path.exists", "line_number": 142, "usage_type": "call" }, { "api_name": "os.makedirs", "line_number": 145, "usage_type": "call" }, { "api_name": "pathlib.Path", ...
14300436310
# -*- coding: utf-8 -*- """ Created on Sun Jun 20 20:16:15 2021 @author: RISHBANS """ import pandas as pd mnist_data = pd.read_csv("mnist-train.csv") features = mnist_data.columns[1:] X = mnist_data[features] y = mnist_data['label'] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X/255, y, test_size =0.15, random_state = 0) import numpy as np from keras.utils import np_utils print(np.unique(y_train, return_counts = True)) n_classes = 10 y_train = np_utils.to_categorical(y_train, n_classes) y_test = np_utils.to_categorical(y_test, n_classes) from keras.models import Sequential from keras.layers import Dense, Dropout mnist_nn = Sequential() #Hidden Layer mnist_nn.add(Dense(units = 100, kernel_initializer='uniform', activation = 'relu', input_dim=784)) mnist_nn.add(Dropout(0.2)) mnist_nn.add(Dense(units = 10, kernel_initializer='uniform', activation = 'softmax')) mnist_nn.compile(optimizer = 'adam', loss = 'categorical_crossentropy',metrics = ['accuracy']) mnist_nn.fit(X_train, y_train, batch_size = 64, epochs = 20, validation_data = (X_test, y_test)) y_pred = mnist_nn.predict(X_test) y_pred = ( y_pred > 0.9)
edyoda/ML-with-Rishi
mnist_nn.py
mnist_nn.py
py
1,205
python
en
code
4
github-code
36
[ { "api_name": "pandas.read_csv", "line_number": 9, "usage_type": "call" }, { "api_name": "sklearn.model_selection.train_test_split", "line_number": 19, "usage_type": "call" }, { "api_name": "numpy.unique", "line_number": 24, "usage_type": "call" }, { "api_name": "...
38790072566
"""Module for Bresenham kernel""" import numpy as np from copa_map.util.occ_grid import OccGrid import cv2 class KernelGrid(OccGrid): """Class for creating an occupation map with widened walls""" def __init__(self, base_occ_map: OccGrid, digitize_size=0.2, num_of_borders=2): """ Constructor Args: base_occ_map: Occupancy grid map to use as basis of the kernel. The Kernel grid will have the same dimension and origin as the map digitize_size: Discretization size for grid bins num_of_borders: Number of cells around occupied cells, from which covariance factor increases linearly from 0 to 1 """ # We do not need the full map resolution, so we resize the image based on the given parameter assert digitize_size >= base_occ_map.resolution,\ "Kernel map discretization should be larger than Occupancy grid map resolution" # Rescale the occupancy map new_img_size = (np.array(base_occ_map.img.shape) * base_occ_map.resolution / digitize_size).astype(int) new_img = cv2.resize(base_occ_map.img, dsize=(new_img_size[1], new_img_size[0]), interpolation=cv2.INTER_NEAREST_EXACT) super(KernelGrid, self).__init__(img=new_img, width=base_occ_map.width, height=base_occ_map.height, resolution=digitize_size, origin=base_occ_map.orig, rotation=base_occ_map.rotation, ) self.digitize_size = digitize_size self.num_of_borders = num_of_borders self._create_map() def _create_map(self): """ Creates a grid array characterizing walls and cells near walls Reads the map and creates cells with the defined digitize_size, where walls are classified with 0 and free cells with 1. The values of surrounding cells increase linearly to 1 depending on the number of neighboring cells num_of_borders """ # Create kernel for dilation. Every pixels 8-neighbors should be extended kernel = np.ones((3, 3), np.uint8) # Get factor between extension border which determines the occupancy # Interpolates linearly so that every border increases occupancy by same amount increment = 1 / (self.num_of_borders + 1) adj_img = dil_img = self.img # Extend the wall pixels by dilating the image, then multiplying with the respective factor for occupancy # reduction for i in np.arange(0, 1, increment): if i == 0: continue # Dilate the image from last iteration by one more border # Our map has zeros where we want to extend, so we need to use the inverse dil_img = cv2.dilate(~dil_img, kernel) dil_img = ~dil_img # Change the pixels of the new border, where the old image was still white (255) and the new # is now black (0) adj_img[np.logical_and(dil_img == 0, adj_img == 255)] = i * 255 self.img = adj_img self.map = np.flipud(adj_img.astype(float) / 255)
MarvinStuede/copa-map
src/copa_map/kernel/kernel_grid.py
kernel_grid.py
py
3,359
python
en
code
0
github-code
36
[ { "api_name": "copa_map.util.occ_grid.OccGrid", "line_number": 8, "usage_type": "name" }, { "api_name": "copa_map.util.occ_grid.OccGrid", "line_number": 10, "usage_type": "name" }, { "api_name": "numpy.array", "line_number": 26, "usage_type": "call" }, { "api_name...
9044988683
from __future__ import annotations from abc import abstractmethod, ABC from typing import Optional from api.mvc.controller.content_model.i_content_model_controller import IContentModelController from api.mvc.controller.project.i_project_controller import IProjectController from api.mvc.controller.property.i_property_controller import IPropertyController from api.mvc.model.data.aspect_model import AspectModel from api.mvc.model.data.content_model import ContentModel from api.mvc.model.data.content_type_model import ContentTypeModel from api.mvc.model.data.data_model import DataModel from api.mvc.model.data.data_type import DataType from api.mvc.model.data.folder_type_model import FolderTypeModel from api.mvc.model.data.property_model import PropertyModel from api.mvc.model.data.type_model import TypeModel from api.mvc.model.service.file.content_model_service import ContentModelFileService from api_core.exception.api_exception import ApiException from api_core.helper.file_folder_helper import FileFolderHelper from api_core.mvc.controller.controller import Controller from api_core.mvc.service.model.service import Service from api_core.mvc.view.view import View class DataController(Controller, ABC): """ Controller class used to manage API project's data. """ def __init__(self, name: str, service: Service, view: View, pc: IProjectController, cmc: IContentModelController): """ Initialize a new instance of DataController class. :param name: The name of the controller. :param service: The controller's basic service. :param view: The controller's view. :param pc: A project controller. :param cmc: A content model controller. :param prc: A property controller. """ super().__init__(name, service, view) self._pc: IProjectController = pc self._cmc: IContentModelController = cmc self._prc: Optional[IPropertyController] = None self._cmfs: ContentModelFileService = ContentModelFileService() def set_property_controller(self, value: IPropertyController): """ Change value of class property '_rpc' :param value: The new value of the '_rpc' class property. """ self._prc = value def _get(self, content_model: ContentModel, data_type: str, name: str) -> Optional[DataModel]: """ Retrieves the data model of an Alfresco AIO type or aspect. :param data_type: The type of the data. :param content_model: The type's content-model. :param name: The type or aspect name. :return: The data model of a type or aspect otherwise None. """ if data_type.__eq__(DataType.TYPE.value): if name.__eq__("folder"): return FolderTypeModel(content_model) elif name.__eq__("content"): return ContentTypeModel(content_model) filename: str = FileFolderHelper.extract_filename_from_path(content_model.path) # Verification that the type exists. if self._cmfs.find_data(content_model, data_type, name) is None: return None # Verification that the aspect has been declared only once in the file. datas_name: list[str] = self._cmfs.get_data_names(content_model, data_type) if datas_name.count(name).__gt__(1): raise ApiException("{3} '{0}' was declared more than once in content model '{1}' in file '{2}'." .format(name, content_model.complete_name, filename, data_type.title())) # Verification that there is no circular inheritance. ancestors: list[str] = self.__check_ancestors(content_model, data_type, name, "{0}:{1}".format(content_model.prefix, name), []) self._check_mandatory_aspects(content_model, name, "{0}:{1}".format(content_model.prefix, name), ancestors, []) data: Optional[AspectModel | TypeModel] = None if data_type.__eq__(DataType.ASPECT.value): data = AspectModel(content_model, name, self._cmfs.get_aspect_title(content_model, name), self._cmfs.get_aspect_description(content_model, name)) else: data = TypeModel(content_model, name, self._cmfs.get_type_title(content_model, name), self._cmfs.get_type_description(content_model, name)) # Set the parent data. data.parent = self._get(content_model, self._cmfs.get_data_parent(content_model, data_type, name), name) # Set the data mandatory aspects. try: if data_type.__eq__(DataType.TYPE.value): for mandatory_aspect in self._cmfs.get_type_mandatory_aspects(content_model, name): data.add_mandatory_aspect(self._get(content_model, DataType.ASPECT.value, mandatory_aspect.rsplit(":", 1)[1])) else: for mandatory_aspect in self._cmfs.get_aspect_mandatory_aspects(content_model, name): data.add_mandatory_aspect(self._get(content_model, DataType.ASPECT.value, mandatory_aspect.rsplit(":", 1)[1])) except IndexError: raise ApiException("A mandatory aspect value of {0} '{1}' of content model '{2}' in file '{3}' is not " "valid. Its be formed this way: prefix:name." .format(data_type, name, content_model.complete_name, filename)) # Recovery of properties. properties: list[str] = self._cmfs.get_data_property_names(content_model, data) index: int = 0 property_found: bool = False maximum: int = len(properties) prop: Optional[PropertyModel] = None while index.__lt__(maximum) and not property_found: # Recovery of a property. prop = self._prc.load_property(content_model, data, properties[index]) # Verification that a property is not declared twice. (property_found, data_name) = self.is_property_exist(data, data, prop) # Not declare = addition in the data model. if not property_found: data.add_property(prop) index += 1 # property found = Declare twice = error if property_found: raise ApiException("Property '{0}' is defined twice in {1} '{2}' of content model '{3}' of file '{4}'." .format(prop.name, data.typology, data.name, content_model.complete_name, filename)) # Return the data return data def _extend(self, content_model: ContentModel, data_type: str, source_name: str, parent_name: str): """ Method allowing a datum (aspect or type) to extend over another datum. :param content_model: The data content model. :param data_type: The type of data to bind. :param source_name: The name of the data to expand. :param parent_name: The name of the parent data. """ source: DataModel = self._get(content_model, data_type, source_name) parent: DataModel = self._get(content_model, data_type, parent_name) filename: str = FileFolderHelper.extract_filename_from_path(content_model.path) if source is None: raise ApiException("The '{0}' {3} does not exist in the '{1}' content-model of the '{2} file.'" .format(source_name, content_model.complete_name, filename, data_type)) elif parent is None: raise ApiException("The '{0}' {3} does not exist in the '{1}' content-model of the '{2} file.'" .format(source_name, content_model.complete_name, filename, data_type)) self.__check_data_link(content_model, data_type, source, parent) self.__check_data_link(content_model, data_type, parent, source) self._service.extend(content_model, source, parent) def _add_mandatory(self, content_model: ContentModel, data_type: str, source_name: str, mandatory_name: str): """ Method allowing to add a "mandatory-aspect" to data (aspect or type). :param content_model: The data content model. :param data_type: The type of data to bind. :param source_name: The type of data to modify (the one that will include the new mandatory-aspect). :param mandatory_name: The name of the required aspect to add. """ # Retrieving the source data model model. source: DataModel = self._get(content_model, data_type, source_name) filename: str = FileFolderHelper.extract_filename_from_path(content_model.path) # Obligatory aspect recovery. mandatory: DataModel = self._get(content_model, DataType.ASPECT.value, mandatory_name) # Verification of the existence of data models. if source is None: raise ApiException("The '{0}' {3} does not exist in the '{1}' content-model of the '{2} file.'" .format(source_name, content_model.complete_name, filename, data_type)) elif mandatory is None: raise ApiException("The '{0}' {3} does not exist in the '{1}' content-model of the '{2} file.'" .format(source_name, content_model.complete_name, filename, data_type)) # Check that there is no circular inheritance between the two data models self.__check_data_link(content_model, data_type, source, mandatory) self.__check_data_link(content_model, data_type, mandatory, source) # Addition of the aspect in the list of mandatory aspects. self._cmfs.add_mandatory(content_model, source, mandatory) def __check_data_link(self, content_model: ContentModel, data_type: str, data_1: DataModel, data_2: DataModel): # source: str = data_1.name # complete_name: str = "{0}:{1}".format(content_model.prefix, source) filename: str = FileFolderHelper.extract_filename_from_path(content_model.path) ancestors: list[str] = self.__check_ancestors(content_model, data_type, data_1.name, data_1.complete_name, []) if data_2.name in ancestors: raise ApiException("The '{0}' {1} already has the '{2}' {1} for ancestor in the '{3}' file." .format(data_1.name, data_type, data_2.name, filename)) mandatory: list[str] = self._check_mandatory_aspects(content_model, data_1.name, data_1.complete_name, ancestors, []) if data_2.name in mandatory: raise ApiException("The '{0}' {1} already has the '{2}' {1} in the list of mandatory aspects (by " "inheritance or directly) in the '{3}' file." .format(data_1.name, data_type, data_2.name, filename)) def __check_ancestors(self, content_model: ContentModel, typology: str, source: str, complete_name: Optional[str], ancestors: list[str]) -> list[str]: if complete_name is None or (complete_name.__eq__("cm:folder") or complete_name.__eq__("cm:content") and typology.__eq__(DataType.TYPE.value)): # Removing the first element, which is the aspect we're trying to get. if len(ancestors).__gt__(0): ancestors.pop(0) return ancestors name: str = complete_name.rsplit(":", 1)[1] if self._cmfs.find_data(content_model, typology, name) is None: raise ApiException("There is an inheritance problem. {4} '{0}' inherits {5} '{1}' which does not " "exist in content model '{2}' of file '{3}'.\n" .format(ancestors[len(ancestors) - 1 if len(ancestors).__gt__(0) else 0], name, content_model.complete_name, FileFolderHelper.extract_filename_from_path(content_model.path), typology.title(), typology)) if ancestors.count(name).__gt__(0): raise ApiException("There is an inheritance problem. {3} '{0}' appears twice in the ancestors of aspect" " '{1}'.\n{2}".format(name, source, " -> ".join(ancestors), typology.title())) ancestors.append(name) return self.__check_ancestors(content_model, typology, source, self._cmfs.get_aspect_parent(content_model, name), ancestors) @abstractmethod def _check_mandatory_aspects(self, content_model: ContentModel, source: str, complete_name: Optional[str], ancestors: list[str], mandatory: list[str]) -> list[str]: pass def is_property_exist(self, data_source: DataModel, data: DataModel, property_model: PropertyModel) \ -> tuple[bool, Optional[str]]: if data.parent is not None: self.is_property_exist(data_source, data.parent, property_model) index: int = 0 maximum: int = len(data.properties) while index.__lt__(maximum) and data.properties[index].name.__ne__(property_model.name): index += 1 if index.__ne__(maximum): return True, data.name success: bool = False index = 0 maximum = len(data.mandatory) while index.__lt__(maximum) and not success: (success, data_model) = self.is_property_exist(data_source, data.mandatory[index], property_model) if not success: index += 1 if index.__ne__(maximum): return True, data.name return False, None
seedbaobab/alfresco_helper
api/mvc/controller/data/data_controller.py
data_controller.py
py
13,805
python
en
code
0
github-code
36
[ { "api_name": "api_core.mvc.controller.controller.Controller", "line_number": 25, "usage_type": "name" }, { "api_name": "abc.ABC", "line_number": 25, "usage_type": "name" }, { "api_name": "api_core.mvc.service.model.service.Service", "line_number": 30, "usage_type": "name...
28525524930
import pygame, time, random from cars import car from things import thing from shooting_thing import shoot pygame.init() display_width = 800 display_height = 600 black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) random_color = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255)) gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('fun_run_car') clock = pygame.time.Clock() car_img = pygame.image.load('car.png') dack = pygame.image.load('dack.png') def overall_music():#open music global pause pygame.mixer.music.load('Raining Bits.ogg') pygame.mixer.music.play(-1) def stop_music(): pygame.mixer.music.stop() def things_dodged(count): #counter for dodges font = pygame.font.SysFont(None, 30) text = font.render("Dodge: " + str(count), True, black) gameDisplay.blit(text, (0, 0)) #massages def text_object(text, font): TextSurface = font.render(text, True, red) return TextSurface, TextSurface.get_rect() def message_display(text, game_type): LargeText = pygame.font.Font('freesansbold.ttf', 120) TextSurf, TextRect = text_object(text, LargeText) TextRect.center = ((display_width / 2), (display_height / 2)) gameDisplay.blit(TextSurf, TextRect) pygame.display.update() time.sleep(3) stop_music() #pygame.mixer.music.stop() game_loop(game_type) def crash_sound(): pygame.mixer.music.load('Aargh7.ogg') pygame.mixer.music.play(1) def crash(game_type):#when the car crashes stop_music() crash_sound() message_display('you Crashed', game_type) def game_start(): message_display('time to play') def button(msg,x,y,w,h,ic,ac,action=None):#buttons mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x + w > mouse[0] > x and y + h > mouse[1] > y:#checking if the mouse press any button pygame.draw.rect(gameDisplay, ac, (x, y, w, h)) if click[0] == 1 and action != None: if msg == 'quit': action() else: action(msg) else: pygame.draw.rect(gameDisplay, ic, (x, y, w, h)) smallText = pygame.font.SysFont("comicsansms", 20) textSurf, textRect = text_object(msg, smallText) textRect.center = ((x + (w / 2)), (y + (h / 2))) gameDisplay.blit(textSurf, textRect) def quit_game(): pygame.quit() quit() def game_intro():#game intro screen pygame.mixer.music.load('intro_music.wav')#music pygame.mixer.music.play(-1) intro =True while intro: events = pygame.event.get() for event in events: # event per frame per sec if event.type == pygame.QUIT: pygame.quit() quit() gameDisplay.blit(dack, (0, 0)) LargeText = pygame.font.Font('freesansbold.ttf', 120) TextSurf, TextRect = text_object("fun run car", LargeText) TextRect.center = ((display_width / 2), (display_height / 2)) gameDisplay.blit(TextSurf, TextRect) #add difficulty button("normal", display_width * 0.1875, display_height * 0.85, display_width*0.125, display_height*0.085, green, white, game_loop) # first and sec x,y sec rectangle boundaries button("shooting", display_width * 0.1875, display_height * 0.65, display_width*0.125, display_height*0.085, green, white, game_loop) button("quit", display_width * 0.6875, display_height * 0.75, display_width*0.125, display_height*0.085, blue, white, quit_game) #button("register", display_width * 0.4, display_height * 0.85, display_width * 0.125, display_height * 0.085, # black, white, reg_log) # first and sec x,y sec rectangle boundaries #calls the buttons function pygame.display.update() clock.tick(15) def destroy_thing(things_list, shot):#when obstacles get destroy for thingss in things_list: if shot.y < thingss.thing_starty + thingss.thing_height and shot.y > thingss.thing_starty or \ shot.y + shot.height < thingss.thing_starty + thingss.thing_height and shot.y + shot.height > thingss.thing_starty: # checking his back of the car # print ('y crossover') if shot.x > thingss.thing_startx and shot.x < thingss.thing_startx + thingss.thing_width or \ shot.x + shot.width > thingss.thing_startx and shot.x + shot.width < thingss.thing_startx + thingss.thing_width: return thingss return 0 def reset_things(things,list_thing, dodged):#reset obstacles things.change_thing_starty_reset() things.change_thing_startx(display_width) things.change_thing_speed() things.change_thing_width() new_color = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255)) things.change_thing_color(new_color) if dodged % 7 == 0: list_thing.append(thing(random.randrange(0, display_width), -600, 4, 20, 100, random_color, 1, 1.2)) #normal gamee loop def game_loop(game_type):#main game overall_music() shoot.shooting_counter = 0 shoot_speed = -5.0 #__init__(self, car_width, car_height, x, y, car_img) list_cars = [] #cars list of objects list_cars.append(car(33, 55, (display_width * 0.45), (display_height * 0.8), car_img))#x,y,car_width,car_height,car_img creating car object x_change = 0 y_change = 0 #__init__(self,thing_startx, thing_starty, thing_speed, thing_width, thing_height, color, thing_increase_speed, thing_increase_width): list_thing = [] #obstacles list of objects list_thing.append(thing(random.randrange(0, display_width), -600, 4, 20, 100, random_color, 0.1, 0.5))#x_start,y_start,thing_speed, thing_width,thing height, color, speed_after dodge, width_increase_after_dodge shooting_list = [] y_dack = 0 dodged = 0 gameExit = False while not gameExit: for event in pygame.event.get(): # event per frame per sec, checking every event that occur in game if event.type == pygame.QUIT: pygame.quit() quit() # moving x if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5.0 elif event.key == pygame.K_RIGHT: x_change = +5.0 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0.0 # moving y if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: y_change = -5.0 elif event.key == pygame.K_DOWN: y_change = +5.0 if event.type == pygame.KEYUP: if event.key == pygame.K_UP or event.key == pygame.K_DOWN: y_change = 0.0 #shooting if game_type == 'shooting': if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: #def __init__(self, x, y, speed, width, height, color): for cars in list_cars: shooting_list.append(shoot(cars.x,cars.y, red)) # event endler for cars in list_cars: cars.move_car(x_change,y_change)#moving car gameDisplay.blit(dack, (0, 0)) # background highway drawing things_dodged(dodged) # gameDisplay.fill(black) for things in list_thing: #draw obstacles things.draw_thing(gameDisplay) things.change_thing_starty_speed()#change the y with speed for cars in list_cars: cars.draw_car(gameDisplay) # drawing the car # if cars.x > display_width -cars.car_width or cars.x < 0:#checking ends of screen crash(game_type) if cars.y > display_height - cars.car_height or cars.y < 0:#checking ends of screen crash(game_type) for things in list_thing: if things.thing_starty > display_height: #reseting after obstacles out of screen + counter reset_things(things,list_thing, dodged) dodged += 1 for cars in list_cars: for things in list_thing:#checking crash with obstacles if cars.y < things.thing_starty + things.thing_height and cars.y > things.thing_starty or \ cars.y + cars.car_height < things.thing_starty + things.thing_height and cars.y + cars.car_height > things.thing_starty: #checking his back of the car #print ('y crossover') if cars.x > things.thing_startx and cars.x < things.thing_startx + things.thing_width or \ cars.x +cars.car_width > things.thing_startx and cars.x +cars.car_width < things.thing_startx + things.thing_width: #print (cars.x) #print ("sx: " + str(things.thing_startx) + "tw: " + str(things.thing_startx + things.thing_width)) crash(game_type) #shooting if shoot.shooting_counter > 0:#checking shooting hit with obstacles and counted as dodged for shooting in shooting_list: shooting.move_shoot() shooting.draw_shoot(gameDisplay) destroy = destroy_thing(list_thing, shooting) if (destroy > 0): shooting_list.remove(shooting) list_thing.append(thing(random.randrange(0, display_width), -600, destroy.thing_speed, 20, 100, random_color, 0.1, 0.5)) # x_start,y_start,thing_speed, thing_width,thing height, color, speed_after dodge, width_increase_after_dodge list_thing.remove(destroy) dodged += 1 pygame.display.update() clock.tick(60) #fps #main game_intro()
maoriole/car-game
game_car.py
game_car.py
py
10,448
python
en
code
0
github-code
36
[ { "api_name": "pygame.init", "line_number": 7, "usage_type": "call" }, { "api_name": "random.randrange", "line_number": 24, "usage_type": "call" }, { "api_name": "pygame.display.set_mode", "line_number": 26, "usage_type": "call" }, { "api_name": "pygame.display", ...
31773538373
import pygame pygame.init() tela = pygame.display.set_mode((800, 600)) imgNave = pygame.image.load("Spacepack/Rocket.png") imgNave = pygame.transform.scale(imgNave, (200,100)) imgUFO = pygame.image.load("Spacepack/UFOBoss.png") imgUFO = pygame.transform.scale(imgUFO, (200,200)) rect_nave = imgNave.get_rect() rect_ufo = imgUFO.get_rect() posicao = (400, 300) rect_ufo = rect_ufo.move(posicao) clock = pygame.time.Clock() velocidadeNave = 7 velocidadeUFO = 5 while True: rect_ufo.move_ip(velocidadeUFO, 0) if rect_ufo.right > 800 or rect_ufo.left < 0: velocidadeUFO *= -1 imgUFO = pygame.transform.flip(imgUFO, True, False) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() tecla = pygame.key.get_pressed() if tecla[pygame.K_d]: rect_nave.move_ip(velocidadeNave, 0) if tecla[pygame.K_a]: rect_nave.move_ip(-velocidadeNave, 0) if tecla[pygame.K_w]: rect_nave.move_ip(0, -velocidadeNave) if tecla[pygame.K_s]: rect_nave.move_ip(0, velocidadeNave) if rect_nave.colliderect(rect_ufo): tela.fill((255,0,0)) fonte = pygame.font.SysFont("arial", 48) txtGameOver = fonte.render("GAME OVER!", True, (255,255,255)) tela.blit(txtGameOver,(400, 300)) pygame.display.update() pygame.time.delay(2000) pygame.quit() exit() tela.fill((0,0,0)) tela.blit(imgNave, rect_nave) tela.blit(imgUFO, rect_ufo) pygame.display.update() clock.tick(60)
rafaelleal/extensaoPythonPygame
script3.py
script3.py
py
1,453
python
en
code
0
github-code
36
[ { "api_name": "pygame.init", "line_number": 2, "usage_type": "call" }, { "api_name": "pygame.display.set_mode", "line_number": 3, "usage_type": "call" }, { "api_name": "pygame.display", "line_number": 3, "usage_type": "attribute" }, { "api_name": "pygame.image.loa...
8403047178
from typing import Any, List, Dict class Config: """ Contains parsed yaml config """ def __init__(self, config_yaml: Any) -> None: # self.query: Dict[str, TableConfig] = {} self._parse_conf(config_yaml) def _parse_conf(self, conf_yaml: Any) -> None: """ Parses yaml config and init python structures :param conf_yaml: config :return: None """ for conf_name, conf_dict in conf_yaml.items(): if conf_name == 'sources': self._parse_sources_conf(conf_dict) def _parse_sources_conf(self, conf_yaml: dict): """ Parses "sources" config params :param conf_yaml: config :return: None """ for conf_name, conf_dict in conf_yaml.items(): if conf_name == 'relational_db': self.querys = _get_key_2_conf(conf_dict, QueryConfig) class QueryConfig: """ Parses table config. Example: user_table: db: 'datatp' schema: 'detail' connector_type: 'mysql_db' query: 'select * from [schema].[name]' """ db: str schema: str connector_type: str query: str def __init__(self, conf: Dict): self.schema = conf.get('schema', '') self.name = conf.get('name', '') self.storage_key = conf.get('storage', '') self.storage_type = conf.get('connector_type', '') self.query_template = conf.get('query_template', '') self.expected_columns = conf.get('expected_columns', []) self.allow_empty = True if conf.get('allow_empty', 'no') == 'yes' else False class TableConfig: """ Parses table config. Example: user_table: schema: 'trading_2018' name: 'All_Users_Table' storage: 'trading_db' connector_type: 'mock' expected_columns: [ 'LOGIN', 'NAME' ] query_template: 'select * from [schema].[name]' """ schema: str name: str storage_key: str storage_type: str query_template: str expected_columns: List[str] def __init__(self, conf: Dict): self.schema = conf.get('schema', '') self.name = conf.get('name', '') self.storage_key = conf.get('storage', '') self.storage_type = conf.get('connector_type', '') self.query_template = conf.get('query_template', '') self.expected_columns = conf.get('expected_columns', []) self.allow_empty = True if conf.get('allow_empty', 'no') == 'yes' else False def _get_key_2_conf(conf_dict: dict, class_name: Any) -> Dict[str, Any]: """ Parses deep yaml structures into key-class_object structure :param conf_dict: structures config :param class_name: structure, that describes in config :return: key-class_object """ key_2_conf_obj = {} for key, conf in conf_dict.items(): key_2_conf_obj[key] = class_name(conf) return key_2_conf_obj
parkroyal/Data_Loader
configlayer/models.py
models.py
py
2,975
python
en
code
0
github-code
36
[ { "api_name": "typing.Any", "line_number": 7, "usage_type": "name" }, { "api_name": "typing.Any", "line_number": 12, "usage_type": "name" }, { "api_name": "typing.Dict", "line_number": 46, "usage_type": "name" }, { "api_name": "typing.List", "line_number": 71,...
29580682652
#!/usr/local/bin/py import argparse import hashlib import logging import os import oss2 # pip install oss2 import re logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger('oss2').setLevel(logging.WARNING) logging.basicConfig( level=logging.INFO, format='[%(asctime)s][%(levelname)s] %(message)s', # filename='/tmp/oss-sync.log' ) _CACHE = {} ROOT_API_KEY = os.path.join(os.getenv('HOME'), '.aliyun') # Doc: https://help.aliyun.com/knowledge_detail/5974206.htm # 青岛节点外网地址: oss-cn-qingdao.aliyuncs.com # 青岛节点内网地址: oss-cn-qingdao-internal.aliyuncs.com # # 北京节点外网地址:oss-cn-beijing.aliyuncs.com # 北京节点内网地址:oss-cn-beijing-internal.aliyuncs.com # # 杭州节点外网地址: oss-cn-hangzhou.aliyuncs.com # 杭州节点内网地址: oss-cn-hangzhou-internal.aliyuncs.com # # 上海节点外网地址: oss-cn-shanghai.aliyuncs.com # 上海节点内网地址: oss-cn-shanghai-internal.aliyuncs.com # # 香港节点外网地址: oss-cn-hongkong.aliyuncs.com # 香港节点内网地址: oss-cn-hongkong-internal.aliyuncs.com # # 深圳节点外网地址: oss-cn-shenzhen.aliyuncs.com # 深圳节点内网地址: oss-cn-shenzhen-internal.aliyuncs.com # # 美国节点外网地址: oss-us-west-1.aliyuncs.com # 美国节点内网地址: oss-us-west-1-internal.aliyuncs.com # # 新加坡节点外网地址: oss-ap-southeast-1.aliyuncs.com # 新加坡节点内网地址: oss-ap-southeast-1-internal.aliyuncs.com # # 原地址oss.aliyuncs.com 默认指向杭州节点外网地址。 # 原内网地址oss-internal.aliyuncs.com 默认指向杭州节点内网地址 API_URL = 'oss-cn-hangzhou.aliyuncs.com' IGNORE_FILES = ( '\/\..*$', '\.pyc$', ) def is_in_ignore_files(file_path): for p in IGNORE_FILES: if re.search(p, file_path): return True return False def get_file_md5(file_path): hasher = hashlib.md5() with open(file_path, 'rb') as f: buf = f.read(65536) while len(buf) > 0: hasher.update(buf) buf = f.read(65536) return hasher.hexdigest() def sizeof_fmt(num): if num <= 1024: return '1 KB' for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, x) num /= 1024.0 def get_bucket(args): if 'bucket' in _CACHE: return _CACHE['bucket'] api_key = open(os.path.join(ROOT_API_KEY, 'apikey')).read().strip() api_secret = open(os.path.join(ROOT_API_KEY, 'secretkey')).read().strip() auth = oss2.Auth(api_key, api_secret) bucket = oss2.Bucket(auth, API_URL, args.bucket) _CACHE['bucket'] = bucket return bucket def get_local_objects(target_path): objects = {} oss_dir = os.path.dirname(__file__) if target_path: oss_dir = os.path.join(oss_dir, target_path) else: oss_dir = os.path.join(oss_dir, '.') if not os.path.exists(oss_dir): return objects file_count = 0 if os.path.isdir(oss_dir): for root, dirs, files in os.walk(oss_dir): for f in files: root = re.sub(r'^\./?', '', root) local_path = os.path.join(root, f) if is_in_ignore_files(local_path): logging.info('ignored file: {}'.format(local_path)) continue md5 = get_file_md5(local_path) objects[local_path] = md5.upper() file_count += 1 else: md5 = get_file_md5(oss_dir) local_path = re.sub(r'^\./', '', target_path) objects[local_path] = md5.upper() file_count += 1 logging.info('local files: {}'.format(file_count)) return objects def get_remote_objects(args): objects = {'files': {}, 'etags': {}, 'meta': {}} bucket = get_bucket(args) marker = None file_count = 0 prefix = re.sub(r'^\./?', '', args.target_path or '') while True: result = bucket.list_objects(prefix=prefix, max_keys=100, marker=marker) for obj in result.object_list: if obj.key.endswith('/'): continue if args.min_size and obj.size < args.min_size: continue if args.max_size and obj.size > args.max_size: continue if args.re and not re.search(args.re, obj.key): continue objects['files'][obj.key] = obj.etag objects['etags'][obj.etag] = obj.key objects['meta'][obj.key] = obj file_count += 1 marker = result.next_marker if not result.is_truncated: break logging.info('remote files: {}'.format(file_count)) return objects def upload_file(local_path, args): bucket = get_bucket(args) key = re.sub(r'^\./?', '', local_path) res = bucket.put_object_from_file(key, local_path) if res.status != 200: logging.error('Upload {} failed. Exit.'.format(local_path)) exit(1) def upload_files_to_oss(args): target_path = re.sub(r'^\./?', '', args.target_path) logging.info('Uploading/Updating for: {}'.format(target_path)) los = get_local_objects(target_path) if args.check_duplicated: ros = get_remote_objects(args) else: ros = get_remote_objects(args) files_need_to_update = [] files_need_to_upload = [] for local_path in los.keys(): md5 = los[local_path] if md5 in ros['etags']: logging.info('* Identical file found:') logging.info('* @ {}'.format(ros['etags'][md5])) continue if local_path not in ros['files']: size = sizeof_fmt(os.path.getsize(local_path)) files_need_to_upload.append((local_path, size)) elif ros['files'][local_path] != md5: size = sizeof_fmt(os.path.getsize(local_path)) files_need_to_update.append((local_path, size)) files_need_to_update.sort() files_need_to_upload.sort() index = 1 count = len(files_need_to_update) for local_path, size in files_need_to_update: if args.no: break elif args.yes: upload_file(local_path, args) index += 1 else: print('Q: Do you want to update {}:'.format(local_path)) response = input() while response.lower().strip() not in ('yes', 'no'): print('Q: Do you want to update {}:'.format(local_path)) response = input() if response == 'no': logging.info('skipped {} by user'.format(local_path)) continue logging.info('= [{}/{}] Updating old file: {} ({})'.format( index, count, local_path, size)) upload_file(local_path, args) index += 1 index = 1 count = len(files_need_to_upload) for local_path, size in files_need_to_upload: try: logging.info('+ [{}/{}] Uploading new file: {} ({})'.format( index, count, local_path, size)) except: pass upload_file(local_path, args) index += 1 logging.info('Uploading/Updating Done\n') def _get_dir_of_file(f): return '/'.join(f.split('/')[:-1]) def download_file(oss_path, local_path, args): dir_ = _get_dir_of_file(local_path) if not os.path.exists(dir_): os.makedirs(dir_) logging.info('+ Downloading {}'.format(oss_path)) bucket = get_bucket(args) local_path = local_path.encode('utf-8') res = bucket.get_object_to_file(oss_path, local_path) if res.status != 200: logging.error('Download {} failed. Exit.'.format(oss_path)) exit(1) def list_files_on_oss(args): files = get_remote_objects(args) size_total = 0 for o in files['meta']: size_total += files['meta'][o].size if args.verbose: print('\n- file: {}'.format(o)) print('- size: {}'.format(sizeof_fmt(files['meta'][o].size))) print('- md5: {}'.format(files['meta'][o].etag)) if not args.verbose: keys_to_list = list(files['files'].keys()) keys_to_list.sort() print('== First 3 files:') for x in keys_to_list[:3]: print(' - {}'.format(x)) print('== Last 3 files:') for x in keys_to_list[-3:]: print(' - {}'.format(x)) print('\n== Total file count: {}'.format(len(files['files']))) print('== Total size: {}'.format(sizeof_fmt(size_total))) def delete_files_from_oss(args): files = get_remote_objects(args) keys_to_delete = list(files['files'].keys()) keys_to_delete.sort() print('== Will delete {} files:'.format(len(keys_to_delete))) print('== First 3 files:') for x in keys_to_delete[:3]: print(' - {}'.format(x)) print('== Last 3 files:') for x in keys_to_delete[-3:]: print(' - {}'.format(x)) answer = input('== Please enter YES to delete them ALL: ') if answer.strip() != 'YES': print('\nAction Canceled. Files are safe. Bye.') return bucket = get_bucket(args) count = 0 for x in keys_to_delete: bucket.delete_object(x) count += 1 print('- deleted: {}'.format(x)) print('\nDeleted {} files.'.format(count)) def download_files_from_oss(args): target_path = args.target_path if target_path.startswith('./'): target_path = target_path[2:] if target_path.startswith('/'): raise ValueError('Must use relative path') oss_dir = os.path.dirname(__file__) oss_dir = os.path.join(oss_dir, '.') logging.info('Downloading file from: {}'.format(target_path)) los = get_local_objects(target_path) ros = get_remote_objects(args) target_files = [] for obj_key in ros['files']: if obj_key in los and ros['files'][obj_key] == los[obj_key]: logging.info('= {} exists'.format(obj_key)) continue target_files.append(obj_key) target_files.sort() for oss_path in target_files: local_path = os.path.join(oss_dir, oss_path) download_file(oss_path, local_path, args) logging.info('Downloading Done\n') def main(): parser = argparse.ArgumentParser(description='Use Aliyun-OSS as Dropbox') parser.add_argument( '--target-path', '-p', action='store', const=None, default=None, help='Target path to sync/delete files' ) parser.add_argument( '--download', '-d', action='store_true', default=False, help='Download files from OSS' ) parser.add_argument( '--yes', action='store_true', default=False, help='overwrite existing files' ) parser.add_argument( '--no', action='store_true', default=False, help='Do NOT overwrite existing files' ) parser.add_argument( '--upload', '-u', action='store_true', default=False, help='Upload files to OSS' ) parser.add_argument( '--listing', '-L', action='store_true', default=False, help='List files meta info on OSS' ) parser.add_argument( '--min-size', type=int, default=0, help='[Listing] do not list size smaller than this' ) parser.add_argument( '--max-size', type=int, default=0, help='[Listing] do not list size bigger than this' ) parser.add_argument( '--re', type=str, default='', help='[Listing] filter file name by RE string' ) parser.add_argument( '--check-duplicated', '-c', action='store_false', default=True, help='Do not upload files already in bucket other dirs' ) parser.add_argument( '--bucket', '-b', required=True, help='bucket name to store data', ) parser.add_argument( '--delete', action='store_true', help='To delete files with prefix from OSS', ) parser.add_argument( '--verbose', '-v', action='store_true', help='Print more info', ) args = parser.parse_args() if args.listing: list_files_on_oss(args) elif args.download: download_files_from_oss(args) elif args.delete: delete_files_from_oss(args) else: upload_files_to_oss(args) if __name__ == "__main__": main()
mitnk/oss-sync
sync.py
sync.py
py
12,601
python
en
code
0
github-code
36
[ { "api_name": "logging.getLogger", "line_number": 9, "usage_type": "call" }, { "api_name": "logging.WARNING", "line_number": 9, "usage_type": "attribute" }, { "api_name": "logging.getLogger", "line_number": 10, "usage_type": "call" }, { "api_name": "logging.WARNIN...
20658918357
"""Computes eigenvalues and eigenvectors of the PMI similarity matrices for a given attribute type. Saves the results of this along with kMeans clustering of the attributes, and the assignment of graph nodes to clusters.""" import pickle import time import numpy as np import pandas as pd import optparse from scipy.sparse import coo_matrix, diags from sklearn.cluster import KMeans from gplus import * def generate_cluster_report(attr_analyzer, attr_type, cluster_labels, topN = 30): """Given the AttributeAnalyzer, attr_type, and a list of cluster labels (corresponding to the attribute vocab indices only), generates a report listing the top N members of each cluster, and the frequency and prevalence (relative frequency) of each attribute in the data set. Orders the clusters by total occurrences of attributes in each cluster. If topN = None, list all the attributes in each cluster.""" attr_freq_dict = attr_analyzer.attr_freqs_by_type[attr_type] total_attr_freqs = sum(attr_freq_dict.values()) pfa = attr_analyzer.pairwise_freq_analyzers[attr_type] attr_indices, attr_vocab = get_attr_indices(pfa, attr_analyzer.attributed_nodes) unique_cluster_labels = set(cluster_labels) # compute vocab lists for each cluster attr_vocab_by_cluster = dict((lab, []) for lab in unique_cluster_labels) for (i, lab) in enumerate(cluster_labels): v = attr_vocab[i] if v.startswith('*???*'): continue freq = attr_freq_dict[v] attr_vocab_by_cluster[lab].append((v, freq, freq / total_attr_freqs)) # sort vocab lists by decreasing frequencies for lab in unique_cluster_labels: attr_vocab_by_cluster[lab].sort(key = lambda item : item[1], reverse = True) # total number of occurrences of any attribute in each cluster total_freqs_by_cluster = dict((lab, sum([item[1] for item in attr_vocab_by_cluster[lab]])) for lab in unique_cluster_labels) info_by_cluster = dict((lab, dict()) for lab in unique_cluster_labels) # create a DataFrame for each cluster listing the top N vocab items in order with their frequencies and prevalences for lab in unique_cluster_labels: df = pd.DataFrame(attr_vocab_by_cluster[lab], columns = ['attribute', 'frequency', 'prevalence']) info_by_cluster[lab]['df'] = df if (topN is None) else df[:topN] info_by_cluster[lab]['size'] = len(attr_vocab_by_cluster[lab]) info_by_cluster[lab]['totalFreq'] = total_freqs_by_cluster[lab] info_by_cluster[lab]['totalPrevalence'] = sum(df['prevalence']) # sort clusters by decreasing number of occurrences sorted_clusters_with_total_freqs = sorted(total_freqs_by_cluster.items(), key = lambda item : item[1], reverse = True) # generate report num_attrs = len(attr_vocab) s = '' for (lab, freq) in sorted_clusters_with_total_freqs: info = info_by_cluster[lab] width = 12 + len(str(lab)) s += '#' * width + '\n' s += '# ' + 'CLUSTER ' + str(lab) + ' #\n' s += '#' * width + '\n\n' s += 'attribute prevalence = %6d / %6d = %f\n' % (info['size'], num_attrs, info['size'] / num_attrs) s += 'occurrence prevalence = %6d / %6d = %f\n\n' % (info['totalFreq'], total_attr_freqs, info['totalPrevalence']) s += info['df'].to_string(index = False) + '\n\n\n' return s # save off: # matrix or LinearOperator for similarity matrix # eigenvalues and scree plot # embedded vectors corresponding to attributes # kmeans clusters corresponding to attributes # report of top clusters # mappings from nodes to clusters of the given attribute type def main(): p = optparse.OptionParser() p.add_option('--attr_type', '-a', type = str, help = 'attribute type') p.add_option('-p', type = str, help = 'PMI type (PMIs, NPMI1s, or NPMI2s)') p.add_option('-e', type = str, help = 'embedding (adj, normlap, regnormlap)') p.add_option('-s', action = 'store_true', default = False, help = 'normalize in sphere') p.add_option('-d', type = float, help = 'smoothing parameter') p.add_option('-k', type = int, help = 'number of eigenvalues') p.add_option('-c', type = int, help = 'number of kmeans clusters') p.add_option('-t', type = float, default = None, help = 'tolerance for eigsh') p.add_option('-v', action = 'store_true', default = False, help = 'save scree plot') opts, args = p.parse_args() attr_type = opts.attr_type sim = opts.p embedding = opts.e assert (embedding in ['adj', 'normlap', 'regnormlap']) sphere = opts.s delta = opts.d k = opts.k nclusts = opts.c tol = opts.t save_plot = opts.v topN = 50 # for the report assert (((sim == 'PMIs') or (delta == 0)) and (sim in ['PMIs', 'NPMI1s', 'NPMI2s'])) data_folder = 'gplus0_lcc/data/PMI/' report_folder = 'gplus0_lcc/reports/PMI/' plot_folder = 'gplus0_lcc/plots/PMI/' file_prefix1 = ('%s_%s_%s_delta' % (attr_type, sim, embedding)) + str(delta) + ('_k%d' % k) file_prefix2 = ('%s_%s_%s_delta' % (attr_type, sim, embedding)) + str(delta) + ('_k%d%s_c%d' % (k, '_normalized' if sphere else '', nclusts)) print_flush("\nLoading AttributeAnalyzer...") a = AttributeAnalyzer() a.load_pairwise_freq_analyzer(attr_type) a.make_attrs_by_node_by_type() attrs_by_node = a.attrs_by_node_by_type[attr_type] pfa = a.pairwise_freq_analyzers[attr_type] n = pfa.num_vocab tol = (1.0 / n) if (tol is None) else tol # use 1/n instead of machine precision as default tolerance attr_indices, attr_vocab = get_attr_indices(pfa, a.attributed_nodes) try: print_flush("\nLoading labels from '%s%s_labels.csv'..." % (data_folder, file_prefix2)) labels = np.loadtxt('%s%s_labels.csv' % (data_folder, file_prefix2), dtype = int) print_flush("\nLoading cluster centers from '%s%s_cluster_centers.csv'..." % (data_folder, file_prefix2)) cluster_centers = np.loadtxt('%s%s_cluster_centers.csv' % (data_folder, file_prefix2), delimiter = ',') print_flush("\nLoading eigenvalues from '%s%s_eigvals.csv'..." % (data_folder, file_prefix1)) eigvals = np.loadtxt('%s%s_eigvals.csv' % (data_folder, file_prefix1), delimiter = ',') print_flush("\nLoading embedded features from '%s%s_features.pickle'..." % (data_folder, file_prefix1)) features = pickle.load(open('%s%s_features.pickle' % (data_folder, file_prefix1), 'rb')) if sphere: for i in range(len(attr_indices)): features[i] = normalize(features[i]) except FileNotFoundError: print_flush("Failed to load.") try: print_flush("\nLoading eigenvalues from '%s%s_eigvals.csv'..." % (data_folder, file_prefix1)) eigvals = np.loadtxt('%s%s_eigvals.csv' % (data_folder, file_prefix1), delimiter = ',') print_flush("\nLoading embedded features from '%s%s_features.pickle'..." % (data_folder, file_prefix1)) features = pickle.load(open('%s%s_features.pickle' % (data_folder, file_prefix1), 'rb')) except FileNotFoundError: print_flush("Failed to load.") print_flush("\nComputing similarity matrix (%s)..." % sim) sim_op = pfa.to_sparse_PMI_operator(sim, delta) matrix_type = 'adjacency' if (embedding == 'adj') else ('normalized Laplacian' if (embedding == 'normlap') else 'regularized normalized Laplacian') print_flush("\nComputing eigenvectors of %s matrix (k = %d)..." % (matrix_type, k)) if (embedding == 'adj'): (eigvals, features) = timeit(eigsh)(sim_op, k = k, tol = tol) features = np.sqrt(np.abs(eigvals)) * features # scale the feature columns by the sqrt of the eigenvalues elif (embedding == 'normlap'): normlap = SparseNormalizedLaplacian(sim_op) (eigvals, features) = timeit(eigsh)(normlap, k = k, tol = tol) elif (embedding == 'regnormlap'): regnormlap = SparseRegularizedNormalizedLaplacian(sim_op) (eigvals, features) = timeit(eigsh)(regnormlap, k = k, tol = tol) features = features[attr_indices, :] # free up memory by deleting embeddings of nodes with no attributes np.savetxt('%s%s_eigvals.csv' % (data_folder, file_prefix1), eigvals, delimiter = ',') pickle.dump(features, open('%s%s_features.pickle' % (data_folder, file_prefix1), 'wb')) if sphere: # normalize the features to have unit norm (better for kMeans) for i in range(len(attr_indices)): features[i] = normalize(features[i]) km = KMeans(nclusts) print_flush("\nClustering attribute feature vectors into %d clusters using kMeans..." % nclusts) labels = timeit(km.fit_predict)(features) # save the cluster labels np.savetxt('%s%s_labels.csv' % (data_folder, file_prefix2), np.array(labels, dtype = int), delimiter = ',', fmt = '%d') # save the cluster centers cluster_centers = km.cluster_centers_ np.savetxt('%s%s_cluster_centers.csv' % (data_folder, file_prefix2), cluster_centers, delimiter = ',') # save the attribute cluster report with open('%s%s_cluster_report.txt' % (report_folder, file_prefix2), 'w') as f: f.write(generate_cluster_report(a, attr_type, labels, topN)) if save_plot: print_flush("\nSaving scree plot to '%s%s_screeplot.png'..." % (plot_folder, file_prefix1)) scree_plot(eigvals, show = False, filename = '%s%s_screeplot.png' % (plot_folder, file_prefix1)) print_flush("\nAssigning cluster labels to each node...") indices_by_vocab = dict((v, i) for (i, v) in enumerate(attr_vocab)) centers = [normalize(center) for center in cluster_centers] if sphere else cluster_centers def assign_cluster(node): """Assigns -1 to a node with no attribute present. Otherwise, takes the cluster whose center is closest to the mean of the attribute vectors. Uses cosine distance if sphere = True, otherwise Euclidean distance.""" if (node not in attrs_by_node): return -1 else: attrs = list(attrs_by_node[node]) if (len(attrs) == 1): return labels[indices_by_vocab[attrs[0]]] else: vec = np.zeros(k, dtype = float) for attr in attrs: vec += features[indices_by_vocab[attr]] vec /= len(attrs) if sphere: vec = normalize(vec) sims = [np.dot(vec, center) for center in centers] else: sims = [-np.linalg.norm(vec - center) for center in centers] max_index, max_sim = -1, -float('inf') for (i, sim) in enumerate(sims): if (sim > max_sim): max_index = i max_sim = sim return max_index # save file with the list of cluster labels for each node clusters_by_node = [assign_cluster(i) for i in range(a.num_vertices)] np.savetxt('%s%s_node_labels.csv' % (data_folder, file_prefix2), np.array(clusters_by_node, dtype = int), delimiter = ',', fmt = '%d') print_flush("\nDone!") if __name__ == "__main__": main()
jeremander/Gplus
factor_attr_mat.py
factor_attr_mat.py
py
11,356
python
en
code
2
github-code
36
[ { "api_name": "pandas.DataFrame", "line_number": 36, "usage_type": "call" }, { "api_name": "optparse.OptionParser", "line_number": 65, "usage_type": "call" }, { "api_name": "numpy.loadtxt", "line_number": 108, "usage_type": "call" }, { "api_name": "numpy.loadtxt",...
38665711112
# -*- coding: utf-8 -*- from __future__ import (unicode_literals, division, absolute_import, print_function) import six __license__ = 'GPL v3' __copyright__ = '2021, Jim Miller' __docformat__ = 'restructuredtext en' import logging logger = logging.getLogger(__name__) import re import threading from collections import OrderedDict from PyQt5 import QtWidgets as QtGui from PyQt5.Qt import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QLabel, QLineEdit, QComboBox, QCheckBox, QPushButton, QTabWidget, QScrollArea, QGroupBox, QButtonGroup, QRadioButton, Qt) from calibre.gui2 import dynamic, info_dialog from calibre.gui2.complete2 import EditWithComplete from calibre.gui2.dialogs.confirm_delete import confirm from fanficfare.six import text_type as unicode try: from calibre.ebooks.covers import generate_cover as cal_generate_cover HAS_CALGC=True except: HAS_CALGC=False # pulls in translation files for _() strings try: load_translations() except NameError: pass # load_translations() added in calibre 1.9 from calibre.library.field_metadata import FieldMetadata field_metadata = FieldMetadata() # There are a number of things used several times that shouldn't be # translated. This is just a way to make that easier by keeping them # out of the _() strings. # I'm tempted to override _() to include them... no_trans = { 'pini':'personal.ini', 'gcset':'generate_cover_settings', 'ccset':'custom_columns_settings', 'gc':'Generate Cover', 'rl':'Reading List', 'cp':'Count Pages', 'cmplt':'Completed', 'inprog':'In-Progress', 'lul':'Last Updated', 'lus':'lastupdate', 'is':'include_subject', 'isa':'is_adult', 'u':'username', 'p':'password', } STD_COLS_SKIP = ['size','cover','news','ondevice','path','series_sort','sort'] from calibre_plugins.fanficfare_plugin.prefs import ( prefs, rejects_data, PREFS_NAMESPACE, prefs_save_options, updatecalcover_order, gencalcover_order, do_wordcount_order, SAVE_YES, SAVE_NO) from calibre_plugins.fanficfare_plugin.dialogs import ( UPDATE, UPDATEALWAYS, collision_order, save_collisions, RejectListDialog, EditTextDialog, IniTextDialog, RejectUrlEntry) from fanficfare.adapters import getSiteSections, get_section_url from calibre_plugins.fanficfare_plugin.common_utils import ( KeyboardConfigDialog, PrefsViewerDialog, busy_cursor ) class RejectURLList: def __init__(self,prefs,rejects_data): self.prefs = prefs self.rejects_data = rejects_data self.sync_lock = threading.RLock() self.listcache = None def _read_list_from_text(self,text,addreasontext='',normalize=True): cache = OrderedDict() #print("_read_list_from_text") for line in text.splitlines(): rue = RejectUrlEntry(line,addreasontext=addreasontext, fromline=True,normalize=normalize) #print("rue.url:%s"%rue.url) if rue.valid: cache[get_section_url(rue.url)] = rue return cache ## Note that RejectURLList now applies ## adapters.get_section_url(url) to all urls before caching and ## before checking so ffnet/a/123/1/Title -> ffnet/a/123/1/, ## xenforo too. Saved list still contains full URL so we're not ## destorying any data. Could have duplicates, though. def _get_listcache(self): with busy_cursor(): if self.listcache == None: # logger.debug("prefs['last_saved_version']:%s"%unicode(self.prefs['last_saved_version'])) if tuple(self.prefs['last_saved_version']) > (3, 1, 7) and \ self.rejects_data['rejecturls_data']: # logger.debug("_get_listcache: rejects_data['rejecturls_data']") self.listcache = OrderedDict() for x in self.rejects_data['rejecturls_data']: rue = RejectUrlEntry.from_data(x) if rue.valid: # if rue.url != get_section_url(rue.url): # logger.debug("\n=============\nurl:%s section:%s\n================"%(rue.url,get_section_url(rue.url))) section_url = get_section_url(rue.url) if section_url in self.listcache: logger.debug("Duplicate in Reject list: %s %s (use longer)"%( self.listcache[section_url].url, rue.url)) ## if there's a dup, keep the one with the ## longer URL, more likely to be titled ## version. if( section_url not in self.listcache or len(rue.url) > len(self.listcache[section_url].url) ): self.listcache[section_url] = rue else: # Assume saved rejects list is already normalized after # v2.10.9. If normalization needs to change someday, can # increase this to do it again. normalize = tuple(self.prefs['last_saved_version']) < (2, 10, 9) #print("normalize:%s"%normalize) self.listcache = self._read_list_from_text(self.prefs['rejecturls'], normalize=normalize) if normalize: self._save_list(self.listcache,clearcache=False) # logger.debug("_get_listcache: prefs['rejecturls']") # logger.debug(self.listcache) # logger.debug([ x.to_data() for x in self.listcache.values()]) return self.listcache def _save_list(self,listcache,clearcache=True): with busy_cursor(): #print("_save_list") ## As of July 2020 it's been > 1.5 years since ## rejects_data added. Stop keeping older version in ## prefs. del self.prefs['rejecturls'] self.prefs.save_to_db() rejects_data['rejecturls_data'] = [x.to_data() for x in listcache.values()] rejects_data.save_to_db() if clearcache: self.listcache = None def clear_cache(self): self.listcache = None # true if url is in list. def check(self,url): # logger.debug("Checking %s(%s)"%(url,get_section_url(url))) url = get_section_url(url) with self.sync_lock: listcache = self._get_listcache() return url in listcache def get_note(self,url): url = get_section_url(url) with self.sync_lock: listcache = self._get_listcache() if url in listcache: return listcache[url].note # not found return '' def get_full_note(self,url): url = get_section_url(url) with self.sync_lock: listcache = self._get_listcache() if url in listcache: return listcache[url].fullnote() # not found return '' def remove(self,url): url = get_section_url(url) with self.sync_lock: listcache = self._get_listcache() if url in listcache: del listcache[url] self._save_list(listcache) def add_text(self,rejecttext,addreasontext): self.add(list(self._read_list_from_text(rejecttext,addreasontext).values())) def add(self,rejectlist,clear=False): with self.sync_lock: if clear: listcache=OrderedDict() else: listcache = self._get_listcache() for l in rejectlist: listcache[get_section_url(l.url)]=l self._save_list(listcache) def get_list(self): return list(self._get_listcache().values()) def get_reject_reasons(self): return self.prefs['rejectreasons'].splitlines() rejecturllist = RejectURLList(prefs,rejects_data) class ConfigWidget(QWidget): def __init__(self, plugin_action): QWidget.__init__(self) self.plugin_action = plugin_action self.l = QVBoxLayout() self.setLayout(self.l) label = QLabel('<a href="'\ +'https://github.com/JimmXinu/FanFicFare/wiki/Supportedsites">'\ +_('List of Supported Sites')+'</a> -- <a href="'\ +'https://github.com/JimmXinu/FanFicFare/wiki/FAQs">'\ +_('FAQs')+'</a>') label.setOpenExternalLinks(True) self.l.addWidget(label) self.scroll_area = QScrollArea(self) self.scroll_area.setFrameShape(QScrollArea.NoFrame) self.scroll_area.setWidgetResizable(True) self.l.addWidget(self.scroll_area) tab_widget = QTabWidget(self) self.scroll_area.setWidget(tab_widget) self.basic_tab = BasicTab(self, plugin_action) tab_widget.addTab(self.basic_tab, _('Basic')) self.personalini_tab = PersonalIniTab(self, plugin_action) tab_widget.addTab(self.personalini_tab, 'personal.ini') self.readinglist_tab = ReadingListTab(self, plugin_action) tab_widget.addTab(self.readinglist_tab, 'Reading Lists') if 'Reading List' not in plugin_action.gui.iactions: self.readinglist_tab.setEnabled(False) self.calibrecover_tab = CalibreCoverTab(self, plugin_action) tab_widget.addTab(self.calibrecover_tab, _('Calibre Cover')) self.countpages_tab = CountPagesTab(self, plugin_action) tab_widget.addTab(self.countpages_tab, 'Count Pages') if 'Count Pages' not in plugin_action.gui.iactions: self.countpages_tab.setEnabled(False) self.std_columns_tab = StandardColumnsTab(self, plugin_action) tab_widget.addTab(self.std_columns_tab, _('Standard Columns')) self.cust_columns_tab = CustomColumnsTab(self, plugin_action) tab_widget.addTab(self.cust_columns_tab, _('Custom Columns')) self.imap_tab = ImapTab(self, plugin_action) tab_widget.addTab(self.imap_tab, _('Email Settings')) self.other_tab = OtherTab(self, plugin_action) tab_widget.addTab(self.other_tab, _('Other')) def save_settings(self): with busy_cursor(): # basic prefs['fileform'] = unicode(self.basic_tab.fileform.currentText()) prefs['collision'] = save_collisions[unicode(self.basic_tab.collision.currentText())] prefs['updatemeta'] = self.basic_tab.updatemeta.isChecked() prefs['bgmeta'] = self.basic_tab.bgmeta.isChecked() prefs['keeptags'] = self.basic_tab.keeptags.isChecked() prefs['mark'] = self.basic_tab.mark.isChecked() prefs['mark_success'] = self.basic_tab.mark_success.isChecked() prefs['mark_failed'] = self.basic_tab.mark_failed.isChecked() prefs['mark_chapter_error'] = self.basic_tab.mark_chapter_error.isChecked() prefs['showmarked'] = self.basic_tab.showmarked.isChecked() prefs['autoconvert'] = self.basic_tab.autoconvert.isChecked() prefs['show_est_time'] = self.basic_tab.show_est_time.isChecked() prefs['urlsfromclip'] = self.basic_tab.urlsfromclip.isChecked() prefs['button_instantpopup'] = self.basic_tab.button_instantpopup.isChecked() prefs['updatedefault'] = self.basic_tab.updatedefault.isChecked() prefs['deleteotherforms'] = self.basic_tab.deleteotherforms.isChecked() prefs['adddialogstaysontop'] = self.basic_tab.adddialogstaysontop.isChecked() prefs['lookforurlinhtml'] = self.basic_tab.lookforurlinhtml.isChecked() prefs['checkforseriesurlid'] = self.basic_tab.checkforseriesurlid.isChecked() prefs['auto_reject_seriesurlid'] = self.basic_tab.auto_reject_seriesurlid.isChecked() prefs['mark_series_anthologies'] = self.basic_tab.mark_series_anthologies.isChecked() prefs['checkforurlchange'] = self.basic_tab.checkforurlchange.isChecked() prefs['injectseries'] = self.basic_tab.injectseries.isChecked() prefs['matchtitleauth'] = self.basic_tab.matchtitleauth.isChecked() prefs['do_wordcount'] = prefs_save_options[unicode(self.basic_tab.do_wordcount.currentText())] prefs['smarten_punctuation'] = self.basic_tab.smarten_punctuation.isChecked() prefs['reject_always'] = self.basic_tab.reject_always.isChecked() prefs['reject_delete_default'] = self.basic_tab.reject_delete_default.isChecked() if self.readinglist_tab: # lists prefs['send_lists'] = ', '.join([ x.strip() for x in unicode(self.readinglist_tab.send_lists_box.text()).split(',') if x.strip() ]) prefs['read_lists'] = ', '.join([ x.strip() for x in unicode(self.readinglist_tab.read_lists_box.text()).split(',') if x.strip() ]) # logger.debug("send_lists: %s"%prefs['send_lists']) # logger.debug("read_lists: %s"%prefs['read_lists']) prefs['addtolists'] = self.readinglist_tab.addtolists.isChecked() prefs['addtoreadlists'] = self.readinglist_tab.addtoreadlists.isChecked() prefs['addtolistsonread'] = self.readinglist_tab.addtolistsonread.isChecked() prefs['autounnew'] = self.readinglist_tab.autounnew.isChecked() # personal.ini ini = self.personalini_tab.personalini if ini: prefs['personal.ini'] = ini else: # if they've removed everything, reset to default. prefs['personal.ini'] = get_resources('plugin-example.ini') prefs['cal_cols_pass_in'] = self.personalini_tab.cal_cols_pass_in.isChecked() # Covers tab prefs['updatecalcover'] = prefs_save_options[unicode(self.calibrecover_tab.updatecalcover.currentText())] # for backward compatibility: prefs['updatecover'] = prefs['updatecalcover'] == SAVE_YES prefs['gencalcover'] = prefs_save_options[unicode(self.calibrecover_tab.gencalcover.currentText())] prefs['calibre_gen_cover'] = self.calibrecover_tab.calibre_gen_cover.isChecked() prefs['plugin_gen_cover'] = self.calibrecover_tab.plugin_gen_cover.isChecked() prefs['gcnewonly'] = self.calibrecover_tab.gcnewonly.isChecked() prefs['covernewonly'] = self.calibrecover_tab.covernewonly.isChecked() gc_site_settings = {} for (site,combo) in six.iteritems(self.calibrecover_tab.gc_dropdowns): val = unicode(combo.itemData(combo.currentIndex())) if val != 'none': gc_site_settings[site] = val #print("gc_site_settings[%s]:%s"%(site,gc_site_settings[site])) prefs['gc_site_settings'] = gc_site_settings prefs['allow_gc_from_ini'] = self.calibrecover_tab.allow_gc_from_ini.isChecked() prefs['gc_polish_cover'] = self.calibrecover_tab.gc_polish_cover.isChecked() # Count Pages tab countpagesstats = [] if self.countpages_tab.pagecount.isChecked(): countpagesstats.append('PageCount') if self.countpages_tab.wordcount.isChecked(): countpagesstats.append('WordCount') if self.countpages_tab.fleschreading.isChecked(): countpagesstats.append('FleschReading') if self.countpages_tab.fleschgrade.isChecked(): countpagesstats.append('FleschGrade') if self.countpages_tab.gunningfog.isChecked(): countpagesstats.append('GunningFog') prefs['countpagesstats'] = countpagesstats prefs['wordcountmissing'] = self.countpages_tab.wordcount.isChecked() and self.countpages_tab.wordcountmissing.isChecked() # Standard Columns tab colsnewonly = {} for (col,checkbox) in six.iteritems(self.std_columns_tab.stdcol_newonlycheck): colsnewonly[col] = checkbox.isChecked() prefs['std_cols_newonly'] = colsnewonly prefs['suppressauthorsort'] = self.std_columns_tab.suppressauthorsort.isChecked() prefs['suppresstitlesort'] = self.std_columns_tab.suppresstitlesort.isChecked() prefs['authorcase'] = self.std_columns_tab.authorcase.isChecked() prefs['titlecase'] = self.std_columns_tab.titlecase.isChecked() prefs['setanthologyseries'] = self.std_columns_tab.setanthologyseries.isChecked() prefs['set_author_url'] =self.std_columns_tab.set_author_url.isChecked() prefs['set_series_url'] =self.std_columns_tab.set_series_url.isChecked() prefs['includecomments'] =self.std_columns_tab.includecomments.isChecked() prefs['anth_comments_newonly'] =self.std_columns_tab.anth_comments_newonly.isChecked() # Custom Columns tab # error column prefs['errorcol'] = unicode(self.cust_columns_tab.errorcol.itemData(self.cust_columns_tab.errorcol.currentIndex())) prefs['save_all_errors'] = self.cust_columns_tab.save_all_errors.isChecked() # metadata column prefs['savemetacol'] = unicode(self.cust_columns_tab.savemetacol.itemData(self.cust_columns_tab.savemetacol.currentIndex())) # lastchecked column prefs['lastcheckedcol'] = unicode(self.cust_columns_tab.lastcheckedcol.itemData(self.cust_columns_tab.lastcheckedcol.currentIndex())) # cust cols tab colsmap = {} for (col,combo) in six.iteritems(self.cust_columns_tab.custcol_dropdowns): val = unicode(combo.itemData(combo.currentIndex())) if val != 'none': colsmap[col] = val #print("colsmap[%s]:%s"%(col,colsmap[col])) prefs['custom_cols'] = colsmap colsnewonly = {} for (col,checkbox) in six.iteritems(self.cust_columns_tab.custcol_newonlycheck): colsnewonly[col] = checkbox.isChecked() prefs['custom_cols_newonly'] = colsnewonly prefs['allow_custcol_from_ini'] = self.cust_columns_tab.allow_custcol_from_ini.isChecked() prefs['imapserver'] = unicode(self.imap_tab.imapserver.text()).strip() prefs['imapuser'] = unicode(self.imap_tab.imapuser.text()).strip() prefs['imappass'] = unicode(self.imap_tab.imappass.text()).strip() prefs['imapfolder'] = unicode(self.imap_tab.imapfolder.text()).strip() # prefs['imaptags'] = unicode(self.imap_tab.imaptags.text()).strip() prefs['imaptags'] = ', '.join([ x.strip() for x in unicode(self.imap_tab.imaptags.text()).split(',') if x.strip() ]) prefs['imapmarkread'] = self.imap_tab.imapmarkread.isChecked() prefs['imapsessionpass'] = self.imap_tab.imapsessionpass.isChecked() prefs['auto_reject_from_email'] = self.imap_tab.auto_reject_from_email.isChecked() prefs['update_existing_only_from_email'] = self.imap_tab.update_existing_only_from_email.isChecked() prefs['download_from_email_immediately'] = self.imap_tab.download_from_email_immediately.isChecked() prefs.save_to_db() self.plugin_action.set_popup_mode() def edit_shortcuts(self): self.save_settings() # Force the menus to be rebuilt immediately, so we have all our actions registered self.plugin_action.rebuild_menus() d = KeyboardConfigDialog(self.plugin_action.gui, self.plugin_action.action_spec[0]) if d.exec_() == d.Accepted: self.plugin_action.gui.keyboard.finalize() class BasicTab(QWidget): def __init__(self, parent_dialog, plugin_action): self.parent_dialog = parent_dialog self.plugin_action = plugin_action QWidget.__init__(self) topl = QVBoxLayout() self.setLayout(topl) label = QLabel(_('These settings control the basic features of the plugin--downloading FanFiction.')) label.setWordWrap(True) topl.addWidget(label) defs_gb = groupbox = QGroupBox(_("Defaults Options on Download")) self.l = QVBoxLayout() groupbox.setLayout(self.l) tooltip = _("On each download, FanFicFare offers an option to select the output format. <br />This sets what that option will default to.") horz = QHBoxLayout() label = QLabel(_('Default Output &Format:')) label.setToolTip(tooltip) horz.addWidget(label) self.fileform = QComboBox(self) self.fileform.addItem('epub') self.fileform.addItem('mobi') self.fileform.addItem('html') self.fileform.addItem('txt') self.fileform.setCurrentIndex(self.fileform.findText(prefs['fileform'])) self.fileform.setToolTip(tooltip) self.fileform.activated.connect(self.set_collisions) label.setBuddy(self.fileform) horz.addWidget(self.fileform) self.l.addLayout(horz) tooltip = _("On each download, FanFicFare offers an option of what happens if that story already exists. <br />This sets what that option will default to.") horz = QHBoxLayout() label = QLabel(_('Default If Story Already Exists?')) label.setToolTip(tooltip) horz.addWidget(label) self.collision = QComboBox(self) # add collision options self.set_collisions() i = self.collision.findText(save_collisions[prefs['collision']]) if i > -1: self.collision.setCurrentIndex(i) self.collision.setToolTip(tooltip) label.setBuddy(self.collision) horz.addWidget(self.collision) self.l.addLayout(horz) horz = QHBoxLayout() self.updatemeta = QCheckBox(_('Default Update Calibre &Metadata?'),self) self.updatemeta.setToolTip(_("On each download, FanFicFare offers an option to update Calibre's metadata (title, author, URL, tags, custom columns, etc) from the web site. <br />This sets whether that will default to on or off. <br />Columns set to 'New Only' in the column tabs will only be set for new books.")) self.updatemeta.setChecked(prefs['updatemeta']) horz.addWidget(self.updatemeta) self.bgmeta = QCheckBox(_('Default Background Metadata?'),self) self.bgmeta.setToolTip(_("On each download, FanFicFare offers an option to Collect Metadata from sites in a Background process.<br />This returns control to you quicker while updating, but you won't be asked for username/passwords or if you are an adult--stories that need those will just fail.<br />Only available for Update/Overwrite of existing books in case URL given isn't canonical or matches to existing book by Title/Author.")) self.bgmeta.setChecked(prefs['bgmeta']) horz.addWidget(self.bgmeta) self.l.addLayout(horz) cali_gb = groupbox = QGroupBox(_("Updating Calibre Options")) self.l = QVBoxLayout() groupbox.setLayout(self.l) self.deleteotherforms = QCheckBox(_('Delete other existing formats?'),self) self.deleteotherforms.setToolTip(_('Check this to automatically delete all other ebook formats when updating an existing book.\nHandy if you have both a Nook(epub) and Kindle(mobi), for example.')) self.deleteotherforms.setChecked(prefs['deleteotherforms']) self.l.addWidget(self.deleteotherforms) self.keeptags = QCheckBox(_('Keep Existing Tags when Updating Metadata?'),self) self.keeptags.setToolTip(_("Existing tags will be kept and any new tags added.\n%(cmplt)s and %(inprog)s tags will be still be updated, if known.\n%(lul)s tags will be updated if %(lus)s in %(is)s.\n(If Tags is set to 'New Only' in the Standard Columns tab, this has no effect.)")%no_trans) self.keeptags.setChecked(prefs['keeptags']) self.l.addWidget(self.keeptags) self.checkforseriesurlid = QCheckBox(_("Check for existing Series Anthology books?"),self) self.checkforseriesurlid.setToolTip(_("Check for existing Series Anthology books using each new story's series URL before downloading.\nOffer to skip downloading if a Series Anthology is found.\nDoesn't work when Collect Metadata in Background is selected.")) self.checkforseriesurlid.setChecked(prefs['checkforseriesurlid']) self.l.addWidget(self.checkforseriesurlid) self.auto_reject_seriesurlid = QCheckBox(_("Reject Without Confirmation?"),self) self.auto_reject_seriesurlid.setToolTip(_("Automatically reject storys with existing Series Anthology books.\nOnly works if 'Check for existing Series Anthology books' is on.\nDoesn't work when Collect Metadata in Background is selected.")) self.auto_reject_seriesurlid.setChecked(prefs['auto_reject_seriesurlid']) self.auto_reject_seriesurlid.setEnabled(self.checkforseriesurlid.isChecked()) self.mark_series_anthologies = QCheckBox(_("Mark Matching Anthologies?"),self) self.mark_series_anthologies.setToolTip(_("Mark and show existing Series Anthology books when individual updates are skipped.\nOnly works if 'Check for existing Series Anthology books' is on.\nDoesn't work when Collect Metadata in Background is selected.")) self.mark_series_anthologies.setChecked(prefs['mark_series_anthologies']) self.mark_series_anthologies.setEnabled(self.checkforseriesurlid.isChecked()) def mark_anthologies(): self.auto_reject_seriesurlid.setEnabled(self.checkforseriesurlid.isChecked()) self.mark_series_anthologies.setEnabled(self.checkforseriesurlid.isChecked()) self.checkforseriesurlid.stateChanged.connect(mark_anthologies) mark_anthologies() horz = QHBoxLayout() horz.addItem(QtGui.QSpacerItem(20, 1)) vertright = QVBoxLayout() horz.addLayout(vertright) vertright.addWidget(self.auto_reject_seriesurlid) vertright.addWidget(self.mark_series_anthologies) self.l.addLayout(horz) self.checkforurlchange = QCheckBox(_("Check for changed Story URL?"),self) self.checkforurlchange.setToolTip(_("Warn you if an update will change the URL of an existing book(normally automatic and silent).\nURLs may be changed from http to https silently if the site changed.")) self.checkforurlchange.setChecked(prefs['checkforurlchange']) self.l.addWidget(self.checkforurlchange) self.lookforurlinhtml = QCheckBox(_("Search inside ebooks for Story URL?"),self) self.lookforurlinhtml.setToolTip(_("Look for first valid story URL inside EPUB, ZIP(HTML) or TXT ebook formats if not found in metadata.\nSomewhat risky, could find wrong URL depending on ebook content.")) self.lookforurlinhtml.setChecked(prefs['lookforurlinhtml']) self.l.addWidget(self.lookforurlinhtml) proc_gb = groupbox = QGroupBox(_("Post Processing Options")) self.l = QVBoxLayout() groupbox.setLayout(self.l) self.mark = QCheckBox(_("Mark added/updated books when finished?"),self) self.mark.setToolTip(_("Mark added/updated books when finished. Use with option below.\nYou can also manually search for 'marked:fff_success'.\n'marked:fff_failed' and 'marked:fff_chapter_error' are also available, or search 'marked:fff' for all.")) self.mark.setChecked(prefs['mark']) self.l.addWidget(self.mark) horz = QHBoxLayout() horz.addItem(QtGui.QSpacerItem(20, 1)) self.l.addLayout(horz) self.mark_success = QCheckBox(_("Success"),self) self.mark_success.setToolTip(_("Mark successfully downloaded or updated books.")) self.mark_success.setChecked(prefs['mark_success']) self.mark_success.setEnabled(self.checkforseriesurlid.isChecked()) horz.addWidget(self.mark_success) self.mark_failed = QCheckBox(_("Failed"),self) self.mark_failed.setToolTip(_("Mark failed downloaded or updated books.")) self.mark_failed.setChecked(prefs['mark_failed']) self.mark_failed.setEnabled(self.checkforseriesurlid.isChecked()) horz.addWidget(self.mark_failed) self.mark_chapter_error = QCheckBox(_("Chapter Error"),self) self.mark_chapter_error.setToolTip(_("Mark downloaded or updated books with chapter errors (only when <i>continue_on_chapter_error:true</i>).")) self.mark_chapter_error.setChecked(prefs['mark_chapter_error']) self.mark_chapter_error.setEnabled(self.checkforseriesurlid.isChecked()) horz.addWidget(self.mark_chapter_error) def mark_state(): self.mark_success.setEnabled(self.mark.isChecked()) self.mark_failed.setEnabled(self.mark.isChecked()) self.mark_chapter_error.setEnabled(self.mark.isChecked()) self.mark.stateChanged.connect(mark_state) mark_state() self.showmarked = QCheckBox(_("Show Marked books when finished?"),self) self.showmarked.setToolTip(_("Show Marked added/updated books only when finished.\nYou can also manually search for 'marked:fff_success'.\n'marked:fff_failed' and 'marked:fff_chapter_error' are also available, or search 'marked:fff' for all.")) self.showmarked.setChecked(prefs['showmarked']) self.l.addWidget(self.showmarked) self.smarten_punctuation = QCheckBox(_('Smarten Punctuation (EPUB only)'),self) self.smarten_punctuation.setToolTip(_("Run Smarten Punctuation from Calibre's Polish Book feature on each EPUB download and update.")) self.smarten_punctuation.setChecked(prefs['smarten_punctuation']) self.l.addWidget(self.smarten_punctuation) tooltip = _("Calculate Word Counts using Calibre internal methods.\n" "Many sites include Word Count, but many do not.\n" "This will count the words in each book and include it as if it came from the site.") horz = QHBoxLayout() label = QLabel(_('Calculate Word Count:')) label.setToolTip(tooltip) horz.addWidget(label) self.do_wordcount = QComboBox(self) for i in do_wordcount_order: self.do_wordcount.addItem(i) self.do_wordcount.setCurrentIndex(self.do_wordcount.findText(prefs_save_options[prefs['do_wordcount']])) self.do_wordcount.setToolTip(tooltip) label.setBuddy(self.do_wordcount) horz.addWidget(self.do_wordcount) self.l.addLayout(horz) self.autoconvert = QCheckBox(_("Automatically Convert new/update books?"),self) self.autoconvert.setToolTip(_("Automatically call calibre's Convert for new/update books.\nConverts to the current output format as chosen in calibre's\nPreferences->Behavior settings.")) self.autoconvert.setChecked(prefs['autoconvert']) self.l.addWidget(self.autoconvert) gui_gb = groupbox = QGroupBox(_("GUI Options")) self.l = QVBoxLayout() groupbox.setLayout(self.l) self.urlsfromclip = QCheckBox(_('Take URLs from Clipboard?'),self) self.urlsfromclip.setToolTip(_('Prefill URLs from valid URLs in Clipboard when Adding New.')) self.urlsfromclip.setChecked(prefs['urlsfromclip']) self.l.addWidget(self.urlsfromclip) self.button_instantpopup = QCheckBox(_('FanFicFare button opens menu?'),self) self.button_instantpopup.setToolTip(_('The FanFicFare toolbar button will bring up the plugin menu. If unchecked, it will <i>Download from URLs</i> or optionally Update, see below.')) self.button_instantpopup.setChecked(prefs['button_instantpopup']) self.l.addWidget(self.button_instantpopup) self.updatedefault = QCheckBox(_('Default to Update when books selected?'),self) self.updatedefault.setToolTip(_('The FanFicFare toolbar button will Update if books are selected. If unchecked, it will always <i>Download from URLs</i>.')) self.updatedefault.setChecked(prefs['updatedefault']) self.updatedefault.setEnabled(not self.button_instantpopup.isChecked()) self.button_instantpopup.stateChanged.connect(lambda x : self.updatedefault.setEnabled(not self.button_instantpopup.isChecked())) horz = QHBoxLayout() horz.addItem(QtGui.QSpacerItem(20, 1)) horz.addWidget(self.updatedefault) self.l.addLayout(horz) self.adddialogstaysontop = QCheckBox(_("Keep 'Add New from URL(s)' dialog on top?"),self) self.adddialogstaysontop.setToolTip(_("Instructs the OS and Window Manager to keep the 'Add New from URL(s)'\ndialog on top of all other windows. Useful for dragging URLs onto it.")) self.adddialogstaysontop.setChecked(prefs['adddialogstaysontop']) self.l.addWidget(self.adddialogstaysontop) self.show_est_time = QCheckBox(_("Show estimated time left?"),self) self.show_est_time.setToolTip(_("When a Progress Bar is shown, show a rough estimate of the time left.")) self.show_est_time.setChecked(prefs['show_est_time']) self.l.addWidget(self.show_est_time) misc_gb = groupbox = QGroupBox(_("Misc Options")) self.l = QVBoxLayout() groupbox.setLayout(self.l) self.injectseries = QCheckBox(_("Inject calibre Series when none found?"),self) self.injectseries.setToolTip(_("If no series is found, inject the calibre series (if there is one) so \nit appears on the FanFicFare title page(not cover).")) self.injectseries.setChecked(prefs['injectseries']) self.l.addWidget(self.injectseries) self.matchtitleauth = QCheckBox(_("Search by Title/Author(s) for If Story Already Exists?"),self) self.matchtitleauth.setToolTip(_("When checking <i>If Story Already Exists</i> FanFicFare will first match by URL Identifier. But if not found, it can also search existing books by Title and Author(s).")) self.matchtitleauth.setChecked(prefs['matchtitleauth']) self.l.addWidget(self.matchtitleauth) rej_gb = groupbox = QGroupBox(_("Reject List")) self.l = QVBoxLayout() groupbox.setLayout(self.l) self.rejectlist = QPushButton(_('Edit Reject URL List'), self) self.rejectlist.setToolTip(_("Edit list of URLs FanFicFare will automatically Reject.")) self.rejectlist.clicked.connect(self.show_rejectlist) self.l.addWidget(self.rejectlist) self.reject_urls = QPushButton(_('Add Reject URLs'), self) self.reject_urls.setToolTip(_("Add additional URLs to Reject as text.")) self.reject_urls.clicked.connect(self.add_reject_urls) self.l.addWidget(self.reject_urls) self.reject_reasons = QPushButton(_('Edit Reject Reasons List'), self) self.reject_reasons.setToolTip(_("Customize the Reasons presented when Rejecting URLs")) self.reject_reasons.clicked.connect(self.show_reject_reasons) self.l.addWidget(self.reject_reasons) self.reject_always = QCheckBox(_('Reject Without Confirmation?'),self) self.reject_always.setToolTip(_("Always reject URLs on the Reject List without stopping and asking.")) self.reject_always.setChecked(prefs['reject_always']) self.l.addWidget(self.reject_always) self.reject_delete_default = QCheckBox(_('Delete on Reject by Default?'),self) self.reject_delete_default.setToolTip(_("Should the checkbox to delete Rejected books be checked by default?")) self.reject_delete_default.setChecked(prefs['reject_delete_default']) self.l.addWidget(self.reject_delete_default) topl.addWidget(defs_gb) horz = QHBoxLayout() vertleft = QVBoxLayout() vertleft.addWidget(cali_gb) vertleft.addWidget(proc_gb) vertright = QVBoxLayout() vertright.addWidget(gui_gb) vertright.addWidget(misc_gb) vertright.addWidget(rej_gb) horz.addLayout(vertleft) horz.addLayout(vertright) topl.addLayout(horz) topl.insertStretch(-1) def set_collisions(self): prev=self.collision.currentText() self.collision.clear() for o in collision_order: if self.fileform.currentText() == 'epub' or o not in [UPDATE,UPDATEALWAYS]: self.collision.addItem(o) i = self.collision.findText(prev) if i > -1: self.collision.setCurrentIndex(i) def show_rejectlist(self): with busy_cursor(): d = RejectListDialog(self, rejecturllist.get_list(), rejectreasons=rejecturllist.get_reject_reasons(), header=_("Edit Reject URLs List"), show_delete=False, show_all_reasons=False) d.exec_() if d.result() != d.Accepted: return with busy_cursor(): rejecturllist.add(d.get_reject_list(),clear=True) def show_reject_reasons(self): d = EditTextDialog(self, prefs['rejectreasons'], icon=self.windowIcon(), title=_("Reject Reasons"), label=_("Customize Reject List Reasons"), tooltip=_("Customize the Reasons presented when Rejecting URLs"), save_size_name='fff:Reject List Reasons') d.exec_() if d.result() == d.Accepted: prefs['rejectreasons'] = d.get_plain_text() def add_reject_urls(self): d = EditTextDialog(self, "http://example.com/story.php?sid=5,"+_("Reason why I rejected it")+"\nhttp://example.com/story.php?sid=6,"+_("Title by Author")+" - "+_("Reason why I rejected it"), icon=self.windowIcon(), title=_("Add Reject URLs"), label=_("Add Reject URLs. Use: <b>http://...,note</b> or <b>http://...,title by author - note</b><br>Invalid story URLs will be ignored."), tooltip=_("One URL per line:\n<b>http://...,note</b>\n<b>http://...,title by author - note</b>"), rejectreasons=rejecturllist.get_reject_reasons(), reasonslabel=_('Add this reason to all URLs added:'), save_size_name='fff:Add Reject List') d.exec_() if d.result() == d.Accepted: rejecturllist.add_text(d.get_plain_text(),d.get_reason_text()) class PersonalIniTab(QWidget): def __init__(self, parent_dialog, plugin_action): self.parent_dialog = parent_dialog self.plugin_action = plugin_action QWidget.__init__(self) self.l = QVBoxLayout() self.setLayout(self.l) label = QLabel(_('These settings provide more detailed control over what metadata will be displayed inside the ebook as well as let you set %(isa)s and %(u)s/%(p)s for different sites.')%no_trans) label.setWordWrap(True) self.l.addWidget(label) self.l.addSpacing(5) self.personalini = prefs['personal.ini'] groupbox = QGroupBox(_("personal.ini")) vert = QVBoxLayout() groupbox.setLayout(vert) self.l.addWidget(groupbox) horz = QHBoxLayout() vert.addLayout(horz) self.ini_button = QPushButton(_('Edit personal.ini'), self) #self.ini_button.setToolTip(_("Edit personal.ini file.")) self.ini_button.clicked.connect(self.add_ini_button) horz.addWidget(self.ini_button) label = QLabel(_("FanFicFare now includes find, color coding, and error checking for personal.ini editing. Red generally indicates errors.")) label.setWordWrap(True) horz.addWidget(label) vert.addSpacing(5) horz = QHBoxLayout() vert.addLayout(horz) self.ini_button = QPushButton(_('View "Safe" personal.ini'), self) #self.ini_button.setToolTip(_("Edit personal.ini file.")) self.ini_button.clicked.connect(self.safe_ini_button) horz.addWidget(self.ini_button) label = QLabel(_("View your personal.ini with usernames and passwords removed. For safely sharing your personal.ini settings with others.")) label.setWordWrap(True) horz.addWidget(label) self.l.addSpacing(5) groupbox = QGroupBox(_("defaults.ini")) horz = QHBoxLayout() groupbox.setLayout(horz) self.l.addWidget(groupbox) view_label = _("View all of the plugin's configurable settings\nand their default settings.") self.defaults = QPushButton(_('View Defaults')+' (plugin-defaults.ini)', self) self.defaults.setToolTip(view_label) self.defaults.clicked.connect(self.show_defaults) horz.addWidget(self.defaults) label = QLabel(view_label) label.setWordWrap(True) horz.addWidget(label) self.l.addSpacing(5) groupbox = QGroupBox(_("Calibre Columns")) vert = QVBoxLayout() groupbox.setLayout(vert) self.l.addWidget(groupbox) horz = QHBoxLayout() vert.addLayout(horz) pass_label = _("If checked, when updating/overwriting an existing book, FanFicFare will have the Calibre Columns available to use in replace_metadata, title_page, etc.<br>Click the button below to see the Calibre Column names.")%no_trans self.cal_cols_pass_in = QCheckBox(_('Pass Calibre Columns into FanFicFare on Update/Overwrite')%no_trans,self) self.cal_cols_pass_in.setToolTip(pass_label) self.cal_cols_pass_in.setChecked(prefs['cal_cols_pass_in']) horz.addWidget(self.cal_cols_pass_in) label = QLabel(pass_label) label.setWordWrap(True) horz.addWidget(label) vert.addSpacing(5) horz = QHBoxLayout() vert.addLayout(horz) col_label = _("FanFicFare can pass the Calibre Columns into the download/update process.<br>This will show you the columns available by name.") self.showcalcols = QPushButton(_('Show Calibre Column Names'), self) self.showcalcols.setToolTip(col_label) self.showcalcols.clicked.connect(self.show_showcalcols) horz.addWidget(self.showcalcols) label = QLabel(col_label) label.setWordWrap(True) horz.addWidget(label) label = QLabel(_("Changes will only be saved if you click 'OK' to leave Customize FanFicFare.")) label.setWordWrap(True) self.l.addWidget(label) self.l.insertStretch(-1) def show_defaults(self): IniTextDialog(self, get_resources('plugin-defaults.ini').decode('utf-8'), icon=self.windowIcon(), title=_('Plugin Defaults'), label=_("Plugin Defaults (%s) (Read-Only)")%'plugin-defaults.ini', use_find=True, read_only=True, save_size_name='fff:defaults.ini').exec_() def safe_ini_button(self): personalini = re.sub(r'((username|password) *[=:]).*$',r'\1XXXXXXXX',self.personalini,flags=re.MULTILINE) d = EditTextDialog(self, personalini, icon=self.windowIcon(), title=_("View 'Safe' personal.ini"), label=_("View your personal.ini with usernames and passwords removed. For safely sharing your personal.ini settings with others."), save_size_name='fff:safe personal.ini', read_only=True) d.exec_() def add_ini_button(self): d = IniTextDialog(self, self.personalini, icon=self.windowIcon(), title=_("Edit personal.ini"), label=_("Edit personal.ini"), use_find=True, save_size_name='fff:personal.ini') d.exec_() if d.result() == d.Accepted: self.personalini = d.get_plain_text() def show_showcalcols(self): lines=[]#[('calibre_std_user_categories',_('User Categories'))] for k,f in six.iteritems(field_metadata): if f['name'] and k not in STD_COLS_SKIP: # only if it has a human readable name. lines.append(('calibre_std_'+k,f['name'])) for k, column in six.iteritems(self.plugin_action.gui.library_view.model().custom_columns): if k != prefs['savemetacol']: # custom always have name. lines.append(('calibre_cust_'+k[1:],column['name'])) lines.sort() # sort by key. EditTextDialog(self, '\n'.join(['%s (%s)'%(l,k) for (k,l) in lines]), icon=self.windowIcon(), title=_('Calibre Column Entry Names'), label=_('Label (entry_name)'), read_only=True, save_size_name='fff:showcalcols').exec_() class ReadingListTab(QWidget): def __init__(self, parent_dialog, plugin_action): self.parent_dialog = parent_dialog self.plugin_action = plugin_action QWidget.__init__(self) self.l = QVBoxLayout() self.setLayout(self.l) try: rl_plugin = plugin_action.gui.iactions['Reading List'] reading_lists = rl_plugin.get_list_names() except KeyError: reading_lists= [] label = QLabel(_('These settings provide integration with the %(rl)s Plugin. %(rl)s can automatically send to devices and change custom columns. You have to create and configure the lists in %(rl)s to be useful.')%no_trans) label.setWordWrap(True) self.l.addWidget(label) self.l.addSpacing(5) self.addtolists = QCheckBox(_('Add new/updated stories to "Send to Device" Reading List(s).'),self) self.addtolists.setToolTip(_('Automatically add new/updated stories to these lists in the %(rl)s plugin.')%no_trans) self.addtolists.setChecked(prefs['addtolists']) self.l.addWidget(self.addtolists) horz = QHBoxLayout() label = QLabel(_('"Send to Device" Reading Lists')) label.setToolTip(_("When enabled, new/updated stories will be automatically added to these lists.")) horz.addWidget(label) self.send_lists_box = EditWithComplete(self) self.send_lists_box.setToolTip(_("When enabled, new/updated stories will be automatically added to these lists.")) self.send_lists_box.update_items_cache(reading_lists) self.send_lists_box.setText(prefs['send_lists']) horz.addWidget(self.send_lists_box) self.send_lists_box.setCursorPosition(0) self.l.addLayout(horz) self.addtoreadlists = QCheckBox(_('Add new/updated stories to "To Read" Reading List(s).'),self) self.addtoreadlists.setToolTip(_('Automatically add new/updated stories to these lists in the %(rl)s plugin.\nAlso offers menu option to remove stories from the "To Read" lists.')%no_trans) self.addtoreadlists.setChecked(prefs['addtoreadlists']) self.l.addWidget(self.addtoreadlists) horz = QHBoxLayout() label = QLabel(_('"To Read" Reading Lists')) label.setToolTip(_("When enabled, new/updated stories will be automatically added to these lists.")) horz.addWidget(label) self.read_lists_box = EditWithComplete(self) self.read_lists_box.setToolTip(_("When enabled, new/updated stories will be automatically added to these lists.")) self.read_lists_box.update_items_cache(reading_lists) self.read_lists_box.setText(prefs['read_lists']) horz.addWidget(self.read_lists_box) self.read_lists_box.setCursorPosition(0) self.l.addLayout(horz) self.addtolistsonread = QCheckBox(_('Add stories back to "Send to Device" Reading List(s) when marked "Read".'),self) self.addtolistsonread.setToolTip(_('Menu option to remove from "To Read" lists will also add stories back to "Send to Device" Reading List(s)')) self.addtolistsonread.setChecked(prefs['addtolistsonread']) self.l.addWidget(self.addtolistsonread) self.autounnew = QCheckBox(_('Automatically run Remove "New" Chapter Marks when marking books "Read".'),self) self.autounnew.setToolTip(_('Menu option to remove from "To Read" lists will also remove "(new)" chapter marks created by personal.ini <i>mark_new_chapters</i> setting.')) self.autounnew.setChecked(prefs['autounnew']) self.l.addWidget(self.autounnew) self.l.insertStretch(-1) class CalibreCoverTab(QWidget): def __init__(self, parent_dialog, plugin_action): self.parent_dialog = parent_dialog self.plugin_action = plugin_action QWidget.__init__(self) self.gencov_elements=[] ## used to disable/enable when gen ## cover is off/on. This is more ## about being a visual cue than real ## necessary function. topl = self.l = QVBoxLayout() self.setLayout(self.l) try: gc_plugin = plugin_action.gui.iactions['Generate Cover'] gc_settings = gc_plugin.get_saved_setting_names() except KeyError: gc_settings= [] label = QLabel(_("The Calibre cover image for a downloaded book can come" " from the story site(if EPUB and images are enabled), or" " from either Calibre's built-in random cover generator or" " the %(gc)s plugin.")%no_trans) label.setWordWrap(True) self.l.addWidget(label) self.l.addSpacing(5) tooltip = _("Update Calibre book cover image from EPUB when Calibre metadata is updated.\n" "Doesn't go looking for new images on 'Update Calibre Metadata Only'.\n" "Cover in EPUB could be from site or previously injected into the EPUB.\n" "This comes before Generate Cover so %(gc)s(Plugin) use the image if configured to.")%no_trans horz = QHBoxLayout() label = QLabel(_('Update Calibre Cover (from EPUB):')) label.setToolTip(tooltip) horz.addWidget(label) self.updatecalcover = QComboBox(self) for i in updatecalcover_order: self.updatecalcover.addItem(i) # back compat. If has own value, use. if prefs['updatecalcover']: self.updatecalcover.setCurrentIndex(self.updatecalcover.findText(prefs_save_options[prefs['updatecalcover']])) elif prefs['updatecover']: # doesn't have own val, set YES if old value set. self.updatecalcover.setCurrentIndex(self.updatecalcover.findText(prefs_save_options[SAVE_YES])) else: # doesn't have own value, old value not set, NO. self.updatecalcover.setCurrentIndex(self.updatecalcover.findText(prefs_save_options[SAVE_NO])) self.updatecalcover.setToolTip(tooltip) label.setBuddy(self.updatecalcover) horz.addWidget(self.updatecalcover) self.l.addLayout(horz) self.covernewonly = QCheckBox(_("Set Calibre Cover Only for New Books"),self) self.covernewonly.setToolTip(_("Set the Calibre cover from EPUB only for new\nbooks, not updates to existing books.")) self.covernewonly.setChecked(prefs['covernewonly']) horz = QHBoxLayout() horz.addItem(QtGui.QSpacerItem(20, 1)) horz.addWidget(self.covernewonly) self.l.addLayout(horz) self.l.addSpacing(5) tooltip = _("Generate a Calibre book cover image when Calibre metadata is updated.<br />" "Note that %(gc)s(Plugin) will only run if there is a %(gc)s setting configured below for Default or the appropriate site.")%no_trans horz = QHBoxLayout() label = QLabel(_('Generate Calibre Cover:')) label.setToolTip(tooltip) horz.addWidget(label) self.gencalcover = QComboBox(self) for i in gencalcover_order: self.gencalcover.addItem(i) self.gencalcover.setCurrentIndex(self.gencalcover.findText(prefs_save_options[prefs['gencalcover']])) self.gencalcover.setToolTip(tooltip) label.setBuddy(self.gencalcover) horz.addWidget(self.gencalcover) self.l.addLayout(horz) self.gencalcover.currentIndexChanged.connect(self.endisable_elements) horz = QHBoxLayout() horz.addItem(QtGui.QSpacerItem(20, 1)) vert = QVBoxLayout() horz.addLayout(vert) self.l.addLayout(horz) self.gcnewonly = QCheckBox(_("Generate Covers Only for New Books")%no_trans,self) self.gcnewonly.setToolTip(_("Default is to generate a cover any time the calibre metadata is" " updated.<br />Used for both Calibre and Plugin generated covers.")) self.gcnewonly.setChecked(prefs['gcnewonly']) vert.addWidget(self.gcnewonly) self.gencov_elements.append(self.gcnewonly) self.gc_polish_cover = QCheckBox(_("Inject/update the generated cover inside EPUB"),self) self.gc_polish_cover.setToolTip(_("Calibre's Polish feature will be used to inject or update the generated" " cover into the EPUB ebook file.<br />Used for both Calibre and Plugin generated covers.")) self.gc_polish_cover.setChecked(prefs['gc_polish_cover']) vert.addWidget(self.gc_polish_cover) self.gencov_elements.append(self.gc_polish_cover) # can't be local or it's destroyed when __init__ is done and # connected things don't fire. self.gencov_rdgrp = QButtonGroup() self.gencov_gb = QGroupBox() horz = QHBoxLayout() self.gencov_gb.setLayout(horz) self.plugin_gen_cover = QRadioButton(_('Plugin %(gc)s')%no_trans,self) self.plugin_gen_cover.setToolTip(_("Use the %(gc)s plugin to create covers.<br>" "Requires that you have the the %(gc)s plugin installed.<br>" "Additional settings are below."%no_trans)) self.gencov_rdgrp.addButton(self.plugin_gen_cover) # always, new only, when no cover from site, inject yes/no... self.plugin_gen_cover.setChecked(prefs['plugin_gen_cover']) horz.addWidget(self.plugin_gen_cover) self.gencov_elements.append(self.plugin_gen_cover) self.calibre_gen_cover = QRadioButton(_('Calibre Generate Cover'),self) self.calibre_gen_cover.setToolTip(_("Call Calibre's Edit Metadata Generate cover" " feature to create a random cover each time" " a story is downloaded or updated.<br />" "Right click or long click the 'Generate cover'" " button in Calibre's Edit Metadata to customize.")) self.gencov_rdgrp.addButton(self.calibre_gen_cover) # always, new only, when no cover from site, inject yes/no... self.calibre_gen_cover.setChecked(prefs['calibre_gen_cover']) horz.addWidget(self.calibre_gen_cover) self.gencov_elements.append(self.calibre_gen_cover) #self.l.addLayout(horz) self.l.addWidget(self.gencov_gb) self.gcp_gb = QGroupBox(_("%(gc)s(Plugin) Settings")%no_trans) topl.addWidget(self.gcp_gb) self.l = QVBoxLayout() self.gcp_gb.setLayout(self.l) self.gencov_elements.append(self.gcp_gb) self.gencov_rdgrp.buttonClicked.connect(self.endisable_elements) label = QLabel(_('The %(gc)s plugin can create cover images for books using various metadata (including existing cover image). If you have %(gc)s installed, FanFicFare can run %(gc)s on new downloads and metadata updates. Pick a %(gc)s setting by site and/or one to use by Default.')%no_trans) label.setWordWrap(True) self.l.addWidget(label) self.l.addSpacing(5) scrollable = QScrollArea() scrollcontent = QWidget() scrollable.setWidget(scrollcontent) scrollable.setWidgetResizable(True) self.l.addWidget(scrollable) self.sl = QVBoxLayout() scrollcontent.setLayout(self.sl) self.gc_dropdowns = {} sitelist = getSiteSections() sitelist.sort() sitelist.insert(0,_("Default")) for site in sitelist: horz = QHBoxLayout() label = QLabel(site) if site == _("Default"): s = _("On Metadata update, run %(gc)s with this setting, if there isn't a more specific setting below.")%no_trans else: no_trans['site']=site # not ideal, but, meh. s = _("On Metadata update, run %(gc)s with this setting for %(site)s stories.")%no_trans label.setToolTip(s) horz.addWidget(label) dropdown = QComboBox(self) dropdown.setToolTip(s) dropdown.addItem('','none') for setting in gc_settings: dropdown.addItem(setting,setting) if site == _("Default"): self.gc_dropdowns["Default"] = dropdown if 'Default' in prefs['gc_site_settings']: dropdown.setCurrentIndex(dropdown.findData(prefs['gc_site_settings']['Default'])) else: self.gc_dropdowns[site] = dropdown if site in prefs['gc_site_settings']: dropdown.setCurrentIndex(dropdown.findData(prefs['gc_site_settings'][site])) horz.addWidget(dropdown) self.sl.addLayout(horz) self.sl.insertStretch(-1) self.allow_gc_from_ini = QCheckBox(_('Allow %(gcset)s from %(pini)s to override')%no_trans,self) self.allow_gc_from_ini.setToolTip(_("The %(pini)s parameter %(gcset)s allows you to choose a %(gc)s setting based on metadata" " rather than site, but it's much more complex.<br />%(gcset)s is ignored when this is off.")%no_trans) self.allow_gc_from_ini.setChecked(prefs['allow_gc_from_ini']) self.l.addWidget(self.allow_gc_from_ini) # keep at end. self.endisable_elements() def endisable_elements(self,button=None): "Clearing house function for setting elements of Calibre" "Cover tab enabled/disabled depending on all factors." ## First, cover gen on/off for e in self.gencov_elements: e.setEnabled(prefs_save_options[unicode(self.gencalcover.currentText())] != SAVE_NO) # next, disable plugin settings when using calibre gen cov. if not self.plugin_gen_cover.isChecked(): self.gcp_gb.setEnabled(False) # disable (but not enable) unsupported options. if not HAS_CALGC: self.calibre_gen_cover.setEnabled(False) if not 'Generate Cover' in self.plugin_action.gui.iactions: self.plugin_gen_cover.setEnabled(False) self.gcp_gb.setEnabled(False) class CountPagesTab(QWidget): def __init__(self, parent_dialog, plugin_action): self.parent_dialog = parent_dialog self.plugin_action = plugin_action QWidget.__init__(self) self.l = QVBoxLayout() self.setLayout(self.l) label = QLabel(_('These settings provide integration with the %(cp)s Plugin. %(cp)s can automatically update custom columns with page, word and reading level statistics. You have to create and configure the columns in %(cp)s first.')%no_trans) label.setWordWrap(True) self.l.addWidget(label) self.l.addSpacing(5) label = QLabel(_('If any of the settings below are checked, when stories are added or updated, the %(cp)s Plugin will be called to update the checked statistics.')%no_trans) label.setWordWrap(True) self.l.addWidget(label) self.l.addSpacing(5) # the same for all settings. Mostly. tooltip = _('Which column and algorithm to use are configured in %(cp)s.')%no_trans # 'PageCount', 'WordCount', 'FleschReading', 'FleschGrade', 'GunningFog' self.pagecount = QCheckBox('Page Count',self) self.pagecount.setToolTip(tooltip) self.pagecount.setChecked('PageCount' in prefs['countpagesstats']) self.l.addWidget(self.pagecount) horz = QHBoxLayout() self.wordcount = QCheckBox('Word Count',self) self.wordcount.setToolTip(tooltip+"\n"+_('Will overwrite word count from FanFicFare metadata if set to update the same custom column.')) self.wordcount.setChecked('WordCount' in prefs['countpagesstats']) horz.addWidget(self.wordcount) self.wordcountmissing = QCheckBox('Only if Word Count is Missing in FanFicFare Metadata',self) self.wordcountmissing.setToolTip(_("Only run Count Page's Word Count if checked <i>and</i> FanFicFare metadata doesn't already have a word count. If this is used with one of the other Page Counts, the Page Count plugin will be called twice.")) self.wordcountmissing.setChecked(prefs['wordcountmissing']) self.wordcountmissing.setEnabled(self.wordcount.isChecked()) horz.addWidget(self.wordcountmissing) self.wordcount.stateChanged.connect(lambda x : self.wordcountmissing.setEnabled(self.wordcount.isChecked())) self.l.addLayout(horz) self.fleschreading = QCheckBox('Flesch Reading Ease',self) self.fleschreading.setToolTip(tooltip) self.fleschreading.setChecked('FleschReading' in prefs['countpagesstats']) self.l.addWidget(self.fleschreading) self.fleschgrade = QCheckBox('Flesch-Kincaid Grade Level',self) self.fleschgrade.setToolTip(tooltip) self.fleschgrade.setChecked('FleschGrade' in prefs['countpagesstats']) self.l.addWidget(self.fleschgrade) self.gunningfog = QCheckBox('Gunning Fog Index',self) self.gunningfog.setToolTip(tooltip) self.gunningfog.setChecked('GunningFog' in prefs['countpagesstats']) self.l.addWidget(self.gunningfog) self.l.insertStretch(-1) class OtherTab(QWidget): def __init__(self, parent_dialog, plugin_action): self.parent_dialog = parent_dialog self.plugin_action = plugin_action QWidget.__init__(self) self.l = QVBoxLayout() self.setLayout(self.l) label = QLabel(_("These controls aren't plugin settings as such, but convenience buttons for setting Keyboard shortcuts and getting all the FanFicFare confirmation dialogs back again.")) label.setWordWrap(True) self.l.addWidget(label) self.l.addSpacing(5) keyboard_shortcuts_button = QPushButton(_('Keyboard shortcuts...'), self) keyboard_shortcuts_button.setToolTip(_('Edit the keyboard shortcuts associated with this plugin')) keyboard_shortcuts_button.clicked.connect(parent_dialog.edit_shortcuts) self.l.addWidget(keyboard_shortcuts_button) reset_confirmation_button = QPushButton(_('Reset disabled &confirmation dialogs'), self) reset_confirmation_button.setToolTip(_('Reset all show me again dialogs for the FanFicFare plugin')) reset_confirmation_button.clicked.connect(self.reset_dialogs) self.l.addWidget(reset_confirmation_button) view_prefs_button = QPushButton(_('&View library preferences...'), self) view_prefs_button.setToolTip(_('View data stored in the library database for this plugin')) view_prefs_button.clicked.connect(self.view_prefs) self.l.addWidget(view_prefs_button) self.l.insertStretch(-1) def reset_dialogs(self): for key in dynamic.keys(): if key.startswith('fff_') and dynamic[key] is False: dynamic[key] = True info_dialog(self, _('Done'), _('Confirmation dialogs have all been reset'), show=True, show_copy_button=False) def view_prefs(self): d = PrefsViewerDialog(self.plugin_action.gui, PREFS_NAMESPACE) d.exec_() permitted_values = { 'int' : ['numWords','numChapters'], 'float' : ['numWords','numChapters'], 'bool' : ['status-C','status-I'], 'datetime' : ['datePublished', 'dateUpdated', 'dateCreated'], 'series' : ['series'], 'enumeration' : ['category', 'genre', 'language', 'series', 'characters', 'ships', 'status', 'datePublished', 'dateUpdated', 'dateCreated', 'rating', 'warnings', 'numChapters', 'numWords', 'site', 'publisher', 'storyId', 'authorId', 'extratags', 'title', 'storyUrl', 'description', 'author', 'authorUrl', 'formatname', 'version' #,'formatext' # not useful information. #,'siteabbrev' ] } # no point copying the whole list. permitted_values['text'] = permitted_values['enumeration'] permitted_values['comments'] = permitted_values['enumeration'] titleLabels = { 'category':_('Category'), 'genre':_('Genre'), 'language':_('Language'), 'status':_('Status'), 'status-C':_('Status:%(cmplt)s')%no_trans, 'status-I':_('Status:%(inprog)s')%no_trans, 'series':_('Series'), 'characters':_('Characters'), 'ships':_('Relationships'), 'datePublished':_('Published'), 'dateUpdated':_('Updated'), 'dateCreated':_('Created'), 'rating':_('Rating'), 'warnings':_('Warnings'), 'numChapters':_('Chapters'), 'numWords':_('Words'), 'site':_('Site'), 'publisher':_('Publisher'), 'storyId':_('Story ID'), 'authorId':_('Author ID'), 'extratags':_('Extra Tags'), 'title':_('Title'), 'storyUrl':_('Story URL'), 'description':_('Description'), 'author':_('Author'), 'authorUrl':_('Author URL'), 'formatname':_('File Format'), 'formatext':_('File Extension'), 'siteabbrev':_('Site Abbrev'), 'version':_('FanFicFare Version') } class CustomColumnsTab(QWidget): def __init__(self, parent_dialog, plugin_action): self.parent_dialog = parent_dialog self.plugin_action = plugin_action QWidget.__init__(self) ## sort by visible Column Name (vs #name) custom_columns = sorted(self.plugin_action.gui.library_view.model().custom_columns.items(), key=lambda x: x[1]['name']) self.l = QVBoxLayout() self.setLayout(self.l) label = QLabel(_("If you have custom columns defined, they will be listed below. Choose a metadata value type to fill your columns automatically.")) label.setWordWrap(True) self.l.addWidget(label) self.l.addSpacing(5) self.custcol_dropdowns = {} self.custcol_newonlycheck = {} scrollable = QScrollArea() scrollcontent = QWidget() scrollable.setWidget(scrollcontent) scrollable.setWidgetResizable(True) self.l.addWidget(scrollable) self.sl = QVBoxLayout() scrollcontent.setLayout(self.sl) for key, column in custom_columns: if column['datatype'] in permitted_values: # print("\n============== %s ===========\n"%key) # for (k,v) in column.iteritems(): # print("column['%s'] => %s"%(k,v)) horz = QHBoxLayout() # label = QLabel(column['name']) label = QLabel('%s(%s)'%(column['name'],key)) label.setToolTip(_("Update this %s column(%s) with...")%(key,column['datatype'])) horz.addWidget(label) dropdown = QComboBox(self) dropdown.addItem('','none') for md in permitted_values[column['datatype']]: dropdown.addItem(titleLabels[md],md) self.custcol_dropdowns[key] = dropdown if key in prefs['custom_cols']: dropdown.setCurrentIndex(dropdown.findData(prefs['custom_cols'][key])) if column['datatype'] == 'enumeration': dropdown.setToolTip(_("Metadata values valid for this type of column.")+"\n"+_("Values that aren't valid for this enumeration column will be ignored.")) else: dropdown.setToolTip(_("Metadata values valid for this type of column.")) horz.addWidget(dropdown) newonlycheck = QCheckBox(_("New Only"),self) newonlycheck.setToolTip(_("Write to %s(%s) only for new\nbooks, not updates to existing books.")%(column['name'],key)) self.custcol_newonlycheck[key] = newonlycheck if key in prefs['custom_cols_newonly']: newonlycheck.setChecked(prefs['custom_cols_newonly'][key]) horz.addWidget(newonlycheck) self.sl.addLayout(horz) self.sl.insertStretch(-1) self.l.addSpacing(5) self.allow_custcol_from_ini = QCheckBox(_('Allow %(ccset)s from %(pini)s to override')%no_trans,self) self.allow_custcol_from_ini.setToolTip(_("The %(pini)s parameter %(ccset)s allows you to set custom columns to site specific values that aren't common to all sites.<br />%(ccset)s is ignored when this is off.")%no_trans) self.allow_custcol_from_ini.setChecked(prefs['allow_custcol_from_ini']) self.l.addWidget(self.allow_custcol_from_ini) label = QLabel(_("Special column:")) label.setWordWrap(True) self.l.addWidget(label) horz = QHBoxLayout() label = QLabel(_("Update/Overwrite Error Column:")) tooltip=_("When an update or overwrite of an existing story fails, record the reason in this column.\n(Text and Long Text columns only.)") label.setToolTip(tooltip) horz.addWidget(label) self.errorcol = QComboBox(self) self.errorcol.setToolTip(tooltip) self.errorcol.addItem('','none') for key, column in custom_columns: if column['datatype'] in ('text','comments'): self.errorcol.addItem(column['name'],key) self.errorcol.setCurrentIndex(self.errorcol.findData(prefs['errorcol'])) horz.addWidget(self.errorcol) self.save_all_errors = QCheckBox(_('Save All Errors'),self) self.save_all_errors.setToolTip(_('If unchecked, these errors will not be saved: %s')%( '\n'+ '\n'.join((_("Not Overwriting, web site is not newer."), _("Already contains %d chapters.").replace('%d','X'))))) self.save_all_errors.setChecked(prefs['save_all_errors']) horz.addWidget(self.save_all_errors) self.l.addLayout(horz) horz = QHBoxLayout() label = QLabel(_("Saved Metadata Column:")) tooltip=_("If set, FanFicFare will save a copy of all its metadata in this column when the book is downloaded or updated.<br/>The metadata from this column can later be used to update custom columns without having to request the metadata from the server again.<br/>(Long Text columns only.)") label.setToolTip(tooltip) horz.addWidget(label) self.savemetacol = QComboBox(self) self.savemetacol.setToolTip(tooltip) self.savemetacol.addItem('','') for key, column in custom_columns: if column['datatype'] in ('comments'): self.savemetacol.addItem(column['name'],key) self.savemetacol.setCurrentIndex(self.savemetacol.findData(prefs['savemetacol'])) horz.addWidget(self.savemetacol) label = QLabel('') horz.addWidget(label) # empty spacer for alignment with error column line. self.l.addLayout(horz) horz = QHBoxLayout() label = QLabel(_("Last Checked Column:")) tooltip=_("Record the last time FanFicFare updated or checked for updates.\n(Date columns only.)") label.setToolTip(tooltip) horz.addWidget(label) self.lastcheckedcol = QComboBox(self) self.lastcheckedcol.setToolTip(tooltip) self.lastcheckedcol.addItem('','none') ## sort by visible Column Name (vs #name) for key, column in custom_columns: if column['datatype'] == 'datetime': self.lastcheckedcol.addItem(column['name'],key) self.lastcheckedcol.setCurrentIndex(self.lastcheckedcol.findData(prefs['lastcheckedcol'])) horz.addWidget(self.lastcheckedcol) label = QLabel('') horz.addWidget(label) # empty spacer for alignment with error column line. self.l.addLayout(horz) class StandardColumnsTab(QWidget): def __init__(self, parent_dialog, plugin_action): self.parent_dialog = parent_dialog self.plugin_action = plugin_action QWidget.__init__(self) columns=OrderedDict() columns["title"]=_("Title") columns["authors"]=_("Author(s)") columns["publisher"]=_("Publisher") columns["tags"]=_("Tags") columns["languages"]=_("Languages") columns["pubdate"]=_("Published Date") columns["timestamp"]=_("Date") columns["comments"]=_("Comments") columns["series"]=_("Series") columns["identifiers"]=_("Ids(url id only)") self.l = QVBoxLayout() self.setLayout(self.l) label = QLabel(_("The standard calibre metadata columns are listed below. You may choose whether FanFicFare will fill each column automatically on updates or only for new books.")) label.setWordWrap(True) self.l.addWidget(label) self.l.addSpacing(5) self.stdcol_newonlycheck = {} rows=[] for key, column in six.iteritems(columns): row = [] rows.append(row) label = QLabel(column) #label.setToolTip("Update this %s column(%s) with..."%(key,column['datatype'])) row.append(label) newonlycheck = QCheckBox(_("New Only"),self) newonlycheck.setToolTip(_("Write to %s only for new\nbooks, not updates to existing books.")%column) self.stdcol_newonlycheck[key] = newonlycheck if key in prefs['std_cols_newonly']: newonlycheck.setChecked(prefs['std_cols_newonly'][key]) row.append(newonlycheck) if key == 'title': self.suppresstitlesort = QCheckBox(_('Force Title into Title Sort?'),self) self.suppresstitlesort.setToolTip(_("If checked, the title as given will be used for the Title Sort, too.\nIf not checked, calibre will apply it's built in algorithm which makes 'The Title' sort as 'Title, The', etc.")) self.suppresstitlesort.setChecked(prefs['suppresstitlesort']) row.append(self.suppresstitlesort) self.titlecase = QCheckBox(_('Fix Title Case?'),self) self.titlecase.setToolTip(_("If checked, Calibre's routine for correcting the capitalization of title will be applied.") +"\n"+_("This effects Calibre metadata only, not FanFicFare metadata in title page.")) self.titlecase.setChecked(prefs['titlecase']) row.append(self.titlecase) elif key == 'authors': self.set_author_url = QCheckBox(_('Set Calibre Author URL'),self) self.set_author_url.setToolTip(_("Set Calibre Author URL to Author's URL on story site.")) self.set_author_url.setChecked(prefs['set_author_url']) row.append(self.set_author_url) self.suppressauthorsort = QCheckBox(_('Force Author into Author Sort?'),self) self.suppressauthorsort.setToolTip(_("If checked, the author(s) as given will be used for the Author Sort, too.\nIf not checked, calibre will apply it's built in algorithm which makes 'Bob Smith' sort as 'Smith, Bob', etc.")) self.suppressauthorsort.setChecked(prefs['suppressauthorsort']) row.append(self.suppressauthorsort) self.authorcase = QCheckBox(_('Fix Author Case?'),self) self.authorcase.setToolTip(_("If checked, Calibre's routine for correcting the capitalization of author names will be applied.") +"\n"+_("Calibre remembers all authors in the library; changing the author case on one book will effect all books by that author.") +"\n"+_("This effects Calibre metadata only, not FanFicFare metadata in title page.")) self.authorcase.setChecked(prefs['authorcase']) row.append(self.authorcase) elif key == 'series': self.set_series_url = QCheckBox(_('Set Calibre Series URL'),self) self.set_series_url.setToolTip(_("Set Calibre Series URL to Series's URL on story site.")) self.set_series_url.setChecked(prefs['set_series_url']) row.append(self.set_series_url) self.setanthologyseries = QCheckBox(_("Set 'Series [0]' for New Anthologies?"),self) self.setanthologyseries.setToolTip(_("If checked, the Series column will be set to 'Series Name [0]' when an Anthology for a series is first created.")) self.setanthologyseries.setChecked(prefs['setanthologyseries']) row.append(self.setanthologyseries) grid = QGridLayout() for rownum, row in enumerate(rows): for colnum, col in enumerate(row): grid.addWidget(col,rownum,colnum) self.l.addLayout(grid) self.l.addSpacing(5) label = QLabel(_("Other Standard Column Options")) label.setWordWrap(True) self.l.addWidget(label) self.l.addSpacing(5) self.includecomments = QCheckBox(_("Include Books' Comments in Anthology Comments?"),self) self.includecomments.setToolTip(_('''Include all the merged books' comments in the new book's comments. Default is a list of included titles only.''')) self.includecomments.setChecked(prefs['includecomments']) self.l.addWidget(self.includecomments) self.anth_comments_newonly = QCheckBox(_("Set Anthology Comments only for new books"),self) self.anth_comments_newonly.setToolTip(_("Comments will only be set for New Anthologies, not updates.\nThat way comments you set manually are retained.")) self.anth_comments_newonly.setChecked(prefs['anth_comments_newonly']) self.l.addWidget(self.anth_comments_newonly) self.l.insertStretch(-1) class ImapTab(QWidget): def __init__(self, parent_dialog, plugin_action): self.parent_dialog = parent_dialog self.plugin_action = plugin_action QWidget.__init__(self) self.l = QGridLayout() self.setLayout(self.l) row=0 label = QLabel(_('These settings will allow FanFicFare to fetch story URLs from your email account. It will only look for story URLs in unread emails in the folder specified below.')) label.setWordWrap(True) self.l.addWidget(label,row,0,1,-1) row+=1 label = QLabel(_('IMAP Server Name')) tooltip = _("Name of IMAP server--must allow IMAP4 with SSL. Eg: imap.gmail.com") label.setToolTip(tooltip) self.l.addWidget(label,row,0) self.imapserver = QLineEdit(self) self.imapserver.setToolTip(tooltip) self.imapserver.setText(prefs['imapserver']) self.l.addWidget(self.imapserver,row,1) row+=1 label = QLabel(_('IMAP User Name')) tooltip = _("Name of IMAP user. Eg: yourname@gmail.com\nNote that Gmail accounts need to have IMAP enabled in Gmail Settings first.") label.setToolTip(tooltip) self.l.addWidget(label,row,0) self.imapuser = QLineEdit(self) self.imapuser.setToolTip(tooltip) self.imapuser.setText(prefs['imapuser']) self.l.addWidget(self.imapuser,row,1) row+=1 label = QLabel(_('IMAP User Password')) tooltip = _("IMAP password. If left empty, FanFicFare will ask you for your password when you use the feature.") label.setToolTip(tooltip) self.l.addWidget(label,row,0) self.imappass = QLineEdit(self) self.imappass.setToolTip(tooltip) self.imappass.setEchoMode(QLineEdit.Password) self.imappass.setText(prefs['imappass']) self.l.addWidget(self.imappass,row,1) row+=1 self.imapsessionpass = QCheckBox(_('Remember Password for Session (when not saved above)'),self) self.imapsessionpass.setToolTip(_('If checked, and no password is entered above, FanFicFare will remember your password until you close calibre or change Libraries.')) self.imapsessionpass.setChecked(prefs['imapsessionpass']) self.l.addWidget(self.imapsessionpass,row,0,1,-1) row+=1 label = QLabel(_('IMAP Folder Name')) tooltip = _("Name of IMAP folder to search for new emails. The folder (or label) has to already exist. Use INBOX for your default inbox.") label.setToolTip(tooltip) self.l.addWidget(label,row,0) self.imapfolder = QLineEdit(self) self.imapfolder.setToolTip(tooltip) self.imapfolder.setText(prefs['imapfolder']) self.l.addWidget(self.imapfolder,row,1) row+=1 self.imapmarkread = QCheckBox(_('Mark Emails Read'),self) self.imapmarkread.setToolTip(_('If checked, emails will be marked as having been read if they contain any story URLs.')) self.imapmarkread.setChecked(prefs['imapmarkread']) self.l.addWidget(self.imapmarkread,row,0,1,-1) row+=1 self.auto_reject_from_email = QCheckBox(_('Discard URLs on Reject List'),self) self.auto_reject_from_email.setToolTip(_('If checked, FanFicFare will silently discard story URLs from emails that are on your Reject URL List.<br>Otherwise they will appear and you will see the normal Reject URL dialog.<br>The Emails will still be marked Read if configured to.')) self.auto_reject_from_email.setChecked(prefs['auto_reject_from_email']) self.l.addWidget(self.auto_reject_from_email,row,0,1,-1) row+=1 self.update_existing_only_from_email = QCheckBox(_('Update Existing Books Only'),self) self.update_existing_only_from_email.setToolTip(_('If checked, FanFicFare will silently discard story URLs from emails that are not already in your library.<br>Otherwise all story URLs, new and existing, will be used.<br>The Emails will still be marked Read if configured to.')) self.update_existing_only_from_email.setChecked(prefs['update_existing_only_from_email']) self.l.addWidget(self.update_existing_only_from_email,row,0,1,-1) row+=1 self.download_from_email_immediately = QCheckBox(_('Download from Email Immediately'),self) self.download_from_email_immediately.setToolTip(_('If checked, FanFicFare will start downloading story URLs from emails immediately.<br>Otherwise the usual Download from URLs dialog will appear.')) self.download_from_email_immediately.setChecked(prefs['download_from_email_immediately']) self.l.addWidget(self.download_from_email_immediately,row,0,1,-1) row+=1 label = QLabel(_('Add these Tag(s) Automatically')) tooltip = ( _("Tags entered here will be automatically added to stories downloaded from email story URLs.") +"\n"+ _("Any additional stories you then manually add to the Story URL dialog will also have these tags added.") ) label.setToolTip(tooltip) self.l.addWidget(label,row,0) self.imaptags = EditWithComplete(self) # QLineEdit(self) self.imaptags.update_items_cache(self.plugin_action.gui.current_db.all_tags()) self.imaptags.setToolTip(tooltip) self.imaptags.setText(prefs['imaptags']) self.imaptags.setCursorPosition(0) self.l.addWidget(self.imaptags,row,1) row+=1 label = QLabel(_("<b>It's safest if you create a separate email account that you use only " "for your story update notices. FanFicFare and calibre cannot guarantee that " "malicious code cannot get your email password once you've entered it. " "<br>Use this feature at your own risk. </b>")) label.setWordWrap(True) self.l.addWidget(label,row,0,1,-1,Qt.AlignTop) self.l.setRowStretch(row,1) row+=1
JimmXinu/FanFicFare
calibre-plugin/config.py
config.py
py
85,977
python
en
code
664
github-code
36
[ { "api_name": "logging.getLogger", "line_number": 12, "usage_type": "call" }, { "api_name": "calibre.library.field_metadata.FieldMetadata", "line_number": 42, "usage_type": "call" }, { "api_name": "calibre_plugins.fanficfare_plugin.prefs.prefs", "line_number": 83, "usage_...
19751656745
import requests import json import yaml import os from bs4 import BeautifulSoup # set URLS for APIs proPublica_DataTable_url = ( "https://api.propublica.org/congress/v1/bills/search.json?query={}&sort=date" ) proPublica_bill_url = "https://api.propublica.org/congress/v1/116/bills/{}.json" proPublica_SENATE_member_url = ( "https://api.propublica.org/congress/v1/members/{}/{}/current.json" ) proPublica_SENATE_member_id_url = ( "https://api.propublica.org/congress/v1/members/{}.json" ) proPublica_HOUSE_member_url = "https://api.propublica.org/congress/v1/members/{chamber}/{state}/{district}/current.json" govtrack_bill_url = "https://www.govinfo.gov/link/bills/116/{}/{}?link-type=html" def generate_datatable_JSON(api_key, topicQueryString): proPublica_DataTable_request_url = proPublica_DataTable_url.format(topicQueryString) response = requests.get( proPublica_DataTable_request_url, headers={"X-API-KEY": api_key} ) return response, json.dumps(response.json()["results"][0]["bills"]) def generate_bill_data(api_key, bill_slug): proPublica_bill_url_slug = proPublica_bill_url.format(bill_slug) response = requests.get(proPublica_bill_url_slug, headers={"X-API-KEY": api_key}) return response, response.json()["results"] def generate_bill_fulltext(api_key, bill_type, bill_number): govtrack_bill_url_formatted = govtrack_bill_url.format(bill_type, bill_number) response = requests.get(govtrack_bill_url_formatted) soup = BeautifulSoup(response.text, features="html.parser") soupTitle = soup.find("title") if soupTitle and "Service Error" in soupTitle.text: return "There was an error fetching the bill's full text. It could be this bill is too recent, or another error with GovTrack." return response, response.text def get_contact_form_url(member_id): member_file = "{}.yaml".format(member_id) yaml_file = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "yaml", member_file) ) with open(yaml_file, "r") as stream: yaml_data = yaml.safe_load(stream) return yaml_data["contact_form"]["steps"][0]["visit"] def get_members_by_state(api_key, member_state): senate_members_formatted_url = proPublica_SENATE_member_url.format( "senate", member_state ) response = requests.get( senate_members_formatted_url, headers={"X-API-KEY": api_key} ) response_with_contact = [] for i in response.json()["results"]: member_id = i["id"] contact_url = get_contact_form_url(member_id) i["contact_url"] = contact_url response_with_contact.append(i) return response, response_with_contact def get_member_by_id(api_key, member_id): senate_member_by_id_url = proPublica_SENATE_member_id_url.format(member_id) response = requests.get(senate_member_by_id_url, headers={"X-API-KEY": api_key}) response_with_contact = [] for i in response.json()["results"]: member_id = i["id"] contact_url = get_contact_form_url(member_id) i["contact_url"] = contact_url response_with_contact.append(i) return response, response_with_contact
jon-behnken/reform-project
code/powertools/main.py
main.py
py
3,180
python
en
code
0
github-code
36
[ { "api_name": "requests.get", "line_number": 26, "usage_type": "call" }, { "api_name": "json.dumps", "line_number": 29, "usage_type": "call" }, { "api_name": "requests.get", "line_number": 34, "usage_type": "call" }, { "api_name": "requests.get", "line_number"...
27697116
from enum import Enum from typing import List from datetime import datetime from typing import Optional class FileType(Enum): PDF = "pdf" LINK = "link" DIRECTORY = "directory" GITHUB = "github" GENERIC = "generic" class File: def __init__( self, id: str, name: str, type: FileType, parent_id: str, path: str, created_at: datetime, updated_at: datetime, tags: List[str], processed: bool, summary: Optional[str] = None, index_id: Optional[str] = None, ): self.id = id self.name = name self.type = type self.parent_id = parent_id self.path = path self.created_at = created_at self.updated_at = updated_at self.tags = tags self.processed = processed self.summary = summary self.index_id = index_id @staticmethod def from_dict_factory(data: dict): file_type = FileType(data.get("type")) if file_type == FileType.DIRECTORY: return Directory.from_dict(data) elif file_type == FileType.PDF: return PdfFile.from_dict(data) elif file_type == FileType.LINK: return LinkFile.from_dict(data) elif file_type == FileType.GITHUB: return GithubFile.from_dict(data) else: return File.from_dict(data) def to_dict(self) -> dict: return { "id": self.id, "name": self.name, "type": self.type.value, "parent_id": self.parent_id, "path": self.path, "created_at": self.created_at.isoformat(), "updated_at": self.updated_at.isoformat(), "tags": self.tags, "processed": self.processed, "index_id": self.index_id, "summary": self.summary, } @classmethod def from_dict(cls, data: dict): return cls( id=data["id"], name=data["name"], type=FileType(data["type"]), parent_id=data["parent_id"], path=data["path"], created_at=datetime.fromisoformat(data["created_at"]), updated_at=datetime.fromisoformat(data["updated_at"]), tags=data["tags"], processed=data["processed"], index_id=data.get("index_id"), summary=data.get("summary"), ) class PdfFile(File): def __init__(self, fs_id: Optional[str] = None, **kwargs): super().__init__(type=FileType.PDF, **kwargs) self.fs_id = fs_id def to_dict(self) -> dict: result = super().to_dict() result["fs_id"] = self.fs_id return result @classmethod def from_dict(cls, data: dict): return cls( fs_id=data.get("fs_id"), # .get() is used here in case fs_id is not present id=data["id"], name=data["name"], parent_id=data["parent_id"], path=data["path"], created_at=datetime.fromisoformat(data["created_at"]), updated_at=datetime.fromisoformat(data["updated_at"]), tags=data["tags"], processed=data["processed"], index_id=data.get("index_id"), summary=data.get("summary"), ) class LinkFile(File): def __init__(self, url: str, **kwargs): super().__init__(type=FileType.LINK, **kwargs) self.url = url def to_dict(self) -> dict: result = super().to_dict() result["url"] = self.url return result @classmethod def from_dict(cls, data: dict): return cls( url=data["url"], id=data["id"], name=data["name"], parent_id=data["parent_id"], path=data["path"], created_at=datetime.fromisoformat(data["created_at"]), updated_at=datetime.fromisoformat(data["updated_at"]), tags=data["tags"], processed=data["processed"], index_id=data.get("index_id"), summary=data.get("summary"), ) class GithubFile(File): def __init__(self, url: str, **kwargs): super().__init__(type=FileType.GITHUB, **kwargs) self.url = url def to_dict(self) -> dict: result = super().to_dict() result["url"] = self.url return result @classmethod def from_dict(cls, data: dict): return cls( url=data["url"], id=data["id"], name=data["name"], parent_id=data["parent_id"], path=data["path"], created_at=datetime.fromisoformat(data["created_at"]), updated_at=datetime.fromisoformat(data["updated_at"]), tags=data["tags"], processed=data["processed"], index_id=data.get("index_id"), summary=data.get("summary"), ) class Directory(File): def __init__(self, **kwargs): super().__init__(**kwargs)
Kitenite/llm-kb
server/src/datasource/file_system.py
file_system.py
py
5,030
python
en
code
31
github-code
36
[ { "api_name": "enum.Enum", "line_number": 7, "usage_type": "name" }, { "api_name": "datetime.datetime", "line_number": 23, "usage_type": "name" }, { "api_name": "datetime.datetime", "line_number": 24, "usage_type": "name" }, { "api_name": "typing.List", "line_...
6937535017
# -*- coding: utf-8 -*- from __future__ import division, print_function __all__ = ["RotationModel"] import numpy as np from scipy.optimize import minimize from scipy.linalg import cho_factor, cho_solve import celerite from celerite import modeling from .pld import PLDModel from .gp import get_simple_gp, get_rotation_gp from .estimator import lomb_scargle_estimator, autocorr_estimator class RotationModel(modeling.ModelSet): def __init__(self, t, F, yerr, min_period=0.1, max_period=40.0, lomb_scargle_kwargs=None, autocorr_kwargs=None, **pld_kwargs): self.t = np.array(t) self.F = np.array(F) self.fsap = np.sum(F, axis=1) self.yerr = yerr A = self.F / self.fsap[:, None] self.min_period = min_period self.max_period = max_period # Run 1st order PLD w = np.linalg.solve(np.dot(A.T, A), np.dot(A.T, self.fsap-1.0)) self.fdet = self.fsap - np.dot(A, w) self.update_estimators(lomb_scargle_kwargs, autocorr_kwargs) # Set up the PLD model pld = PLDModel(self.t, self.F / self.fsap[:, None], **pld_kwargs) # Set up the GP model: self.simple_gp = get_simple_gp(self.t, self.fsap, yerr) self.rotation_gp = get_rotation_gp(self.t, self.fsap, yerr, self.lomb_scargle_period, min_period, max_period) super(RotationModel, self).__init__([("gp", self.simple_gp), ("pld", pld)]) # Save the default parameters self.default_pld_vector = \ pld.get_parameter_vector(include_frozen=True) self.default_simple_vector = \ self.simple_gp.get_parameter_vector(include_frozen=True) self.default_rotation_vector = \ self.rotation_gp.get_parameter_vector(include_frozen=True) # Set up an optimization cache self.model_cache = [] def update_estimators(self, lomb_scargle_kwargs=None, autocorr_kwargs=None): # Esimate the periods if lomb_scargle_kwargs is None: lomb_scargle_kwargs = dict(filter_period=10.0) self.lomb_scargle_result = \ lomb_scargle_estimator(self.t, self.fdet, self.yerr, self.min_period, self.max_period, **lomb_scargle_kwargs) peaks = self.lomb_scargle_result["peaks"] if len(peaks): self.lomb_scargle_period = peaks[0]["period"] else: self.lomb_scargle_period = self.max_period if autocorr_kwargs is None: autocorr_kwargs = {} self.autocorr_result = \ autocorr_estimator(self.t, self.fdet, self.yerr, self.min_period, self.max_period, **autocorr_kwargs) peaks = self.autocorr_result["peaks"] if len(peaks): self.autocorr_period = peaks[0]["period"] else: self.autocorr_period = self.max_period def use_simple_gp(self): self.models["gp"] = self.simple_gp def use_rotation_gp(self): self.models["gp"] = self.rotation_gp def get_weights(self): log_lams = self.pld.get_parameter_vector() A = self.pld.A fsap = self.fsap gp = self.gp alpha = np.dot(A.T, gp.apply_inverse(fsap - gp.mean.value)[:, 0]) ATKinvA = np.dot(A.T, gp.apply_inverse(A)) S = np.array(ATKinvA) dids = np.diag_indices_from(S) for bid, (s, f) in enumerate(self.pld.block_inds): S[(dids[0][s:f], dids[1][s:f])] += np.exp(-log_lams[bid]) factor = cho_factor(S, overwrite_a=True) alpha -= np.dot(ATKinvA, cho_solve(factor, alpha)) for bid, (s, f) in enumerate(self.pld.block_inds): alpha[s:f] *= np.exp(log_lams[bid]) return alpha def get_pld_model(self): return np.dot(self.pld.A, self.get_weights()) def get_predictions(self): pld_pred = self.get_pld_model() gp_pred = self.gp.predict(self.fsap - pld_pred, return_cov=False) return pld_pred, gp_pred def log_likelihood(self): log_lams = self.pld.get_parameter_vector() A = self.pld.A fsap = self.fsap gp = self.gp r = fsap - gp.mean.value try: alpha = gp.apply_inverse(r)[:, 0] except celerite.solver.LinAlgError: return -np.inf value = np.dot(r, alpha) ATalpha = np.dot(A.T, alpha) try: KA = gp.apply_inverse(A) except celerite.solver.LinAlgError: return -np.inf S = np.dot(A.T, KA) dids = np.diag_indices_from(S) for bid, (s, f) in enumerate(self.pld.block_inds): S[(dids[0][s:f], dids[1][s:f])] += np.exp(-log_lams[bid]) try: factor = cho_factor(S, overwrite_a=True) value -= np.dot(ATalpha, cho_solve(factor, ATalpha)) except (np.linalg.LinAlgError, ValueError): return -np.inf # Penalty terms log_det = 2*np.sum(np.log(np.diag(factor[0]))) log_det += np.sum(log_lams * self.pld.nblocks) log_det += gp.solver.log_determinant() return -0.5 * (value + log_det) def nll(self, params): self.set_parameter_vector(params) ll = self.log_likelihood() if not np.isfinite(ll): ll = -1e10 + np.random.randn() return -ll @property def period(self): return np.exp(self.rotation_gp.kernel.get_parameter("terms[2]:log_P")) @period.setter def period(self, period): self.rotation_gp.kernel.set_parameter("terms[2]:log_P", np.log(period)) def set_default(self): self.pld.set_parameter_vector(self.default_pld_vector, include_frozen=True) self.simple_gp.set_parameter_vector(self.default_simple_vector, include_frozen=True) self.rotation_gp.set_parameter_vector(self.default_rotation_vector, include_frozen=True) def optimize(self, **kwargs): init = self.get_parameter_vector() bounds = self.get_parameter_bounds() soln = minimize(self.nll, init, bounds=bounds, **kwargs) self.set_parameter_vector(soln.x) pld_pred = self.get_pld_model() self.fdet = self.fsap - pld_pred return soln def gp_grad_nll(self, params): self.gp.set_parameter_vector(params) gll = self.gp.grad_log_likelihood(self.fdet, quiet=True) if not np.isfinite(gll[0]): return (1e10 + np.random.randn(), 10000*np.random.randn(len(params))) return -gll[0], -gll[1] def optimize_gp(self, **kwargs): init = self.gp.get_parameter_vector() bounds = self.gp.get_parameter_bounds() soln = minimize(self.gp_grad_nll, init, bounds=bounds, jac=True, **kwargs) self.gp.set_parameter_vector(soln.x) return soln
dfm/rotate
rotate/model.py
model.py
py
7,231
python
en
code
3
github-code
36
[ { "api_name": "celerite.modeling.ModelSet", "line_number": 19, "usage_type": "attribute" }, { "api_name": "celerite.modeling", "line_number": 19, "usage_type": "name" }, { "api_name": "numpy.array", "line_number": 24, "usage_type": "call" }, { "api_name": "numpy.a...
7209789987
"""Functionality related to listing and querying apps""" import os import subprocess import logging import time import re from typing import Optional from bundle.bundle import Bundle, InvalidBundle from binary.binary import Binary from extern.tools import tool_named, call_sbpl def all_apps(at: str = "/Applications", mas_only: bool = False, sandboxed_only: bool = False): """ Returns all apps from a target folder :param at: The base folder where to search for applications :param mas_only: Whether to only consider applications from the Mac App Store :param sandboxed_only: Whether to only return sandboxed applications :return: Filepaths to applications fulfilling the criteria specified """ all_entries = [ os.path.join(at, x) for x in os.listdir(at) if x.endswith(".app") ] for entry in all_entries: try: app_bundle = Bundle.make(entry) if mas_only and not app_bundle.is_mas_app(): continue if sandboxed_only and not app_bundle.is_sandboxed(): continue yield entry except InvalidBundle: continue def container_for_app(app): """ Returns the container directory used by the application or None if the container does not exist. :param app: The app for which to find the container directory. Note that valid arguments are both a filepath to the application and a bundle for that application :return: Filepath to the container or None, if the lookup failed. """ # Handle code that already has a bundle for an app if isinstance(app, Bundle): app_bundle = app elif isinstance(app, str): try: app_bundle = Bundle.make(app) except InvalidBundle: return None bid = app_bundle.bundle_identifier(normalized=True) # Verify the container exists. container_path = os.path.join(os.path.expanduser("~/Library/Containers/"), bid) if not os.path.exists(container_path): return None # Also verify that the metadata file is present, else the container is invalid and of # no use to other code container_metadata = os.path.join(container_path, "Container.plist") if not os.path.exists(container_metadata): return None return container_path def _entitlements_can_be_parsed(app_bundle: Bundle) -> bool: """ Check whether an application's entitlements can be parsed by libsecinit. We only check part of the process, namely the parsing of entitlements via xpc_create_from_plist. :param app_bundle: Bundle for which to check whether the entitlements can be parsed :type app_bundle: Bundle :return: True, iff the entitlements of the main executable can be parsed, else false. """ # No entitlements, no problem # If the app contains no entitlements, entitlement validation cannot fail. if not app_bundle.has_entitlements(): return True exe_path = app_bundle.executable_path() raw_entitlements = Binary.get_entitlements(exe_path, raw=True) # Call the local xpc_vuln_checker program that does the actual checking. exit_code, _ = tool_named("xpc_vuln_checker")(input=raw_entitlements) return exit_code != 1 def init_sandbox(app_bundle: Bundle, logger: logging.Logger, force_initialisation: bool = False) -> bool: """ Initialises the sandbox for a particular app bundle. :param app_bundle: The App for which to initialise the App Sandbox :param logger: Logger object used to record failure cases :param force_initialisation: Whether to overwrite / start initialisation even if metadata exists that indicates the sandbox has already been initialised :return: Boolean value indicating whether the sandbox was successfully initialised (or was already initialised) """ # Guarding against a few applications that ship with entitlements libsecinit cannot parse. if not _entitlements_can_be_parsed(app_bundle): return False # Super useful environment variable used by libsecinit. If this variable is set, the application # is terminated after its sandbox is initialised. init_sandbox_environ = {**os.environ, 'APP_SANDBOX_EXIT_AFTER_INIT': str(1)} app_container = container_for_app(app_bundle) if app_container is not None and not force_initialisation: if logger: logger.info("Container directory already existed. Skipping sandbox initialisation.") return True if logger: logger.info("Starting process {} to initialize sandbox.".format(app_bundle.executable_path())) process = subprocess.Popen([app_bundle.executable_path()], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=init_sandbox_environ) # Sandbox initialisation should be almost instant. If the application is still # running after a couple of seconds, the sandbox failed to initialise. # We use 10 seconds as an arbitrary cutoff time. try: process.wait(10) except subprocess.TimeoutExpired: process.kill() if logger: logger.error("Sandbox was not initialised successfully for executable at {}. Skipping.".format( app_bundle.executable_path()) ) return False # Check that there now is an appropriate container if container_for_app(app_bundle) is None: if logger: logger.info( "Sandbox initialisation for executable {} succeeded \ but no appropriate container metadata was created.".format( app_bundle.executable_path() ) ) return False return True def sandbox_status(app_bundle: Bundle, logger: logging.Logger) -> Optional[int]: process = subprocess.Popen([app_bundle.executable_path()], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # Sandbox initialisation should be almost instant. If the application is still # running after a couple of seconds, the sandbox failed to initialise or is # not enabled at all. # We use 10 seconds as an arbitrary cutoff time. time.sleep(10) pid = str(process.pid) if process.poll() is not None: logger.error("Process terminated early: {}".format(app_bundle.executable_path())) return None sandbox_status = tool_named("sandbox_status") returncode, sb_status = sandbox_status(pid) process.kill() rx = re.compile(r'^Sandbox status for PID {} is (\d+)$'.format(pid)) m = rx.match(sb_status.decode().strip()) if m: return int(m.group(1)) logger.error("`sandbox_status` did not return a status for executable at {}. Skipping.".format( app_bundle.executable_path()) ) return None def run_process(executable, duration, stdout_file=subprocess.DEVNULL, stderr_file=subprocess.DEVNULL) -> int: """ Executes and runs a process for a certain number of seconds, then kills the process. :param executable: Filepath to executable to execute :param duration: Duration in seconds or None to let the executable run indefinitely. :param stdout_file: File object to write standard output to :param stderr_file: File object to write standard error to :return: The PID of the running process """ process = subprocess.Popen([executable], stdout=stdout_file, stderr=stderr_file) process_pid = process.pid try: process.wait(duration) except subprocess.TimeoutExpired: process.kill() return process_pid def get_sandbox_rules(app_bundle, result_format: str = 'scheme', patch: bool = False): """ Obtain the final sandbox ruleset for a target application. Optionally also patches the result so that all allow decisions are logged to the syslog. :param app_bundle: The bundle for which to obtain the sandbox ruleset :param result_format: The format to return. Supported are \"scheme\" and \"json\" :param patch: Whether to patch the resulting profile. Patching a profile results in a profile that logs all allowed decisions. :return: Raw bytes of sandbox profile. """ container = container_for_app(app_bundle) return call_sbpl(container, result_format=result_format, patch=patch)
0xbf00/maap
misc/app_utils.py
app_utils.py
py
8,464
python
en
code
8
github-code
36
[ { "api_name": "os.path.join", "line_number": 24, "usage_type": "call" }, { "api_name": "os.path", "line_number": 24, "usage_type": "attribute" }, { "api_name": "os.listdir", "line_number": 24, "usage_type": "call" }, { "api_name": "bundle.bundle.Bundle.make", ...
42998550666
from __future__ import annotations # # SSL wrap socket for PyOpenSSL. # Mostly copied from # # https://github.com/shazow/urllib3/blob/master/urllib3/contrib/pyopenssl.py # # and added OCSP validator on the top. import logging import time from functools import wraps from inspect import getfullargspec as get_args from socket import socket from typing import Any import certifi import OpenSSL.SSL from .constants import OCSPMode from .errorcode import ER_OCSP_RESPONSE_CERT_STATUS_REVOKED from .errors import OperationalError from .vendored.urllib3 import connection as connection_ from .vendored.urllib3.contrib.pyopenssl import PyOpenSSLContext, WrappedSocket from .vendored.urllib3.util import ssl_ as ssl_ DEFAULT_OCSP_MODE: OCSPMode = OCSPMode.FAIL_OPEN FEATURE_OCSP_MODE: OCSPMode = DEFAULT_OCSP_MODE """ OCSP Response cache file name """ FEATURE_OCSP_RESPONSE_CACHE_FILE_NAME: str | None = None log = logging.getLogger(__name__) def inject_into_urllib3() -> None: """Monkey-patch urllib3 with PyOpenSSL-backed SSL-support and OCSP.""" log.debug("Injecting ssl_wrap_socket_with_ocsp") connection_.ssl_wrap_socket = ssl_wrap_socket_with_ocsp @wraps(ssl_.ssl_wrap_socket) def ssl_wrap_socket_with_ocsp(*args: Any, **kwargs: Any) -> WrappedSocket: # Extract host_name hostname_index = get_args(ssl_.ssl_wrap_socket).args.index("server_hostname") server_hostname = ( args[hostname_index] if len(args) > hostname_index else kwargs.get("server_hostname", None) ) # Remove context if present ssl_context_index = get_args(ssl_.ssl_wrap_socket).args.index("ssl_context") context_in_args = len(args) > ssl_context_index ssl_context = ( args[hostname_index] if context_in_args else kwargs.get("ssl_context", None) ) if not isinstance(ssl_context, PyOpenSSLContext): # Create new default context if context_in_args: new_args = list(args) new_args[ssl_context_index] = None args = tuple(new_args) else: del kwargs["ssl_context"] # Fix ca certs location ca_certs_index = get_args(ssl_.ssl_wrap_socket).args.index("ca_certs") ca_certs_in_args = len(args) > ca_certs_index if not ca_certs_in_args and not kwargs.get("ca_certs"): kwargs["ca_certs"] = certifi.where() ret = ssl_.ssl_wrap_socket(*args, **kwargs) log.debug( "OCSP Mode: %s, " "OCSP response cache file name: %s", FEATURE_OCSP_MODE.name, FEATURE_OCSP_RESPONSE_CACHE_FILE_NAME, ) if FEATURE_OCSP_MODE != OCSPMode.INSECURE: from .ocsp_asn1crypto import SnowflakeOCSPAsn1Crypto as SFOCSP v = SFOCSP( ocsp_response_cache_uri=FEATURE_OCSP_RESPONSE_CACHE_FILE_NAME, use_fail_open=FEATURE_OCSP_MODE == OCSPMode.FAIL_OPEN, ).validate(server_hostname, ret.connection) if not v: raise OperationalError( msg=( "The certificate is revoked or " "could not be validated: hostname={}".format(server_hostname) ), errno=ER_OCSP_RESPONSE_CERT_STATUS_REVOKED, ) else: log.info( "THIS CONNECTION IS IN INSECURE " "MODE. IT MEANS THE CERTIFICATE WILL BE " "VALIDATED BUT THE CERTIFICATE REVOCATION " "STATUS WILL NOT BE CHECKED." ) return ret def _openssl_connect( hostname: str, port: int = 443, max_retry: int = 20, timeout: int | None = None ) -> OpenSSL.SSL.Connection: """The OpenSSL connection without validating certificates. This is used to diagnose SSL issues. """ err = None sleeping_time = 1 for _ in range(max_retry): try: client = socket() client.connect((hostname, port)) context = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD) if timeout is not None: context.set_timeout(timeout) client_ssl = OpenSSL.SSL.Connection(context, client) client_ssl.set_connect_state() client_ssl.set_tlsext_host_name(hostname.encode("utf-8")) client_ssl.do_handshake() return client_ssl except ( OpenSSL.SSL.SysCallError, OSError, ) as ex: err = ex sleeping_time = min(sleeping_time * 2, 16) time.sleep(sleeping_time) if err: raise err
snowflakedb/snowflake-connector-python
src/snowflake/connector/ssl_wrap_socket.py
ssl_wrap_socket.py
py
4,486
python
en
code
511
github-code
36
[ { "api_name": "constants.OCSPMode", "line_number": 27, "usage_type": "name" }, { "api_name": "constants.OCSPMode.FAIL_OPEN", "line_number": 27, "usage_type": "attribute" }, { "api_name": "constants.OCSPMode", "line_number": 28, "usage_type": "name" }, { "api_name"...
540233672
import torch import numpy as np import encoding_tree import time import copy def find(x, parent, dep): if parent[x] == -1: dep[x] = 0 return dep[x] if (dep[x] > 0): return dep[x] dep[x] = find(parent[x], parent, dep) + 1 return dep[x] def get_tree(input_): data, k = input_ edges = data.edge_index.transpose(0, 1).numpy() G = encoding_tree.Graph(edges=edges, n=data.num_nodes) T = encoding_tree.Tree(G=G) parent = T.k_HCSE(k) parent = np.array(parent) dep = [-1] * parent.size dep = np.array(dep) for i in range(parent.size): dep[i] = find(i, parent, dep) return parent, dep def graph2tree(input_): data, k = input_ parent, dep = get_tree((data, k)) dt = np.dtype([('dep', int), ('id', int)]) node = [(-d, i) for i, d in enumerate(dep)] node = np.array(node, dtype=dt) node.sort(order='dep') data.num_edges = data.edge_index.shape[1] data.num_nodes = len(parent) data.x = torch.cat([data.x, torch.zeros(data.num_nodes - data.x.shape[0], data.x.shape[1])], dim=0) d = 0 st, pn = 0, 0 data.layer_mask = torch.zeros(k + 1, len(parent), dtype=torch.bool) for i in range(node.size): pn += 1 if i + 1 == node.size or node[i][0] != node[i + 1][0]: data.layer_mask[d, st:pn] = True if i + 1 != node.size: t = torch.zeros(2, pn - st, dtype=torch.int64) for j in range(0, pn - st): t[0, j], t[1, j] = j + st, parent[j + st] data['pool' + str(d)] = t d += 1 st = pn layer_edge = [data.edge_index] for i in range(k - 1): edge = copy.deepcopy(layer_edge[-1]) edge = edge.reshape(-1) for j in range(edge.shape[0]): edge[j] = parent[edge[j]] edge = edge.reshape(2, -1) layer_edge.append(edge) data.edge_index = torch.cat(layer_edge, dim=1) return data
zzq229-creator/entpool
data/graph2tree.py
graph2tree.py
py
1,985
python
en
code
0
github-code
36
[ { "api_name": "encoding_tree.Graph", "line_number": 21, "usage_type": "call" }, { "api_name": "encoding_tree.Tree", "line_number": 22, "usage_type": "call" }, { "api_name": "numpy.array", "line_number": 24, "usage_type": "call" }, { "api_name": "numpy.array", ...
29620128812
import mysql.connector import json # pip3 install mysql-connector-python # 连接数据库 config = { 'user': 'root', 'password': 'xxx', 'host': '192.168.137.129', 'port': '3306', 'database': 'db_example' } json_data = {} with open('./data.json', 'r', encoding='utf8')as fp: json_data = json.load(fp)[0] print(json_data) fp.close() con = mysql.connector.connect(**config) mycursor = con.cursor(buffered=True) # 查询这里面所有的人: val = (json_data["businessRegistration"]["socialCreditCode"],) sql = "SELECT * FROM company where social_credit_code = %s " print(sql % val) mycursor.execute(sql, val) data = mycursor.fetchone() # fetchone() 获取一条记录 if data: print(data) updateVal = (json_data["companyName"], json_data["companyPhone"], json_data["companyEmail"], json_data["officialWebsite"], json_data["companyAddress"], json_data["companyProfile"], data[0]) updateSql = "UPDATE company SET company_name = %s, company_phone = %s, company_email = %s, official_website = %s, company_address = %s, company_profile = %s,update_at = now() WHERE id = %s ;" print(updateSql % updateVal) mycursor.execute(updateSql, updateVal) companyRegistration = json_data["businessRegistration"] registeredCapital = companyRegistration["registeredCapital"].replace( "万(元)", "").replace(",", "") paidInCapital = companyRegistration["paidInCapital"] if '-' == paidInCapital: paidInCapital = None operatingPeriod = companyRegistration["operatingPeriod"] operatingPeriodList = operatingPeriod.split("至") operatingPeriodBegin = operatingPeriodList[0].strip() operatingPeriodEnd = operatingPeriodList[1].strip() updateDetailVal = (companyRegistration["legalRepresentative"], companyRegistration["operatingStatus"], registeredCapital, paidInCapital, companyRegistration["industry"], companyRegistration[ "socialCreditCode"], companyRegistration["taxpayerIdentificationNumber"], companyRegistration["businessRegistrationNumber"], companyRegistration[ "organizationCode"], companyRegistration["registrationAuthority"], companyRegistration["establishmentDate"], companyRegistration[ "enterpriseType"], operatingPeriodBegin, operatingPeriodEnd, companyRegistration["administrativeDivisions"], companyRegistration[ "annualInspectionDate"], companyRegistration["registeredAddress"], companyRegistration["businessScope"], data[0]) updateDetailSql = "UPDATE db_example.company_registration SET legal_representative = %s, operating_status = %s, registered_capital = %s, paidIn_capital = %s, industry = %s, social_credit_code = %s, taxpayer_identification_number = %s, company_registration_number = %s, organization_code = %s, registration_authority = %s, establishment_date = %s, enterprise_type = %s, operating_period_begin = %s, operating_period_end = %s, administrative_divisions = %s, annualInspection_date = %s, registered_address = %s, business_scope = %s, update_at = now() WHERE company_id = %s;" print(updateDetailSql % updateDetailVal) company = mycursor.execute(updateDetailSql, updateDetailVal) else: insertVal = (json_data["businessRegistration"]["socialCreditCode"], json_data["companyName"], json_data["companyPhone"], json_data["companyEmail"], json_data["officialWebsite"], json_data["companyAddress"], json_data["companyProfile"],) insertSql = "INSERT INTO company (social_credit_code, company_name, company_phone, company_email, official_website, company_address, company_profile) VALUES (%s, %s, %s, %s, %s, %s, %s);" print(insertSql % insertVal) company = mycursor.execute(insertSql, insertVal) # 最后插入行的主键id print(mycursor.lastrowid) companyRegistration = json_data["businessRegistration"] registeredCapital = companyRegistration["registeredCapital"].replace( "万(元)", "").replace(",", "") paidInCapital = companyRegistration["paidInCapital"] if '-' == paidInCapital: paidInCapital = None operatingPeriod = companyRegistration["operatingPeriod"] operatingPeriodList = operatingPeriod.split("至") operatingPeriodBegin = operatingPeriodList[0].strip() operatingPeriodEnd = operatingPeriodList[1].strip() insertDetailVal = (mycursor.lastrowid, companyRegistration["legalRepresentative"], companyRegistration["operatingStatus"], registeredCapital, paidInCapital, companyRegistration["industry"], companyRegistration[ "socialCreditCode"], companyRegistration["taxpayerIdentificationNumber"], companyRegistration["businessRegistrationNumber"], companyRegistration[ "organizationCode"], companyRegistration["registrationAuthority"], companyRegistration["establishmentDate"], companyRegistration[ "enterpriseType"], operatingPeriodBegin, operatingPeriodEnd, companyRegistration["administrativeDivisions"], companyRegistration[ "annualInspectionDate"], companyRegistration["registeredAddress"], companyRegistration["businessScope"]) insertDetailSql = "INSERT INTO company_registration (company_id, legal_representative, operating_status, registered_capital, paidIn_capital, industry, social_credit_code, taxpayer_identification_number, company_registration_number, organization_code, registration_authority, establishment_date, enterprise_type, operating_period_begin, operating_period_end, administrative_divisions, annualInspection_date, registered_address, business_scope) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);" print(insertDetailSql % insertDetailVal) company = mycursor.execute(insertDetailSql, insertDetailVal) con.commit()
hua345/myBlog
python/mysql/index.py
index.py
py
6,087
python
en
code
0
github-code
36
[ { "api_name": "json.load", "line_number": 15, "usage_type": "call" }, { "api_name": "mysql.connector.connector.connect", "line_number": 20, "usage_type": "call" }, { "api_name": "mysql.connector.connector", "line_number": 20, "usage_type": "attribute" }, { "api_na...
31324286848
#!/usr/bin/python3 import sqlite3 from itertools import chain conn = sqlite3.connect('vexdb.db') curs = conn.cursor() ItyToId=dict() for row in curs.execute('SELECT id, "Ity_" || btype || nbits AS cenum FROM IRType'): ItyToId[row[1]]=row[0] curs.execute('DELETE FROM AiOpSig') conn.commit() ItyToId['ity_RMode']=ItyToId['Ity_I32'] with open('unique-opsigs.csv') as f: for line in f: fields=line.rstrip().split(',') n=int(fields[0]) if n<2 or n>5: raise Exception("Invalid operand count.") u=int(fields[1]) r=False; if fields[2]=='ity_RMode': r=True values=chain((n, u, r), (int(ItyToId[x]) for x in fields[2:2+n])) i_stub='INSERT INTO AiOpSig(nopds, ntypes, rmode, res,opd1' v_stub=') VALUES (?,?,?,?,?' if n>=3: i_stub += ',opd2' v_stub += ',?' if n>=4: i_stub += ',opd3' v_stub += ',?' if n==5: i_stub += ',opd4' v_stub += ',?' try: curs.execute(i_stub + v_stub + ')', tuple(values)) except Exception as e: print(e) print(line) conn.commit() conn.close()
EmmetCaulfield/valgrind
arinx/hacking/insert-opsigs.py
insert-opsigs.py
py
1,236
python
en
code
0
github-code
36
[ { "api_name": "sqlite3.connect", "line_number": 6, "usage_type": "call" }, { "api_name": "itertools.chain", "line_number": 30, "usage_type": "call" } ]
15215617350
# -*- coding: utf-8 -*- from get_data import getData import numpy as np import matplotlib.pyplot as plt from lung_mask import getLungMask from keras.models import Model from keras.layers import Input, BatchNormalization, Activation, Dropout from keras.layers.convolutional import Conv3D, Conv3DTranspose from keras.layers.pooling import MaxPooling3D from keras.layers.merge import concatenate from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau from keras.optimizers import Adam #import keras import cv2 train_volumes, train_volumes_masks, _, val_volumes, val_volumes_masks, _, test_volumes, test_volumes_masks, _ = getData(type_ = "volume") #%% def run_segmentation_CNN(): train_volumes, train_volumes_masks, _, val_volumes, val_volumes_masks, _, test_volumes, test_volumes_masks, _ = getData(type_ = "volume") train, test, val, trainMasks, testMasks, valMasks=prepare_CNN(train_volumes, train_volumes_masks, val_volumes, val_volumes_masks, test_volumes, test_volumes_masks) results, accuracy, dice, jaccard, preds_test_nodules, accuracy_val, dice_val, jaccard_val, preds_val_nodules=train_model(train, test, val, trainMasks, testMasks, valMasks) plot_loss(results) print("Test set: The dice value is %.2f and the jaccard value is %.2f. The accuracy is %.2f" % (dice, jaccard, accuracy)) print("validation set: The dice value is %.2f and the jaccard value is %.2f. The accuracy is %.2f" % (dice_val, jaccard_val, accuracy_val)) #%% """ prepare_CNN =============== prepares the input for the model of the CNN Arguments: Returns:train_volumes, test_volumes, val_volumes - images of train, test and validation sets after aplying lung mask, normalization and reshaped for input on the CNN train_volumes_masks, test_volumes_masks, val_volumes_masks - classes in the format of one-hot-vector (1,0,0) """ def prepare_CNN(train_volumes, train_volumes_masks, val_volumes, val_volumes_masks, test_volumes, test_volumes_masks): mean_int=np.mean(train_volumes) std_int=np.std(train_volumes) train_volumes = (train_volumes - mean_int)/std_int val_volumes = (val_volumes - mean_int)/std_int test_volumes = (test_volumes - mean_int)/std_int train=[] test=[] val=[] train_mask=[] val_mask=[] #reshape to a multiple of 16 to better applye the U-net CNN - padding from 51 to 64 for train_volume, i in zip(train_volumes, range(len(train_volumes))): train_volumes[i]= [cv2.copyMakeBorder(train_volume[i],7,6,6,7,cv2.BORDER_CONSTANT,value=0) for i in range(len(train_volume))] #val_volume_mask= [cv2.copyMakeBorder(val_volume_mask[i],7,6,6,7,cv2.BORDER_CONSTANT,value=0) for i in range(len(val_volume_mask))] train_volumes_masks = np.asarray(train_volumes_masks) test_volumes_masks = np.asarray(test_volumes_masks) val_volumes_masks = np.asarray(val_volumes_masks) train_volumes = np.asarray(train_volumes) test_volumes = np.asarray(test_volumes) val_volumes = np.asarray(val_volumes) train_volumes_masks = train_volumes_masks.astype('float32') test_volumes_masks = test_volumes_masks.astype('float32') val_volumes_masks = val_volumes_masks.astype('float32') train_volumes = train_volumes.astype('float32') test_volumes = test_volumes.astype('float32') val_volumes = val_volumes.astype('float32') train_volumes = train_volumes.reshape(-1,64,64,64,1) test_volumes = test_volumes.reshape(-1,64,64,64,1) val_volumes = val_volumes.reshape(-1, 64,64, 64,1) train_volumes_masks = train_volumes_masks.reshape(-1,64,64,64,1) val_volumes_masks = val_volumes_masks.reshape(-1, 64,64,64, 1) return train_volumes, test_volumes, val_volumes, train_volumes_masks, test_volumes_masks, val_volumes_masks #%% def conv3d_block(input_tensor, n_filters, kernel_size=3, batchnorm=True): # first layer x = Conv3D(filters=n_filters, kernel_size=(kernel_size, kernel_size,kernel_size ), kernel_initializer="he_normal", padding="same")(input_tensor) if batchnorm: x = BatchNormalization()(x) x = Activation("relu")(x) # second layer x = Conv3D(filters=n_filters, kernel_size=(kernel_size, kernel_size,kernel_size), kernel_initializer="he_normal", padding="same")(x) if batchnorm: x = BatchNormalization()(x) x = Activation("relu")(x) return x def get_unet(input_img, n_filters=16, dropout=0.4, batchnorm=True): # contracting path c1 = conv3d_block(input_img, n_filters=n_filters*1, kernel_size=3, batchnorm=batchnorm) p1 = MaxPooling3D((2, 2,2)) (c1) p1 = Dropout(dropout*0.5)(p1) c2 = conv3d_block(p1, n_filters=n_filters*2, kernel_size=3, batchnorm=batchnorm) p2 = MaxPooling3D((2, 2,2)) (c2) p2 = Dropout(dropout)(p2) c3 = conv3d_block(p2, n_filters=n_filters*4, kernel_size=3, batchnorm=batchnorm) p3 = MaxPooling3D((2, 2,2)) (c3) p3 = Dropout(dropout)(p3) c4 = conv3d_block(p3, n_filters=n_filters*8, kernel_size=3, batchnorm=batchnorm) p4 = MaxPooling3D(pool_size=(2, 2,2)) (c4) p4 = Dropout(dropout)(p4) c5 = conv3d_block(p4, n_filters=n_filters*16, kernel_size=3, batchnorm=batchnorm) # expansive path u6 = Conv3DTranspose(n_filters*8, (3, 3,3), strides=(2, 2, 2), padding='same') (c5) u6 = concatenate([u6, c4]) u6 = Dropout(dropout)(u6) c6 = conv3d_block(u6, n_filters=n_filters*8, kernel_size=3, batchnorm=batchnorm) u7 = Conv3DTranspose(n_filters*4, (3, 3, 3), strides=(2, 2, 2), padding='same') (c6) u7 = concatenate([u7, c3]) u7 = Dropout(dropout)(u7) c7 = conv3d_block(u7, n_filters=n_filters*4, kernel_size=3, batchnorm=batchnorm) u8 = Conv3DTranspose(n_filters*2, (3, 3, 3), strides=(2, 2, 2), padding='same') (c7) u8 = concatenate([u8, c2]) u8 = Dropout(dropout)(u8) c8 = conv3d_block(u8, n_filters=n_filters*2, kernel_size=3, batchnorm=batchnorm) u9 = Conv3DTranspose(n_filters*1, (3, 3, 3), strides=(2, 2,2), padding='same') (c8) u9 = concatenate([u9, c1], axis=3) u9 = Dropout(dropout)(u9) c9 = conv3d_block(u9, n_filters=n_filters*1, kernel_size=3, batchnorm=batchnorm) outputs = Conv3D(1, (1, 1, 1), activation='sigmoid') (c9) model = Model(inputs=[input_img], outputs=[outputs]) return model #%% """ IoU_loss =============== defenition of loss for binary problem - try to maximize the jaccard coefficient ( as only true values matter) it solves the problem of having more false (0) pixeis Arguments: Returns: * results- coefiicient to minimize (1-jaccard) """ from keras import backend as K def IoU_loss(y_true,y_pred): smooth = 1e-12 # author = Vladimir Iglovikov intersection = K.sum(y_true * y_pred) sum_ = K.sum(y_true + y_pred) jac = (intersection + smooth) / (sum_ - intersection + smooth) return K.mean(1-jac) #%% """ train_model =============== train the model with tarin set and validation set to define treshold - evaluates test set Arguments: Returns: * results- result of the trained model with keras accuracy, dice, jaccard - evaluation scores for the test set preds_test_nodules - predicted nodules on test set """ def train_model(train_volumes, test_volumes, val_volumes, train_volumes_masks, test_volumes_masks, val_volumes_masks): # define parameters im_width = 64 im_height = 64 epochs=100 batch=len(train_volumes) input_img = Input((im_height, im_width, 1), name='img') model = get_unet(input_img, n_filters=3, dropout=0.05, batchnorm=True) model.compile(optimizer=Adam(), loss=IoU_loss) #model.summary() callbacks = [ EarlyStopping(patience=10, verbose=1), ReduceLROnPlateau(factor=0.1, patience=3, min_lr=0.00001, verbose=1), ModelCheckpoint('model3dsegmentation.h5', verbose=1, save_best_only=True, save_weights_only=True) ] results = model.fit(train_volumes, train_volumes_masks, batch_size=batch,steps_per_epoch=10, epochs=epochs, callback=callbacks, verbose=0, validation_data=(val_volumes, val_volumes_masks)) model.load_weights('model3dsegmentation.h5') treshold=(0.35,0.4, 0.45, 0.5,0.55,0.6,0.65,0.7,0.75) maximo=0 # Predict for test with treshold preds_train = model.predict(train_volumes, verbose=0) for tresh in treshold: preds_train_nodules = (preds_train >tresh).astype(np.uint8) preds_train_nodules=preds_train_nodules.reshape(-1,64,64) train_volumes_masks=train_volumes_masks.reshape(-1,64,64) _, dice, jaccard = confusionMatrix(np.hstack(np.hstack(preds_train_nodules)), np.hstack(np.hstack(train_volumes_masks))) metrics=dice+jaccard # the best result will dictate which is the bst treshold if metrics > maximo : maximo=metrics best_treshold=tresh # Predict for test with treshold already defined by training set preds_val = model.predict(val_volumes, verbose=0) preds_val_nodules = (preds_val >best_treshold).astype(np.uint8) val_volumes_masks=val_volumes_masks.reshape(-1,64,64) preds_val_nodules=preds_val_nodules.reshape(-1,64,64) accuracy_val, dice_val, jaccard_val = confusionMatrix(np.hstack(np.hstack(preds_val_nodules)), np.hstack(np.hstack(val_volumes_masks))) # Predict for test with treshold already defined by training set preds_test = model.predict(test_volumes, verbose=0) preds_test_nodules = (preds_test >best_treshold).astype(np.uint8) preds_test_nodules=preds_test_nodules.reshape(-1,64,64) #test_volumes_masks=test_volumes_masks.reshape(-1,51,51) #cut the border previously used to match the ground truth border_size_top_right=6 border_size_bottom_left=6 preds_test_nodules=[nodule[border_size_top_right:-(border_size_top_right+1),border_size_bottom_left:-(border_size_bottom_left+1)] for nodule in preds_test_nodules] #Aplly morphologic operation to close some holes on predicted images preds_test_nodules=closing(preds_test_nodules) accuracy, dice, jaccard = confusionMatrix(np.hstack(np.hstack(preds_test_nodules)), np.hstack(np.hstack(test_volumes_masks))) return results, accuracy, dice, jaccard, preds_test_nodules, accuracy_val, dice_val, jaccard_val, preds_val_nodules #%% """ closing- morpological closing operation ================================================= Arguments: image array return: image array after closing """ def closing(preds_image): new_preds=[] for i in range(len(preds_image)): kernel_ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)) dilated_mask = cv2.dilate(preds_image[i],kernel_ellipse,iterations = 2) erode_mask = cv2.erode(dilated_mask,kernel_ellipse,iterations = 2) new_preds.append(erode_mask) return new_preds #%% def confusionMatrix(predictions, labels): true_positives = 0 false_negatives = 0 false_positives = 0 true_negatives = 0 predictions= predictions.astype('float32') labels = labels.astype('float32') for i in range(len(predictions)): if predictions[i] == labels[i] : if predictions[i] == 1.0: true_positives += 1 elif predictions[i] == 0.0: true_negatives += 1 elif predictions[i] != labels[i]: if predictions[i] == 1.0: false_positives += 1 elif predictions[i] == 0.0: false_negatives += 1 accuracy = (true_positives + true_negatives)/(true_positives + true_negatives + false_positives + false_negatives) dice = (2*true_positives/(false_positives+false_negatives+(2*true_positives))) jaccard = (true_positives)/(true_positives+false_positives+false_negatives) return accuracy, dice, jaccard #%% """ show loss =============== shows the progression of loss during the training of the model Arguments: results - model trained Returns: *void """ def plot_loss(results): plt.figure(figsize=(8, 8)) plt.title("Learning curve") plt.plot(results.history["loss"], 'bo', label="loss") plt.plot(results.history["val_loss"],'b', label="val_loss") plt.xlabel("Epochs") plt.ylabel("log_loss") plt.legend(); #%% run_segmentation_CNN()
franciscapessanha/Pulmonary-nodules-analysis
CNN_segmentation_3D.py
CNN_segmentation_3D.py
py
12,525
python
en
code
1
github-code
36
[ { "api_name": "get_data.getData", "line_number": 19, "usage_type": "call" }, { "api_name": "get_data.getData", "line_number": 26, "usage_type": "call" }, { "api_name": "numpy.mean", "line_number": 52, "usage_type": "call" }, { "api_name": "numpy.std", "line_nu...
17013470871
import datetime from components import line_bot_api from utils import utils_database import json from linebot.models import ( TextSendMessage, ) def get_event_info(event): event_dict = event.message.as_json_dict() timestamp = float(event.timestamp/1000) dt_object = datetime.datetime.fromtimestamp(timestamp) datetime_string = dt_object.strftime("%Y-%m-%d %H:%M:%S") # 0.日期時間 date_string = dt_object.strftime("%Y-%m-%d") # 1.日期 time_string = dt_object.strftime("%H:%M:%S") # 2.時間 session = 'A' if float(time_string.replace(':', '')) < 12e4 else 'P' source_type = event.source.type group_id = event.source.group_id if source_type == "group" else "" # 4.群組ID summary = line_bot_api.get_group_summary(group_id) if group_id != '' else "" group_name = summary.group_name if group_id != '' else "" # 5.群組名稱 user_id = event.source.user_id # 6.傳訊者ID profile = line_bot_api.get_group_member_profile(group_id, event.source.user_id) if group_id != '' else "" user_name = profile.display_name if group_id != '' else "" # 7.傳訊者顯示名稱 user_img = profile.picture_url if group_id != '' else "" msg_type = event.message.type msg_id = event.message.id image_set_id = event_dict["imageSet"]["id"] if "imageSet" in event_dict.keys() else 'null' return { "source_type": source_type, "datetime": datetime_string, "date": date_string, "time": time_string, "session": session, "group_id": group_id, "group_name": group_name, "user_id": user_id, "user_name": user_name, "user_img": user_img, "msg_type": msg_type, "msg_id": msg_id, "image_set_id": image_set_id } def get_img_count(img_event): def __check_is_image_set(img_event): return "imageSet" in img_event.message.as_json_dict().keys() is_image_set = __check_is_image_set(img_event) count = 0 if is_image_set: index = img_event.message.image_set.index total = img_event.message.image_set.total db_is_image_set = utils_database.check_is_image_set_by_id(img_event.message.image_set.id) count = total if db_is_image_set else 0 else: count = 1 status = (True if count != 0 else False) or db_is_image_set reply_info = { "status": status, "img_count": count } return reply_info def get_user_info(event): user_id = event.source.user_id profile = line_bot_api.get_profile(user_id) return { "user_id": user_id, "display_name": profile.display_name, "picture_url": profile.picture_url } def update_group_name(): group_ids = utils_database.get_all_joined_groups() for group_id in group_ids: try: group_summary = line_bot_api.get_group_summary(group_id) group_name = group_summary.group_name status = utils_database.update_group_name_by_group_id(group_id=group_id, group_name=group_name) except Exception as e: utils_database.set_disbanded_group_by_group_id(group_id=group_id, note="已解散/disbanded") return {"status": True} def linebot_send_text(reply_token, msg): message = TextSendMessage(text=msg) try: line_bot_api.reply_message(reply_token, message) except Exception as e: print("error: ", str(e)) return
jialiang8931/WRA06-Volunteer-LineBot
src/utils/utils_common.py
utils_common.py
py
3,726
python
en
code
0
github-code
36
[ { "api_name": "datetime.datetime.fromtimestamp", "line_number": 14, "usage_type": "call" }, { "api_name": "datetime.datetime", "line_number": 14, "usage_type": "attribute" }, { "api_name": "components.line_bot_api.get_group_summary", "line_number": 21, "usage_type": "call...
21290035402
import sqlalchemy as sqla from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, sql import psycopg2 import re import os import matplotlib.pyplot as plt import matplotlib.patches as patch from matplotlib.patches import Patch import matplotlib.lines as mlines import numpy as np import math def schanger(x, s1, s2): if (x in s1): return s2 return x #Parsowanie inserta/update'a/deleta def parser(table, opera, ins=None, wher=None): exc="" to_kill=[] if (ins!=None): for x, y in ins.items(): if (len(str(y))==0): to_kill.append(x) for x in to_kill: ins.pop(x, None) if (wher!=None): to_kill=[] for x, y in wher.items(): if (str(x)=="hero_name" or (table=="castle_on_map" and str(x)=='color') or str(x)=='estimated_power'): to_kill.append(x) for x in to_kill: wher.pop(x, None) if (opera=='insert'): ins1str=str([x for x in ins.keys()])[1:-1] ins2str=str([x for x in ins.values()])[1:-1] ins1str="".join([schanger(x, "'\"", "") for x in ins1str]) ins2str="".join([schanger(x, '"', "'") for x in ins2str]) exc=opera+" into "+table+" ("+ins1str+")"+" values ("+ins2str+")" elif (opera=='update'): exc=opera+" "+table+" set " c=len(ins.items()) for i, a in enumerate(ins.items()): x, y=a if (str(y)==y): exc=exc+x+"='"+y+"'" else: exc=exc+x+"="+str(y) if (c-1!=i): exc=exc+"," exc=exc+" " elif (opera=='delete'): exc=opera+" from "+table+" " if (opera=="update" or opera=="delete"): c=len(wher.items()) if (wher!=None and len(wher)>0): exc=exc+"where " for i, a in enumerate(wher.items()): x, y=a if (str(y)==y): exc=exc+x+"='"+y+"'" else: exc=exc+x+"="+str(y) if (c-1!=i): exc=exc+" and " return exc+";" #Zamiana dicta z niepoprawnymi nazwami na sensownego dicta def dictvisioner(dct, alter=1): dct=dict(dct) ancient_dict={} dct.pop('which', None) if (alter==1): for x in dct.keys(): sv=x[re.search('-', x).span()[1]:] for v, y in zip(re.split('-', sv), re.split('-', dct[x])): ancient_dict[v]=y else: return dct return ancient_dict #Wbijacz zapytań def interactor(engine, query, tp=None, arg=[]): _Dict_prime={ 'player_pkey':"Player already inserted!", 'pk_castle_on_map':"Castle already exists on that point!", 'pk_build_in_castle_on_map':"This building is already created in that castle!", 'pk_army_connect':"This army already has some unit on that position!", 'hero_pkey':"This hero name is already used!", 'pk_point':"This point already exists!", } _Dict_foreign={ 'fk_playh':"Player doesn't exist!", 'fk_armyxy':"You tried to place army on non-existent point of map!", 'fk_tohero':"This hero doesn't exist!", 'fk_toarmy':"This army doesn't exist!", 'fk_armycon':"This army doesn't exist!", 'fk_unit_from_army':"This unit doesn't exist", 'fk_castle_map_point':"You tried to place castle on non-existent point of map!" , 'fk_castle_merge':"You tried to create castle of non-existent type!", 'fk_to_player':"Player does not exist!", 'fk_castle_build_map':"This type of building doesn't exist for that castle!", 'fk_xy_place':"You tried to attach building on non-existent point on map!", } e=1 comm="" connection = engine.raw_connection() cursor = connection.cursor() try: if (tp==None): cursor.execute(query) elif (tp=='proc'): cursor.callproc(*arg) elif (tp=='procp'): if (len(arg[1])>0): pv=str(*arg[1]) cursor.execute(f"do $$ begin call {arg[0]}('{pv}'); end $$;") else: cursor.execute(f"do $$ begin call {arg[0]}(); end $$;") cursor.close() connection.commit() except BaseException as ex: comm=ex.args[0][:re.search('\n', ex.args[0]).span()[0]] print(comm) if (re.search('too long for type character', comm)): comm="You cannot use names longer than 50 characters!" if (re.search('unique', comm)): for x in _Dict_prime.keys(): if (re.search(x, comm)): comm=_Dict_prime[x] break elif (re.search("violates foreign key", comm)): for x in _Dict_foreign.keys(): if (re.search(x, comm)): comm=_Dict_foreign[x] break elif (re.search("violates not-null constraint", comm)): if (re.search("id_army", comm)): comm="You must fill army id field!!" if (re.search("color", comm)): comm="You cannot create a hero without player!" if (re.search('"x"', comm) or re.search('"y"', comm)): comm="You cannot leave empty map coordinates!" if (re.search("castle", comm)): comm="You need to provide a castle type!" if (re.search("unit_name", comm)): comm="You need to provide unit name!" else: e=0 finally: connection.close() return(e, comm) #Selekcja danych def selector(engine, table, order=None, col=None): g=engine.execute("SELECT * FROM information_schema.columns WHERE table_name = '"+table+"'") cols=[] for x in g: cols.append(x[3]) cols=cols[::-1] if (order==None and col==None): f=engine.execute(f'select {", ".join(cols)} from '+table) elif (order!=None): f=engine.execute(f'select {", ".join(cols)} from '+table+' order by '+col+' '+order) res=[] for x in f: res.append(x) #Dodanie generowanej funkcji if (table=='player'): cols.append("estimated_power") lst=[] for x in res: wn=engine.execute(f"select firepower('{x[0]}')") for y in wn: y=y[0] if (len(y)>10): y=[int(z) for z in y[1:-1].split(',')] wnn=math.log((y[0]+y[1])/2*math.sqrt(y[4])+y[5]/100+(y[2]+y[3])/2) else: wnn=0 #print(x[0], wn) lst.append([*x, wnn]) return (lst, cols) return(res, cols) #twórca tablicy z zapytania selecta(lst) i nazwy tabeli(table) def selhtmler(table, lst): sv=[] #Button do th bth=""" <div class="buth"> <button class="sbtnd"> v </button> <button class="sbtnu"> v </button> </div>""" sv.append("<div class=\"wrapped\"><table id="+table+"><thead><tr>") for x in lst[1]: sv.append("<th>"+x+bth+"</th>") sv.append("</tr></thead>") sv.append("<tbody>") for x in lst[0]: sv.append("<tr>") for y in x: sv.append(f"<td>{y}</td>") sv.append("</tr>") sv.append("</tbody>") sv.append("</table>") sv.append("</div>") return ''.join(sv) #Wyrysowanie 2 grup dla 1 koloru - armii i zamków def doubleprinter(ax, l1, l2, coll): if (len(l1)>0): ax.scatter(l1[0], l1[1], color=coll, s=100, marker='P') if (len(l2)>0): ax.scatter(l2[0], l2[1], color=coll, s=100) #Colorland to zbiór kolorów dla konkretnych graczy colorland={} #Twórca mapy dla jakiejś osi def map_maker(engine, ax): #Poszukiwanie rzeczy w DB csel=engine.execute('select x, y, color from castle_on_map') csel2=engine.execute('select a.x, a.y, h.color from army a left join hero h on a.hero_name=h.name') xm=engine.execute('select max(x), max(y) from point_on_map') conn=1 #Ustalanie wymiaru mapy for k in xm: xmax, ymax=k[0], k[1] ax.set_xlim(0, conn*xmax) ax.set_ylim(0, ymax) #Zamek, armie - dicty z 2 listami i nazwami graczy jako klucze, wypełnianie punktami hlegs=[] castel={} here={} for w in csel: try: castel[w[2]].append((w[0], w[1])) except: castel[w[2]]=[(w[0], w[1])] for w in csel2: try: here[w[2]].append((w[0], w[1])) except: here[w[2]]=[(w[0], w[1])] if (not w[2] in castel): castel[w[2]]=[] for x, y in castel.items(): #Poszukiwanie x-koloru, y-zamka, z-armia if (not x in here.keys()): here[x]=[] z=here[x] lst=list(zip(*y)) lst2=list(zip(*z)) try: doubleprinter(ax, lst, lst2, colorland[x]) except: if (x==None): clr='Grey' else: clr=str(x).lower() try: doubleprinter(ax, lst, lst2, clr) vs=clr except: vs=np.random.uniform(0, 1, 3) doubleprinter(ax, lst, lst2, vs) #Definiowanie nowego koloru dla usera w przypadku jego nieistnienia colorland[x]=vs finally: hlegs.append(Patch(facecolor=colorland[x], alpha=1.0, label=f"Player: {x}")) hlegs.append(mlines.Line2D([], [], color='#FFFFFF', marker='P', markerfacecolor='#000000', markersize=15, label='Castle')) hlegs.append(mlines.Line2D([], [], color='#FFFFFF', marker='o', markerfacecolor='#000000', markersize=15, label='Hero')) ax.legend(handles=hlegs, loc=1, facecolor='#FFFFFF', shadow=1.0, prop={'size': 12}) ax.fill_between([xmax, conn*xmax], [0, 0], [ymax, ymax], color='#000000') ax.set_xticks(ax.get_xticks()[ax.get_xticks()<=xmax]) #Funkcja tworząca/updatująca mapę def inserto_creato_mapo(engine, arg='n'): fig, ax=plt.subplots(1, 1, figsize=(24, 18)) if (arg=='n'): map_maker(engine, ax) dirname = os.path.dirname(__file__) filename = os.path.join(dirname, 'arda.png') plt.savefig(filename, bbox_inches='tight') plt.close()
JonothorDarry/PostgreProject
flaskk/alchlib.py
alchlib.py
py
10,498
python
en
code
0
github-code
36
[ { "api_name": "re.search", "line_number": 84, "usage_type": "call" }, { "api_name": "re.split", "line_number": 85, "usage_type": "call" }, { "api_name": "re.search", "line_number": 138, "usage_type": "call" }, { "api_name": "re.search", "line_number": 141, ...
70519989225
import sys sys.path.append('path/to/SPFlow') import numpy as np import pandas as pd from spn.structure.Base import Context from spn.algorithms.oSLRAU import oSLRAU, oSLRAUParams from spn.structure.leaves.parametric.Parametric import Gaussian, In_Latent from spn.algorithms.LearningWrappers import learn_parametric from spn.io.Graphics import plot_spn from spn.algorithms.Inference import log_likelihood from spn.algorithms.TransformStructure import Prune ,Prune_oSLRAU def run_oSLRAU(dataset, update_after_no_min_batches, prune_after): data = get_data(dataset) data = np.where(np.isnan(data), np.ma.array(data, mask=np.isnan(data)).mean(axis=0), data) from sklearn.model_selection import train_test_split train_data, test_data = train_test_split(data, test_size=0.33, random_state=42) # make first mini_batch from data mini_batch_size = 50 first_mini_batch = data[0:mini_batch_size] n = first_mini_batch.shape[1] # num of variables print(n) context = [Gaussian] * n ds_context = Context(parametric_types=context).add_domains(first_mini_batch) # Learn initial spn spn = learn_parametric(first_mini_batch, ds_context) plot_spn(spn, 'intitial_spn.pdf') print(np.mean(log_likelihood(spn, test_data))) oSLRAU_params = oSLRAUParams(mergebatch_threshold=128, corrthresh=0.1, mvmaxscope=1, equalweight=True, currVals=True) no_of_minibatches = int(data.shape[0] / mini_batch_size) # update using oSLRAU for i in range(1, no_of_minibatches): mini_batch = data[i * mini_batch_size: (i+1) * mini_batch_size] update_structure = False if update_after_no_min_batches//i == 0: print(i) update_structure = True spn = oSLRAU(spn, mini_batch, oSLRAU_params, update_structure) if i == prune_after: spn = Prune_oSLRAU(spn) print(np.mean(log_likelihood(spn, test_data))) plot_spn(spn, 'final_spn.pdf') def get_data(dataset): csv_file_path_hh_power = 'path/to/file' csv_file_path_other_power = 'path/to/file' csv_file_path_wine_qual = 'path/to/file' if dataset == 'hh_power': file_path = csv_file_path_hh_power df = pd.read_csv(file_path, sep=',') df = df.iloc[:, 2:6] df = df.convert_objects(convert_numeric=True) data = df.values data = data.astype(float) print(data) return data elif dataset == 'other_power': file_path = csv_file_path_other_power df = pd.read_csv(file_path, sep=',') df = df.iloc[:] df = df.convert_objects(convert_numeric=True) data = df.values data = data[0:-1] data = data.astype(float) print(data) return data elif dataset == 'wine_qual': file_path = csv_file_path_wine_qual df = pd.read_csv(file_path, sep=';') df = df.iloc[:] df = df.convert_objects(convert_numeric=True) data = df.values data = data[0:-1] data = data.astype(float) print(data) return data def main(): dataset = 'wine_qual' update_after_no_min_batches = 15 prune_after = 50 run_oSLRAU(dataset, update_after_no_min_batches, prune_after) if __name__ == "__main__": main()
c0derzer0/oSLRAU_and_RSPN
oSLRAU_run.py
oSLRAU_run.py
py
3,323
python
en
code
0
github-code
36
[ { "api_name": "sys.path.append", "line_number": 2, "usage_type": "call" }, { "api_name": "sys.path", "line_number": 2, "usage_type": "attribute" }, { "api_name": "numpy.where", "line_number": 17, "usage_type": "call" }, { "api_name": "numpy.isnan", "line_numbe...
18903378632
from os import makedirs from os.path import join, dirname, isfile from uuid import uuid4 from json import dumps from logging import getLogger from uchicagoldrtoolsuite import log_aware from uchicagoldrtoolsuite.core.lib.bash_cmd import BashCommand from uchicagoldrtoolsuite.core.lib.convenience import log_init_attempt, \ log_init_success from ..ldritems.ldrpath import LDRPath from ..ldritems.abc.ldritem import LDRItem from ..ldritems.ldritemcopier import LDRItemCopier from .abc.technicalmetadatacreator import TechnicalMetadataCreator __author__ = "Brian Balsamo" __email__ = "balsamo@uchicago.edu" __company__ = "The University of Chicago Library" __copyright__ = "Copyright University of Chicago, 2016" __publication__ = "" __version__ = "0.0.1dev" log = getLogger(__name__) class FITsCreator(TechnicalMetadataCreator): # TODO: Technical metadata creators probably need a go over # like the converters """ A TechnicalMetadataCreator which runs a local FITs instance against the content of a MaterialSuite in order to generate a technical metadata entry """ @log_aware(log) def __init__(self, materialsuite, working_dir, timeout=None, data_transfer_obj={}): """ Creates a new FITsCreator __Args__ 1. materialsuite (MaterialSuite): The materialsuite whose content to create the technical metadata for 2. working_dir (str): A path to a directory where the techmd creator can write files __KWArgs__ * timeout (int): A timeout (in seconds) after which the technical metadata creation process will fail out, if it hasn't finished * data_transfer_obj (dict): A dictionary for passing techmd creator specific configuration values into the class from a wrapper. """ log_init_attempt(self, log, locals()) super().__init__(materialsuite, working_dir, timeout) self.fits_path = data_transfer_obj.get('fits_path', None) if self.fits_path is None: raise ValueError('No fits_path specified in the data ' + 'transfer object!') log_init_success(self, log) @log_aware(log) def __repr__(self): attr_dict = { 'source_materialsuite': str(self.source_materialsuite), 'working_dir': str(self.working_dir), 'timeout': self.timeout } return "<FITsCreator {}>".format(dumps(attr_dict, sort_keys=True)) @log_aware(log) def process(self): """ runs a local FITs installation against the MaterialSuite's content """ if not isinstance(self.get_source_materialsuite().get_premis(), LDRItem): raise ValueError("All material suites must have a PREMIS record " + "in order to generate technical metadata.") log.debug("Building FITS-ing environment") premis_file_path = join(self.working_dir, str(uuid4())) LDRItemCopier( self.get_source_materialsuite().get_premis(), LDRPath(premis_file_path) ).copy() # hacky fix for not setting the originalName in presforms during the # staging tearup in response to some filename encodings not being # interoperable on different operating systems. (OSX/BSD/Windows/Linux) original_name = uuid4().hex content_file_path = dirname( join( self.working_dir, uuid4().hex, original_name ) ) content_file_containing_dir_path = dirname(content_file_path) makedirs(content_file_containing_dir_path, exist_ok=True) original_holder = LDRPath(content_file_path) LDRItemCopier( self.get_source_materialsuite().get_content(), original_holder ).copy() fits_file_path = join(self.working_dir, uuid4().hex) cmd = BashCommand([self.fits_path, '-i', content_file_path, '-o', fits_file_path]) if self.get_timeout() is not None: cmd.set_timeout(self.get_timeout()) log.debug( "Running FITS on file. Timeout: {}".format(str(self.get_timeout())) ) cmd.run_command() cmd_data = cmd.get_data() if isfile(fits_file_path): success = True log.debug("FITS successfully created") else: success = False log.warn("FITS creation failed on {}".format( self.get_source_materialsuite().identifier) ) self.handle_premis(cmd_data, self.get_source_materialsuite(), "FITs", success, "fitsRecord", fits_file_path) log.debug("Cleaning up temporary file instantiation") original_holder.delete(final=True)
uchicago-library/uchicagoldr-toolsuite
uchicagoldrtoolsuite/bit_level/lib/techmdcreators/fitscreator.py
fitscreator.py
py
4,907
python
en
code
0
github-code
36
[ { "api_name": "logging.getLogger", "line_number": 25, "usage_type": "call" }, { "api_name": "abc.technicalmetadatacreator.TechnicalMetadataCreator", "line_number": 28, "usage_type": "name" }, { "api_name": "uchicagoldrtoolsuite.core.lib.convenience.log_init_attempt", "line_nu...
22807184796
# Makes some radial plots of gas density and temperature. import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import numpy as np import os import sys x_field = 'Radiuspc' y_fields = ['Density', 'Temperature'] weight_field = 'CellMass' x_min = 1.0e-1 x_max = 2.0e2 fns = sys.argv[1:] plot_folder = 'profiles' n_bins = 128 # Make a folder in which to save the profiles. if not os.path.isdir(plot_folder): os.mkdir(plot_folder) # Make plots for each dataset. for fn in fns: pf = load(fn) profile = BinnedProfile1D(pf.h.all_data(), n_bins, x_field, x_min, x_max) profile.add_fields(y_fields, weight = weight_field) # Make the plot for y_field in y_fields: fig = plt.figure() ax = fig.add_subplot(111) ax.loglog(profile[x_field], profile[y_field]) ax.set_xlabel(x_field) ax.set_ylabel(y_field) plt.savefig('%s/%s_%s.png' % (plot_folder, pf, y_field));
enzo-project/enzo-dev
run/Hydro/Hydro-3D/RotatingSphere/profile_script.py
profile_script.py
py
936
python
en
code
72
github-code
36
[ { "api_name": "matplotlib.use", "line_number": 4, "usage_type": "call" }, { "api_name": "sys.argv", "line_number": 19, "usage_type": "attribute" }, { "api_name": "os.path.isdir", "line_number": 25, "usage_type": "call" }, { "api_name": "os.path", "line_number"...
35436780435
import urllib.request from bs4 import BeautifulSoup url = 'http://127.0.0.1:8000/' res = urllib.request.urlopen(url) data = res.read() html = data.decode("utf-8") soup = BeautifulSoup(html, 'html.parser') print(soup) h1 = soup.html.body.h1 print('h1:', h1.string)
SeungYeopB/bigdata
crawling1/sample01.py
sample01.py
py
266
python
en
code
0
github-code
36
[ { "api_name": "urllib.request.request.urlopen", "line_number": 6, "usage_type": "call" }, { "api_name": "urllib.request.request", "line_number": 6, "usage_type": "attribute" }, { "api_name": "urllib.request", "line_number": 6, "usage_type": "name" }, { "api_name":...
40890241642
""" Python utils for RFC calls to SAP NetWeaver System """ import sys if sys.version < '2.4': print('Wrong Python Version (must be >=2.4) !!!') sys.exit(1) # load the native extensions import nwsaprfcutil import sapnwrfc.rfc from struct import * from string import * import re from types import * #from copy import deepcopy # Parameter types IMPORT = 1 EXPORT = 2 CHANGING = 3 TABLES = 7 CONFIG_OK = ('ashost', 'sysnr', 'client', 'lang', 'user', 'passwd', 'gwhost', 'gwserv', 'tpname', 'lcheck') CONF_FILE = 'sap.yml' class RFCException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class base(object): """ Base class used to trigger everything off """ config_location = CONF_FILE configuration = {} @classmethod def load_config(cls): # REFACTOR: there is no need to depend on yaml import yaml cls.configuration = yaml.load(open(cls.config_location, 'rb').read()) #cls.configuration = yaml.load(open(cls.config_location, 'rb').read()) return cls.configuration @classmethod def rfc_connect(cls, cfg=None): config = {} # pass in the config load from config_location YAML file for k, v in cls.configuration.items(): if k in CONFIG_OK: if not k in ('gwserv', 'gwhost', 'tpname', 'loglevel'): config[k] = str(v) # Overload the YAML file config with parameters passed to # rfc_connect if not cfg == None: if not type(cfg) == dict: raise RFCException("Config passed to rfc_connect must be a Dictionary object") for k, v in cfg.items(): if k in CONFIG_OK: if not k in ('gwserv', 'gwhost', 'tpname', 'loglevel'): config[k] = str(v) #conn = sapnwrfcconn.new_connection(config) conn = nwsaprfcutil.Conn(config) c = connection(conn) return c class connection: """ Connection class - must not be created by the user - automatically generated by a call to sapnwrfc.base.rfc_connect() """ def __init__(self, handle=None): self.handle = handle def connection_attributes(self): if self.handle == None: raise RFCException("Invalid handle (connection_attributes)\n") return self.handle.connection_attributes() def discover(self, name): if self.handle == None: raise RFCException("Invalid handle (discover)\n") func = self.handle.function_lookup(name) f = FunctionDescriptor(func) return f def close(self): if self.handle == None: raise RFCException("Invalid handle (close)\n") rc = self.handle.close() self.handle = None return rc class FunctionDescriptor: """ FunctionDescriptor class - must not be created by the user - automatically generated by a call to sapnwrfc.connection.function_lookup() """ def __init__(self, handle=None): self.handle = handle self.name = self.handle.name def create_function_call(self): call = self.handle.create_function_call() c = FunctionCall(call) return c class FunctionCall: """ FunctionCall class - must not be created by the user - automatically generated by a call to sapnwrfc.FunctionDescriptor.create_function_call() """ def __init__(self, handle=None): #sys.stderr.write("inside funccall python init\n") self.handle = handle self.name = self.handle.name for k, v in self.handle.function_descriptor.parameters.items(): # value: {'direction': 1, 'name': 'QUERY_TABLE', 'type': 0, 'len': 30, 'decimals': 0, 'ulen': 60} if v['direction'] == IMPORT: cpy = sapnwrfc.rfc.Import(self.function_descriptor, v['name'], v['type'], v['len'], v['ulen'], v['decimals'], None) elif v['direction'] == EXPORT: cpy = sapnwrfc.rfc.Export(self.function_descriptor, v['name'], v['type'], v['len'], v['ulen'], v['decimals'], None) elif v['direction'] == CHANGING: cpy = sapnwrfc.rfc.Changing(self.function_descriptor, v['name'], v['type'], v['len'], v['ulen'], v['decimals'], None) elif v['direction'] == TABLES: cpy = sapnwrfc.rfc.Table(self.function_descriptor, v['name'], v['type'], v['len'], v['ulen'], v['decimals'], None) else: raise RFCException("Unknown parameter type: %d\n" % v['direction']) self.handle.parameters[k] = cpy def __repr__(self): return "<FunctionCall %s instance at 0x%x>" % (self.name, id(self)) def __getattr__(self, *args, **kwdargs): if args[0] in self.handle.parameters: return self.handle.parameters[args[0]] else: return None def __call__(self, *args, **kwdargs): # REFACTOR: This seems not to make too much sense here ;-) print("Hello!\n") def invoke(self): return self.handle.invoke()
piersharding/python-sapnwrfc
sapnwrfc/__init__.py
__init__.py
py
5,163
python
en
code
26
github-code
36
[ { "api_name": "sys.version", "line_number": 7, "usage_type": "attribute" }, { "api_name": "sys.exit", "line_number": 9, "usage_type": "call" }, { "api_name": "yaml.load", "line_number": 56, "usage_type": "call" }, { "api_name": "nwsaprfcutil.Conn", "line_numbe...
71129782185
from urllib.request import urlopen import random import datetime from Initialize import sqlitewrite, sqliteread, settings, sqliteFetchAll, getmoderators commands_BotCommands = { "!ping": ('bot.ping', 'cmdarguments', 'user'), "!uptime": ('bot.uptime', 'cmdarguments', 'user'), "!roll": ('bot.roll', 'cmdarguments', 'user'), "!r": ('bot.roll', 'cmdarguments', 'user'), # Alias "!reloaddb": ("STREAMER", 'dbCloner.manualCloneDb', 'None', 'None'), "!quote": ('quotes', 'cmdarguments', 'user'), "!addquote": ('quotes.addQuote', 'cmdarguments', 'user'), "!removequote": ("MOD", 'quotes.rmQuote', 'cmdarguments', 'user'), "!deletequote": ("MOD", 'quotes.rmQuote', 'cmdarguments', 'user'), # Alias "!test": ('getCurrentGame', 'cmdarguments', 'user'), } def is_number(s): try: int(s) return True except ValueError: return False def todaysDate(): today = datetime.datetime.now() return today.strftime("%m/%d/%y") class BotCommands: def __init__(self): pass def ping(self, arg, user): return "Pong" def uptime(self, arg, user): f = urlopen("https://beta.decapi.me/twitch/uptime/" + settings['CHANNEL']) file = f.read().decode("utf-8") if "offline" in file: return file + "." else: return "The stream has been live for: " + file def roll(self, arg, user): arg = arg.replace("\r", "") splitCmd = arg.split("d") operators = ["+", "-", "/", "*"] op = '' mod = '' if not is_number(splitCmd[0]): splitCmd[0] = 1 for item in operators: if item in splitCmd[1]: op = item secondSplitCmd = (splitCmd[1].split(item)) mod = secondSplitCmd[1] splitCmd[1] = secondSplitCmd[0] # Calculate Values amt = int(splitCmd[0]) size = int(splitCmd[1]) total = 0 rolls = [] for item in operators: if item in splitCmd[1]: size = int(splitCmd[1].split(item)[0]) op = item mod = int(splitCmd[1].split(item)[1]) # Roll Stuff for x in range(0, amt): roll = random.randint(1, size) rolls.append(roll) total = eval(str(sum(rolls)) + " " + op + " " + mod) if (len(rolls) == 1) or (len(rolls) > 20): return("You rolled: >[ " + str(total) + " ]<") return("You rolled: " + str(rolls) + " with a total of: >[ " + str(total) + " ]<") class QuoteControl: def __init__(self): self.usedQuotes = [] def __call__(self, arg, user): if not arg.strip(): return self.displayQuote() firstArg = arg.split()[0].lower() arg = (arg.replace(arg.split()[0], '').strip()) if is_number(firstArg): return self.displayQuoteById(firstArg) elif firstArg == "add": return self.addQuote(arg, user) elif firstArg == "remove": if not (user in getmoderators()) or (user == "Hotkey"): return user + " >> You need to be a moderator to delete a quote." return self.rmQuote(arg, user) elif firstArg == "delete": if not (user in getmoderators()) or (user == "Hotkey"): return user + " >> You need to be a moderator to delete a quote." return self.rmQuote(arg, user) def displayQuote(self): if not self.usedQuotes: # Don't filter if theres nothing to filter data = sqliteFetchAll('''SELECT * FROM quotes ORDER BY RANDOM()''') else: strUsedQuotes = "" for item in self.usedQuotes: strUsedQuotes += '"%s", ' % item # dude i dunno math strUsedQuotes = strUsedQuotes[:-2] # Format a string to filter by and filter by it data = sqliteFetchAll('''SELECT * FROM quotes WHERE id NOT IN (%s) ORDER BY RANDOM()''' % strUsedQuotes) if not data: # If it's returned empty, reset the list and grab a random quote self.usedQuotes = [] data = sqliteFetchAll('''SELECT * FROM quotes ORDER BY RANDOM()''') if not data: # No quotes in db return "There are currently no quotes. Add one with !quote add" quote = data[0] # Fuck its 1am self.usedQuotes.append(quote[0]) if "''" in quote[1]: return '%s (%s)' % (quote[1], quote[2]) else: return '"%s" (%s)' % (quote[1], quote[2]) def displayQuoteById(self, id): data = sqliteread("SELECT * FROM quotes WHERE id=%s" % id) if not data: return "No quote exists with that ID." if "''" in data[1]: return '%s (%s)' % (data[1], data[2]) else: return '"%s" (%s)' % (data[1], data[2]) def addQuote(self, arg, user): if not arg or (arg == " "): return "You need to specify something to be quoted." arg = arg.strip() if arg[0] in ["'", '"'] and arg[-1] in ["'", '"']: arg = arg.strip("'") arg = arg.strip('"') arg = arg.replace('"', "''") # Replace double quotes with two single quotes if sqlitewrite('''INSERT INTO quotes(quote, date) VALUES("%s", "%s");''' % (arg, todaysDate())): newId = str(sqliteread('SELECT id FROM quotes ORDER BY id DESC LIMIT 1')[0]) return "Quote successfully added [ID: %s]" % newId else: print(user + " >> Your quote was not successfully added. Please try again.") def rmQuote(self, arg, user): if not arg or (arg == " "): return "You need to specify a quote ID to remove." arg = arg.strip() idExists = sqliteread('''SELECT id FROM quotes WHERE id = "%s";''' % arg) if idExists: sqlitewrite('''DELETE FROM quotes WHERE id = "%s";''' % arg) return "Quote %s successfully removed." % arg else: return "Quote %s does not exist." % arg quotes = QuoteControl() bot = BotCommands()
gcfrxbots/rxbot
RxBot/Bot.py
Bot.py
py
6,155
python
en
code
6
github-code
36
[ { "api_name": "datetime.datetime.now", "line_number": 29, "usage_type": "call" }, { "api_name": "datetime.datetime", "line_number": 29, "usage_type": "attribute" }, { "api_name": "urllib.request.urlopen", "line_number": 41, "usage_type": "call" }, { "api_name": "I...
31112021799
""" Store packages in GCS """ import io import json import logging import os import posixpath from datetime import timedelta from google.auth import compute_engine from google.auth.transport import requests from google.cloud import storage from pyramid.settings import asbool from pypicloud.models import Package from .object_store import ObjectStoreStorage LOG = logging.getLogger(__name__) class GoogleCloudStorage(ObjectStoreStorage): """Storage backend that uses GCS""" test = False def __init__( self, request=None, bucket_factory=None, service_account_json_filename=None, project_id=None, use_iam_signer=False, iam_signer_service_account_email=None, **kwargs ): super(GoogleCloudStorage, self).__init__(request=request, **kwargs) self._bucket = None self._bucket_factory = bucket_factory self.use_iam_signer = use_iam_signer self.iam_signer_service_account_email = iam_signer_service_account_email if self.public_url: raise NotImplementedError( "GoogleCloudStorage backend does not yet support public URLs" ) if self.sse: raise NotImplementedError( "GoogleCloudStorage backend does not yet support customized " "server-side encryption" ) @classmethod def _subclass_specific_config(cls, settings, common_config): """Extract GCP-specific config settings: specifically, the path to the service account key file, and the project id. Both are optional. """ service_account_json_filename = settings.get( "storage.gcp_service_account_json_filename" ) or os.getenv("GOOGLE_APPLICATION_CREDENTIALS") if ( service_account_json_filename and not os.path.isfile(service_account_json_filename) and not cls.test ): raise Exception( "Service account json file not found at path {}".format( service_account_json_filename ) ) bucket_name = settings.get("storage.bucket") if bucket_name is None: raise ValueError("You must specify the 'storage.bucket'") iam_signer_service_account_email = settings.get( "storage.iam_signer_service_account_email" ) if iam_signer_service_account_email is None and service_account_json_filename: with io.open(service_account_json_filename, "r", encoding="utf-8") as ifile: credentials = json.load(ifile) iam_signer_service_account_email = credentials.get("client_email") return { "service_account_json_filename": service_account_json_filename, "project_id": settings.get("storage.gcp_project_id"), "use_iam_signer": asbool(settings.get("storage.gcp_use_iam_signer", False)), "iam_signer_service_account_email": iam_signer_service_account_email, "bucket_factory": lambda: cls.get_bucket(bucket_name, settings), } @classmethod def _get_storage_client(cls, settings): """Helper method for constructing a properly-configured GCS client object from the provided settings. """ client_settings = cls._subclass_specific_config(settings, {}) client_args = {} if client_settings["project_id"]: LOG.info("Using GCP project id `%s`", client_settings["project_id"]) client_args["project"] = client_settings["project_id"] service_account_json_filename = client_settings.get( "service_account_json_filename" ) if not service_account_json_filename: LOG.info("Creating GCS client without service account JSON file") client = storage.Client(**client_args) else: if not os.path.isfile(service_account_json_filename) and not cls.test: raise Exception( "Service account JSON file not found at provided " "path {}".format(service_account_json_filename) ) LOG.info( "Creating GCS client from service account JSON file %s", service_account_json_filename, ) client = storage.Client.from_service_account_json( service_account_json_filename, **client_args ) return client @classmethod def get_bucket(cls, bucket_name, settings): client = cls._get_storage_client(settings) bucket = client.bucket(bucket_name) if not bucket.exists(): bucket.location = settings.get("storage.region_name") LOG.info( "Creating GCS bucket %s in location %s", bucket_name, bucket.location ) bucket.create() return bucket @classmethod def package_from_object(cls, blob, factory): """Create a package from a GCS object""" filename = posixpath.basename(blob.name) if blob.metadata is None: return None name = blob.metadata.get("name") version = blob.metadata.get("version") if name is None or version is None: return None metadata = Package.read_metadata(blob.metadata) return factory( name, version, filename, blob.updated, path=blob.name, **metadata ) @property def bucket(self): if self._bucket is None: self._bucket = self._bucket_factory() return self._bucket def list(self, factory=Package): blobs = self.bucket.list_blobs(prefix=self.bucket_prefix or None) for blob in blobs: pkg = self.package_from_object(blob, factory) if pkg is not None: # If we have a separate upload prefix, flag THIS package as being a fallback. Otherwise # we don't know enough to differentiate. pkg.origin = "fallback" if self.upload_prefix else None yield pkg # If we have an upload_prefix, now go back and process anything that matches. if self.upload_prefix: blobs = self.bucket.list_blobs(prefix=self.upload_prefix) for blob in blobs: pkg = self.package_from_object(blob, factory) if pkg is not None: # If we have a separate upload prefix, flag THIS package as being a fallback. Otherwise # we don't know enough to differentiate. pkg.origin = "upload" yield pkg def _generate_url(self, package): """Generate a signed url to the GCS file""" blob = self._get_gcs_blob(package) if self.use_iam_signer: # Workaround for https://github.com/googleapis/google-auth-library-python/issues/50 signing_credentials = compute_engine.IDTokenCredentials( requests.Request(), "", service_account_email=self.iam_signer_service_account_email, ) else: signing_credentials = None return blob.generate_signed_url( expiration=timedelta(seconds=self.expire_after), credentials=signing_credentials, version="v4", ) def _get_gcs_blob(self, package): """Get a GCS blob object for the specified package""" return self.bucket.blob(self.get_path(package)) def upload(self, package, datastream): """Upload the package to GCS""" metadata = {"name": package.name, "version": package.version} metadata.update(package.get_metadata()) blob = self._get_gcs_blob(package) blob.metadata = metadata blob.upload_from_file(datastream, predefined_acl=self.object_acl) if self.storage_class is not None: blob.update_storage_class(self.storage_class) def delete(self, package): """Delete the package""" blob = self._get_gcs_blob(package) blob.delete()
ambitioninc/pypicloud
pypicloud/storage/gcs.py
gcs.py
py
8,167
python
en
code
null
github-code
36
[ { "api_name": "logging.getLogger", "line_number": 18, "usage_type": "call" }, { "api_name": "object_store.ObjectStoreStorage", "line_number": 21, "usage_type": "name" }, { "api_name": "os.getenv", "line_number": 63, "usage_type": "call" }, { "api_name": "os.path.i...
18114969380
#!/usr/bin/env python3 from enum import Enum from io import BytesIO from itertools import count from struct import pack import csv import sys usage = 'To use this script, run it in a directory containing csv files generated by par2csv. It will compile them back into a new EARTH2150.par in the same directory.' class Faction(Enum): NEUTRAL = 0 UCS = 1 ED = 2 LC = 3 class EntityType(Enum): Vehicle = 1 Cannon = 2 Missile = 3 Building = 4 Special = 5 Equipment = 6 ShieldGenerator = 7 SoundPack = 8 SpecialUpdatesLinks = 9 Parameters = 10 class ResearchTab(Enum): CHASSIS = 0 WEAPON = 1 AMMO = 2 SPECIAL = 3 next_id = count() class Research: def __init__(self, row): self.previous = row[10].strip().split() self.id = next(next_id) self.faction = Faction.__members__[row[1]] self.campaign_cost = int(row[2]) self.skirmish_cost = int(row[3]) self.campaign_time = int(row[4]) self.skirmish_time = int(row[5]) self.name = row[0] self.video = row[6] self.type = ResearchTab.__members__[row[7]] self.mesh = row[8] self.meshParamsIndex = int(row[9]) def __repr__(self): items = ', '.join(f'{k}={v!r}' for k, v in self.__dict__.items()) return 'Research{{{items}}}' class Entity: def __init__(self, row): self.name = row[0] self.req_research = row[1].strip().split() self.fields = list() for f in row[2:]: # This will need extra processing later once par2csv can handle enums and floats try: self.fields.append(int(f)) except ValueError: self.fields.append(f) def __repr__(self): return f'Entity{{name={self.name!r}, req_research={self.req_research}, fields={len(self.fields)}{self.fields}}}' class EntityGroup: def __init__(self): self.faction = None self.entity_type = None self.entities = list() self.ref_fields = None def __repr__(self): entities = '' for entity in self.entities: entities += f' {entity}\n' return f'EntityGroup{{faction={self.faction}, entity_type={self.entity_type}, entities=\n{entities}}}' class ParWriter: def __init__(self, fd): self.fd = fd def write_header(self): self.fd.write(b'PAR\x00\x99\x00\x00\x00') def write(self, value): if isinstance(value, str): self.fd.write(pack('<I', len(value))) self.fd.write(value.encode(encoding='latin_1')) elif isinstance(value, int): self.fd.write(pack('<I', value)) elif isinstance(value, float): self.fd.write(pack('<f', value)) elif isinstance(value, list): self.fd.write(pack('<I', len(value))) for v in value: self.write(v) elif isinstance(value, Enum): self.write(value.value) else: raise TypeError(f'Cannot encode {type(value)}') def write_fields(self, fields, pad=True): types = bytearray() values = BytesIO() # Use a second internal writer to avoid duplicating the write method's logic here writer = ParWriter(values) for f in fields: is_string = type(f) is str types.append(1 if is_string else 0) writer.write(f) self.write(len(types)) self.fd.write(types) self.fd.write(values.getbuffer()) csv_files = [ ('buildrobot.csv', EntityType.Vehicle, {6, 7, 8, 9, 18, 19, 33, 34, 35, 36, 37, 38, 39, 66}), ('vehicle.csv', EntityType.Vehicle, {6, 7, 8, 9, 18, 19, 33, 34, 35, 36, 37}), ('miningrobot.csv', EntityType.Vehicle, {6, 7, 8, 9, 18, 19, 33, 34, 35, 36, 37, 47}), ('sapperrobot.csv', EntityType.Vehicle, {6, 7, 8, 9, 18, 19, 33, 34, 35, 36, 37, 39, 45}), ('supplytransporter.csv', EntityType.Vehicle, {6, 7, 8, 9, 18, 19, 33, 34, 35, 36, 37}), ('buildingtransporter.csv', EntityType.Special, {6, 7, 8, 9, 18, 19, 27}), ('resourcetransporter.csv', EntityType.Special, {6, 7, 8, 9, 18, 19}), ('unittransporter.csv', EntityType.Special, {6, 7, 8, 9, 18, 19}), ('building.csv', EntityType.Building, {6, 7, 8, 9, 18, 19, 28, 29, 30, 31, 32, 34, 35, 36, 37, 39, 47, 50, 51, 53, 55, 58}), ('cannon.csv', EntityType.Cannon, {6, 7, 8, 9, 20, 30}), ('missile.csv', EntityType.Missile, {6, 7, 8, 9, 20, 29}), ('soundpack.csv', EntityType.SoundPack, set()), ('repairer.csv', EntityType.Equipment, {6, 7, 8, 9}), ('containertransporter.csv', EntityType.Equipment, {6, 7, 8, 9}), ('transporterhook.csv', EntityType.Equipment, {6, 7, 8, 9}), ('lookroundequipment.csv', EntityType.Equipment, {6, 7, 8, 9}), ('upgradecopula.csv', EntityType.Special, {6, 7, 8, 9}), ('equipment.csv', EntityType.Equipment, {6, 7, 8, 9}), ('passive.csv', EntityType.Special, {6, 7, 8, 9, 18}), ('artefact.csv', EntityType.Special, {6, 7, 8, 9, 18}), ('startingpositionmark.csv', EntityType.Special, {6, 7, 8, 9, 18, 19}), ('multiexplosion.csv', EntityType.Special, {6, 7, 8, 9, 13, 17, 21, 25, 29, 33, 37, 41}), ('explosion.csv', EntityType.Special, {6, 7, 8, 9}), ('smoke.csv', EntityType.Special, {6, 7, 8, 9}), ('flyingwaste.csv', EntityType.Special, {6, 7, 8, 9, 18, 20, 22, 24}), ('mine.csv', EntityType.Special, {6, 7, 8, 9}), ('walllaser.csv', EntityType.Special, {6, 7, 8, 9}), ('builderline.csv', EntityType.Special, {6, 7, 8, 9}), ('platoon.csv', EntityType.Special, {6, 7, 8, 9, 18, 19}), ('shieldgenerator.csv', EntityType.ShieldGenerator, set()), ('talkpack.csv', EntityType.SoundPack, set()), ('parameters.csv', EntityType.Parameters, set()), ('playertalkpack.csv', EntityType.SoundPack, set()), ('specialupdateslinks.csv', EntityType.SpecialUpdatesLinks, {0}) ] research = None entity_groups = [] try: with open('research.csv', newline='') as csv_file: reader = csv.reader(csv_file) next(reader) # Skip header line research = [Research(row) for row in reader] except FileNotFoundError: print(usage) sys.exit(1) research_ids = {r.name : r.id for r in research} for (filename, etype, ref_fields) in csv_files: try: with open(filename, newline='') as csv_file: print(f'Reading {filename}') reader = csv.reader(csv_file) next(reader) # Skip header line group = None for row in reader: if not row: continue if len(row) < 3: group = EntityGroup() group.faction = Faction.__members__[row[-1]] group.entity_type = etype group.ref_fields = ref_fields entity_groups.append(group) else: group.entities.append(Entity(row)) except FileNotFoundError: print(f'{filename} not found') continue with open('EARTH2150.par', 'wb') as parfile: writer = ParWriter(parfile) writer.write_header() writer.write(len(entity_groups)) writer.write(0) for group in entity_groups: writer.write(group.faction.value) writer.write(group.entity_type.value) writer.write(len(group.entities)) for entity in group.entities: writer.write(entity.name) writer.write([research_ids[r] for r in entity.req_research]) fields = list() for (i, f) in enumerate(entity.fields): fields.append(f) if i in group.ref_fields: fields.append(0xffffffff) writer.write_fields(fields) writer.write(len(research)) for r in research: writer.write([research_ids[p] for p in r.previous]) writer.write(r.id) writer.write(r.faction.value) writer.write(r.campaign_cost) writer.write(r.skirmish_cost) writer.write(r.campaign_time) writer.write(r.skirmish_time) writer.write(r.name) writer.write(r.video) writer.write(r.type) writer.write(r.mesh) writer.write(r.meshParamsIndex) writer.write(1) writer.write(len(research) - 1) print(f'Wrote EARTH2150.par containing {sum(len(g.entities) for g in entity_groups)} entities (in {len(entity_groups)} groups) and {len(research)} research topics')
InsideEarth2150/Programming
Tools/Community Tools/Ninetailed/earth-2150/csv2par.py
csv2par.py
py
8,490
python
en
code
1
github-code
36
[ { "api_name": "enum.Enum", "line_number": 14, "usage_type": "name" }, { "api_name": "enum.Enum", "line_number": 21, "usage_type": "name" }, { "api_name": "enum.Enum", "line_number": 34, "usage_type": "name" }, { "api_name": "itertools.count", "line_number": 41...
24623808952
import matplotlib.pyplot as plt from generator import Generator import torch from discriminator import Discriminator import torch.nn as nn import utils import torch.utils.data as data G = Generator() input_z = torch.randn(1, 20) input_z = input_z.view(input_z.size(0), input_z.size(1), 1, 1) fake_image = G(input_z) D = Discriminator() G.apply(utils.weights_init) D.apply(utils.weights_init) print('ネットワーク初期化完了') train_img_list = utils.make_datapath_list() mean = (0.5,) std = (0.5,) train_dataset = utils.GAN_Img_Dataset(filelist=train_img_list, transform=utils.ImageTransform(mean, std)) batch_size = 64 train_dataloader = data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True) num_epochs = 200 G_updated, D_updated = utils.train_model(G, D, dataloader=train_dataloader, num_epochs=num_epochs) device = torch.device('cuda:0') batch_size = 8 z_dim = 20 fixed_z = torch.randn(batch_size, z_dim) fixed_z = fixed_z.view(fixed_z.size(0), fixed_z.size(1), 1, 1) # 訓練したジェネレータで画像を生成 fake_image = G_updated(fixed_z.to(device)) # 訓練データを取得 batch_iterator = iter(train_dataloader) imgs = next(batch_iterator) fig = plt.figure(figsize=(15, 6)) for i in range(0, 5): plt.subplot(2, 5, i+1) plt.imshow(imgs[i][0].cpu().detach().numpy(), 'gray') plt.subplot(2, 5, 5+i+1) plt.imshow(fake_image[i][0].cpu().detach().numpy(), 'gray') plt.show()
TOnodera/pytorch-advanced
gan/main.py
main.py
py
1,442
python
en
code
0
github-code
36
[ { "api_name": "generator.Generator", "line_number": 9, "usage_type": "call" }, { "api_name": "torch.randn", "line_number": 10, "usage_type": "call" }, { "api_name": "discriminator.Discriminator", "line_number": 14, "usage_type": "call" }, { "api_name": "utils.weig...
24569667329
import tensorflow as tf import cv2 import time import argparse import posenet from joblib import dump, load import pandas as pd column_names = ['Eye_L_x', 'Eye_L_y', 'Eye_R_x', 'Eye_R_y', 'Hip_L_x', 'Hip_L_y', 'Knee_L_x', 'Knee_L_y', 'Ankle_L_x', 'Ankle_L_y', 'Toes_L_x', 'Toes_L_y', 'ToesEnd_L_x', 'ToesEnd_L_y', 'Shoulder_L_x', 'Shoulder_L_y', 'Elbow_L_x', 'Elbow_L_y', 'Wrist_L_x', 'Wrist_L_y', 'Hip_R_x', 'Hip_R_y', 'Knee_R_x', 'Knee_R_y', 'Ankle_R_x', 'Ankle_R_y', 'Shoulder_R_x', 'Shoulder_R_y', 'Elbow_R_x', 'Elbow_R_y', 'Wrist_R_x', 'Wrist_R_y'] UNITY_PART_MAP = { # 'nose' : '', 'leftEye' : 'Eye_L', 'rightEye' : 'Eye_R', # 'leftEar' : '', # 'rightEar' : '', 'leftShoulder' : 'Shoulder_L', 'rightShoulder' : 'Shoulder_R', 'leftElbow' : 'Elbow_L', 'rightElbow' : 'Elbow_R', 'leftWrist' : 'Wrist_L', 'rightWrist' : 'Wrist_R', 'leftHip' : 'Hip_L', 'rightHip' : 'Hip_R', 'leftKnee' : 'Knee_L', 'rightKnee' : 'Knee_R', 'leftAnkle' : 'Ankle_L', 'rightAnkle' : 'Ankle_R', } parser = argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101) parser.add_argument('--cam_id', type=int, default=0) parser.add_argument('--cam_width', type=int, default=1280) parser.add_argument('--cam_height', type=int, default=720) parser.add_argument('--scale_factor', type=float, default=0.7125) parser.add_argument('--file', type=str, default=None, help="Optionally use a video file instead of a live camera") parser.add_argument('--notxt', action='store_true') parser.add_argument("-s", "--size", type=int, default=5, help="size of queue for averaging") args = parser.parse_args() def unitCoords(coords, oldResolution): unitCoords = {} unitCoords['x'] = coords['x'] / oldResolution['x']; unitCoords['y'] = coords['y'] / oldResolution['y'] return unitCoords; def addText(image, text): # font font = cv2.FONT_HERSHEY_SIMPLEX # org org = (50, 50) # fontScale fontScale = 1 # Blue color in BGR color = (255, 0, 0) # Line thickness of 2 px thickness = 2 # Using cv2.putText() method image = cv2.putText(image, text, org, font, fontScale, color, thickness, cv2.LINE_AA) return image from collections import deque, Counter Q = deque(maxlen=args.size) def main(): with tf.Session() as sess: model_cfg, model_outputs = posenet.load_model(args.model, sess) output_stride = model_cfg['output_stride'] cap = cv2.VideoCapture(args.cam_id) # default value if args.file is not None: cap = cv2.VideoCapture(args.file) else: cap = cv2.VideoCapture(args.cam_id) cap.set(3, args.cam_width) cap.set(4, args.cam_height) start = time.time() frame_count = 0 while True: input_image, display_image, output_scale = posenet.read_cap( cap, scale_factor=args.scale_factor, output_stride=output_stride) heatmaps_result, offsets_result, displacement_fwd_result, displacement_bwd_result = sess.run( model_outputs, feed_dict={'image:0': input_image} ) pose_scores, keypoint_scores, keypoint_coords = posenet.decode_multi.decode_multiple_poses( heatmaps_result.squeeze(axis=0), offsets_result.squeeze(axis=0), displacement_fwd_result.squeeze(axis=0), displacement_bwd_result.squeeze(axis=0), output_stride=output_stride, max_pose_detections=10, min_pose_score=0.15) keypoint_coords *= output_scale cp_keypoint_coords = keypoint_coords.copy() # copy keypoint_coords /= [input_image.shape[1], input_image.shape[2]] # keypoint_coords *= 400 clf = load('synthpose.joblib') # TODO this isn't particularly fast, use GL for drawing and display someday... overlay_image = posenet.draw_skel_and_kp( display_image, pose_scores, keypoint_scores, cp_keypoint_coords, min_pose_score=0.15, min_part_score=0.1) if not args.notxt: for pi in range(len(pose_scores)): if pose_scores[pi] == 0.: break # print('Pose #%d, score = %f' % (pi, pose_scores[pi])) t_row = {} # f_df = pd.DataFrame(columns = column_names) for ki, (s, c) in enumerate(zip(keypoint_scores[pi, :], keypoint_coords[pi, :, :])): # print('Keypoint %s, score = %f, coord = %s' % (posenet.PART_NAMES[ki], s, c)) if posenet.PART_NAMES[ki] in UNITY_PART_MAP: t_row[UNITY_PART_MAP[posenet.PART_NAMES[ki]] + '_x'] = c[1]; t_row[UNITY_PART_MAP[posenet.PART_NAMES[ki]] + '_y'] = c[0]; f_df = f_df.append(t_row, ignore_index=True) f_df = f_df.fillna(0) y = clf.predict(f_df)[0] # print(y, pose_scores[pi]) if pose_scores[pi] > 0.4: Q.append(y) b = Counter(Q).most_common(1)[0][0] print (b) overlay_image = addText(overlay_image, b) cv2.imshow('posenet', overlay_image) frame_count += 1 if cv2.waitKey(1) & 0xFF == ord('q'): break print('Average FPS: ', frame_count / (time.time() - start)) if __name__ == "__main__": main()
rahul-islam/posenet-python
webcam_demo.py
webcam_demo.py
py
5,792
python
en
code
null
github-code
36
[ { "api_name": "argparse.ArgumentParser", "line_number": 38, "usage_type": "call" }, { "api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 57, "usage_type": "attribute" }, { "api_name": "cv2.putText", "line_number": 71, "usage_type": "call" }, { "api_name": "cv2...
30478421727
import pprint import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_ranking as tfr import tensorflow_recommenders as tfrs import collections def _create_feature_dict(): """Helper function for creating an empty feature dict for defaultdict.""" return {"embeddings": [], "ranking": []} def _sample_list( feature_lists, num_examples_per_list, random_state, ): """Function for sampling a list example from given feature lists.""" if random_state is None: random_state = np.random.RandomState() sampled_indices = random_state.choice( range(len(feature_lists["embeddings"])), size=num_examples_per_list, replace=False, ) sampled_embeddings = [ feature_lists["embeddings"][idx] for idx in sampled_indices ] sampled_rankings = [ feature_lists["ranking"][idx] for idx in sampled_indices ] return ( sampled_embeddings, tf.concat(sampled_rankings, 0), ) def sample_listwise( ranking_dataset, num_list_per_cc, num_examples_per_list, seed, ): """Function for converting the rankings dataset to a listwise dataset. Args: ranking_dataset: The training dataset with [CC,embeddinga,rank] for the specified time period num_list_per_cc: An integer representing the number of lists that should be sampled for each cc in the training dataset. num_examples_per_list: An integer representing the number of store ranks to be sampled for each list from the list of stores ranked "by" the cc. Like a user ranking movies. seed: An integer for creating `np.random.RandomState. Returns: A tf.data.Dataset containing list examples. Each example contains three keys: "cc_id", "embeddings", and "ranking". "cc_id" maps to a integer tensor that represents the cc_id for the example. "embeddings" maps to a tensor of shape [sum(num_example_per_list)] with dtype tf.Tensor. It represents the list of store,cc embedding descriptions. "ranking" maps to a tensor of shape [sum(num_example_per_list)] with dtype tf.float32. It represents the ranking of each store attached to the cc_id in the candidate list. """ random_state = np.random.RandomState(seed) example_lists_by_cc = collections.defaultdict(_create_feature_dict) for example in ranking_dataset: user_id = example["cc_id"].numpy() example_lists_by_cc[user_id]["embeddings"].append( example["embeddings"]) example_lists_by_cc[user_id]["ranking"].append( example["ranking"]) tensor_slices = {"cc_id": [], "embeddings": [], "ranking": []} for cc_id, feature_lists in example_lists_by_cc.items(): for _ in range(num_list_per_cc): # Drop the user if they don't have enough ratings. if len(feature_lists["embeddings"]) < num_examples_per_list: continue sampled_embeddings, sampled_rankings = _sample_list( feature_lists, num_examples_per_list, random_state=random_state, ) tensor_slices["cc_id"].append(cc_id) tensor_slices["embeddings"].append(sampled_embeddings) tensor_slices["ranking"].append(sampled_rankings) return tf.data.Dataset.from_tensor_slices(tensor_slices)
colinfritz-ai/GAP_Recommender_System_MVP
GAP_Recommender_System_Utilities.py
GAP_Recommender_System_Utilities.py
py
3,307
python
en
code
0
github-code
36
[ { "api_name": "numpy.random.RandomState", "line_number": 23, "usage_type": "call" }, { "api_name": "numpy.random", "line_number": 23, "usage_type": "attribute" }, { "api_name": "tensorflow.concat", "line_number": 40, "usage_type": "call" }, { "api_name": "numpy.ra...
30160636048
import pytest from django.urls import reverse from mixer.backend.django import mixer pytestmark = [pytest.mark.django_db] def test_get_user_list(api_client): """Получение списка пользователей.""" url = reverse('users') response = api_client.get(url) assert response.status_code == 200 def test_new_user_in_list(api_client): """Появление нового пользователя.""" url = reverse('users') response = api_client.get(url) mixer.blend('users.User') new_response = api_client.get(url) assert response.content != new_response.content
X-Viktor/FLStudy
users/tests/api/test_users.py
test_users.py
py
627
python
en
code
1
github-code
36
[ { "api_name": "pytest.mark", "line_number": 5, "usage_type": "attribute" }, { "api_name": "django.urls.reverse", "line_number": 10, "usage_type": "call" }, { "api_name": "django.urls.reverse", "line_number": 18, "usage_type": "call" }, { "api_name": "mixer.backend...
72387880423
# -*- coding:utf-8 -*- from scrapy import Spider from scrapy.selector import Selector from qhpage.items import QhpageItem class QhpageSpider(Spider): name = "qhpage" allowed_domains = ["stackoverflow.com"] start_urls = [ "http://stackoverflow.com/questions?pagesize=50&sort=newest", ] def parse(self, response): questions = Selector(response).xpath('//div[@class="summary"]') for question in questions: item = QhpageItem() item['name'] = question.xpath('./h3/a[@class="question-hyperlink"]/text()').extract()[0] item['url'] = question.xpath('./h3/a[@class="question-hyperlink"]/@href').extract()[0] item['title'] = question.xpath('./div[@class="excerpt"]/text()').extract()[0] yield item
yangaoquan/qhpage
qhpage/spiders/qhspider.py
qhspider.py
py
796
python
en
code
2
github-code
36
[ { "api_name": "scrapy.Spider", "line_number": 7, "usage_type": "name" }, { "api_name": "scrapy.selector.Selector", "line_number": 14, "usage_type": "call" }, { "api_name": "qhpage.items.QhpageItem", "line_number": 17, "usage_type": "call" } ]
3592662594
from fastapi import APIRouter, Depends, HTTPException, UploadFile from sqlalchemy.orm import Session from typing import List from db.database import get_db from security.auth import oauth2_scheme, get_current_user from . import schemas, crud router = APIRouter() @router.post("/events/add") async def add_event(text: str, image: UploadFile, db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)): user = get_current_user(db, token) if not user.is_admin: raise HTTPException(status_code=400, detail="No permision") return crud.add_event(db, text, image) @router.delete("/events/{event_id}/delete") async def delete_event(event_id: int, db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)): user = get_current_user(db, token) if not user.is_admin: raise HTTPException(status_code=400, detail="No permision") return crud.delete_event(db, event_id) @router.get("/events", response_model=List[schemas.Events]) async def read_events(db: Session = Depends(get_db)): return crud.get_events(db)
ostrekodowanie/Synapsis
backend/api/events/routes.py
routes.py
py
1,070
python
en
code
0
github-code
36
[ { "api_name": "fastapi.APIRouter", "line_number": 11, "usage_type": "call" }, { "api_name": "fastapi.UploadFile", "line_number": 15, "usage_type": "name" }, { "api_name": "sqlalchemy.orm.Session", "line_number": 15, "usage_type": "name" }, { "api_name": "fastapi.D...
27158727859
""" CartoonPhoto Yotam Levit Date: 13/11/2020 """ import cv2 def read_image(image_name): return cv2.imread(image_name) def get_edged(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) grey = cv2.medianBlur(gray, 5) edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9) return edges def cartoonization(image, edges): color = cv2.bilateralFilter(image, 9, 250, 250) cartoon = cv2.bitwise_and(color, color, mask=edges) return cartoon def show_images(image, edges, cartoon): cv2.imshow("Image" ,image) cv2.imshow("edges", edges) cv2.imshow("Cartoon", cartoon) cv2.waitKey(0) cv2.destroyAllWindows() def convert(image_name): image = read_image(image_name) edges = get_edged(image) cartoon = cartoonization(image, edges) show_images(image, edges, cartoon) convert("dana4.png")
yotamlevit/CartoonPhoto
Convertor.py
Convertor.py
py
961
python
en
code
0
github-code
36
[ { "api_name": "cv2.imread", "line_number": 10, "usage_type": "call" }, { "api_name": "cv2.cvtColor", "line_number": 14, "usage_type": "call" }, { "api_name": "cv2.COLOR_BGR2GRAY", "line_number": 14, "usage_type": "attribute" }, { "api_name": "cv2.medianBlur", ...
38092864913
import abc import collections import copyreg import enum import functools import inspect import logging import operator import random import string import typing from .. import _exception, _struct from . import series if typing.TYPE_CHECKING: from forml.io import dsl LOGGER = logging.getLogger(__name__) class Rows(typing.NamedTuple): """Row limit spec container. Attention: Instances are expected to be created internally via :meth:`dsl.Queryable.limit <forml.io.dsl.Queryable.limit>`. """ count: int """Number of rows to return.""" offset: int = 0 """Skip the given number of rows.""" def __repr__(self): return f'{self.offset}:{self.count}' class Source(tuple, metaclass=abc.ABCMeta): """Base class of the *tabular* data frame sources. A *Source* is anything that can be used to obtain tabular data *FROM*. It is a logical collection of :class:`dsl.Feature <forml.io.dsl.Feature>` instances represented by its :attr:`schema`. """ class Schema(type): """Meta-class for schema types construction. It guarantees consistent hashing and comparability for equality of the produced schema classes. Attention: This meta-class is used internally, for schema frontend API see the :class:`dsl.Schema <forml.io.dsl.Schema>`. """ def __new__(mcs, name: str, bases: tuple[type], namespace: dict[str, typing.Any]): seen = set() existing = collections.ChainMap( *( {f.name: k} for b in bases if isinstance(b, Source.Schema) for c in reversed(inspect.getmro(b)) for k, f in c.__dict__.items() if isinstance(f, _struct.Field) and k not in seen and not seen.add(k) ) ) if existing and len(existing.maps) > len(existing): raise _exception.GrammarError(f'Colliding base classes in schema {name}') for key, field in namespace.items(): if not isinstance(field, _struct.Field): continue if not field.name: namespace[key] = field = field.renamed(key) # to normalize so that hash/eq is consistent if field.name in existing and existing[field.name] != key: raise _exception.GrammarError(f'Colliding field name {field.name} in schema {name}') existing[field.name] = key cls = super().__new__(mcs, name, bases, namespace) cls.__qualname__ = f'{name}.schema' return cls def __hash__(cls): # pylint: disable=not-an-iterable return functools.reduce(operator.xor, (hash(f) for f in cls), 0) def __eq__(cls, other: 'dsl.Source.Schema'): return ( isinstance(other, cls.__class__) and len(cls) == len(other) and all(c == o for c, o in zip(cls, other)) ) def __len__(cls): return sum(1 for _ in cls) # pylint: disable=not-an-iterable def __repr__(cls): return f'{cls.__module__}:{cls.__qualname__}' @functools.lru_cache def __getitem__(cls, name: str) -> 'dsl.Field': try: item = getattr(cls, name) except AttributeError: for field in cls: # pylint: disable=not-an-iterable if name == field.name: return field else: if isinstance(item, _struct.Field): return item raise KeyError(f'Unknown field {name}') def __iter__(cls) -> typing.Iterator['dsl.Field']: return iter( { k: f for c in reversed(inspect.getmro(cls)) for k, f in c.__dict__.items() if isinstance(f, _struct.Field) }.values() ) copyreg.pickle( Schema, lambda s: ( Source.Schema, (s.__name__, s.__bases__, {k: f for k, f in s.__dict__.items() if isinstance(f, _struct.Field)}), ), ) class Visitor: """Source visitor.""" def visit_source(self, source: 'dsl.Source') -> None: # pylint: disable=unused-argument """Generic source hook. Args: source: Source instance to be visited. """ def visit_table(self, source: 'dsl.Table') -> None: """Table hook. Args: source: Source instance to be visited. """ self.visit_source(source) def visit_reference(self, source: 'dsl.Reference') -> None: """Reference hook. Args: source: Instance to be visited. """ source.instance.accept(self) self.visit_source(source) def visit_join(self, source: 'dsl.Join') -> None: """Join hook. Args: source: Instance to be visited. """ source.left.accept(self) source.right.accept(self) self.visit_source(source) def visit_set(self, source: 'dsl.Set') -> None: """Set hook. Args: source: Instance to be visited. """ source.left.accept(self) source.right.accept(self) self.visit_source(source) def visit_query(self, source: 'dsl.Query') -> None: """Query hook. Args: source: Instance to be visited. """ source.source.accept(self) self.visit_source(source) def __new__(cls, *args): return super().__new__(cls, args) def __getnewargs__(self): return tuple(self) def __hash__(self): return hash(self.__class__.__module__) ^ hash(self.__class__.__qualname__) ^ super().__hash__() def __repr__(self): return f'{self.__class__.__name__}({", ".join(repr(a) for a in self)})' def __getattr__(self, name: str) -> 'dsl.Feature': try: return self[name] except KeyError as err: raise AttributeError(f'Invalid feature {name}') from err @functools.lru_cache def __getitem__(self, name: typing.Union[int, str]) -> typing.Any: try: return super().__getitem__(name) except (TypeError, IndexError) as err: name = self.schema[name].name for field, feature in zip(self.schema, self.features): if name == field.name: return feature raise RuntimeError(f'Inconsistent {name} lookup vs schema iteration') from err @abc.abstractmethod def accept(self, visitor: 'dsl.Source.Visitor') -> None: """Visitor acceptor. Args: visitor: Visitor instance. """ @functools.cached_property def schema(self) -> 'dsl.Source.Schema': """Schema type representing this source. Returns: Schema type. """ return self.Schema( self.__class__.__name__, (_struct.Schema.schema,), {(c.name or f'_{i}'): _struct.Field(c.kind, c.name) for i, c in enumerate(self.features)}, ) @functools.cached_property @abc.abstractmethod def features(self) -> typing.Sequence['dsl.Feature']: """List of features logically contained in or potentially produced by this Source. Returns: Sequence of contained features. """ @property def query(self) -> 'dsl.Query': """Query equivalent of this Source. Returns: Query instance. """ return Query(self) @property def statement(self) -> 'dsl.Statement': """Statement equivalent of this Source. Returns: Statement instance. """ return self.query @property def instance(self) -> 'dsl.Source': """Return the source instance. Apart from the ``Reference`` type is the Source itself. Returns: Source instance. """ return self def reference(self, name: typing.Optional[str] = None) -> 'dsl.Reference': """Get an independent reference to this Source (e.g. for self-join conditions). Args: name: Optional alias to be used for this reference (random by default). Returns: New reference to this Source. Examples: >>> manager = staff.Employee.reference('manager') >>> subs = ( ... manager.join(staff.Employee, staff.Employee.manager == manager.id) ... .select(manager.name, function.Count(staff.Employee.id).alias('subs')) ... .groupby(manager.id) ... ) """ return Reference(self, name) def union(self, other: 'dsl.Source') -> 'dsl.Set': """Create a new Source as a set union of this and the other Source. Args: other: Source to union with. Returns: Set instance. Examples: >>> barbaz = ( ... foo.Bar.select(foo.Bar.X, foo.Bar.Y) ... .union(foo.Baz.select(foo.Baz.X, foo.Baz.Y)) ... ) """ return Set(self, other, Set.Kind.UNION) def intersection(self, other: 'dsl.Source') -> 'dsl.Set': """Create a new Source as a set intersection of this and the other Source. Args: other: Source to intersect with. Returns: Set instance. Examples: >>> barbaz = ( ... foo.Bar.select(foo.Bar.X, foo.Bar.Y) ... .intersection(foo.Baz.select(foo.Baz.X, foo.Baz.Y)) ... ) """ return Set(self, other, Set.Kind.INTERSECTION) def difference(self, other: 'dsl.Source') -> 'dsl.Set': """Create a new Source as a set difference of this and the other Source. Args: other: Source to difference with. Returns: Set instance. Examples: >>> barbaz = ( ... foo.Bar.select(foo.Bar.X, foo.Bar.Y) ... .difference(foo.Baz.select(foo.Baz.X, foo.Baz.Y)) ... ) """ return Set(self, other, Set.Kind.DIFFERENCE) class Statement(Source, metaclass=abc.ABCMeta): """Base class for complete statements. Complete statements are: * :class:`forml.io.dsl.Query` * :class:`forml.io.dsl.Set`. """ class Set(Statement): """Source made of two set-combined sub-statements with the same schema. Attention: Instances are expected to be created internally via: * :meth:`dsl.Source.union() <forml.io.dsl.Source.union>` * :meth:`dsl.Source.intersection() <forml.io.dsl.Source.intersection>` * :meth:`dsl.Source.difference() <forml.io.dsl.Source.difference>` """ @enum.unique class Kind(enum.Enum): """Set type enum.""" UNION = 'union' """Union set operation type.""" INTERSECTION = 'intersection' """Intersection set operation type.""" DIFFERENCE = 'difference' """Difference set operation type.""" left: 'dsl.Statement' = property(operator.itemgetter(0)) """Left side of the set operation.""" right: 'dsl.Statement' = property(operator.itemgetter(1)) """Right side of the set operation.""" kind: 'dsl.Set.Kind' = property(operator.itemgetter(2)) """Set operation enum type.""" def __new__(cls, left: 'dsl.Source', right: 'dsl.Source', kind: 'dsl.Set.Kind'): if left.schema != right.schema: raise _exception.GrammarError('Incompatible sources') return super().__new__(cls, left.statement, right.statement, kind) def __repr__(self): return f'{repr(self.left)} {self.kind.value} {repr(self.right)}' @property def statement(self) -> 'dsl.Statement': return self @functools.cached_property def features(self) -> typing.Sequence['dsl.Feature']: return self.left.features + self.right.features def accept(self, visitor: 'dsl.Source.Visitor') -> None: visitor.visit_set(self) class Queryable(Source, metaclass=abc.ABCMeta): """Base class for any *Source* that can be queried directly.""" def select(self, *features: 'dsl.Feature') -> 'dsl.Query': """Specify the output features to be provided (projection). Repeated calls to ``.select`` replace the earlier selection. Args: features: Sequence of features. Returns: Query instance. Examples: >>> barxy = foo.Bar.select(foo.Bar.X, foo.Bar.Y) """ return self.query.select(*features) def where(self, condition: 'dsl.Predicate') -> 'dsl.Query': """Add a row-filtering condition that's evaluated before any aggregations. Repeated calls to ``.where`` combine all the conditions (logical AND). Args: condition: Boolean feature expression. Returns: Query instance. Examples: >>> barx10 = foo.Bar.where(foo.Bar.X == 10) """ return self.query.where(condition) def having(self, condition: 'dsl.Predicate') -> 'dsl.Query': """Add a row-filtering condition that's applied to the evaluated aggregations. Repeated calls to ``.having`` combine all the conditions (logical AND). Args: condition: Boolean feature expression. Returns: Query instance. Examples: >>> bargy10 = foo.Bar.groupby(foo.Bar.X).having(function.Count(foo.Bar.Y) == 10) """ return self.query.having(condition) def groupby(self, *features: 'dsl.Operable') -> 'dsl.Query': """Aggregation grouping specifiers. Repeated calls to ``.groupby`` replace the earlier grouping. Args: features: Sequence of aggregation features. Returns: Query instance. Examples: >>> bargbx = foo.Bar.groupby(foo.Bar.X).select(foo.Bar.X, function.Count(foo.Bar.Y)) """ return self.query.groupby(*features) def orderby(self, *terms: 'dsl.Ordering.Term') -> 'dsl.Query': """Ordering specifiers. Default direction is *ascending*. Repeated calls to ``.orderby`` replace the earlier ordering. Args: terms: Sequence of feature and direction tuples. Returns: Query instance. Examples: >>> barbyx = foo.Bar.orderby(foo.Bar.X) >>> barbyxd = foo.Bar.orderby(foo.Bar.X, 'desc') >>> barbxy = foo.Bar.orderby(foo.Bar.X, foo.Bar.Y) >>> barbxdy = foo.Bar.orderby( ... foo.Bar.X, dsl.Ordering.Direction.DESCENDING, foo.Bar.Y, 'asc' ... ) >>> barbydxd = foo.Bar.orderby( ... (foo.Bar.X, 'desc'), ... (foo.Bar.Y, dsl.Ordering.Direction.DESCENDING), ... ) """ return self.query.orderby(*terms) def limit(self, count: int, offset: int = 0) -> 'dsl.Query': """Restrict the result rows by its max *count* with an optional *offset*. Repeated calls to ``.limit`` replace the earlier restriction. Args: count: Number of rows to return. offset: Skip the given number of rows. Returns: Query instance. Examples: >>> bar10 = foo.Bar.limit(10) """ return self.query.limit(count, offset) class Origin(Queryable, metaclass=abc.ABCMeta): """Origin is a queryable Source with some handle. Its features are represented using :class:`dsl.Element <forml.io.dsl.Element>`. """ @property @abc.abstractmethod def features(self) -> typing.Sequence['dsl.Element']: """Origin features are instances of ``dsl.Element``. Returns: Sequence of ``dsl.Element`` instances. """ def inner_join(self, other: 'dsl.Origin', condition: 'dsl.Predicate') -> 'dsl.Join': """Construct an *inner* join with the other *origin* using the provided *condition*. Args: other: Source to join with. condition: Feature expression as the join condition. Returns: Join instance. Examples: >>> barbaz = foo.Bar.inner_join(foo.Baz, foo.Bar.baz == foo.Baz.id) """ return Join(self, other, Join.Kind.INNER, condition) def left_join(self, other: 'dsl.Origin', condition: 'dsl.Predicate') -> 'dsl.Join': """Construct a *left* join with the other *origin* using the provided *condition*. Args: other: Source to join with. condition: Feature expression as the join condition. Returns: Join instance. Examples: >>> barbaz = foo.Bar.left_join(foo.Baz, foo.Bar.baz == foo.Baz.id) """ return Join(self, other, Join.Kind.LEFT, condition) def right_join(self, other: 'dsl.Origin', condition: 'dsl.Predicate') -> 'dsl.Join': """Construct a *right* join with the other *origin* using the provided *condition*. Args: other: Source to join with. condition: Feature expression as the join condition. Returns: Join instance. Examples: >>> barbaz = foo.Bar.right_join(foo.Baz, foo.Bar.baz == foo.Baz.id) """ return Join(self, other, Join.Kind.RIGHT, condition) def full_join(self, other: 'dsl.Origin', condition: 'dsl.Predicate') -> 'dsl.Join': """Construct a *full* join with the other *origin* using the provided *condition*. Args: other: Source to join with. condition: Feature expression as the join condition. Returns: Join instance. Examples: >>> barbaz = foo.Bar.full_join(foo.Baz, foo.Bar.baz == foo.Baz.id) """ return Join(self, other, Join.Kind.FULL, condition) def cross_join(self, other: 'dsl.Origin') -> 'dsl.Join': """Construct a *cross* join with the other *origin*. Args: other: Source to join with. Returns: Join instance. Examples: >>> barbaz = foo.Bar.cross_join(foo.Baz) """ return Join(self, other, kind=Join.Kind.CROSS) class Join(Origin): """Source made of two join-combined sub-sources. Attention: Instances are expected to be created internally via: * :meth:`dsl.Origin.inner_join() <forml.io.dsl.Origin.inner_join>` * :meth:`dsl.Origin.left_join() <forml.io.dsl.Origin.left_join>` * :meth:`dsl.Origin.right_join() <forml.io.dsl.Origin.right_join>` * :meth:`dsl.Origin.full_join() <forml.io.dsl.Origin.full_join>` * :meth:`dsl.Origin.cross_join() <forml.io.dsl.Origin.cross_join>` """ @enum.unique class Kind(enum.Enum): """Join type enum.""" INNER = 'inner' """Inner join type (default if *condition* is provided).""" LEFT = 'left' """Left outer join type.""" RIGHT = 'right' """Right outer join type.""" FULL = 'full' """Full join type.""" CROSS = 'cross' """Cross join type (default if *condition* is not provided).""" def __repr__(self): return f'<{self.value}-join>' left: 'dsl.Origin' = property(operator.itemgetter(0)) """Left side of the join operation.""" right: 'dsl.Origin' = property(operator.itemgetter(1)) """Right side of the join operation.""" kind: 'dsl.Join.Kind' = property(operator.itemgetter(2)) """Join type.""" condition: typing.Optional['dsl.Predicate'] = property(operator.itemgetter(3)) """Join condition (invalid for *CROSS*-join).""" def __new__( cls, left: 'dsl.Origin', right: 'dsl.Origin', kind: typing.Union['dsl.Join.Kind', str], condition: typing.Optional['dsl.Predicate'] = None, ): if (kind is cls.Kind.CROSS) ^ (condition is None): raise _exception.GrammarError('Illegal use of condition and join type') if condition is not None: condition = series.Cumulative.ensure_notin(series.Predicate.ensure_is(condition)) if not series.Element.dissect(condition).issubset(series.Element.dissect(*left.features, *right.features)): raise _exception.GrammarError( f'({condition}) not a subset of source features ({left.features}, {right.features})' ) return super().__new__(cls, left, right, kind, condition) def __repr__(self): return f'{repr(self.left)}{repr(self.kind)}{repr(self.right)}' @functools.cached_property def features(self) -> typing.Sequence['dsl.Element']: return self.left.features + self.right.features def accept(self, visitor: 'dsl.Source.Visitor') -> None: visitor.visit_join(self) class Reference(Origin): """Wrapper around any *Source* associating it with a (possibly random) name. Attention: Instances are expected to be created internally via :meth:`dsl.Source.reference <forml.io.dsl.Source.reference>`. """ _NAMELEN: int = 8 instance: 'dsl.Source' = property(operator.itemgetter(0)) """Wrapped *Source* instance.""" name: str = property(operator.itemgetter(1)) """Reference name.""" def __new__(cls, instance: 'dsl.Source', name: typing.Optional[str] = None): if not name: name = ''.join(random.choice(string.ascii_lowercase) for _ in range(cls._NAMELEN)) return super().__new__(cls, instance.instance, name) def __repr__(self): return f'{self.name}=[{repr(self.instance)}]' @functools.cached_property def features(self) -> typing.Sequence['dsl.Element']: return tuple(series.Element(self, c.name) for c in self.instance.features) @property def schema(self) -> 'dsl.Source.Schema': return self.instance.schema def accept(self, visitor: 'dsl.Source.Visitor') -> None: """Visitor acceptor. Args: visitor: Visitor instance. """ visitor.visit_reference(self) class Table(Origin): """Table based *Source* with an explicit *schema*. Attention: The primary way of creating ``Table`` instances is by inheriting the :class:`dsl.Schema <forml.io.dsl.Schema>` which is using this type as a meta-class. """ class Meta(abc.ABCMeta): """Metaclass for dynamic parent classes.""" copyreg.pickle( Meta, lambda c: ( Table.Meta, (c.__name__, c.__bases__, {}), ), ) @typing.overload def __new__( # pylint: disable=bad-classmethod-argument mcs, name: str, bases: tuple[type], namespace: dict[str, typing.Any], ): """Meta-class mode constructor. Args: name: Table class name. bases: Table base classes. namespace: Class namespace container. """ @typing.overload def __new__(cls, schema: 'dsl.Source.Schema'): """Standard class mode constructor. Args: schema: Table *schema* type. """ def __new__(mcs, schema, bases=None, namespace=None): # pylint: disable=bad-classmethod-argument if isinstance(schema, str): # used as metaclass if bases: bases = tuple(b.schema for b in bases if isinstance(b, Table)) # strip the parent base class and namespace mcs = mcs.Meta(schema, mcs.__bases__, {}) # pylint: disable=self-cls-assignment elif not any(isinstance(a, _struct.Field) for a in namespace.values()): # used as a base class definition - let's propagate the namespace mcs = mcs.Meta(schema, (mcs,), namespace) # pylint: disable=self-cls-assignment schema = mcs.Schema(schema, bases, namespace) elif bases or namespace: raise TypeError('Unexpected use of schema table') return super().__new__(mcs, schema) # used as constructor def __repr__(self): return self.schema.__name__ @property def schema(self) -> 'dsl.Source.Schema': return self[0] @functools.cached_property def features(self) -> typing.Sequence['dsl.Column']: return tuple(series.Column(self, f.name) for f in self.schema) def accept(self, visitor: 'dsl.Source.Visitor') -> None: visitor.visit_table(self) class Query(Queryable, Statement): """Query based *Source*. Container for holding all the parameters supplied via the :class:`dsl.Queryable <forml.io.dsl.Queryable>` interface. Attention: Instances are expected to be created internally via the ``dsl.Queryable`` interface methods. """ source: 'dsl.Source' = property(operator.itemgetter(0)) """Base *Source* to query *FROM*.""" selection: tuple['dsl.Feature'] = property(operator.itemgetter(1)) """Result projection features.""" prefilter: typing.Optional['dsl.Predicate'] = property(operator.itemgetter(2)) """Row-filtering condition to be applied before potential aggregations.""" grouping: tuple['dsl.Operable'] = property(operator.itemgetter(3)) """Aggregation grouping specifiers.""" postfilter: typing.Optional['dsl.Predicate'] = property(operator.itemgetter(4)) """Row-filtering condition to be applied after aggregations.""" ordering: tuple['dsl.Ordering'] = property(operator.itemgetter(5)) """Ordering specifiers.""" rows: typing.Optional['dsl.Rows'] = property(operator.itemgetter(6)) """Row restriction limit.""" def __new__( cls, source: 'dsl.Source', selection: typing.Optional[typing.Iterable['dsl.Feature']] = None, prefilter: typing.Optional['dsl.Predicate'] = None, grouping: typing.Optional[typing.Iterable['dsl.Operable']] = None, postfilter: typing.Optional['dsl.Predicate'] = None, ordering: typing.Optional[typing.Sequence['dsl.Ordering.Term']] = None, rows: typing.Optional['dsl.Rows'] = None, ): def ensure_subset(*features: 'dsl.Feature') -> typing.Sequence['dsl.Feature']: """Ensure the provided features is a valid subset of the available Source features. Args: *features: List of features to validate. Returns: Original list of features if all valid. """ if not series.Element.dissect(*features).issubset(superset): raise _exception.GrammarError(f'{features} not a subset of source features: {superset}') return features superset = series.Element.dissect(*source.features) selection = tuple(ensure_subset(*(series.Feature.ensure_is(c) for c in selection or []))) if prefilter is not None: prefilter = series.Cumulative.ensure_notin( series.Predicate.ensure_is(*ensure_subset(series.Operable.ensure_is(prefilter))) ) if grouping: grouping = ensure_subset(*(series.Cumulative.ensure_notin(series.Operable.ensure_is(g)) for g in grouping)) for aggregate in {c.operable for c in selection or source.features}.difference(grouping): series.Aggregate.ensure_in(aggregate) if postfilter is not None: postfilter = series.Window.ensure_notin( series.Predicate.ensure_is(*ensure_subset(series.Operable.ensure_is(postfilter))) ) ordering = tuple(series.Ordering.make(*(ordering or []))) ensure_subset(*(o.feature for o in ordering)) return super().__new__(cls, source, selection, prefilter, tuple(grouping or []), postfilter, ordering, rows) def __repr__(self): value = repr(self.source) if self.selection: value += f'[{", ".join(repr(c) for c in self.selection)}]' if self.prefilter: value += f'.where({repr(self.prefilter)})' if self.grouping: value += f'.groupby({", ".join(repr(c) for c in self.grouping)})' if self.postfilter: value += f'.having({repr(self.postfilter)})' if self.ordering: value += f'.orderby({", ".join(repr(c) for c in self.ordering)})' if self.rows: value += f'[{repr(self.rows)}]' return value @property def query(self) -> 'dsl.Query': return self @functools.cached_property def features(self) -> typing.Sequence['dsl.Feature']: """Get the list of features supplied by this query. Returns: A sequence of supplying features. """ return self.selection if self.selection else self.source.features def accept(self, visitor: 'dsl.Source.Visitor') -> None: visitor.visit_query(self) def select(self, *features: 'dsl.Feature') -> 'dsl.Query': return Query(self.source, features, self.prefilter, self.grouping, self.postfilter, self.ordering, self.rows) def where(self, condition: 'dsl.Predicate') -> 'dsl.Query': if self.prefilter is not None: condition &= self.prefilter return Query(self.source, self.selection, condition, self.grouping, self.postfilter, self.ordering, self.rows) def having(self, condition: 'dsl.Predicate') -> 'dsl.Query': if self.postfilter is not None: condition &= self.postfilter return Query(self.source, self.selection, self.prefilter, self.grouping, condition, self.ordering, self.rows) def groupby(self, *features: 'dsl.Operable') -> 'dsl.Query': return Query(self.source, self.selection, self.prefilter, features, self.postfilter, self.ordering, self.rows) def orderby(self, *terms: 'dsl.Ordering.Term') -> 'dsl.Query': return Query(self.source, self.selection, self.prefilter, self.grouping, self.postfilter, terms, self.rows) def limit(self, count: int, offset: int = 0) -> 'dsl.Query': return Query( self.source, self.selection, self.prefilter, self.grouping, self.postfilter, self.ordering, Rows(count, offset), )
formlio/forml
forml/io/dsl/_struct/frame.py
frame.py
py
30,727
python
en
code
103
github-code
36
[ { "api_name": "typing.TYPE_CHECKING", "line_number": 16, "usage_type": "attribute" }, { "api_name": "logging.getLogger", "line_number": 20, "usage_type": "call" }, { "api_name": "typing.NamedTuple", "line_number": 23, "usage_type": "attribute" }, { "api_name": "ab...
16558040325
import network # Importar librerías necesarias import socket import time import secrets # Librería con las credenciales de tu red Wi-Fi from machine import Pin #Asignación de pin para el LED led = Pin(15, Pin.OUT) # Configuración de red Wi-Fi wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.config(pm = 0xa11140) wlan.connect(secrets.SSID, secrets.PASSWORD) # Página HTML html_on = """<!DOCTYPE html> <html> <head> <title>Raspberry pi Pico W</title> <style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;} .buttonRed { background-color: #d11d53; border: 2px solid #000000;; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: font-size: 16px; margin: 4px 2px; cursor: pointer; } text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;} </style></head> <body> <center><h1>Server on a Pico W</h1></center><br><br> <form><center> <center> <button class="buttonRed" name="Apagar" value="Off" formaction="/light/off" type="submit">Apagar LED </button> <br><br> <center><p>%s</p> </center></form> </body> </html> """ html_off = """<!DOCTYPE html> <html> <head> <title>Raspberry pi Pico W</title> <style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;} .button { background-color: #4CAF50; border: 2px solid #000000;; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: font-size: 16px; margin: 4px 2px; cursor: pointer; } text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;} </style></head> <body> <center><h1>Server on a Pico W</h1></center><br><br> <form><center> <center> <button class="button" name="Encender" value="On" formaction="/light/on" type="submit">Encender LED </button> <br><br> <center><p>%s</p> </center></form> </body> </html> """ #Esperamos que la conexion WiFi se establezca o falle max_wait = 10 while max_wait > 0: if wlan.status() < 0 or wlan.status() >= 3: break max_wait -= 1 print('waiting for connection...') time.sleep(1) # Error al conectar la red WiFi if wlan.status() != 3: raise RuntimeError('network connection failed') else: print('connected') status = wlan.ifconfig() print( 'ip = ' + status[0] ) print( 'Subnet = ' + status[1] ) print( 'Gateway = ' + status[2] ) print( 'DNS = ' + status[3] ) # Open socket addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket() s.bind(addr) s.listen(1) print('listening on', addr) #Esperamos una conexion a nuestra pagina while True: try: cl, addr = s.accept() print('client connected from', addr) request = cl.recv(1024) print(request) request = str(request) led_on = request.find('/light/on') led_off = request.find('/light/off') print( 'led on = ' + str(led_on)) print( 'led off = ' + str(led_off)) if led_on == 6: print("led on") led.value(1) stateis = "Encendido" response = html_on % stateis if led_off == 6: print("led off") led.value(0) stateis = "Apagado" response = html_off % stateis cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n') cl.send(response) cl.close() except OSError as e: cl.close() print('connection closed')
LuisSkap/ServerRaspberryPiPICO
Led_1.py
Led_1.py
py
3,618
python
en
code
1
github-code
36
[ { "api_name": "machine.Pin", "line_number": 9, "usage_type": "call" }, { "api_name": "machine.Pin.OUT", "line_number": 9, "usage_type": "attribute" }, { "api_name": "network.WLAN", "line_number": 12, "usage_type": "call" }, { "api_name": "network.STA_IF", "lin...
8135943468
from accounts.serializers import UserSerializer from django.shortcuts import redirect from django.conf import settings from django.contrib.auth import get_user_model from rest_framework.generics import CreateAPIView from rest_framework.views import APIView from rest_framework import serializers, status from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework_jwt.settings import api_settings from .utils import google_obtain_access_token, google_get_user_info, user_get_or_create, jwt_login, get_user_info BASE_URL = settings.BASE_URL BASE_FRONTEND_URL= settings.BASE_FRONTEND_URL LOGIN_URL = f'{BASE_URL}/accounts/auth/login' UserModel = get_user_model() class GetUserApi(APIView): """ Determine current user. Return user name, email and profile image """ permission_classes = [AllowAny] def get(self, request, *args, **kwargs): if request.user.is_authenticated: return Response(get_user_info(user=request.user)) return Response(status=status.HTTP_204_NO_CONTENT) class GoogleLoginAPI(APIView): """ Manage login with Google Get token from request and obtain user information: email, user name and profile image """ permission_classes = [] class InputSerializer(serializers.Serializer): code = serializers.CharField(required=True) def get(self, request, *args, **kwargs): input_serializer = self.InputSerializer(data=request.GET) input_serializer.is_valid(raise_exception=True) validated_data = input_serializer.validated_data code = validated_data.get('code') if not code: return redirect(f'{LOGIN_URL}?error') redirect_uri = f'{LOGIN_URL}/google' access_token = google_obtain_access_token( code=code, redirect_uri=redirect_uri) user_info = google_get_user_info(access_token) profile_data = { 'first_name': user_info.get('given_name'), 'last_name': user_info.get('family_name'), 'email': user_info.get('email'), 'profile_image': user_info.get('picture'), } user = user_get_or_create(profile_data) res = redirect(BASE_FRONTEND_URL) res = jwt_login(response=res, user=user) return res class LogoutAPI(APIView): """ Log out user by removing JWT cookie header """ permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): response = Response(status=status.HTTP_202_ACCEPTED) params = { 'expires': 'Thu, 01 Jan 1970 00:00:00 GMT', 'domain': api_settings.JWT_AUTH_COOKIE_DOMAIN, 'path': api_settings.JWT_AUTH_COOKIE_PATH, 'secure': api_settings.JWT_AUTH_COOKIE_SECURE, 'samesite': api_settings.JWT_AUTH_COOKIE_SAMESITE, 'httponly': True } response.set_cookie(api_settings.JWT_AUTH_COOKIE, **params) return response class SignUpUserApi(CreateAPIView): """ Create new user with email and password and log user in """ serializer_class = UserSerializer permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) email = serializer.data['email'] user = UserModel.objects.get(email=email) res = Response(serializer.data, status=status.HTTP_201_CREATED) res = jwt_login(response=res, user=user) return res
QuocHung52/course-pool-react
backend/accounts/views.py
views.py
py
3,658
python
en
code
0
github-code
36
[ { "api_name": "django.conf.settings.BASE_URL", "line_number": 15, "usage_type": "attribute" }, { "api_name": "django.conf.settings", "line_number": 15, "usage_type": "name" }, { "api_name": "django.conf.settings.BASE_FRONTEND_URL", "line_number": 16, "usage_type": "attrib...
74253274663
""" Module containing implementation of evolutionary computation algorithms, such as: - basic Evolutionary Algorithm - Genetic Programming - Evolutionary Strategies for solving the cases (see 'cases' module). """ import random import copy from typing import Tuple, Union, Dict, Any, List from deap import base, creator, tools import evolution.solution as sol import evolution.evaluator as evaluator import evolution.ec_utils as ecu from utils.logger import glob_logger # Some default values used in the algorithms # Population size, No. Generations, Mutation prob., Crossover prob. NPOP, NGEN, PMUT, PCX = 20, 100, 0.5, 0.2 class EvolutionParameters: """ Class containing parameters of the evolution process. The class generally assumes only the most generic parameters employed in all evolutionary techniques: - Population size - Number of generations - Probability of mutation - Probability of crossover Additional parameters can be supplied as keyword arguments and will be made available in the object through the . (dot) notation, i.e.: - EvolutionParameters(..., my_parameter=13.5) -> evo_param.my_parameter The general rules are that 1) each case should provide parameter values that are different from the default ones and 2) each algorithm should contain an initialization phase where all required parameters are set to their default value if no parameter value was supplied. :ivar pop: the requested population size :ivar gen: the number of generations :ivar pmut: the probability of mutation :ivar pcx: the probability of crossover """ def __init__( self, popsize: int = NPOP, generations: int = NGEN, prob_mut: float = PMUT, prob_cx: float = PCX, **kwargs: Any ) -> None: """ Constructor :param popsize: the requested population size :param generations: the number of generations :param prob_mut: the probability of mutation :param prob_cx: the probability of crossover """ self.pop = popsize self.gen = generations self.pmut = prob_mut self.pcx = prob_cx # Set the additional kwargs parameters as attributes for attr, value in kwargs.items(): setattr(self, attr, value) def update_defaults(self, defaults: Dict[str, Any]) -> None: """ Set default parameter values for those parameters that are not present in the object. We do not impose any restriction on the type of the parameters. :param defaults: map of default parameters and their values """ for attr, value in defaults.items(): if not hasattr(self, attr): setattr(self, attr, value) def __setattr__(self, name: str, value: Any) -> None: """ Setattr override to allow for dynamic attributes type checking. https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html#when-you-re-puzzled-or-when-things-are-complicated :param name: name of the attribute :param value: value of the attribute """ super().__setattr__(name, value) def __getattr__(self, name: str) -> Any: """ Getattr override to allow for dynamic attributes type checking. https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html#when-you-re-puzzled-or-when-things-are-complicated :param name: name of the attribute :return: value of the attribute """ return super().__getattribute__(name) # def opt_ga( # solutions: sol.SolutionSet, # evo_params: EvolutionParameters, # apply_func: sol.ApplySignature, # fitness_func: sol.FitnessSignature, # workers: int, # **apply_params: Union[int, float] # ) -> ecu.OptIndividual: # """ TODO: doc # """ # evo_params.update_defaults({ # 'pop_lambda': evo_params.pop, # 'tourn_size': 4 # }) # hof = ecu.BestTracker() # creator.create('FitnessMax', base.Fitness, weights=(1.0,)) # str_limits = solutions.get_strength_limits() # try: # # Create an evaluator context that handles the multiprocess / single process evaluation # with evaluator.Evaluator(workers, solutions, apply_func, fitness_func) as ev: # # Initialize the population # population = [ # ecu.OptIndividual(str_limits, creator.FitnessMax()) # for _ in range(evo_params.pop) # ] # # Evaluate the initial population # for ind in population: # # Make it tuple of one element # ind.fitness.values = ev.evaluate( # None, None, strength=ind.str_map, **apply_params # )[0], # hof.update(population) # for g in range(evo_params.gen): # # Randomly select 'lambda' parents and deepcopy them => offsprings # chosen = tools.selTournament(population, k=evo_params.pop_lambda, tournsize=evo_params.tourn_size) # offsprings: List[ecu.OptIndividual] = list(map(copy.deepcopy, chosen)) # # Perform the crossover (mating) among the offsprings # for o1, o2 in zip(offsprings[::2], offsprings[1::2]): # if random.random() < evo_params.pcx: # ecu.crossover_strength(o1, o2) # # Mutate some of the offsprings # for o in offsprings: # ecu.mutate_strength(o, evo_params.pmut) # # Recalculate the fitness for offsprings that have changed # for ind in [o for o in offsprings if not o.fitness.valid]: # ind.fitness.values = ev.evaluate( # None, None, strength=ind.str_map, **apply_params # )[0], # # Select 'mu' best offsprings and make them the new population # population[:] = tools.selBest(offsprings, evo_params.pop) # hof.update(population) # print(f'Gen {g}: fitness={hof[0].fitness:.2f}; str=[{",".join(hof[0].str_map.values())}]') # # Re-evaluate the solutions to contain the all-time best results # ev.evaluate(None, None, strength=hof[0].str_map, **apply_params) # return hof[0] # finally: # # Make sure we remove the created FitnessMax class when multiple algorithms # # are run back to back in one session # del creator.FitnessMax def opt_es_plus( solutions: sol.SolutionSet, evo_params: EvolutionParameters, apply_func: sol.ApplySignature, fitness_func: sol.FitnessSignature, workers: int, **apply_params: Union[int, float] ) -> ecu.OptIndividual: """ TODO: doc """ evo_params.update_defaults({ 'pop_lambda': evo_params.pop * 2 }) hof = ecu.BestTracker() creator.create('FitnessMax', base.Fitness, weights=(1.0,)) str_limits = solutions.get_strength_limits() sol_count = len(solutions) opt_goal = next(iter(solutions)).result.opt_goal try: # Create an evaluator context that handles the multiprocess / single process evaluation with evaluator.Evaluator(workers, solutions, apply_func, fitness_func) as ev: # Initialize the population population = [ ecu.OptIndividual(str_limits, creator.FitnessMax()) for _ in range(evo_params.pop) ] # Evaluate the initial population for ind in population: # Make it tuple of one element ind.fitness.values = ev.evaluate( None, None, strength=ind.str_map, **apply_params )[0], hof.update(population) for g in range(evo_params.gen): gen_best = ecu.BestTracker() # Randomly select 'lambda' parents and deepcopy them => offsprings offsprings: List[ecu.OptIndividual] = list( map(copy.deepcopy, random.choices(population, k=evo_params.pop_lambda)) ) # Mutate some of the offsprings for o in offsprings: ecu.mutate_strength(o) # Recalculate the fitness for offsprings that have changed for ind in [o for o in offsprings if not o.fitness.valid]: ind.fitness.values = ev.evaluate( None, None, strength=ind.str_map, **apply_params )[0], # Select 'mu' best individuals and make them the new population population[:] = tools.selBest(population + offsprings, evo_params.pop) hof.update(population) gen_best.update(population) best = gen_best.get_best() ev.evaluate(None, None, strength=best.str_map, **apply_params) # Gen, goal, fitness, data_ratio, time_ratio r_time, r_data = 0.0, 0.0 for sol in solutions: r_time += sol.result.time_ratio r_data += sol.result.data_ratio glob_logger.add_record( (g, opt_goal, best.fitness.values[0], best.get_str(), r_data / sol_count, r_time / sol_count) ) # print( # f'Gen {g}: fitness={best.fitness.values[0]}; '\ # f'str=[{",".join(map(str, best.str_map.values()))}]' # ) # Re-evaluate the solutions to contain the all-time best results ev.evaluate(None, None, strength=hof.get_best().str_map, **apply_params) best = hof.get_best() print("Strength legend: [CGP, SB, DT, DB, DS]") print( f'ALL TIME BEST: fitness={best.fitness.values[0]}; '\ f'str=[{",".join(map(str, best.str_map.values()))}]' ) print(best.str_map) for sol in solutions: print(f'[{sol.workload.name}]({sol.result.opt_goal}); Time ratio: {sol.result.time_ratio:.8f}; Data ratio: {sol.result.data_ratio:.8f}') sol.result.print_effect() return hof.get_best() finally: # Make sure we remove the created FitnessMax class when multiple algorithms # are run back to back in one session del creator.FitnessMax def opt_es_comma( solutions: sol.SolutionSet, evo_params: EvolutionParameters, apply_func: sol.ApplySignature, fitness_func: sol.FitnessSignature, workers: int, **apply_params: Union[int, float] ) -> ecu.OptIndividual: """ TODO: doc """ evo_params.update_defaults({ 'pop_lambda': evo_params.pop * 2 }) hof = ecu.BestTracker() creator.create('FitnessMax', base.Fitness, weights=(1.0,)) str_limits = solutions.get_strength_limits() sol_count = len(solutions) opt_goal = next(iter(solutions)).result.opt_goal try: # Create an evaluator context that handles the multiprocess / single process evaluation with evaluator.Evaluator(workers, solutions, apply_func, fitness_func) as ev: # Initialize the population population = [ ecu.OptIndividual(str_limits, creator.FitnessMax()) for _ in range(evo_params.pop) ] # Evaluate the initial population for ind in population: # Make it tuple of one element ind.fitness.values = ev.evaluate( None, None, strength=ind.str_map, **apply_params )[0], hof.update(population) for g in range(evo_params.gen): gen_best = ecu.BestTracker() # Randomly select 'lambda' parents and deepcopy them => offsprings offsprings: List[ecu.OptIndividual] = list( map(copy.deepcopy, random.choices(population, k=evo_params.pop_lambda)) ) # Mutate some of the offsprings for o in offsprings: ecu.mutate_strength(o) # Recalculate the fitness for offsprings that have changed for ind in [o for o in offsprings if not o.fitness.valid]: ind.fitness.values = ev.evaluate( None, None, strength=ind.str_map, **apply_params )[0], # Select 'mu' best individuals and make them the new population population[:] = tools.selBest(offsprings, evo_params.pop) hof.update(population) gen_best.update(population) best = gen_best.get_best() ev.evaluate(None, None, strength=best.str_map, **apply_params) # Gen, goal, fitness, data_ratio, time_ratio r_time, r_data = 0.0, 0.0 for sol in solutions: r_time += sol.result.time_ratio r_data += sol.result.data_ratio glob_logger.add_record( (g, opt_goal, best.fitness.values[0], best.get_str(), r_data / sol_count, r_time / sol_count) ) # print( # f'Gen {g}: fitness={best.fitness.values[0]}; '\ # f'str=[{",".join(map(str, best.str_map.values()))}]' # ) # Re-evaluate the solutions to contain the all-time best results ev.evaluate(None, None, strength=hof.get_best().str_map, **apply_params) best = hof.get_best() print("Strength legend: [CGP, SB, DT, DB, DS]") print( f'ALL TIME BEST: fitness={best.fitness.values[0]}; '\ f'str=[{",".join(map(str, best.str_map.values()))}]' ) print(best.str_map) for sol in solutions: print(f'[{sol.workload.name}]({sol.result.opt_goal}); Time ratio: {sol.result.time_ratio:.8f}; Data ratio: {sol.result.data_ratio:.8f}') sol.result.print_effect() return hof.get_best() finally: # Make sure we remove the created FitnessMax class when multiple algorithms # are run back to back in one session del creator.FitnessMax def basic_ea( solutions: sol.SolutionSet, evo_params: EvolutionParameters, apply_func: sol.ApplySignature, fitness_func: sol.FitnessSignature, workers: int, **apply_params: Union[int, float] ) -> Tuple[float, float]: """ Evolutionary algorithm for solving the 'basic' variants of the initial sampling function where we tune only the 'base' parameter. Heavily inspired by 'https://deap.readthedocs.io/en/master/overview.html'. :param solutions: a collection of solutions, one for each workload being solved :param evo_params: the supplied parameters for the evolution process :param apply_func: function to use for genotype -> fenotype mapping :param fitness_func: function to use for fitness evaluation :param workers: number of worker processes :param apply_params: additional parameters for the apply function :return: the best individual and its fitness value """ # First make sure that we have all the parameters we need evo_params.update_defaults({ 'attr_low': 0.0, 'attr_high': 100.0, 'cx_eta': 2.0, 'mut_eta': 2.0, 'mut_mu': 1, 'mut_sigma': 5, 'tourn_size': 3 }) # Store the all-time best individual hof = tools.HallOfFame(1) # Create maximization fitness and an individual class creator.create('FitnessMax', base.Fitness, weights=(1.0,)) creator.create('Individual', list, fitness=creator.FitnessMax) try: # Create an evaluator context that handles the multiprocess / single process evaluation with evaluator.Evaluator(workers, solutions, apply_func, fitness_func) as ev: # Set the individual and population initializers toolbox = base.Toolbox() toolbox.register( 'attribute', random.uniform, evo_params.attr_low, evo_params.attr_high ) toolbox.register( 'individual', tools.initRepeat, creator.Individual, toolbox.attribute, n=1 ) toolbox.register( 'population', tools.initRepeat, list, toolbox.individual ) # Set the evolution operators: crossover, mutation, selection # The evaluation will be performed by the evaluator toolbox.register( 'mate', tools.cxSimulatedBinary, eta=evo_params.cx_eta ) toolbox.register( 'mutate', tools.mutGaussian, mu=evo_params.mut_mu, sigma=evo_params.mut_sigma, indpb=evo_params.pmut ) toolbox.register( 'select', tools.selTournament, tournsize=evo_params.tourn_size, k=evo_params.pop - 1 ) # Evaluate fitness of the initial random population pop = toolbox.population(evo_params.pop) for ind in pop: ind.fitness.values = tuple(ev.evaluate(None, None, base=ind[0], **apply_params)) hof.update(pop) # Run all the generations for g in range(evo_params.gen): print(f'Generation: {g}') # Create new offsprings, always include the all-time best solution # The cloning is necessary since crossover and mutations work in-situ offsprings = list(map(toolbox.clone, toolbox.select(pop))) + [toolbox.clone(hof[0])] # Perform the crossover (mating) among the offsprings for o1, o2 in zip(offsprings[::2], offsprings[1::2]): if random.random() < evo_params.pcx: toolbox.mate(o1, o2) del o1.fitness.values del o2.fitness.values # Additionally mutate some of the new offsprings for mutant in offsprings: toolbox.mutate(mutant) del mutant.fitness.values # Recalculate the fitness for the modified offsprings (mating, mutation) for ind in [o for o in offsprings if not o.fitness.valid]: ind.fitness.values = tuple(ev.evaluate(None, None, base=ind[0], **apply_params)) # Update the population and all-time best pop[:] = offsprings hof.update(pop) # Re-evaluate the solutions to contain the all-time best results ev.evaluate(None, None, base=hof[0][0], **apply_params) return hof[0][0], hof[0].fitness.values[0] finally: # Make sure we remove the created Individual and Fitness classes when multiple algorithms # are run back to back in one session del creator.Individual del creator.FitnessMax
JiriPavela/perun-optimization-evolution
src/evolution/ec.py
ec.py
py
19,236
python
en
code
0
github-code
36
[ { "api_name": "typing.Any", "line_number": 48, "usage_type": "name" }, { "api_name": "typing.Dict", "line_number": 65, "usage_type": "name" }, { "api_name": "typing.Any", "line_number": 65, "usage_type": "name" }, { "api_name": "typing.Any", "line_number": 75,...
5603106879
import discord from utils.auth import AuthManager class Account(discord.Cog): @discord.slash_command(name="register", description="Register using your discord username") async def register(self, ctx): AuthManager.registerGuild(ctx.author) AuthManager.registerUser(ctx.author) await ctx.response.send_message(content=AuthManager.signUp(ctx.author), ephemeral=True) def setup(bot): # this is called by Pycord to setup the cog bot.add_cog(Account(bot)) # add the cog to the bot
liang799/rivenDealer
cogs/account.py
account.py
py
517
python
en
code
1
github-code
36
[ { "api_name": "discord.Cog", "line_number": 5, "usage_type": "attribute" }, { "api_name": "utils.auth.AuthManager.registerGuild", "line_number": 8, "usage_type": "call" }, { "api_name": "utils.auth.AuthManager", "line_number": 8, "usage_type": "name" }, { "api_nam...
73881856745
import sys import os from numpy.lib.arraysetops import isin from argparse import ArgumentParser sys.path.insert(1, './tendims') sys.path.insert(2, './complexity') sys.path.insert(3, './sentiment') sys.path.insert(4, './empathy') import logging import json import numpy as np import wget import pickle import oyaml as yaml from flask import Flask, request, redirect , jsonify, send_file, send_from_directory, safe_join, abort from flask.json import JSONEncoder from flask_cors import CORS from flask_socketio import SocketIO, send, emit import uuid import pandas as pd from cryptography.fernet import Fernet from complexity import ComplexityClassifier from sentiment import SentimentClassifier from success import SuccessPredictor from tendims import TenDimensionsClassifier from empathy import empathy_processing from werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage from dh_encryption import DiffieHellman, decrypt_data, encrypt_data, decrypt_file, encrypt_file import sys import urllib import urllib.request from cryptography.fernet import Fernet import base64 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC class CustomJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() return JSONEncoder.default(self, obj) class Engine(): class Models: All = "all" Sentiment = "sentiment" TenDims = "tendims" Success = "success" Complexity = "complexity" Empathy = "empathy" def register_model(self, model_name, model_fun): self.models_map[model_name] = model_fun def get_model_methods(self, model_name): fun_list = [] if model_name == Engine.Models.All: fun_list = list(self.models_map.values()) else: fun_list = self.models_map[model_name] return fun_list def __init__(self, logger, load_ten_dims=True): self.models_map = {} self.ip_keys_dict = {} self.using_encryption = True self.no_key_error_msg = 'Connection is not secure, request a shared key first' self.wrong_key_error_msg = 'The shared key is not the same' self.dh = DiffieHellman() #### Complexity Models #### logger.info('Loading complexity models...') self.ic_model_file = 'complexity/models/Vocab+FullPOS_xbgoost.model' self.liwc_dictionary_file = 'complexity/data/LIWC2007_English100131.dic' self.model_complexity = ComplexityClassifier(self.ic_model_file, self.liwc_dictionary_file) self.register_model(Engine.Models.Complexity, self.get_complexity) logger.info('Complexity models loaded') ##################### # #### Ten Dimensions Models #### if load_ten_dims: logger.info('Loading tenDims models...') self.models_dir = 'tendims/models/lstm_trained_models' self.embeddings_dir = 'tendims/embeddings' # change urls to embeddings dir self.success_model_file = 'tendims/models/meeting_success/xgboost_10dims_success_prediction_model_v0.81.dat' # Success is not available self.model_tendim = TenDimensionsClassifier(models_dir=self.models_dir, embeddings_dir=self.embeddings_dir) self.success_predictor = SuccessPredictor(self.success_model_file) # Sucess prediction self.register_model(Engine.Models.TenDims, self.get_ten_dims) logger.info('Tend dims models loaded') ##################### # self.empathy_model_file = './empathy/models/Vocab+FullPOS+LIWCtrained_XGboost_model_99perc.pickle' # self.empathy_ic_model_file = './empathy/models/Vocab+FullPOS_xbgoost.pickle' # self.empathy_scorer = empathy_processing.EmpathyScorer(self.empathy_model_file, self.empathy_ic_model_file) # self.register_model(Engine.Models.Empathy, self.empathyIC_from_texts) ##################### #### Sentiment Models #### logger.info('Loading sentiment model...') self.model_sentim = SentimentClassifier() self.register_model(Engine.Models.Sentiment, self.get_sentiment) logger.info('Sentiment models loaded') ##################### def generate_keys(self, ip_address, logger): self.ip_keys_dict[ip_address] = {} client_private_key, client_public_key = self.dh.get_private_key(), self.dh.gen_public_key() server_private_key, server_public_key = self.dh.get_private_key(), self.dh.gen_public_key() self.ip_keys_dict[ip_address]["client"] = {"private_key": client_private_key, "public_key": client_public_key} self.ip_keys_dict[ip_address]["server"] = {"private_key": server_private_key, "public_key": server_public_key} return {"private_key": client_private_key, "public_key": client_public_key, 'server_public_key':server_public_key} def generate_shared_keys(self, ip_address, local_private_key, remote_public_key, logger): client_shared_key = DiffieHellman.gen_shared_key_static(local_private_key, remote_public_key) server_shared_key = DiffieHellman.gen_shared_key_static(self.ip_keys_dict[ip_address]["server"]["private_key"], self.ip_keys_dict[ip_address]["server"]["public_key"]) self.ip_keys_dict[ip_address]["client"]["shared_key"] = client_shared_key self.ip_keys_dict[ip_address]["server"]["shared_key"] = server_shared_key return client_shared_key # https://dev.to/ruppysuppy/implementing-end-to-end-encryption-in-your-cross-platform-app-3a2k # https://dev.to/ruppysuppy/implementing-end-to-end-encryption-in-your-cross-platform-app-part-2-cgg def check_request_key(self, ip_address, logger): if ip_address not in self.ip_keys_dict: logger.error(self.no_key_error_msg) return 400, self.no_key_error_msg elif "shared_key" not in self.ip_keys_dict[ip_address]["server"] or "shared_key" not in self.ip_keys_dict[ip_address]["client"]: logger.error(self.wrong_key_error_msg) return 400, self.wrong_key_error_msg return 200, None def encrypt_decrypt_file(self, ip_address, folder, filename, logger, new_prefix="", decrypt=False): code, error_text = self.check_request_key(ip_address, logger) if code >= 400: return code, error_text try: with open(os.path.join(folder, filename), 'rb') as enc_file: file_data = enc_file.read() if self.using_encryption: temp_filename = new_prefix+'_temp_file_data.csv' client_shared_key = self.ip_keys_dict[ip_address]["client"]["shared_key"] if decrypt: new_data = decrypt_file(file_data, client_shared_key) else: new_data = encrypt_file(file_data, client_shared_key) with open(os.path.join(folder, temp_filename), 'wb') as dec_file: dec_file.write(new_data) try: os.remove(os.path.join(folder, filename)) except: print(f"Error removing file {filename}") filename = temp_filename if decrypt: logger.debug(f"\n\nReceived encrypted File, decrypted using {ip_address} key {client_shared_key}") else: logger.debug(f"\n\nFile Encrypted using {ip_address} key {client_shared_key}") else: logger.debug(f"\n\n: Received non encrypted File from {ip_address}") return 200, filename except Exception as e: error_text = f"\n\n Something went wrong while decrypting/encrypting the file {filename}: {e}" logger.error(error_text) return 400, error_text def get_decrypted_text(self, ip_address, text, method, logger): code, error_text = self.check_request_key(ip_address, logger) if code >= 400: return code, error_text try: if engine.using_encryption: client_shared_key = engine.ip_keys_dict[ip_address]["client"]["shared_key"] text = decrypt_data(text, client_shared_key) logger.debug(f"\n\n{method}: Received encrypted Text, decrypted using {ip_address} key {client_shared_key}: {text}") else: logger.debug(f"\n\n{method}: Received plain Text from {ip_address}: {text}") return 200, text except Exception as e: error_text = f"\n\n{method}: Something went wrong while getting the request's text {e}" logger.error(error_text) return 400, error_text def get_ten_dims(self, text, logger): if USE_TEN_DIMS: # you can give in input one string of text # dimensions = None extracts all dimensions tendim_scores = engine.model_tendim.compute_score(text, dimensions=None) success_probability = engine.success_predictor.predict_success(tendim_scores) tendim_scores['success'] = float(success_probability) else: tendim_scores = {'conflict': 0, 'fun': 0, 'identity': 0, 'knowledge': 0, 'power': 0, 'romance': 0, 'similarity': 0, 'status': 0, 'support': 0, 'trust': 0} tendim_scores['success'] = 0 return tendim_scores def get_sentiment(self, text, logger): return self.model_sentim.get_sentiment(text) def get_complexity(self, text, logger): return self.model_complexity.get_complexity(text) def get_empathy(self, text, logger): avg_empathy, avg_ic, scored_text_list = engine.empathy_scorer.empathyIC_from_texts(text) return {'Average_Empathy': avg_empathy , 'Average_IC':avg_ic} def calculate_stats(self, texts, text_ids, stat_method, logger): if not isinstance(stat_method, list): stat_method = [stat_method] returnAll = [] for txt, txt_id in zip(texts,text_ids): return_data = {} return_data["server_text_id"] = txt_id # return_data["server_text_data"] = str(txt) for stat_fun in stat_method: return_data.update(stat_fun(txt, logger)) returnAll.append(return_data) return returnAll def call_model_from_text(self, ip_address, text, no_encryption, method, logger): try: logger.debug(f"Text Getting decrypted text") if not isinstance(text, list): text = [text] retCode = 200 if not no_encryption: retCode, text = engine.get_decrypted_text(ip_address, text, method, logger) if retCode == 200: text_id = range(0, len(text)) ret = engine.calculate_stats(text, text_id, self.get_model_methods(method), logger) return ret, retCode else: error_msg = f"\n\nText {method}: Something went wrong while calculating {method} stats. Code: {retCode}" logger.error(f"Error {retCode}\n{error_msg}\n{text}") return {"message": error_msg, "error_info":text, "status": retCode}, retCode except Exception as e: logger.error(f"Exception in Text {method}:{e}") return {"message": f"Internal Server Error in Text {method}", "error_info":str(e), "status": 500}, 500 def call_model_from_request(self, flask_request, method, logger): try: text = flask_request.form.getlist('text') if len(text) <= 0: text = [flask_request.form.get('text')] no_encryption = flask_request.form.get('no_encryption', False) retCode = 200 if not no_encryption: retCode, text = engine.get_decrypted_text(flask_request.remote_addr, text, method, logger) text_id = flask_request.form.getlist('id') if len(text_id) <= 0: text_id = [flask_request.form.get('id')] logger.info(f"Text stats request from {flask_request.remote_addr}. Encrypted: {not no_encryption}. List len: {len(text)}") if retCode == 200: ret = engine.calculate_stats(text, text_id, self.get_model_methods(method), logger) return ret, retCode else: error_msg = f"\n\nRequest {method}: Something went wrong while calculating {method} stats. Code: {retCode}" logger.error(f"Error {retCode}\n{error_msg}\n{text}") return {"message": error_msg, "error_info":text, "status": retCode}, retCode except Exception as e: logger.error(f"Exception in Request {method}:{e}") return {"message": f"Internal Server Error in Request {method}", "error_info":str(e), "status": 500}, 500 def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS parser = ArgumentParser() parser.add_argument('-c', nargs='?', const="config.yaml", type=str) args = parser.parse_args() config_filename = args.c # config_filename = "config5000.yaml" global config try: config = yaml.safe_load(open(config_filename)) except: config = {} UPLOAD_FOLDER = config.get("upload_folder", './uploaded_files/') ALLOWED_EXTENSIONS = config.get("allowed_extensions", {'csv', 'txt', 'dat', 'json'}) IP = config.get("ip", "0.0.0.0") PORT = config.get("port", 5000) USE_TEN_DIMS = config.get("use_ten_dims", True) LOG_FILENAME = config.get("log_filename", "flask_log.log") app = Flask(__name__) with open(LOG_FILENAME, 'w'): pass handler = logging.FileHandler(LOG_FILENAME) # Create the file logger app.logger.addHandler(handler) # Add it to the built-in logger app.logger.setLevel(logging.DEBUG) # Set the log level to debug app.json_encoder = CustomJSONEncoder app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER socketio = SocketIO(app) engine = Engine(app.logger, USE_TEN_DIMS) @app.route("/request-keys", methods=["GET"]) def request_keys(): method = "Request Keys" try: retCode = 200 ip_address = request.remote_addr keys_dict = engine.generate_keys(ip_address, app.logger) keys_dict["status"] = retCode return jsonify(keys_dict), retCode except Exception as e: app.logger.error(f"Exception in {method}:{e}") return jsonify({"message": f"Internal Server Error in {method}", "error_info":str(e), "status": 500}), 500 @app.route("/request-shared-key", methods=["GET"]) def request_shared_key(): method = "Request Shared Key" try: retCode = 200 ip_address = request.remote_addr try: local_private_key = request.args.get("local_private_key") remote_public_key = request.args.get("remote_public_key") client_shared_key = engine.generate_shared_keys(ip_address, local_private_key, remote_public_key, app.logger) except Exception as e: retCode = 400 return jsonify({"message": "Invalid shared key", "error_info":str(e), "status": retCode}), retCode return jsonify({"shared_key": client_shared_key, "status": retCode}), retCode except Exception as e: app.logger.error(f"Exception in {method}:{e}") return jsonify({"message": f"Internal Server Error in {method}", "error_info":str(e), "status": 500}), 500 @app.route("/getStats", methods=['POST']) def getStats(): ret_data, code = engine.call_model_from_request(request, Engine.Models.All, app.logger) return jsonify(ret_data), code @app.route("/getStatsFile", methods=['POST']) def getStatsFile(): no_encryption = str(request.form.get('no_encryption')) != "False" # No clue why the boolean is returned as a string... But just in case I converted it to a string every time # check if the post request has the file part if 'file' not in request.files: return jsonify({"message": f"No file submitted", "error_info":f"No file submitted", "status": 400}), 400 file = request.files['file'] # If the user does not select a file, the browser submits an empty file without a filename. if file.filename == '': return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) if not no_encryption: code, filename = engine.encrypt_decrypt_file(request.remote_addr, UPLOAD_FOLDER, filename, app.logger, new_prefix="decrypted", decrypt=True) txt_col = request.form["txt_col_name"] amount = int(request.form.get("amount", 0)) data_df = pd.read_csv(os.path.join(app.config['UPLOAD_FOLDER'], filename)) try: os.remove(os.path.join(app.config['UPLOAD_FOLDER'], filename)) except: print(f"Error removing file {filename}") # remove file data_df["idx"] = range(0,len(data_df)) app.logger.info(f"File stats request from {request.remote_addr}. Encrypted: {not no_encryption}. Row col: {txt_col}, limit: {amount}, rows: {len(data_df)}") output_filename = os.path.splitext(filename)[0] output_filename = UPLOAD_FOLDER+output_filename+"_pandas_res.csv" initialized = False for index, row in data_df.iterrows(): ret_data, code = engine.call_model_from_text(request.remote_addr, str(row[txt_col]), True, Engine.Models.All, app.logger) if code == 200 : for key, value in ret_data[0].items(): if not initialized: data_df[key] = 0 if type(value) == int or float else "" initialized = True data_df.at[index, key] = value else: app.logger.error(f"{ret_data}\t{index}\t{row[txt_col]}") if amount > 0 and index >= amount: break data_df.to_csv(output_filename) if not no_encryption: code, output_filename = engine.encrypt_decrypt_file(request.remote_addr, UPLOAD_FOLDER, output_filename, app.logger, new_prefix="encrypted", decrypt=False) try: return send_file(output_filename, attachment_filename=output_filename+"_pandas_res.csv") except Exception as e: app.logger.error(f"Exception in files stats:{e}") return jsonify({"message": f"Internal Server Error in files stats", "error_info":str(e), "status": 500}), 500 @app.route("/tenDimensions", methods=['POST']) def tenDimensions(): ret_data, code = engine.call_model_from_request(request, Engine.Models.TenDims, app.logger) return jsonify(ret_data), code @app.route("/complexity", methods=['POST']) def complexity(): ret_data, code = engine.call_model_from_request(request, Engine.Models.Complexity, app.logger) return jsonify(ret_data), code @app.route("/sentiment", methods=['POST']) def sentiment(): ret_data, code = engine.call_model_from_request(request, Engine.Models.Sentiment, app.logger) return jsonify(ret_data), code @app.route("/empathy", methods=['GET']) def empathy(): ret_data, code = engine.call_model_from_request(request, Engine.Models.Sentiment, app.logger) return jsonify(ret_data), code @socketio.on('json') def handle_json(json): app.logger.info('received json: ' + str(json)) # data = engine.call_model(json, "All", app.logger) send(json.dumps({"test":0}), json=True) @socketio.on('message') def handle_message(message): app.logger.info('received message: ' + str(message)) send(message) if __name__ == '__main__': CORS(app) app.run(host="0.0.0.0",port=5000,threaded=True) socketio.run(app) app.run() # Run gunicorn # sudo nohup sudo gunicorn3 --workers 30 --timeout 0 --bind 0.0.0.0:5000 wsgi:app & # sudo nohup sudo gunicorn3 --threads 100 --timeout 0 --bind 0.0.0.0:5000 wsgi:app & # sudo pkill -P [PID] # ps -ef | grep gun
Gabryxx7/nlp-flask-server
nlp_flask_server.py
nlp_flask_server.py
py
20,471
python
en
code
2
github-code
36
[ { "api_name": "sys.path.insert", "line_number": 5, "usage_type": "call" }, { "api_name": "sys.path", "line_number": 5, "usage_type": "attribute" }, { "api_name": "sys.path.insert", "line_number": 6, "usage_type": "call" }, { "api_name": "sys.path", "line_numbe...
33403799483
import os.path import bitarray # Класс создан для хранения предыдущего блока и ксора переданного с предудущим для последующего сохранения class CBCEncrypter: def __init__(self, init_key: bitarray.bitarray) -> None: super().__init__() # Ключ инициализации self.key = init_key self.prev_block: bitarray.bitarray = None def save_block(self, block): self.prev_block = block def xor_block(self, block: bitarray.bitarray): if self.prev_block is None: return block ^ self.key else: res = block ^ self.prev_block self.prev_block = block return res class CBCDecrypter: def __init__(self, init_key: bitarray.bitarray) -> None: super().__init__() # Ключ инициализации self.key = init_key self.prev_block: bitarray.bitarray = None self.lazy_block = None def save_lazy_block(self, block): self.lazy_block = block def xor_block(self, block: bitarray.bitarray): if self.prev_block is None: self.prev_block = self.lazy_block return block ^ self.key else: res = block ^ self.prev_block self.prev_block = self.lazy_block return res def read_file_to_bit_arr(filename: str) -> bitarray: """ Считывание файла в битовый массив :param filename: имя файла :return: битовый массив текста с файла """ filesize = os.path.getsize(filename) with open(filename, 'rb') as f: bit_arr = bitarray.bitarray(1) bit_arr.fromfile(f, filesize) return bit_arr[1:] pass def write_bit_arr_to_file(crypto_msg, filename='output.crypto'): with open(filename, 'wb') as f: f.write(crypto_msg) def read_key(filename: str) -> bitarray: """ Считывание ключа из файла. Ожидается, что ключ 64 битный (8 байт) :param filename: имя файла :return: битовый массив ключа """ filesize = os.path.getsize(filename) with open(filename, 'rb') as f: bit_arr = bitarray.bitarray(1) bit_arr.fromfile(f, filesize) return bit_arr[1:] def ror(value: bitarray, shift: int) -> bitarray: """ Циклический битовый сдвиг вправо :param value: битовый массив :param shift: значение сдвига :return: измененный битовый массив """ shift = shift % len(value) right = value[:shift] left = value[:-shift] return right + left pass def rol(value: bitarray, shift: int) -> bitarray: """ Циклический битовый сдвиг влево :param value: битовый массив :param shift: значение сдвига :return: измененный битовый массив """ shift = shift % len(value) left = value[:shift] right = value[shift:] return right + left pass def gen_key_vector(secret_key: bitarray, round_col: int): res = [] for i in range(round_col): step1 = rol(secret_key, i * 3) step2 = bitarray.bitarray(32) pointer = 0 for i, elem in enumerate(step1): if i % 2 == 1: step2[pointer] = elem pointer += 1 step3 = step2[16:] res.append(step3) return res pass def encrypt(msg, init_key, iv, round_cols=1, block_size=64, minimum_bits_block=16): """ Функция шифрования сообщиения :param minimum_bits_block: размер минимального блока для шифрования (кратно 8) :param block_size: размер блока для шифрования (кратно minimum_bytes_block) :param msg: сообщение для шифровки :param init_key: стартовый ключ для шифования :param round_cols: количество раундов шифрования :return: зашифрованное сообщение """ # Добивка последнего блока до 64 битов if minimum_bits_block % 8 != 0 or block_size % minimum_bits_block != 0: raise Exception("Неверные размеры блоков для шифрования!!!") tail_cell_size = len(msg) % block_size if tail_cell_size != 0: msg += '0' * (block_size - tail_cell_size) block_col = len(msg) // block_size crypto_msg = bitarray.bitarray(0) key_vec = gen_key_vector(init_key, round_cols) cbc = CBCEncrypter(iv) for round_num in range(round_cols): for block_num in range(block_col): start = block_num * block_size end = block_num * block_size + block_size block = msg[start:end] # Реализация CBC block = cbc.xor_block(block) # Блок, разбитый на 4 подблока blocks = [block[i * minimum_bits_block: i * minimum_bits_block + minimum_bits_block] for i in range(4)] del block res_block = [None for i in range(4)] res_block[0] = blocks[1] res_block[1] = blocks[2] ^ blocks[0] res_block[2] = ((blocks[1] ^ key_vec[round_num]) ^ blocks[3]) ^ (blocks[2] ^ blocks[0]) res_block[3] = blocks[0] res = bitarray.bitarray(0) for r in res_block: res += r cbc.save_block(res) crypto_msg += res msg = crypto_msg return msg def decrypt(crypto_msg, init_key, iv, round_cols=1, block_size=64, minimum_bits_block=16, clear_output=True): """ :param crypto_msg: зашифрованное сообщение :param init_key: начальный ключ инициализации :param round_cols: количество раундов :param block_size: размер блока для шифрования (кратен minimum_bits_block) :param minimum_bits_block: минимальный блок кодирования (кратен 8) :param clear_output: очищает вывод от NULL байтов (есть возможность выключить, если сообщение их намеренно содежит) :return: """ if minimum_bits_block % 8 != 0 or block_size % minimum_bits_block != 0: raise Exception("Неверные размеры блоков для шифрования!!!") tail_cell_size = len(crypto_msg) % block_size if tail_cell_size != 0: crypto_msg += '0' * (block_size - tail_cell_size) block_col = len(crypto_msg) // block_size decrypt_msg = bitarray.bitarray(0) key_vec = gen_key_vector(init_key, round_cols) cbc = CBCDecrypter(iv) for round_num in range(round_cols): for block_num in range(block_col): start = block_num * block_size end = block_num * block_size + block_size block = crypto_msg[start:end] cbc.save_lazy_block(block) # Блок, разбитый на 4 подблока blocks = [block[i * minimum_bits_block: i * minimum_bits_block + minimum_bits_block] for i in range(4)] res_block = [None for i in range(4)] res_block[0] = blocks[3] res_block[1] = blocks[0] res_block[2] = blocks[1] ^ blocks[3] res_block[3] = (blocks[2] ^ blocks[1]) ^ (key_vec[round_num] ^ blocks[0]) res = bitarray.bitarray(0) for r in res_block: res += r res = cbc.xor_block(res) decrypt_msg += res crypto_msg = decrypt_msg decrypt_msg = bitarray.bitarray(0) decrypt_msg = [crypto_msg[i * 8: i * 8 + 8] for i in range(len(crypto_msg) // 8)] NULL = bitarray.bitarray('0' * 8) while bitarray.bitarray(NULL) in decrypt_msg: decrypt_msg.remove(NULL) crypto_msg = bitarray.bitarray(0) for partition in decrypt_msg: crypto_msg += partition return crypto_msg pass def get_iv(data: str): iv = bitarray.bitarray(1) iv.frombytes(data.encode()) return iv[1:] if __name__ == '__main__': f = open('iv.txt') iv_v = f.readline() iv_data = get_iv(iv_v) key = read_key('./key.txt') crypto = read_file_to_bit_arr('./flag.bin') new_text = decrypt(crypto, key, iv_data) print("Шифротекст: ", new_text) write_bit_arr_to_file(new_text, 'decrypt_message.txt') pass
remoppou/CTF
crypto/Feistel-song/solution/solve.py
solve.py
py
8,778
python
ru
code
0
github-code
36
[ { "api_name": "bitarray.bitarray", "line_number": 8, "usage_type": "attribute" }, { "api_name": "bitarray.bitarray", "line_number": 12, "usage_type": "attribute" }, { "api_name": "bitarray.bitarray", "line_number": 17, "usage_type": "attribute" }, { "api_name": "b...
36570521283
import json import math import re import os import boto import tinys3 import random from django.shortcuts import render, redirect from django.http.response import HttpResponse, HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.conf import settings from django.utils import timezone from datetime import date, datetime from django.db.models import Q, F, Case, When, Value from django.urls import reverse from django.template import loader, Template, Context from django.db.models import Count from django.core import serializers from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from django.contrib.auth import authenticate, login from django.utils.crypto import get_random_string from django.template.defaultfilters import slugify from django.http import QueryDict from django.contrib.auth import load_backend from mpcomp.views import ( jobseeker_login_required, get_prev_after_pages_count, get_valid_skills_list, get_meta_data, get_valid_locations_list, get_social_referer, get_resume_data, handle_uploaded_file, get_valid_qualifications, get_meta, get_ordered_skill_degrees, get_404_meta, ) from peeldb.models import ( JobPost, AppliedJobs, MetaData, User, City, Industry, Skill, Subscriber, VisitedJobs, State, TechnicalSkill, Company, UserEmail, Qualification, ) from pjob.calendar_events import ( create_google_calendar_event, get_calendar_events_list, delete_google_calendar_event, get_service, ) from psite.forms import ( SubscribeForm, UserEmailRegisterForm, UserPassChangeForm, AuthenticationForm, ForgotPassForm, ) from .refine_search import refined_search from django.db.models import Prefetch from django.core.cache import cache from dashboard.tasks import save_search_results, send_email months = [ {"Name": "Jan", "id": 1}, {"Name": "Feb", "id": 2}, {"Name": "Mar", "id": 3}, {"Name": "Apr", "id": 4}, {"Name": "May", "id": 5}, {"Name": "Jun", "id": 6}, {"Name": "Jul", "id": 7}, {"Name": "Aug", "id": 8}, {"Name": "Sep", "id": 9}, {"Name": "Oct", "id": 10}, {"Name": "Nov", "id": 11}, {"Name": "Dec", "id": 12}, ] def get_page_number(request, kwargs, no_pages): page = request.POST.get("page") or kwargs.get("page_num", 1) try: page = int(page) if page == 1 or page > 0 and page < (no_pages + 1): page = page else: page = False except: page = False return page def get_next_year(year, current_year): if year == current_year + 1: return "" return year + 1 def get_prev_year(year, current_year): if year == current_year - 1: return "" return year - 1 def get_next_month(month, year, current_year): if month["id"] == 12: if get_next_year(year, current_year): return next((item for item in months if item["id"] == 1), None) return "" return next((item for item in months if item["id"] == month["id"] + 1), None) def get_prev_month(month, year, current_year): if month["id"] == 1: if get_prev_year(year, current_year): return next((item for item in months if item["id"] == 12), None) return "" return next((item for item in months if item["id"] == month["id"] - 1), None) def subscribers_creation_with_skills(email, skill, user): subscribers = Subscriber.objects.filter(email=email, user=None, skill=skill) if subscribers: for each in subscribers: if user: sub = Subscriber.objects.create( email=each.email, skill=each.skill, user=user ) while True: unsubscribe_code = get_random_string(length=15) if not Subscriber.objects.filter( unsubscribe_code__iexact=unsubscribe_code ): break while True: subscribe_code = get_random_string(length=15) if not Subscriber.objects.filter( subscribe_code__iexact=unsubscribe_code ): break sub.subscribe_code = subscribe_code sub.unsubscribe_code = unsubscribe_code sub.save() each.delete() else: while True: unsubscribe_code = get_random_string(length=15) if not Subscriber.objects.filter(unsubscribe_code__iexact=unsubscribe_code): break if user: sub = Subscriber.objects.create(email=email, skill=skill, user=user) else: sub = Subscriber.objects.create(email=email, skill=skill) sub.unsubscribe_code = unsubscribe_code while True: subscribe_code = get_random_string(length=15) if not Subscriber.objects.filter(subscribe_code__iexact=unsubscribe_code): break sub.subscribe_code = subscribe_code sub.save() return sub.subscribe_code def jobs_applied(request): if request.user.is_authenticated and request.user.user_type == "JS": request.session["formdata"] = "" applied_jobs = AppliedJobs.objects.filter(user=request.user).exclude( ip_address="", user_agent="" ) suggested_jobs = [] if not applied_jobs: user_skills = Skill.objects.filter( id__in=request.user.skills.all().values("skill") ) suggested_jobs = JobPost.objects.filter( Q(skills__in=user_skills) | Q(location__in=[request.user.current_city]) ) suggested_jobs = list(suggested_jobs.filter(status="Live")) suggested_jobs = suggested_jobs + list( JobPost.objects.filter(status="Live").order_by("-published_on")[:10] ) items_per_page = 15 no_of_jobs = applied_jobs.count() no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) if ( "page" in request.GET and bool(re.search(r"[0-9]", request.GET.get("page"))) and int(request.GET.get("page")) > 0 ): if int(request.GET.get("page")) > (no_pages + 2): page = 1 return HttpResponseRedirect(reverse("jobs:jobs_applied")) else: page = int(request.GET.get("page")) else: page = 1 ids = applied_jobs.values_list("job_post", flat=True) applied_jobs = JobPost.objects.filter(id__in=ids) applied_jobs = applied_jobs[(page - 1) * items_per_page : page * items_per_page] prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) data = { "applied_jobs": applied_jobs, "year": date.today().year, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "suggested_jobs": suggested_jobs[:10], } template = "candidate/applied_jobs.html" return render(request, template, data) else: return HttpResponseRedirect("/") def job_detail(request, job_title_slug, job_id): if not job_id or bool(re.search(r"[A-Za-z]", job_id)): reason = "The URL may be misspelled or the page you're looking for is no longer available." template = "404.html" return render( request, template, {"message": "Sorry, No Jobs Found", "job_search": True, "reason": reason}, status=404, ) job = ( JobPost.objects.filter(id=job_id) .select_related("company", "user") .prefetch_related( "location", "skills", "industry", "functional_area", "job_interview_location", ) .first() ) if job: if str(job.get_absolute_url()) != str(request.path): return redirect(job.get_absolute_url(), permanent=False) if job.status == "Live": if request.user.is_authenticated: visited_jobs = VisitedJobs.objects.filter( user=request.user, job_post=job ) if not visited_jobs: VisitedJobs.objects.create(user=request.user, job_post=job) field = get_social_referer(request) if field == "fb": job.fb_views += 1 elif field == "tw": job.tw_views += 1 elif field == "ln": job.ln_views += 1 else: job.other_views += 1 job.save() elif job.status == "Disabled": if job.major_skill and job.major_skill.status == "Active": return HttpResponseRedirect(job.major_skill.get_job_url()) elif job.skills.filter(status="Active").exists(): return HttpResponseRedirect( job.skills.filter(status="Active").first().get_job_url() ) return HttpResponseRedirect(reverse("jobs:index")) else: template = "404.html" return render( request, template, { "message": "Sorry, No Jobs Found", "job_search": True, "reason": "The URL may be misspelled or the page you're looking for is no longer available.", }, status=404, ) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title = meta_description = "" meta = MetaData.objects.filter(name="job_detail_page") if meta: meta_title = Template(meta[0].meta_title).render(Context({"job": job})) meta_description = Template(meta[0].meta_description).render( Context({"job": job}) ) template = "jobs/detail.html" data = { "job": job, "show_pop_up": show_pop, "meta_title": meta_title, "meta_description": meta_description, } return render(request, template, data) else: latest = JobPost.objects.order_by("id").last().id if int(job_id) < latest: return redirect(reverse("jobs:index"), permanent=True) message = "Sorry, no jobs available" reason = "Unfortunately, we are unable to locate the job you are looking for" template = "404.html" return render( request, template, {"message": message, "reason": reason, "job_search": True}, status=404, ) def recruiter_profile(request, recruiter_name, **kwargs): current_url = reverse( "recruiter_profile", kwargs={"recruiter_name": recruiter_name} ) if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(current_url, permanent=True) if "page" in request.GET: url = current_url + request.GET.get("page") + "/" return redirect(url, permanent=True) if re.match( r"^/jobs/recruiter/(?P<recruiter_name>[a-zA-Z0-9_-]+)/", request.get_full_path() ): url = ( request.get_full_path() .replace("jobs/", "") .replace("recruiter", "recruiters") ) return redirect(url, permanent=True) job_list = ( JobPost.objects.filter(user__username__iexact=recruiter_name, status="Live") .select_related("company", "user") .prefetch_related("location", "skills", "industry") .order_by("-published_on") .distinct() ) no_of_jobs = job_list.count() user = User.objects.filter(username__iexact=recruiter_name).prefetch_related( "technical_skills", "functional_area", "industry" ) if user: items_per_page = 10 no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(current_url) prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) job_list = job_list[(page - 1) * items_per_page : page * items_per_page] meta_title = meta_description = h1_tag = "" meta = MetaData.objects.filter(name="recruiter_profile") if meta: meta_title = Template(meta[0].meta_title).render( Context({"current_page": page, "user": user[0]}) ) meta_description = Template(meta[0].meta_description).render( Context({"current_page": page, "user": user[0]}) ) h1_tag = Template(meta[0].h1_tag).render( Context({"current_page": page, "user": user[0]}) ) template = "jobs/recruiter_profile.html" return render( request, template, { "user": user[0], "job_list": job_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "current_url": current_url, "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, }, ) else: template = "404.html" return render( request, template, { "message": "Sorry, Recruiter profile unavailable", "data_empty": True, "reason": "Unfortunately, we are unable to locate the recruiter you are looking for", }, status=404, ) def recruiters(request, **kwargs): if kwargs.get("page_num") == "1": return redirect(reverse("recruiters"), permanent=True) if "page" in request.GET: url = reverse("recruiters") + "page/" + request.GET.get("page") + "/" return redirect(url, permanent=True) recruiters_list = ( User.objects.filter( Q(user_type="RR") | Q(user_type="AR") | Q(user_type="AA") & Q(is_active=True, mobile_verified=True) ) .annotate(num_posts=Count("jobposts")) .prefetch_related("company") .order_by("-num_posts") ) if request.POST.get("alphabet_value"): recruiters_list = recruiters_list.filter( username__istartswith=request.POST.get("alphabet_value") ) items_per_page = 45 no_pages = int(math.ceil(float(len(recruiters_list)) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect("/recruiters/") prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) recruiters_list = recruiters_list[ (page - 1) * items_per_page : page * items_per_page ] meta_title, meta_description, h1_tag = get_meta("recruiters_list", {"page": page}) template = "jobs/recruiters_list.html" return render( request, template, { "recruiters": recruiters_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "current_url": reverse("recruiters"), "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, }, ) def index(request, **kwargs): if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(reverse("jobs:index"), permanent=True) if "page" in request.GET: url = reverse("jobs:index") + request.GET.get("page") + "/" return redirect(url, permanent=True) # jobs_list = JobPost.objects.filter( # status='Live').select_related('company', 'user').prefetch_related( # 'location', 'skills', 'industry').distinct() searched_locations = ( searched_skills ) = searched_industry = searched_edu = searched_states = "" if request.POST.get("refine_search") == "True": ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(request.POST) else: ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search({}) no_of_jobs = jobs_list.count() items_per_page = 20 no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(reverse("jobs:index")) jobs_list = jobs_list[(page - 1) * items_per_page : page * items_per_page] prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title, meta_description, h1_tag = get_meta("jobs_list_page", {"page": page}) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "is_job_list": True, "current_url": reverse("jobs:index"), "show_pop_up": show_pop, "searched_skills": searched_skills, "searched_locations": searched_locations, "searched_industry": searched_industry, "searched_experience": request.POST.get("experience"), "searched_edu": searched_edu, "searched_states": searched_states, "searched_job_type": request.POST.get("job_type"), "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/jobs_list.html" return render(request, template, data) def job_locations(request, location, **kwargs): current_url = reverse("job_locations", kwargs={"location": location}) if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(current_url, permanent=True) if "page" in request.GET: url = current_url + request.GET.get("page") + "/" return redirect(url, permanent=True) request.session["formdata"] = "" final_location = get_valid_locations_list(location) state = State.objects.filter(slug__iexact=location) if request.POST.get("refine_search") == "True": ( job_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(request.POST) final_location = final_location + list( searched_states.values_list("name", flat=True) ) elif state: final_location = [state[0].name] search_dict = QueryDict("", mutable=True) search_dict.setlist("refine_state", [state[0].name]) ( job_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) elif final_location: search_dict = QueryDict("", mutable=True) search_dict.setlist("refine_location", final_location) if request.POST.get("experience"): search_dict.update( {"refine_experience_min": request.POST.get("experience")} ) ( job_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) else: job_list = [] if request.POST.get("location"): save_search_results.delay( request.META["REMOTE_ADDR"], request.POST, job_list.count() if job_list else 0, request.user.id, ) if job_list: items_per_page = 20 searched_industry = searched_skills = searched_edu = "" if request.GET.get("job_type"): job_list = job_list.filter_and(job_type__in=[request.GET.get("job_type")]) no_of_jobs = job_list.count() no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(current_url) jobs_list = job_list[(page - 1) * items_per_page : page * items_per_page] prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title, meta_description, h1_tag = get_meta_data( "location_jobs", { "locations": searched_locations, "final_location": set(final_location), "page": page, "state": bool(state), }, ) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "current_url": current_url, "skill_jobs": True, "show_pop_up": show_pop, "searched_skills": searched_skills, "searched_locations": searched_locations, "searched_states": searched_states, "searched_industry": searched_industry, "searched_experience": request.POST.get("experience"), "searched_edu": searched_edu, "searched_job_type": request.POST.get("job_type"), "searched_functional_area": request.POST.get("functional_area"), "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, "state": state.first(), } template = "jobs/jobs_list.html" return render(request, template, data) else: if final_location: search = final_location status = 200 meta_title, meta_description = get_404_meta( "location_404", {"city": search} ) else: search = [location] status = 404 meta_title = meta_description = "" reason = "Only Cities/States names are accepted in location field" template = "404.html" return render( request, template, { "message": "Unfortunately, we are unable to locate the jobs you are looking for", "meta_title": meta_title, "meta_description": meta_description, "job_search": True, "reason": reason, "searched_locations": search, "data_empty": status != 200, }, status=status, ) def list_deserializer(key, value, flags): import ast value = value.decode("utf-8") value = ast.literal_eval(value) value = [i.strip() for i in value if i.strip()] return value def job_skills(request, skill, **kwargs): # from pymemcache.client.base import Client # from pymemcache import serde # client = Client(('127.0.0.1', 11211), # serializer=serde.python_memcache_serializer, # deserializer=serde.python_memcache_deserializer) from pymemcache.client.base import Client client = Client(("localhost", 11211), deserializer=list_deserializer) current_url = reverse("job_skills", kwargs={"skill": skill}) if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(current_url, permanent=True) if "page" in request.GET: url = current_url + request.GET.get("page") + "/" return redirect(url, permanent=True) final_skill = client.get("final_skill" + skill) if not final_skill: final_skill = get_valid_skills_list(skill) client.set("final_skill" + skill, final_skill, expire=60 * 60 * 24) if final_skill == b"[]": final_skill = [] final_edu = client.get("final_edu" + skill) if not final_edu: final_edu = get_valid_qualifications(skill) client.set("final_edu" + skill, final_edu, expire=60 * 60 * 24) if final_edu == b"[]": final_edu = [] if request.POST.get("refine_search") == "True": ( job_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(request.POST) else: search_dict = QueryDict("", mutable=True) if final_skill or final_edu: search_dict.setlist("refine_skill", final_skill) search_dict.setlist("refine_education", final_edu) else: search_dict.setlist("refine_skill", [skill]) if request.POST.get("experience"): search_dict.update( {"refine_experience_min": request.POST.get("experience")} ) ( job_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) searched_text = get_ordered_skill_degrees( skill, searched_skills.filter(name__in=final_skill), searched_edu.filter(name__in=final_edu), ) if request.POST.get("q"): save_search_results.delay( request.META["REMOTE_ADDR"], request.POST, job_list.count(), request.user.id ) if job_list.count() > 0: if request.GET.get("job_type"): job_list = job_list.filter_and(job_type__in=[request.GET.get("job_type")]) no_of_jobs = job_list.count() no_pages = int(math.ceil(float(no_of_jobs) / 20)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(current_url) jobs_list = job_list[(page - 1) * 20 : page * 20] prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title = meta_description = h1_tag = "" final_edu = ", ".join(final_edu) if searched_edu and not searched_skills: meta = MetaData.objects.filter(name="education_jobs") if meta: meta_title = Template(meta[0].meta_title).render( Context({"current_page": page, "degree": final_edu}) ) meta_description = Template(meta[0].meta_description).render( Context({"current_page": page, "degree": final_edu}) ) h1_tag = Template(meta[0].h1_tag).render( Context({"current_page": page, "degree": final_edu}) ) elif searched_edu and searched_skills: meta = MetaData.objects.filter(name="skill_education_jobs") if meta: search = ", ".join(searched_text) meta_title = Template(meta[0].meta_title).render( Context({"current_page": page, "search": search}) ) meta_description = Template(meta[0].meta_description).render( Context({"current_page": page, "search": search}) ) h1_tag = Template(meta[0].h1_tag).render( Context({"current_page": page, "search": search}) ) elif searched_skills: meta_title, meta_description, h1_tag = get_meta_data( "skill_jobs", {"skills": searched_skills, "final_skill": final_skill, "page": page}, ) else: meta_title, meta_description, h1_tag = get_meta_data( "skill_jobs", {"final_skill": [skill], "page": page} ) searched_text = [skill] data = { "job_list": jobs_list, "current_url": current_url, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "show_pop_up": show_pop, "location_jobs": True, "searched_skills": searched_skills, "searched_locations": searched_locations, "searched_industry": searched_industry, "searched_edu": searched_edu, "searched_states": searched_states, "experience": request.POST.get("experience"), "searched_job_type": request.POST.get("job_type") or request.GET.get("job_type"), "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, "searched_text": searched_text, } template = "jobs/jobs_list.html" return render(request, template, data) else: if final_skill or final_edu: search = final_skill + final_edu status = 200 meta_title, meta_description = get_404_meta("skill_404", {"skill": search}) else: search = [skill] status = 404 meta_title = meta_description = "" reason = "Only valid Skills/Qualifications names are accepted" template = "404.html" return render( request, template, { "message": "Unfortunately, we are unable to locate the jobs you are looking for", "meta_title": meta_title, "meta_description": meta_description, "job_search": True, "reason": reason, "searched_skills": search, "data_empty": status != 200, }, status=status, ) def job_industries(request, industry, **kwargs): current_url = reverse("job_industries", kwargs={"industry": industry}) if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(current_url, permanent=True) if "page" in request.GET: url = current_url + request.GET.get("page") + "/" return redirect(url, permanent=True) searched_locations = searched_skills = searched_edu = searched_states = "" searched_industry = Industry.objects.filter(slug=industry) search_dict = QueryDict("", mutable=True) search_dict.setlist("refine_industry", [searched_industry[0].name]) if request.POST.get("refine_search") == "True": ( job_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(request.POST) else: ( job_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) if job_list: no_of_jobs = job_list.count() items_per_page = 20 no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(current_url) jobs_list = job_list[(page - 1) * items_per_page : page * items_per_page] prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title = meta_description = h1_tag = "" meta = MetaData.objects.filter(name="industry_jobs") if meta: meta_title = Template(meta[0].meta_title).render( Context({"current_page": page, "industry": searched_industry[0].name}) ) meta_description = Template(meta[0].meta_description).render( Context({"current_page": page, "industry": searched_industry[0].name}) ) h1_tag = Template(meta[0].h1_tag).render( Context({"current_page": page, "industry": searched_industry[0].name}) ) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "show_pop_up": show_pop, "current_url": current_url, "searched_skills": searched_skills, "searched_locations": searched_locations, "searched_industry": searched_industry, "searched_edu": searched_edu, "searched_states": searched_states, "searched_experience": request.POST.get("experience"), "searched_job_type": request.POST.get("job_type"), "searched_functional_area": request.POST.get("functional_area"), "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/jobs_list.html" return render(request, template, data) else: if searched_industry: reason = "No Jobs available with searched industry" meta_title, meta_description = get_404_meta( "industry_404", {"industry": industry} ) else: reason = "Unable to locate the industry you are looking for" meta_title = meta_description = "" template = "404.html" return render( request, template, { "message": "Unfortunately, we are unable to locate the jobs you are looking for", "meta_title": meta_title, "meta_description": meta_description, "job_search": True, "reason": reason, "data_empty": False if searched_industry else True, }, status=200 if searched_industry else 404, ) def user_applied_job(request): request.session["job_id"] = request.POST.get("job_id") data = {"error": False, "response": "User successfully applied for a job"} return HttpResponse(json.dumps(data)) @login_required def job_apply(request, job_id): if ( request.user.is_active or request.GET.get("apply_now") ) and request.user.user_type == "JS": job_post = JobPost.objects.filter(id=job_id, status="Live").first() if job_post: if not AppliedJobs.objects.filter(user=request.user, job_post=job_post): if ( request.user.resume or request.user.profile_completion_percentage >= 50 ): # need to check user uploaded a resume or not AppliedJobs.objects.create( user=request.user, job_post=job_post, status="Pending", ip_address=request.META["REMOTE_ADDR"], user_agent=request.META["HTTP_USER_AGENT"], ) message = ( "Your Application successfully sent for " + str(job_post.title) + " at " + job_post.company_name ) t = loader.get_template("email/applicant_apply_job.html") c = { "user": request.user, "recruiter": job_post.user, "job_post": job_post, } rendered = t.render(c) if request.user.resume: import urllib.request urllib.request.urlretrieve( "https://peeljobs.s3.amazonaws.com/" + str( request.user.resume.encode("ascii", "ignore").decode( "ascii" ) ), str(request.user.email) + ".docx", ) msg = MIMEMultipart() msg["Subject"] = "Resume Alert - " + job_post.title msg["From"] = settings.DEFAULT_FROM_EMAIL msg["To"] = job_post.user.email part = MIMEText(rendered, "html") msg.attach(part) if request.user.resume and os.path.exists( str(request.user.email) + ".docx" ): part = MIMEApplication( open(str(request.user.email) + ".docx", "rb").read() ) part.add_header( "Content-Disposition", "attachment", filename=str(request.user.email) + ".docx", ) msg.attach(part) os.remove(str(request.user.email) + ".docx") boto.connect_ses( aws_access_key_id=settings.AM_ACCESS_KEY, aws_secret_access_key=settings.AM_PASS_KEY, ) conn = boto.ses.connect_to_region( "eu-west-1", aws_access_key_id=settings.AM_ACCESS_KEY, aws_secret_access_key=settings.AM_PASS_KEY, ) # and send the message conn.send_raw_email( msg.as_string(), source=msg["From"], destinations=[msg["To"]] ) data = { "error": False, "response": message, "url": job_post.get_absolute_url(), } return HttpResponse(json.dumps(data)) # else: # data = {'error': True, 'response': 'Jobpost is already expired'} # return HttpResponse(json.dumps(data)) else: data = { "error": True, "response": "Please complete your profile to apply for this job", "url": reverse("my:profile"), } return HttpResponse(json.dumps(data)) else: data = {"error": True, "response": "User already applied for this job"} return HttpResponse(json.dumps(data)) data = {"error": True, "response": "Job you are searching not found"} return HttpResponse(json.dumps(data)) if request.user.user_type == "RR": data = {"error": True, "response": "Recruiter not allowed to apply for jobs"} return HttpResponse(json.dumps(data)) if request.user.is_staff: data = {"error": True, "response": "Admin not allowed to apply for jobs"} return HttpResponse(json.dumps(data)) data = { "error": True, "response": "You need to verify your e-mail to apply for this job", } return HttpResponse(json.dumps(data)) def unsubscribe(request, email, job_post_id): job_post = JobPost.objects.filter(id=job_post_id) if job_post: subscribers = Subscriber.objects.filter( email=email, skill__in=job_post[0].skills.all() ) if request.method == "POST": if str(request.POST["is_delete"]) == "True": subscribers.delete() data = { "error": False, "response": "Please update your profile to apply for a job ", } else: data = { "error": True, "response": "Please update your profile to apply for a job ", } return HttpResponse(json.dumps(data)) return render( request, "unsubscribe.html", {"email": email, "subscribers": subscribers} ) else: message = "Sorry, no jobs available" reason = "Unfortunately, we are unable to locate the job you are looking for" template = "404.html" return render( request, template, {"message": message, "reason": reason}, status=404 ) # def year_calendar(request, year): # if request.POST.get("year"): # year = int(request.POST.get("year")) # jobs_list = JobPost.objects.filter(status="Live") # month = {"Name": "Jan", "id": 1} # year = int(year) # calendar_events = [] # # if request.user.is_authenticated: # # calendar_events = get_calendar_events_list() # meta_title, meta_description, h1_tag = get_meta("year_calendar", {"page": 1}) # return render( # request, # "calendar/year_calendar.html", # { # "months": months, # "year": year, # "prev_year": get_prev_year(year, year), # "next_year": get_next_year(year, year), # "post_data": "true" if request.POST else "false", # "jobs_list": jobs_list, # "calendar_type": "year", # "month": month, # "calendar_events": calendar_events, # "meta_title": meta_title, # "h1_tag": h1_tag, # "meta_description": meta_description, # }, # ) # def month_calendar(request, year, month): # current_year = datetime.now().year # year = current_year # month = next((item for item in months if item["id"] == int(month)), None) # calendar_events = [] # if request.user.is_authenticated: # calendar_events = get_calendar_events_list(request) # if request.method == "POST": # if request.POST.get("year"): # year = int(request.POST.get("year")) # if request.POST.get("month"): # month = next( # ( # item # for item in months # if item["id"] == int(request.POST.get("month")) # ), # None, # ) # # return HttpResponseRedirect(reverse('week_calendar', # # kwargs={'year': year, 'month': month['id'], 'week': # # request.POST.get('week')})) # post_data = False # if "status" in request.POST.keys(): # post_data = True # meta_title, meta_description, h1_tag = get_meta("month_calendar", {"page": 1}) # jobs_list = JobPost.objects.filter(status="Live") # return render( # request, # "calendar/year_calendar.html", # { # "requested_month": request.POST.get("month") # if request.POST.get("month") # else None, # "months": months, # "year": year, # "month": month, # "prev_year": get_prev_year(year, current_year), # "next_year": get_next_year(year, current_year), # "prev_month": get_prev_month(month, year, current_year), # "next_month": get_next_month(month, year, current_year), # "jobs_list": jobs_list, # "calendar_type": "month", # "post_data": post_data, # "calendar_events": calendar_events, # "meta_title": meta_title, # "h1_tag": h1_tag, # "meta_description": meta_description, # }, # ) # def week_calendar(request, year, month, week): # current_year = datetime.now().year # year = current_year # month = {"Name": "Jan", "id": 1} # calendar_events = [] # if request.user.is_authenticated: # calendar_events = get_calendar_events_list(request) # if request.POST.get("year"): # year = int(request.POST.get("year")) # if request.POST.get("month"): # month = next( # (item for item in months if item["id"] == int(request.POST.get("month"))), # None, # ) # if request.POST.get("week"): # week = int(request.POST.get("week")) # jobs_list = JobPost.objects.filter(status="Live") # meta_title, meta_description, h1_tag = get_meta("week_calendar", {"page": 1}) # return render( # request, # "calendar/year_calendar.html", # { # "months": months, # "year": year, # "prev_year": get_prev_year(year, year), # "next_year": get_next_year(year, year), # "post_data": "true" if request.POST else "false", # "calendar_type": "week", # "week": week, # "month": month, # "requested_month": month, # "jobs_list": jobs_list, # "calendar_events": calendar_events, # "meta_title": meta_title, # "h1_tag": h1_tag, # "meta_description": meta_description, # }, # ) def jobposts_by_date(request, year, month, date, **kwargs): current_url = reverse( "jobposts_by_date", kwargs={"year": year, "month": month, "date": date} ) if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(current_url, permanent=True) if "page" in request.GET: url = current_url + request.GET.get("page") + "/" return redirect(url, permanent=True) import datetime day = datetime.date(int(year), int(month), int(date)) results = JobPost.objects.filter(status="Live", last_date=day).order_by( "-published_on" ) events = get_calendar_events_list(request) if request.user.is_authenticated else [] event_titles = [] for event in events: if event.get("start_date") and event.get("end_date"): if str(day) >= str(event["start_date"]) and str(day) <= str( event["end_date"] ): event_titles.append(event["summary"]) events = JobPost.objects.filter(title__in=event_titles) if not results: template = "404.html" return render( request, template, { "message": "Sorry, no jobs available", "job_search": True, "data_empty": True, "reason": "Unfortunately, we are unable to locate the job you are looking for", }, status=404, ) no_pages = int(math.ceil(float(len(results)) / 20)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(current_url) prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) meta_title = meta_description = h1_tag = "" meta = MetaData.objects.filter(name="day_calendar") if meta: meta_title = Template(meta[0].meta_title).render( Context({"date": date, "searched_month": day.strftime("%B"), "year": year}) ) meta_description = Template(meta[0].meta_description).render( Context({"date": date, "searched_month": day.strftime("%B"), "year": year}) ) h1_tag = Template(meta[0].h1_tag).render( Context({"date": date, "month": day.strftime("%B"), "year": year}) ) return render( request, "calendar/calendar_day_results.html", { "no_of_jobs": len(results), "results": results[(page - 1) * 20 : page * 20], "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "month_num": day.month, "month": day.strftime("%B"), "year": year, "date": date, "current_url": current_url, "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, "events": events, }, ) def job_add_event(request): is_connected = True if request.POST: request.session["job_event"] = request.POST.get("job_id") if request.user.is_authenticated: service, is_connected = get_service(request) else: return HttpResponseRedirect(reverse("social:google_login")) if not is_connected: return service elif request.session.get("job_event"): jobpost = JobPost.objects.get(id=request.session.get("job_event")) msg = "" for location in jobpost.job_interview_location.all(): if location.show_location: msg = location.venue_details event = { "summary": str(jobpost.title), "location": str(msg), "description": str(jobpost.title), "start": { "date": str(jobpost.last_date), "timeZone": "Asia/Calcutta", }, "end": { "date": str(jobpost.last_date), "timeZone": "Asia/Calcutta", }, "recurrence": ["RRULE:FREQ=DAILY;COUNT=2"], "attendees": [ {"email": str(request.user.email)}, ], "reminders": { "useDefault": False, "overrides": [ {"method": "email", "minutes": 60 * 15}, {"method": "popup", "minutes": 60 * 15}, ], }, } response, created = create_google_calendar_event(request, request.user, event) if created == "redirect": return response elif redirect: request.session["job_event"] = "" return redirect( jobpost.get_absolute_url() + "?event=success", permanent=False ) else: return redirect( jobpost.get_absolute_url() + "?event=error", permanent=False ) # def calendar_add_event(request): # if request.method == "GET": # return render(request, "calendar/add_calendar_event.html", {}) # start_date = datetime.strptime( # str(request.POST.get("start_date")), "%m/%d/%Y" # ).strftime("%Y-%m-%d") # last_date = datetime.strptime( # str(request.POST.get("to_date")), "%m/%d/%Y" # ).strftime("%Y-%m-%d") # event = { # "summary": request.POST.get("title"), # "location": request.POST.get("location"), # "description": request.POST.get("description"), # "start": {"date": str(start_date), "timeZone": "Asia/Calcutta",}, # "end": {"date": str(last_date), "timeZone": "Asia/Calcutta",}, # "recurrence": ["RRULE:FREQ=DAILY;COUNT=2"], # "attendees": [{"email": str(request.user.email)},], # "reminders": { # "useDefault": False, # "overrides": [ # {"method": "email", "minutes": 24 * 60}, # {"method": "popup", "minutes": 10}, # ], # }, # } # response = create_google_calendar_event(request.user, event) # if response: # data = {"error": False, "response": "Event successfully added"} # else: # data = {"error": True, "response": "Please Try again after some time"} # return HttpResponse(json.dumps(data)) # def calendar_event_list(request): # if request.method == "POST": # event_id = request.POST.get("event_id") # response = delete_google_calendar_event(event_id) # if response: # data = {"error": False, "response": "Event successfully Deleted"} # else: # data = {"error": True, "response": "Please Try again after some time"} # return HttpResponse(json.dumps(data)) # events = get_calendar_events_list(request) # return render(request, "calendar/calendar_event_list.html", {"events": events}) def jobs_by_location(request, job_type): all_degrees = Qualification.objects.filter(status="Active").order_by("name") states = ( State.objects.annotate( num_locations=Count("state"), is_duplicate=Count(Case(When(state__name=F("name"), then=Value(1)))), ) .filter(num_locations__gte=1, status="Enabled") .prefetch_related( Prefetch( "state", queryset=City.objects.filter(status="Enabled", parent_city=None), to_attr="active_cities", ) ) ) if request.method == "POST": states = states.filter(name__icontains=request.POST.get("location")) meta_title = meta_description = h1_tag = "" meta = MetaData.objects.filter(name="jobs_by_location") if meta: meta_title = Template(meta[0].meta_title).render( Context({"job_type": job_type}) ) meta_description = Template(meta[0].meta_description).render( Context({"job_type": job_type}) ) h1_tag = Template(meta[0].h1_tag).render(Context({"job_type": job_type})) data = { "states": states, "job_type": job_type, "all_degrees": all_degrees[:10], "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/jobs_by_location.html" return render(request, template, data) def jobs_by_skill(request): all_skills = Skill.objects.filter(status="Active") if request.method == "POST": if str(request.POST.get("alphabet_value")) != "all": all_skills = all_skills.filter( name__istartswith=request.POST.get("alphabet_value") ) if request.POST.get("sorting_value") and ( str(request.POST.get("sorting_value")) == "descending" ): all_skills = all_skills.order_by("-name") else: all_skills = all_skills.order_by("name") meta_title, meta_description, h1_tag = get_meta("jobs_by_skills", {"page": 1}) data = { "all_skills": all_skills, "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/jobs_by_skills.html" return render(request, template, data) def fresher_jobs_by_skills(request, job_type): all_skills = Skill.objects.filter(status="Active") if request.method == "POST": if request.POST.get("alphabet_value"): all_skills = all_skills.filter( name__istartswith=request.POST.get("alphabet_value") ) if ( request.POST.get("sorting_value") and str(request.POST.get("sorting_value")) == "descending" ): all_skills = all_skills.order_by("-name") else: all_skills = all_skills.order_by("name") meta_title = meta_description = h1_tag = "" meta = MetaData.objects.filter(name="fresher_jobs_by_skills") if meta: meta_title = Template(meta[0].meta_title).render( Context({"job_type": job_type}) ) meta_description = Template(meta[0].meta_description).render( Context({"job_type": job_type}) ) h1_tag = Template(meta[0].h1_tag).render(Context({"job_type": job_type})) data = { "all_skills": all_skills, "job_type": job_type, "h1_tag": h1_tag, "meta_title": meta_title, "meta_description": meta_description, } template = "jobs/fresher_jobs_by_skills.html" return render(request, template, data) def jobs_by_industry(request): all_industries = ( Industry.objects.filter(status="Active") .annotate(num_posts=Count("jobpost")) .order_by("-num_posts") ) if request.method == "POST": all_industries = all_industries.filter( name__icontains=request.POST.get("industry") ) if request.POST.get("sorting_value") and ( str(request.POST.get("sorting_value")) == "descending" ): all_industries = all_industries.order_by("-name") else: all_industries = all_industries.order_by("name") meta_title, meta_description, h1_tag = get_meta("jobs_by_industry", {"page": 1}) data = { "all_industries": all_industries, "h1_tag": h1_tag, "meta_title": meta_title, "meta_description": meta_description, } template = "jobs/jobs_by_industries.html" return render(request, template, data) def jobs_by_degree(request): all_degrees = Qualification.objects.filter(status="Active").order_by("name") if request.method == "POST": if str(request.POST.get("alphabet_value")) != "all": all_degrees = all_degrees.filter( name__istartswith=request.POST.get("alphabet_value") ) if request.POST.get("sorting_value") and ( str(request.POST.get("sorting_value")) == "descending" ): all_degrees = all_degrees.order_by("-name") else: all_degrees = all_degrees.order_by("name") meta_title, meta_description, h1_tag = get_meta("jobs_by_degree", {"page": 1}) data = { "all_degrees": all_degrees, "h1_tag": h1_tag, "meta_title": meta_title, "meta_description": meta_description, } template = "jobs/jobs_by_degree.html" return render(request, template, data) def full_time_jobs(request, **kwargs): if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(reverse("full_time_jobs"), permanent=True) if "page" in request.GET: url = reverse("full_time_jobs") + request.GET.get("page") + "/" return redirect(url, permanent=True) request.session["formdata"] = "" searched_locations = ( searched_industry ) = searched_skills = searched_edu = searched_states = "" if request.POST.get("refine_search") == "True": ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(request.POST) else: search_dict = QueryDict("", mutable=True) search_dict.setlist("job_type", ["full-time"]) ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) no_of_jobs = jobs_list.count() items_per_page = 20 no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(reverse("full_time_jobs")) jobs_list = jobs_list[(page - 1) * items_per_page : page * items_per_page] prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title, meta_description, h1_tag = get_meta("full_time_jobs", {"page": page}) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "current_url": reverse("full_time_jobs"), "show_pop_up": show_pop, "searched_skills": searched_skills, "searched_locations": searched_locations, "searched_industry": searched_industry, "searched_edu": searched_edu, "searched_states": searched_states, "experience": request.POST.get("experience"), "searched_job_type": "full-time", "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/jobs_list.html" return render(request, template, data) def internship_jobs(request, **kwargs): request.session["formdata"] = "" jobs_list = ( JobPost.objects.filter(status="Live", job_type="internship") .select_related("company") .prefetch_related("location", "skills")[:9] ) no_of_jobs = jobs_list.count() no_pages = int(math.ceil(float(no_of_jobs) / 20)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(reverse("internship_jobs")) jobs_list = jobs_list[(page - 1) * 20 : page * 20] prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title, meta_description, h1_tag = get_meta("internship_jobs", {"page": page}) return render( request, "internship.html", { "jobs_list": jobs_list[:10], "cities": City.objects.filter(status="Enabled"), "show_pop_up": show_pop, "meta_title": meta_title, "meta_description": meta_description, }, ) def city_internship_jobs(request, location, **kwargs): current_url = reverse("city_internship_jobs", kwargs={"location": location}) if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(current_url, permanent=True) if "page" in request.GET: url = current_url + request.GET.get("page") + "/" return redirect(url, permanent=True) request.session["formdata"] = "" location = City.objects.filter(slug=location) searched_locations = ( searched_industry ) = searched_skills = searched_edu = searched_states = "" if request.POST.get("refine_search") == "True": ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(request.POST) else: search_dict = QueryDict("", mutable=True) search_dict.setlist("job_type", ["internship"]) search_dict.setlist("refine_location", [location[0].name]) ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) no_of_jobs = jobs_list.count() items_per_page = 20 no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(current_url) jobs_list = jobs_list[(page - 1) * items_per_page : page * items_per_page] prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title, meta_description, h1_tag = get_meta_data( "location_internship_jobs", { "searched_locations": [location], "final_location": [location[0].name], "page": page, }, ) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "internship_location": location, "current_url": current_url, "show_pop_up": show_pop, "searched_skills": searched_skills, "searched_locations": searched_locations, "searched_industry": searched_industry, "searched_edu": searched_edu, "searched_states": searched_states, "searched_experience": request.POST.get("experience"), "searched_job_type": "internship", "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/jobs_list.html" return render(request, template, data) def walkin_jobs(request, **kwargs): if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(reverse("walkin_jobs"), permanent=True) if "page" in request.POST: url = reverse("walkin_jobs") + request.POST.get("page") + "/" return redirect(url, permanent=True) request.session["formdata"] = "" jobs_list = ( JobPost.objects.filter(status="Live", job_type="walk-in") .select_related("company", "user") .prefetch_related("location", "skills", "industry") ) searched_locations = ( searched_industry ) = searched_skills = searched_edu = searched_states = "" if request.POST.get("refine_search") == "True": ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(request.POST) no_of_jobs = jobs_list.count() items_per_page = 20 no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(reverse("walkin_jobs")) jobs_list = jobs_list[(page - 1) * items_per_page : page * items_per_page] prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) current_date = datetime.now() field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title, meta_description, h1_tag = get_meta("walkin_jobs", {"page": page}) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "current_url": reverse("walkin_jobs"), "show_pop_up": show_pop, "current_date": current_date, "searched_skills": searched_skills, "searched_locations": searched_locations, "searched_industry": searched_industry, "searched_edu": searched_edu, "searched_states": searched_states, "searched_experience": request.POST.get("experience"), "searched_job_type": "walk-in", "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/jobs_list.html" return render(request, template, data) def government_jobs(request, **kwargs): if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(reverse("government_jobs"), permanent=True) if "page" in request.GET: url = reverse("government_jobs") + request.GET.get("page") + "/" return redirect(url, permanent=True) request.session["formdata"] = "" jobs_list = ( JobPost.objects.filter(status="Live", job_type="government") .select_related("company", "user") .prefetch_related("location", "skills", "industry") ) no_of_jobs = jobs_list.count() items_per_page = 20 no_pages = int(math.ceil(float(len(jobs_list)) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(reverse("government_jobs")) jobs_list = jobs_list[(page - 1) * items_per_page : page * items_per_page] prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title, meta_description, h1_tag = get_meta("government_jobs", {"page": page}) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "job_type": "government", "current_url": reverse("government_jobs"), "show_pop_up": show_pop, "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/jobs_list.html" return render(request, template, data) def each_company_jobs(request, company_name, **kwargs): current_url = reverse("company_jobs", kwargs={"company_name": company_name}) if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(current_url, permanent=True) if "page" in request.GET: url = current_url + request.GET.get("page") + "/" return redirect(url, permanent=True) company = Company.objects.filter(slug=company_name, is_active=True) request.session["formdata"] = "" if not company: data = { "message": "Sorry, no jobs available for " + company_name + " jobs", "reason": "Unfortunately, we are unable to locate the job you are looking for", "meta_title": "404 - Page Not Found - " + company_name + " - Peeljobs", "meta_description": "404 No Jobs available for " + company_name + " - Peeljobs", "data_empty": True, } if request.user.is_authenticated: if str(request.user.user_type) == "RR": return render(request, "recruiter/recruiter_404.html", data, status=404) elif request.user.is_staff: return render(request, "dashboard/404.html", data, status=404) template = "404.html" return render(request, template, data, status=404) else: company = company[0] items_per_page = 10 job_list = ( company.get_jobposts() .select_related("company", "user") .prefetch_related("location", "skills", "industry") .order_by("-published_on") ) no_of_jobs = job_list.count() no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(current_url) prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) skills = Skill.objects.filter(status="Active") industries = Industry.objects.filter(status="Active")[:6] jobs_list = job_list[(page - 1) * items_per_page : page * items_per_page] field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title = meta_description = h1_tag = "" meta = MetaData.objects.filter(name="company_jobs") if meta: meta_title = Template(meta[0].meta_title).render( Context({"current_page": page, "company": company}) ) meta_description = Template(meta[0].meta_description).render( Context({"current_page": page, "company": company}) ) h1_tag = Template(meta[0].h1_tag).render( Context({"current_page": page, "company": company}) ) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "skills": skills, "company": company, "current_url": current_url, "show_pop_up": show_pop, "industries": industries, "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/company_jobs.html" return render(request, template, data) def companies(request, **kwargs): if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(reverse("companies"), permanent=True) if "page" in request.GET: url = reverse("companies") + request.GET.get("page") + "/" return redirect(url, permanent=True) companies = ( Company.objects.annotate(num_posts=Count("jobpost")) .filter(is_active=True) .order_by("-num_posts") ) alphabet_value = request.POST.get("alphabet_value") if alphabet_value: companies = companies.filter(name__istartswith=alphabet_value) no_of_jobs = companies.count() items_per_page = 48 no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(reverse("companies")) prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) companies = companies[(page - 1) * items_per_page : page * items_per_page] meta_title, meta_description, h1_tag = get_meta("companies_list", {"page": page}) data = { "companies": companies, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "alphabet_value": alphabet_value if alphabet_value else None, "current_url": reverse("companies"), "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/companies_list.html" return render(request, template, data) def get_skills(request): skills = cache.get("subscribing_skills") if not skills: skills = Skill.objects.filter(status="Active").order_by("name") skills = serializers.serialize("json", skills) cache.set("subscribing_skills", skills, 60 * 60 * 24) return HttpResponse(json.dumps({"response": skills})) def skill_fresher_jobs(request, skill_name, **kwargs): current_url = reverse("skill_fresher_jobs", kwargs={"skill_name": skill_name}) if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(current_url, permanent=True) if "page" in request.GET: url = current_url + request.GET.get("page") + "/" return redirect(url, permanent=True) final_skill = get_valid_skills_list(skill_name) final_locations = get_valid_locations_list(skill_name) if final_locations: return redirect( reverse("location_fresher_jobs", kwargs={"city_name": skill_name}), permanent=True, ) if request.POST.get("refine_search") == "True": ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(request.POST) elif final_skill: search_dict = QueryDict("", mutable=True) search_dict.setlist("refine_skill", final_skill) search_dict.update({"job_type": "Fresher"}) ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) else: jobs_list = searched_skills = [] if request.POST.get("q"): ip_address = request.META["REMOTE_ADDR"] save_search_results.delay( ip_address, request.POST, jobs_list.count() if jobs_list else 0, request.user.id, ) if jobs_list: no_of_jobs = jobs_list.count() items_per_page = 20 no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(current_url) prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) jobs_list = jobs_list[(page - 1) * items_per_page : page * items_per_page] field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title, meta_description, h1_tag = get_meta_data( "skill_fresher_jobs", { "skills": searched_skills, "fresher": True, "final_skill": final_skill, "page": page, }, ) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "is_job_list": False, "fresher": True, "current_url": current_url, "show_pop_up": show_pop, "searched_skills": searched_skills, "searched_locations": searched_locations, "searched_industry": searched_industry, "searched_edu": searched_edu, "searched_states": searched_states, "searched_experience": request.POST.get("experience"), "searched_job_type": "Fresher", "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/jobs_list.html" return render(request, template, data) else: meta_title = meta_description = "" if searched_skills: reason = "Only valid Skill names are accepted in search field" skills = final_skill status = 200 meta_title, meta_description = get_404_meta( "skill_404", {"skill": skills, "fresher": True} ) else: status = 404 skills = list(filter(None, request.POST.get("q", "").split(", "))) or [ skill_name ] reason = "Only valid Skill/city names are accepted" template = "404.html" return render( request, template, { "message": "Unfortunately, we are unable to locate the jobs you are looking for", "searched_job_type": "Fresher", "job_search": True, "reason": reason, "searched_skills": skills, "meta_title": meta_title, "meta_description": meta_description, "data_empty": status != 200, }, status=status, ) def location_fresher_jobs(request, city_name, **kwargs): current_url = reverse("location_fresher_jobs", kwargs={"city_name": city_name}) if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(current_url, permanent=True) if "page" in request.GET: url = current_url + request.GET.get("page") + "/" return redirect(url, permanent=True) state = State.objects.filter(slug__iexact=city_name) final_locations = get_valid_locations_list(city_name) if request.POST.get("refine_search") == "True": ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(request.POST) final_locations = final_locations + list( searched_states.values_list("name", flat=True) ) elif state: final_locations = [state[0].name] search_dict = QueryDict("", mutable=True) search_dict.setlist("refine_state", final_locations) search_dict.update({"job_type": "Fresher"}) ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) elif final_locations: search_dict = QueryDict("", mutable=True) search_dict.setlist("refine_location", final_locations) search_dict.update({"job_type": "Fresher"}) ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) else: jobs_list = searched_locations = [] if request.POST.get("location") or request.POST.get("q"): ip_address = request.META["REMOTE_ADDR"] save_search_results.delay( ip_address, request.POST, jobs_list.count() if jobs_list else 0, request.user.id, ) if jobs_list: no_of_jobs = jobs_list.count() items_per_page = 20 no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(current_url) prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) jobs_list = jobs_list[(page - 1) * items_per_page : page * items_per_page] field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title, meta_description, h1_tag = get_meta_data( "location_fresher_jobs", { "locations": searched_locations, "final_location": set(final_locations), "page": page, "state": bool(state), "fresher": True, }, ) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "is_job_list": False, "fresher": True, "current_url": current_url, "show_pop_up": show_pop, "searched_skills": searched_skills, "searched_locations": searched_locations, "searched_industry": searched_industry, "searched_edu": searched_edu, "searched_states": searched_states, "searched_experience": request.POST.get("experience"), "searched_job_type": "Fresher", "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, "state": state.first(), } template = "jobs/jobs_list.html" return render(request, template, data) else: if final_locations: status = 200 reason = "Only valid cities names are accepted" location = final_locations meta_title, meta_description = get_404_meta( "location_404", {"city": location, "fresher": True} ) else: status = 404 meta_title = meta_description = "" location = list( filter(None, request.POST.get("location", "").split(", ")) ) or [city_name] reason = "Only valid Skill/city names are accepted" template = "404.html" return render( request, template, { "message": "Unfortunately, we are unable to locate the jobs you are looking for", "searched_job_type": "Fresher", "job_search": True, "reason": reason, "meta_title": meta_title, "meta_description": meta_description, "searched_locations": location, "data_empty": status != 200, }, status=status, ) def skill_location_walkin_jobs(request, skill_name, **kwargs): if "-in-" in request.path: current_url = reverse("location_walkin_jobs", kwargs={"skill_name": skill_name}) else: current_url = reverse("skill_walkin_jobs", kwargs={"skill_name": skill_name}) if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(current_url, permanent=True) if "page" in request.GET: url = current_url + request.GET.get("page") + "/" return redirect(url, permanent=True) final_skill = get_valid_skills_list(skill_name) final_locations = get_valid_locations_list(skill_name) state = State.objects.filter(slug__iexact=skill_name) if request.POST.get("refine_search") == "True": ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(request.POST) final_locations = final_locations + list( searched_states.values_list("name", flat=True) ) elif state: searched_locations = state final_locations = [state[0].name] search_dict = QueryDict("", mutable=True) search_dict.setlist("refine_state", final_locations) search_dict.update({"job_type": "Walk-in"}) ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) elif final_locations or final_skill: search_dict = QueryDict("", mutable=True) search_dict.setlist("refine_skill", final_skill) search_dict.setlist("refine_location", final_locations) search_dict.update({"job_type": "walk-in"}) if request.POST.get("experience"): search_dict.update( {"refine_experience_min": request.POST.get("experience")} ) ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) else: jobs_list = [] if request.POST.get("location") or request.POST.get("q"): ip_address = request.META["REMOTE_ADDR"] save_search_results.delay( ip_address, request.POST, jobs_list.count() if jobs_list else 0, request.user.id, ) if jobs_list: no_of_jobs = jobs_list.count() items_per_page = 20 no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(current_url) prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) jobs_list = jobs_list[(page - 1) * items_per_page : page * items_per_page] field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False if final_locations: meta_title, meta_description, h1_tag = get_meta_data( "location_walkin_jobs", { "locations": searched_locations, "walkin": True, "final_location": set(final_locations), "page": page, "state": bool(state), }, ) else: meta_title, meta_description, h1_tag = get_meta_data( "skill_walkin_jobs", { "skills": searched_skills, "walkin": True, "final_skill": final_skill, "page": page, }, ) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "is_job_list": False, "walkin": True, "current_url": current_url, "show_pop_up": show_pop, "searched_skills": searched_skills, "searched_locations": searched_locations, "searched_industry": searched_industry, "searched_edu": searched_edu, "searched_states": searched_states, "experience": request.POST.get("experience"), "searched_job_type": "walk-in", "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, "state": state.first(), } template = "jobs/jobs_list.html" return render(request, template, data) else: if "-in-" in request.path: if final_locations: location, skills = final_locations, [] status = 200 meta_title, meta_description = get_404_meta( "location_404", {"city": location, "walkin": True} ) else: location, skills = ( list(filter(None, request.POST.get("location", "").split(", "))) or [skill_name], [], ) status = 404 meta_title = meta_description = "" else: if final_skill: skills, location = final_skill, [] status = 200 meta_title, meta_description = get_404_meta( "skill_404", {"skill": skills, "walkin": True} ) else: status = 404 skills, location = ( list(filter(None, request.POST.get("q", "").split(", "))) or [skill_name], [], ) meta_title = meta_description = "" reason = "Only valid Skill/City names are accepted in search field" template = "404.html" return render( request, template, { "message": "Unfortunately, we are unable to locate the jobs you are looking for", "searched_job_type": "walk-in", "job_search": True, "reason": reason, "searched_skills": skills, "meta_title": meta_title, "meta_description": meta_description, "searched_locations": location, "data_empty": status != 200, }, status=status, ) def skill_location_wise_fresher_jobs(request, skill_name, city_name, **kwargs): current_url = reverse( "skill_location_wise_fresher_jobs", kwargs={"skill_name": skill_name, "city_name": city_name}, ) if kwargs.get("page_num") == "1" or request.GET.get("page") == "1": return redirect(current_url, permanent=True) if "page" in request.GET: url = current_url + request.GET.get("page") + "/" return redirect(url, permanent=True) final_skill = get_valid_skills_list(skill_name) final_location = get_valid_locations_list(city_name) if request.POST.get("refine_search") == "True": ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(request.POST) elif final_skill and final_location: search_dict = QueryDict("", mutable=True) search_dict.setlist("refine_skill", final_skill) search_dict.setlist("refine_location", final_location) search_dict.update({"job_type": "Fresher"}) ( jobs_list, searched_skills, searched_locations, searched_industry, searched_edu, searched_states, ) = refined_search(search_dict) else: jobs_list = [] if request.POST.get("location") or request.POST.get("q"): ip_address = request.META["REMOTE_ADDR"] save_search_results.delay( ip_address, request.POST, jobs_list.count() if jobs_list else 0, request.user.id, ) if jobs_list: no_of_jobs = jobs_list.count() items_per_page = 20 no_pages = int(math.ceil(float(no_of_jobs) / items_per_page)) page = get_page_number(request, kwargs, no_pages) if not page: return HttpResponseRedirect(current_url) prev_page, previous_page, aft_page, after_page = get_prev_after_pages_count( page, no_pages ) jobs_list = jobs_list[(page - 1) * items_per_page : page * items_per_page] field = get_social_referer(request) show_pop = True if field == "fb" or field == "tw" or field == "ln" else False meta_title, meta_description, h1_tag = get_meta_data( "skill_location_fresher_jobs", { "skills": searched_skills, "locations": searched_locations, "final_location": final_location, "final_skill": final_skill, "page": page, }, ) data = { "job_list": jobs_list, "aft_page": aft_page, "after_page": after_page, "prev_page": prev_page, "previous_page": previous_page, "current_page": page, "last_page": no_pages, "no_of_jobs": no_of_jobs, "is_job_list": False, "show_pop_up": show_pop, "current_url": current_url, "searched_skills": searched_skills, "searched_locations": searched_locations, "searched_industry": searched_industry, "searched_edu": searched_edu, "searched_states": searched_states, "searched_experience": request.POST.get("experience"), "searched_job_type": "Fresher", "fresher": True, "meta_title": meta_title, "meta_description": meta_description, "h1_tag": h1_tag, } template = "jobs/jobs_list.html" return render(request, template, data) else: status = 200 if final_skill and final_location else 404 reason = "Only valid Skill names are accepted in search field" skills = ( final_skill or list(filter(None, request.POST.get("q", "").split(", "))) or [skill_name] ) location = ( final_location or list(filter(None, request.POST.get("location", "").split(", "))) or [city_name] ) template = "404.html" if status == 200: meta_title, meta_description = get_404_meta( "skill_location_404", {"skill": skills, "city": location, "fresher": True}, ) else: meta_title = meta_description = "" return render( request, template, { "message": "Unfortunately, we are unable to locate the jobs you are looking for", "searched_job_type": "Fresher", "job_search": True, "reason": reason, "searched_skills": skills, "meta_title": meta_title, "meta_description": meta_description, "searched_locations": location, "data_empty": status != 200, }, status=status, ) def add_other_location_to_user(user, request): location = City.objects.filter( name__iexact=request.POST.get("other_location").strip() ) if location: user.current_city = location[0] else: location = City.objects.create( name=request.POST.get("other_location"), status="Disabled", slug=slugify(request.POST.get("other_location")), state=State.objects.get(id=16), ) user.current_city = location user.save() def save_codes_and_send_mail(user, request, passwd): while True: random_code = get_random_string(length=15) if not User.objects.filter(activation_code__iexact=random_code): break while True: unsubscribe_code = get_random_string(length=15) if not User.objects.filter(unsubscribe_code__iexact=unsubscribe_code): break user.activation_code = random_code user.unsubscribe_code = unsubscribe_code user.save() skills = request.POST.getlist("technical_skills") or request.POST.getlist("skill") for s in skills: skill = Skill.objects.filter(id=s) if skill: tech_skill = TechnicalSkill.objects.create(skill=skill[0]) user.skills.add(tech_skill) temp = loader.get_template("email/jobseeker_account.html") subject = "PeelJobs User Account Activation" url = ( request.scheme + "://" + request.META["HTTP_HOST"] + "/user/activation/" + str(user.activation_code) + "/" ) rendered = temp.render( { "activate_url": url, "user_email": user.email, "user_mobile": user.mobile, "user": user, "user_password": passwd, "user_profile": user.profile_completion_percentage, } ) mto = user.email send_email.delay(mto, subject, rendered) def register_using_email(request): if request.method == "POST": if request.FILES.get("get_resume"): handle_uploaded_file( request.FILES["get_resume"], request.FILES["get_resume"].name ) email, mobile, text = get_resume_data(request.FILES["get_resume"]) data = { "error": False, "resume_email": email, "resume_mobile": mobile, "text": text, } return HttpResponse(json.dumps(data)) validate_user = UserEmailRegisterForm(request.POST, request.FILES) if validate_user.is_valid(): if not ( User.objects.filter(email__iexact=request.POST.get("email")) or User.objects.filter(username__iexact=request.POST.get("email")) ): email = request.POST.get("email") password = request.POST.get("password") registered_from = request.POST.get("register_from", "Email") user = User.objects.create( username=email, email=email, user_type="JS", registered_from=registered_from, ) user = UserEmailRegisterForm(request.POST, instance=user) user = user.save(commit=False) if request.POST.get("other_loc"): add_other_location_to_user(user, request) user.email_notifications = ( request.POST.get("email_notifications") == "on" ) user.set_password(password) user.referer = request.session.get("referer", "") user.save() save_codes_and_send_mail(user, request, password) if "resume" in request.FILES: conn = tinys3.Connection( settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY ) random_string = "".join( random.choice("0123456789ABCDEF") for i in range(3) ) user_id = str(user.id) + str(random_string) path = ( "resume/" + user_id + "/" + request.FILES["resume"] .name.replace(" ", "-") .encode("ascii", "ignore") .decode("ascii") ) conn.upload( path, request.FILES["resume"], settings.AWS_STORAGE_BUCKET_NAME, public=True, expires="max", ) user.resume = path user.profile_updated = datetime.now(timezone.utc) user.save() registered_user = authenticate(username=user.username) if registered_user: login(request, registered_user) UserEmail.objects.create(user=user, email=email, is_primary=True) redirect_url = reverse("user_reg_success") if request.POST.get("detail_page"): redirect_url = request.POST.get("detail_page") data = { "error": False, "response": "Registered Successfully", "redirect_url": redirect_url, } return HttpResponse(json.dumps(data)) else: data = { "error": True, "response": "User With This Email Already exists ", } return HttpResponse(json.dumps(data)) else: data = {"error": True, "response": validate_user.errors} return HttpResponse(json.dumps(data)) return HttpResponseRedirect("/index") def user_activation(request, user_id): user = User.objects.filter(activation_code__iexact=str(user_id)).first() if user: registered_user = authenticate(username=user.username) if not request.user.is_authenticated: if not hasattr(user, "backend"): for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.id): user.backend = backend break if hasattr(user, "backend"): login(request, user) url = "/profile/" if user.is_active else "/profile/?verify=true" user.is_active = True user.email_verified = True user.last_login = datetime.now() user.activation_code = "" user.save() return HttpResponseRedirect(url) else: message = "Looks like Activation Url Expired" reason = "The URL may be misspelled or the user you're looking for is no longer available." template = "404.html" return render( request, template, {"message": message, "reason": reason}, status=404 ) def login_user_email(request): if request.method == "POST": validate_user = AuthenticationForm(request.POST) if validate_user.is_valid(): email = request.POST.get("email") password = request.POST.get("password") usr = authenticate(username=email, password=password) if usr: usr.last_login = datetime.now() usr.save() login(request, usr) data = {"error": False, "response": "Logged In Successfully"} data["redirect_url"] = "/profile/" if request.user.user_type == "JS" and request.session.get("job_id"): post = JobPost.objects.filter( id=request.session["job_id"], status="Live" ).first() if ( post and usr.is_active and usr.profile_completion_percentage >= 50 or usr.resume ): job_apply(request, request.session["job_id"]) data["redirect_url"] = ( post.get_absolute_url() + "?job_apply=applied" if post else "/" ) else: url = post.slug + "?job_apply=apply" if post else "/profile/" data["redirect_url"] = url elif request.user.is_recruiter or request.user.is_agency_recruiter: data["redirect_url"] = "/recruiter/" else: data["redirect_url"] = "/dashboard/" if request.POST.get("next"): data["redirect_url"] = request.POST.get("next") if request.POST.get("detail_page"): data["rediret_url"] = request.POST.get("detail_page") else: data = { "error": True, "response_message": "Username Password didn't match", } return HttpResponse(json.dumps(data)) else: data = {"error": True, "response": validate_user.errors} return HttpResponse(json.dumps(data)) return HttpResponseRedirect("/") def set_password(request, user_id, passwd): user = User.objects.filter(id=user_id) if request.method == "POST": validate_changepassword = UserPassChangeForm(request.POST) if validate_changepassword.is_valid(): if request.POST["new_password"] != request.POST["retype_password"]: return HttpResponse( json.dumps( { "error": True, "response_message": "Password and Confirm Password did not match", } ) ) user = user[0] user.set_password(request.POST["new_password"]) user.save() # usr = authenticate( # username=user.email, password=request.POST["new_password"] # ) # if usr: # usr.last_login = datetime.now() # usr.save() # login(request, usr) if user.user_type == "JS": url = "/" else: url = reverse("recruiter:new_user") return HttpResponse( json.dumps( { "error": False, "message": "Password changed successfully", "url": url, } ) ) else: return HttpResponse( json.dumps({"error": True, "response": validate_changepassword.errors}) ) if user: usr = authenticate(username=user[0], password=passwd) if usr: return render(request, "set_password.html") template = "404.html" return render( request, template, {"message": "Not Found", "reason": "URL may Expired"}, status=404, ) def forgot_password(request): form_valid = ForgotPassForm(request.POST) if form_valid.is_valid(): user = User.objects.filter(email=request.POST.get("email")).first() if user and (user.is_recruiter or user.is_agency_admin): data = { "error": True, "response_message": "User Already registered as a Recruiter", } return HttpResponse(json.dumps(data)) if user: new_pass = get_random_string(length=10).lower() user.set_password(new_pass) user.save() temp = loader.get_template("email/subscription_success.html") subject = "Password Reset - PeelJobs" mto = request.POST.get("email") url = ( request.scheme + "://" + request.META["HTTP_HOST"] + "/user/set_password/" + str(user.id) + "/" + str(new_pass) + "/" ) c = {"randpwd": new_pass, "user": user, "redirect_url": url} rendered = temp.render(c) user_active = True if user.is_active else False send_email.delay(mto, subject, rendered) data = {"error": False, "response": "Success", "redirect_url": "/"} else: data = { "error": True, "response_message": "User doesn't exist with this Email", } return HttpResponse(json.dumps(data)) data = {"error": True, "response": form_valid.errors} return HttpResponse(json.dumps(data)) @jobseeker_login_required def user_reg_success(request): if not request.user.is_authenticated: reason = "The URL may be misspelled or the page you're looking for is no longer available." template = "404.html" return render( request, template, {"message": "Sorry, Page Not Found", "reason": reason}, status=404, ) if request.method == "POST": validate_user = UserEmailRegisterForm( request.POST, request.FILES, instance=request.user ) if validate_user.is_valid(): user = validate_user.save(commit=False) while True: unsubscribe_code = get_random_string(length=15) if not User.objects.filter(unsubscribe_code__iexact=unsubscribe_code): break user.unsubscribe_code = unsubscribe_code user.save() for s in request.POST.getlist("technical_skills"): skill = Skill.objects.filter(id=s) if skill: skill = skill[0] tech_skill = TechnicalSkill.objects.create(skill=skill) user.skills.add(tech_skill) if "resume" in request.FILES: conn = tinys3.Connection( settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY ) random_string = "".join( random.choice("0123456789ABCDEF") for i in range(3) ) user_id = str(user.id) + str(random_string) path = ( "resume/" + user_id + "/" + request.FILES["resume"] .name.replace(" ", "-") .encode("ascii", "ignore") .decode("ascii") ) conn.upload( path, request.FILES["resume"], settings.AWS_STORAGE_BUCKET_NAME, public=True, expires="max", ) user.resume = path user.profile_updated = datetime.now(timezone.utc) user.save() data = {"error": False, "response": "Profile Updated Successfully"} return HttpResponse(json.dumps(data)) data = {"error": True, "response": validate_user.errors} return HttpResponse(json.dumps(data)) if request.user.registered_from == "Social" and not request.user.mobile: template_name = "candidate/social_register.html" return render(request, template_name) template = "candidate/user_reg_success.html" return render(request, template) def user_subscribe(request): skills = Skill.objects.filter(status="Active") if request.method == "POST": validate_subscribe = SubscribeForm(request.POST) email = request.POST.get("email") user = User.objects.filter(email__iexact=email).first() if user and not user.user_type == "JS": data = { "error": True, "response_message": "Admin is not allowed to Subscribe" if user.is_staff else "Recruiter/Agency is not allowed to Subscribe", } return HttpResponse(json.dumps(data)) if validate_subscribe.is_valid(): all_subscribers = ( Subscriber.objects.filter(user=request.user) if request.user.is_authenticated else Subscriber.objects.filter(email=email, user=None) ) if request.POST.get("subscribe_from"): if not all_subscribers: for skill in skills: sub_code = subscribers_creation_with_skills( email, skill, request.user if request.user.is_authenticated else "", ) data = {"error": False, "response": "Successfully Subscribed"} else: data = { "error": True, "response_message": "User with this email id already subscribed", } elif request.POST.getlist("skill"): all_subscribers = all_subscribers.filter( skill__in=request.POST.getlist("skill") ) if int(all_subscribers.count()) != int( len(request.POST.getlist("skill")) ): for skill in request.POST.getlist("skill"): skill = Skill.objects.get(id=skill) sub_code = subscribers_creation_with_skills( email, skill, request.user if request.user.is_authenticated else "", ) data = {"error": False, "response": "experience added"} else: data = { "error": True, "response_message": "User with this email id and skill(s) already subscribed", } else: data = { "error": True, "response_message": "Please Enter atleast one skill", } if not data.get("error"): t = loader.get_template("email/subscription_success.html") skills = Skill.objects.filter(id__in=request.POST.getlist("skill")) url = ( request.scheme + "://" + request.META["HTTP_HOST"] + "/subscriber/verification/" + str(sub_code) + "/" ) c = {"user_email": email, "skills": skills, "redirect_url": url} subject = "PeelJobs New Subscription" rendered = t.render(c) mto = [email] send_email.delay(mto, subject, rendered) return HttpResponse(json.dumps(data)) else: data = {"error": True, "response": validate_subscribe.errors} return HttpResponse(json.dumps(data)) return HttpResponseRedirect("/") def process_email(request): body_unicode = request.body.decode("utf-8") body = json.loads(body_unicode) search = re.search(r"[\w\.-]+@[\w\.-]+", body.get("Message")) if search: email = search.group(0) users = User.objects.filter(email__iexact=email) if not users: user = User.objects.create( username=email, email=email, user_type="JS", registered_from="Careers" ) randpwd = rand_string(size=10).lower() user.set_password(randpwd) user.save() save_codes_and_send_mail(user, request, randpwd) return HttpResponseRedirect("/")
MicroPyramid/opensource-job-portal
pjob/views.py
views.py
py
117,784
python
en
code
336
github-code
36
[ { "api_name": "peeldb.models.Subscriber.objects.filter", "line_number": 137, "usage_type": "call" }, { "api_name": "peeldb.models.Subscriber.objects", "line_number": 137, "usage_type": "attribute" }, { "api_name": "peeldb.models.Subscriber", "line_number": 137, "usage_typ...
9019137787
from chessboard import * import pygame import sys def redraw(screen, board, pieces, square_size, WHITE, GREY): # Draw the chess board for row in range(8): for col in range(8): if (row + col) % 2 == 0: color = WHITE else: color = GREY pygame.draw.rect(screen, color, [col * square_size, row * square_size, square_size, square_size]) if board[row][col] != 0: # images are 55x55 piece_image = pieces[str(board[row][col])] piece_width, piece_height = piece_image.get_size() max_size = min(square_size - 25, piece_width, piece_height) # If bigger than square_size, resize it to 55x55 piece_image = pygame.transform.smoothscale(piece_image, (max_size, max_size)) # Make sure the chess pieces are centered on the squares center = (col * square_size + square_size // 2 - max_size // 2, row * square_size + square_size // 2 - max_size // 2) screen.blit(piece_image, center) # Update the display pygame.display.flip() def main(): chessboard = ChessBoard() # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREY = (128, 128, 128) # Set up the display pygame.init() screen = pygame.display.set_mode((640, 640)) pygame.display.set_caption("Chess") # Load the chess pieces pieces = { str(Pawn("white")): pygame.image.load("images/white_pawn.png"), str(Rook("white")): pygame.image.load("images/white_rook.png"), str(Knight("white")): pygame.image.load("images/white_knight.png"), str(Bishop("white")): pygame.image.load("images/white_bishop.png"), str(Queen("white")): pygame.image.load("images/white_queen.png"), str(King("white")): pygame.image.load("images/white_king.png"), str(Pawn("black")): pygame.image.load("images/black_pawn.png"), str(Rook("black")): pygame.image.load("images/black_rook.png"), str(Knight("black")): pygame.image.load("images/black_knight.png"), str(Bishop("black")): pygame.image.load("images/black_bishop.png"), str(Queen("black")): pygame.image.load("images/black_queen.png"), str(King("black")): pygame.image.load("images/black_king.png"), } # Define the chess board board = chessboard.current_position # Define the square size square_size = 80 # Draw the chess board redraw(screen, board, pieces, square_size, WHITE, GREY) # Update the display pygame.display.flip() # Main game loop selected_piece = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: # if playr is in check and checkmate, game over # Get the clicked square x, y = pygame.mouse.get_pos() row = y // square_size col = x // square_size if selected_piece == 0: # If no piece is selected, select the piece on the clicked square selected_piece = board[row][col] if selected_piece != 0 and selected_piece.color != chessboard.current_player: selected_piece = 0 elif selected_piece != 0 and selected_piece.color == chessboard.current_player: # Highlight the possible moves for the selected piece moves, caps = selected_piece.possible_moves(chessboard, pre_check =True) for move in (moves+caps): # Highlight the possible moves for the selected piece and lower the saturation of the highlighted squares pygame.draw.rect(screen, (255, 204, 229), [move[1] * square_size, move[0] * square_size, square_size, square_size]) pygame.display.flip() else: # If no white piece is on the clicked square, do nothing pass elif selected_piece != 0 and selected_piece.color == chessboard.current_player: # If a piece is already selected, try to move the selected piece to the clicked square # moves, caps = selected_piece.possible_moves(row, col, selected_piece, chessboard) if (row, col) in moves or caps: # Move the selected piece to the clicked square selected_piece.move(row, col, chessboard) # Switch players chessboard.current_player = "black" if chessboard.current_player == "white" else "white" if chessboard.is_check(): print("Check!") print(chessboard.is_checkmate()) if chessboard.is_check() and chessboard.is_checkmate(): print(f"GG, {chessboard.current_player} wins") pygame.quit() sys.exit() selected_piece = 0 # Redraw the board redraw(screen, board, pieces, square_size, WHITE, GREY) else: # If the clicked square is not a valid move for the selected piece, do nothing selected_piece = 0 redraw(screen, board, pieces, square_size, WHITE, GREY) else: selected_piece = 0 redraw(screen, board, pieces, square_size, WHITE, GREY) if __name__ == '__main__': main()
Miesjell/chess
main.py
main.py
py
6,010
python
en
code
0
github-code
36
[ { "api_name": "pygame.draw.rect", "line_number": 13, "usage_type": "call" }, { "api_name": "pygame.draw", "line_number": 13, "usage_type": "attribute" }, { "api_name": "pygame.transform.smoothscale", "line_number": 20, "usage_type": "call" }, { "api_name": "pygame...
20422534772
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="webull", version="0.6.1", author="ted chou", description="The unofficial python interface for the WeBull API", license='MIT', author_email="ted.chou12@gmail.com", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/tedchou12/webull.git", packages=setuptools.find_packages(), install_requires=[ "certifi>=2020.4.5.1", "chardet>=3.0.4", "idna>=2.9", "numpy>=1.18.4", "pandas>=0.25.3", "python-dateutil>=2.8.1", "pytz>=2020.1", "requests>=2.23.0", "six>=1.14.0", "urllib3>=1.25.9", "email-validator>=1.1.0", "paho-mqtt>=1.6.0" ], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', )
tedchou12/webull
setup.py
setup.py
py
1,036
python
en
code
576
github-code
36
[ { "api_name": "setuptools.setup", "line_number": 6, "usage_type": "call" }, { "api_name": "setuptools.find_packages", "line_number": 16, "usage_type": "call" } ]
30569661147
""" Привет! ID успешной посылки: 54853357 _____________________________________ Задача: Гоша реализовал структуру данных Дек, максимальный размер которого определяется заданным числом. Методы push_back(x), push_front(x), pop_back(), pop_front() работали корректно. Но, если в деке было много элементов, программа работала очень долго. Дело в том, что не все операции выполнялись за O(1). Помогите Гоше! Напишите эффективную реализацию. Внимание: при реализации нельзя использовать связный список. ____________________________________________________________ Так как связный список использовать нельзя, я подумал и пришел к тому, что самое оптимальное решение это использовать два массива, НО потом мне подсказали и я подумал еще получше - циклический буфер будет лучшим выбором! Будем использовать для метода push_back и push_front для вставки значений в конец и начало буфера. Также мы заведем в классе Deque поле size, в котором будем хранить максимальный размер Дека, задаваемый во входных данных. Поля tail и head для хранения индексов хвоста буфера и начала. Поле count - хранение количества элементов в буфере. Ну и соответственно проинициализируем саму очередь на заданный размер. Идея алгоритма простая, мы считываем данные, упаковываем их в массив, далее через оператов if - elif на нужные команды вызываем нужные методы. Для реализации алгоритма нам нужен класс, в котором будет реализованы следующие методы: * push_back(value) - добавляет элемент в конец буфера * push_front(value) - добавляем элемент в начало буфера * pop_back() - удаляет элемент из конца буфера * pop_front() - удаляет элемент из начала буфера Два дополнительный метода is_full() и is_empty() позволят нам отлавливать моменты, когда дека заполнена или пуста, и выкидывать в методах добавления и удаления элементом исключения, которые мы будем обрабатывать снаружи. При добавление в конец проверяем, что буфер не заполнен, далее проверяем, что элементы в буфере уже есть, проверяем если tail + 1 == size, то обнуляем tail, в противном случае увеличиваем tail на 1, для того, чтобы не перезатереть значение, которое уже лежит в буфере. Если буфер пустой, то tail и head обнуляем и записываем по индексу tail значение value. Увеличиваем счетчик элементов буфере на 1. Аналогичная ситуация для добавления в начало. Только здесь необходимо следить за индексом в head для того, чтобы не перезатереть значение, которое уже записано в буфер. Добавление происходит по индексу head, и увеличение счетчика на 1. Далее методы удаления элементов. Удаление с конца. Проверяем буфер на пустоту. Сохраняем текущий индекс в idx из tail во временную переменную именно по этому индексу мы и извлечем значение. Далее нам нужно переопределить индексы в tail и head, чтобы они указывали на правильные позиции буфера после удаления элемента. Уменьшаем счетчик на 1. Берем элемент по индексу idx из буфера, а на его место записываем None. Удалять элементы нельзя, чтобы не изменился размер буфера. По идее элементы можно не заменять на None, а просто сдвигать tail и head на нужные новые позиции и уменьшать счетчик. Но в задании указано удалить и мы его удаляем. Удаление с начала аналогичное. В idx сохраняем индекс из head, далее переопределяем tail и head для новых позиций, уменьшаем счетчик на 1 и возвращаем элемент. ------------------------------------------------------------ Про сложность. Алгоритм выполняется за линейное время O(n), где n - количество команд. Сами операции выполняются за O(1). Мы тратим на работу алгоритма O(n) памяти, потому что длина буфера не превосходят 0 <= n <= 50_000, где n это маскимальный размер Дека. ------------------------------------------------------------ Данные посылки: 0.56s 19.71Mb """ from typing import List, Tuple, NoReturn class Deque: def __init__(self, n: int): self.queue = [None] * n self.head = 0 self.tail = 0 self.size = n self.count = 0 def is_full(self): return self.count == self.size def is_empty(self): return self.count == 0 def push_back(self, value): if self.is_full(): raise IndexError() if self.count: if self.tail + 1 == self.size: self.tail = 0 else: self.tail += 1 else: self.tail = self.head = 0 self.queue[self.tail] = value self.count += 1 def push_front(self, value: int): if self.is_full(): raise IndexError() if self.count: if self.head - 1 < 0: self.head = self.size - 1 else: self.head -= 1 else: self.tail = self.head = 0 self.queue[self.head] = value self.count += 1 def pop_back(self): if self.is_empty(): raise IndexError() idx = self.tail if self.count == 1: self.tail = self.head = -1 else: if self.tail - 1 < 0: self.tail = self.size - 1 else: self.tail -= 1 self.count -= 1 item = self.queue[idx] self.queue[idx] = None return item def pop_front(self): if self.is_empty(): raise IndexError() idx = self.head if self.count == 1: self.tail = self.head = -1 else: if self.head + 1 == self.size: self.head = 0 else: self.head += 1 self.count -= 1 item = self.queue[idx] self.queue[idx] = None return item def input_data() -> Tuple[int, List[Tuple[str, ...]]]: n = int(input().strip()) m = int(input().strip()) command_list = [] while n: command = tuple(input().strip().split()) command_list.append(command) n -= 1 return m, command_list def solution(deque_length: int, command_list: List[Tuple[str, ...]]) -> NoReturn: deque = Deque(deque_length) for command in command_list: if command[0] == 'push_back': try: deque.push_back(int(command[1])) except IndexError: print('error') elif command[0] == 'push_front': try: deque.push_front(int(command[1])) except IndexError: print('error') elif command[0] == 'pop_back': try: print(deque.pop_back()) except IndexError: print('error') elif command[0] == 'pop_front': try: print(deque.pop_front()) except IndexError: print('error') if __name__ == '__main__': solution(*input_data())
fenixguard/yandex_algorithms
sprint_2/final_tasks/deque.py
deque.py
py
9,249
python
ru
code
2
github-code
36
[ { "api_name": "typing.Tuple", "line_number": 133, "usage_type": "name" }, { "api_name": "typing.List", "line_number": 133, "usage_type": "name" }, { "api_name": "typing.List", "line_number": 144, "usage_type": "name" }, { "api_name": "typing.Tuple", "line_numb...
10739040334
from PyQt5.QtWidgets import * from PyQt5.QtCore import Qt from QLed import QLed class Box(QGroupBox): instances = [] def __init__(self, name, opcID='opcID', horizontal_spacing=10, width=100): #self.setTitle(name) super().__init__(name) self.instances.append(self) self.opcName=name mainLayout = QFormLayout() self.state = False self.setEnabled(self.state) self.led1=QLed(onColour=QLed.Green, shape=QLed.Circle) self.led2=QLed(onColour=QLed.Green, shape=QLed.Circle) self.led3=QLed(onColour=QLed.Green, shape=QLed.Circle) self.radioBtn1=QRadioButton('Hand') self.radioBtn2=QRadioButton('AUS') #self.radioBtn2.setChecked(True) #self.led2.value = True self.radioBtn3=QRadioButton('AUTO') self.opcID=opcID self.radioBtn1.clicked.connect(self.write1) self.radioBtn2.clicked.connect(self.write2) self.radioBtn3.clicked.connect(self.write3) mainLayout.addRow(self.radioBtn1,self.led1) mainLayout.addRow(self.radioBtn2,self.led2) mainLayout.addRow(self.radioBtn3,self.led3) #Settings: mainLayout.setVerticalSpacing(8) mainLayout.setFormAlignment(Qt.AlignLeft) mainLayout.setHorizontalSpacing(horizontal_spacing) self.setFixedHeight(120) self.setFixedWidth(width) self.setLayout(mainLayout) @classmethod def set_all_states(cls, state): for instance in cls.instances: instance.state = state instance.setEnabled(state) def write1(self): if self.led1.value==False: print(self.opcID+': '+ self.radioBtn1.text()) self.led1.setValue(True) self.led2.setValue(False) # Add this line self.led3.setValue(False) # Add this line def write2(self): if self.led2.value==False: print(self.opcID+': '+ self.radioBtn2.text()) self.led2.setValue(True) self.led1.setValue(False) self.led3.setValue(False) def write3(self): if self.led3.value==False: print(self.opcID+': '+ self.radioBtn3.text()) self.led2.setValue(False) self.led1.setValue(False) self.led3.setValue(True) def update(self,val): # self.led1.value=val[self.opcName+'.Hand'] # self.led2.value=val[self.opcName+'.AUS'] # self.led3.value=val[self.opcName+'.AUTO'] if (val[self.opcName+'.Hand']): self.radioBtn2.setChecked(False) self.radioBtn3.setChecked(False) self.radioBtn1.setChecked(True) self.led2.setValue(False) self.led3.setValue(False) self.led1.setValue(True) print("Led1 is true") elif (val[self.opcName+'.AUS']): self.radioBtn1.setChecked(False) self.radioBtn2.setChecked(True) self.radioBtn3.setChecked(False) self.led1.setValue(False) self.led2.setValue(True) self.led3.setValue(False) print("Led2 is true") elif (val[self.opcName+'.AUTO']): self.radioBtn1.setChecked(False) self.radioBtn2.setChecked(False) self.radioBtn3.setChecked(True) self.led1.setValue(False) self.led2.setValue(False) self.led3.setValue(True) print("Led3 is true") #print(val[self.opcName+'.Hand'])
ValdsteiN/metabolon-gui
components/widgets/box.py
box.py
py
3,168
python
en
code
null
github-code
36
[ { "api_name": "QLed.QLed", "line_number": 21, "usage_type": "call" }, { "api_name": "QLed.QLed.Green", "line_number": 21, "usage_type": "attribute" }, { "api_name": "QLed.QLed.Circle", "line_number": 21, "usage_type": "attribute" }, { "api_name": "QLed.QLed", ...
1080065395
from django.contrib import admin from django.urls import path from form1 import views urlpatterns = [ path('form1', views.index,name='index'), path('form2', views.form2, name='Supervisor'), path('', views.login_view, name='home'), path('signup', views.signup_view, name='signup'), path('menu', views.menu_view, name='menu'), path('login', views.login_view, name='login'), path('logout', views.logout_view, name='logout'), path('movetohistory/<int:case_id>', views.move_to_history, name='MoveToHistory'), path('add_frv', views.create_frv ,name='AddFrv'), path('driver', views.driver, name='driver'), #path('drivermap', views.drivermap, name='drivermap'), path('location/case/get', views.get_case_location, name='GetCaseLocation'), path('location/case/set', views.set_case_location, name='SaveCaseLocation'), path('assignfrv', views.assign_frv, name='AssignFRV' ), #path('location/frv/get', views.get_frv_location, name='GetFRVocation'), #path('location/frv/gset', views.set_frv_location, name='SetFRVLocation'), ]
prajwalgh/QuantumGIS-SIH-PH
mainbody/form1/urls.py
urls.py
py
1,079
python
en
code
0
github-code
36
[ { "api_name": "django.urls.path", "line_number": 6, "usage_type": "call" }, { "api_name": "form1.views.index", "line_number": 6, "usage_type": "attribute" }, { "api_name": "form1.views", "line_number": 6, "usage_type": "name" }, { "api_name": "django.urls.path", ...
17702834387
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 1 19:59:15 2023 @author: rockerzega """ from clases import SimpleRNN, STData, RNN from torch.utils.data import DataLoader from funciones import fit, generador, RSME, predict, plot_series # preparacion de la data simulada n_steps = 50 series = generador(10000, n_steps + 1) X_train, y_train = series[:7000, :n_steps], series[:7000, -1] X_valid, y_valid = series[7000:9000, :n_steps], series[7000:9000, -1] X_test, y_test = series[9000:, :n_steps], series[9000:, -1] # Infomracion de la data print(X_train.shape, y_train.shape) # y_pred = X_test[:,-1] dataset = { 'train': STData(X_train, y_train), 'eval': STData(X_valid, y_valid), 'test': STData(X_test, y_test, train=False) } dataloader = { 'train': DataLoader(dataset['train'], shuffle=True, batch_size=64), 'eval': DataLoader(dataset['eval'], shuffle=False, batch_size=64), 'test': DataLoader(dataset['test'], shuffle=False, batch_size=64) } rnn = SimpleRNN() fit(rnn, dataloader) y_pred = predict(rnn, dataloader['test']) plot_series(X_test, y_test, y_pred.cpu().numpy()) print(RSME(y_test, y_pred.cpu())) # Parametros de la RNN Simple print(rnn.rnn.weight_hh_l0.shape, rnn.rnn.weight_ih_l0.shape, rnn.rnn.bias_hh_l0.shape, rnn.rnn.bias_ih_l0.shape) rnn = RNN() # Parametros de la RNN completa print(rnn.rnn.weight_hh_l0.shape, rnn.rnn.weight_ih_l0.shape, rnn.rnn.bias_hh_l0.shape, rnn.rnn.bias_ih_l0.shape, rnn.fc.weight.shape, rnn.fc.bias.shape) fit(rnn, dataloader) print(RSME(y_test, y_pred.cpu()))
rockerzega/rnn-ejemplo
src/rnn-lib.py
rnn-lib.py
py
1,606
python
en
code
0
github-code
36
[ { "api_name": "funciones.generador", "line_number": 15, "usage_type": "call" }, { "api_name": "clases.STData", "line_number": 26, "usage_type": "call" }, { "api_name": "clases.STData", "line_number": 27, "usage_type": "call" }, { "api_name": "clases.STData", "...
28704089727
#!/usr/bin/env python3 import os import sys from pathlib import Path import logging from pdf_tool import PDF_Tool from form import * from PySide2.QtWidgets import QApplication, QMainWindow from PySide2.QtCore import Qt, QObject, QEvent from PySide2.QtGui import QIcon, QMouseEvent os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" logger = logging.getLogger() logger.setLevel(logging.INFO) class TestListView(QListWidget): fileDropped = Signal(list) def __init__(self, parent=None): super(TestListView, self).__init__(parent) self.setAcceptDrops(True) self.setSelectionMode(QAbstractItemView.ExtendedSelection) self.setIconSize(QSize(72, 72)) self.file_paths = [] self.files = [] def dragEnterEvent(self, event): if event.mimeData().hasUrls: event.accept() else: event.ignore() def dragMoveEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(Qt.CopyAction) event.accept() else: event.ignore() def dropEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(Qt.CopyAction) event.accept() self.files = [u.toLocalFile() for u in event.mimeData().urls() if u.toLocalFile()[-4:] == '.pdf'] difference = list(set(self.files) - set(self.file_paths)) if difference: self.fileDropped.emit(difference) self.file_paths.extend(difference) else: event.ignore() class MainWindow(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self) self.old_position = None self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.header.installEventFilter(self) self.ui.view.installEventFilter(self) self.setWindowIcon(QIcon('icons/pdf.ico')) # frameless window flags = Qt.WindowFlags(Qt.FramelessWindowHint | Qt.WindowMaximizeButtonHint) self.setAttribute(Qt.WA_TranslucentBackground) self.setWindowFlags(flags) # button click events self.ui.maximize_button.clicked.connect(self.window_full_screen) self.ui.exit_button.clicked.connect(self.close) self.ui.minimize_button.clicked.connect(self.showMinimized) self.ui.search_button.clicked.connect(self.get_files) self.ui.word_button.clicked.connect(self.extract_to_docx) self.ui.image_button.clicked.connect(self.extract_images) self.ui.text_botton.clicked.connect(self.extract_text) self.ui.view.fileDropped.connect(self.picture_dropped) self.ui.split_button.clicked.connect(self.split_files) self.ui.merge_button.clicked.connect(self.merge_files) # event filter def eventFilter(self, object: QObject, event: QMouseEvent) -> bool: if object.objectName() == 'header': if event.type() == QEvent.MouseButtonDblClick: self.window_full_screen() return True if event.type() == QEvent.MouseButtonPress: self.old_position = event.globalPos() return True if event.type() == QEvent.MouseMove: delta = QPoint(event.globalPos() - self.old_position) self.move(self.x() + delta.x(), self.y() + delta.y()) self.old_position = event.globalPos() return True if event.type() == QEvent.KeyPress: key = event.key() if key == Qt.Key_Backspace or key == Qt.Key_Delete: self.delete_from_list() return True return QMainWindow.eventFilter(self, object, event) def window_full_screen(self): self.setWindowState(self.windowState() ^ Qt.WindowFullScreen) def get_files(self): dlg = QFileDialog() dlg.setFileMode(QFileDialog.ExistingFiles) dlg.setNameFilters(["Pdf files (*.pdf)"]) if dlg.exec_(): self.ui.view.files = dlg.selectedFiles() difference = list(set(self.ui.view.files) - set(self.ui.view.file_paths)) if difference: self.ui.view.fileDropped.emit(difference) self.ui.view.file_paths.extend(difference) def extract_to_docx(self): error = False if self.ui.view.file_paths: for index, file in enumerate(self.ui.view.file_paths): path = Path(file) output_path = '{}/{}-output/'.format(path.parent, path.stem) if not os.path.exists(output_path): os.makedirs(output_path) docx_file = '{}{}.docx'.format(output_path, path.stem) try: PDF_Tool.convert_to_docx(file, docx_file) except Exception as e: logger.error(e) error = True QMessageBox.critical(self, 'Fehler!', 'Es ist ein Fehler aufgetreten') if not error: error = False QMessageBox.information(self, 'Info', "Alles erfolgreich erstellt") else: QMessageBox.warning( self, "Fehler!", "Es ist kein Pfad ausgewählt", defaultButton=QMessageBox.Ok, ) def extract_images(self): error = False if self.ui.view.file_paths: for index, file in enumerate(self.ui.view.file_paths): path = Path(file) output_path = '{}/{}-output/images'.format(path.parent, path.stem) if not os.path.exists(output_path): os.makedirs(output_path) try: PDF_Tool.extract_images(file, output_path) except Exception as e: logger.error(e) error = True QMessageBox.critical(self, 'Fehler!', 'Es ist ein Fehler aufgetreten') if not error: error = False QMessageBox.information(self, 'Info', "Alles erfolgreich erstellt") else: QMessageBox.warning( self, "Fehler!", "Es ist kein Pfad ausgewählt", defaultButton=QMessageBox.Ok, ) def extract_text(self): error = False if self.ui.view.file_paths: for index, file in enumerate(self.ui.view.file_paths): path = Path(file) output_path = '{}/{}-output/'.format(path.parent, path.stem) text_file = '{}{}.txt'.format(output_path, path.stem) if os.path.exists(text_file): os.remove(text_file) try: PDF_Tool.convert_to_txt(file, text_file) except Exception as e: error = True logger.error(e) QMessageBox.critical(self, 'Fehler!', 'Es ist ein Fehler aufgetreten') if not error: error = False QMessageBox.information(self, 'Info', "Alles erfolgreich erstellt") else: QMessageBox.warning( self, "Fehler!", "Es ist kein Pfad ausgewählt", defaultButton=QMessageBox.Ok, ) def split_files(self): error = False if self.ui.view.file_paths: for index, file in enumerate(self.ui.view.file_paths): output_path = Path(file) output_path = '{}/{}-output/einzelne-seiten'.format(output_path.parent, output_path.stem) if not os.path.exists(output_path): os.makedirs(output_path) try: PDF_Tool.split_files(file, output_path) except Exception as e: error = True logger.error(e) QMessageBox.critical(self, 'Fehler!', 'Es ist ein Fehler aufgetreten') if not error: error = False QMessageBox.information(self, 'Info', "Alles erfolgreich erstellt") else: QMessageBox.warning( self, "Fehler!", "Es ist kein Pfad ausgewählt", defaultButton=QMessageBox.Ok, ) def merge_files(self): if self.ui.view.file_paths: path = Path(self.ui.view.file_paths[0]) text, ok = QInputDialog.getText(self, 'Pdf-Files vereinen', 'Name eingeben') if ok: try: output_path = '{}/{}.pdf'.format(str(path.parent), text) PDF_Tool.merge_files(self.ui.view.file_paths, output_path) QMessageBox.information(self, 'Info', "Alles erfolgreich erstellt") except Exception as e: logger.error(e) QMessageBox.critical(self, 'Fehler!', 'Es ist ein Fehler aufgetreten') else: QMessageBox.warning( self, "Fehler!", "Es ist kein Pfad ausgewählt", defaultButton=QMessageBox.Ok, ) def delete_from_list(self): items = self.ui.view.selectedItems() if items: for index, item in reversed(list(enumerate(items))): item_text = str(self.ui.view.selectedItems()[index].text()) list_index = self.ui.view.file_paths.index(item_text) self.ui.view.takeItem(list_index) self.ui.view.file_paths.remove(item_text) print(self.ui.view.file_paths) def picture_dropped(self, files): for url in files: if os.path.exists(url): icon = QIcon(url) pixmap = icon.pixmap(72, 72) icon = QIcon(pixmap) item = QListWidgetItem(url, self.ui.view) item.setIcon(icon) item.setStatusTip(url) if __name__ == "__main__": app = QApplication([]) window = MainWindow() window.show() sys.exit(app.exec_())
GschoesserPhilipp/Pdf-Tool-GUI
mainwindow.py
mainwindow.py
py
10,229
python
en
code
0
github-code
36
[ { "api_name": "os.environ", "line_number": 14, "usage_type": "attribute" }, { "api_name": "logging.getLogger", "line_number": 15, "usage_type": "call" }, { "api_name": "logging.INFO", "line_number": 16, "usage_type": "attribute" }, { "api_name": "PySide2.QtCore.Qt...
32805054000
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import svm import time data = pd.read_csv('wdbc.data') # data.info() # data.columns # replace 'M' and 'B' with 1 and 0 data['diagnosis'] = data['diagnosis'].map({'M':1,'B':0}) print (data['diagnosis']) # dataset[1] = dataset[1].map({'M' : 1, 'B' : 0}) # print (dataset[1]) # drop the column 0, which contains 'id' (useless) data.drop('id', axis=1, inplace=True) print (data.head(5)) # dataset.drop(columns=0, axis=1, inplace=True) feature = ['radius_mean','texture_mean', 'smoothness_mean','compactness_mean','symmetry_mean', 'fractal_dimension_mean'] # visualization # data[feature].hist(bins=50, figsize=(20, 15)) # plt.show() from sklearn.model_selection import train_test_split train, test = train_test_split(data,test_size=0.3,train_size=0.7) feature = ['radius_mean','texture_mean', 'smoothness_mean','compactness_mean','symmetry_mean', 'fractal_dimension_mean'] # 2, 3, 6, 7, 10, 11 print (train.shape) train_X = train[feature] train_y = train['diagnosis'] test_X = test[feature] test_y = test['diagnosis'] print (train_X.head(5)) # min-max normalization def MaxMinNormalization(x): """[0,1] normaliaztion""" x = (x - np.min(x)) / (np.max(x) - np.min(x)) return x train_X = MaxMinNormalization(train_X) test_X = MaxMinNormalization(test_X) print (train_X) print (train_y.shape) def confusion_matrix(y_true, y_pred): matrix = np.zeros([2, 2]) for y_true, y_pred in zip(y_true,y_pred): if y_true == 1 and y_pred == 1: matrix[0][0] += 1 if y_true == 0 and y_pred == 1: matrix[0][1] += 1 if y_true == 0 and y_pred == 0: matrix[1][1] += 1 if y_true == 1 and y_pred == 0: matrix[1][0] += 1 return matrix # Training... # ------------------------ print ("Training...") model = svm.SVC() start = time.thread_time() model.fit(train_X, train_y) ## step 3: testing print ("Testing...") prediction = model.predict(test_X) end = time.thread_time() print ('Time used: ', (end - start)) ## step 4: show the result print ("show the result...") errorCount = 0 for y_res, y_predict in zip(test_y, prediction): if y_res != y_predict: errorCount += 1 print ('The classify accuracy is: ', (len(test_y) - errorCount) / len(test_y)) c_matrix = confusion_matrix(test_y, prediction) print (c_matrix)
Siyuan-gwu/Machine-Learning-SVM-Diagnostic
venv/SVM.py
SVM.py
py
2,386
python
en
code
1
github-code
36
[ { "api_name": "pandas.read_csv", "line_number": 7, "usage_type": "call" }, { "api_name": "sklearn.model_selection.train_test_split", "line_number": 25, "usage_type": "call" }, { "api_name": "numpy.min", "line_number": 37, "usage_type": "call" }, { "api_name": "num...
7737901543
from django.contrib import admin from django.urls import include, path from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions schema_view = get_schema_view( openapi.Info( title="Wallet API", default_version='v1', description="Application made for tracking your transactions", contact=openapi.Contact(email="eugene.osakovich@gmail.com"), license=openapi.License(name="License"), ), public=True, permission_classes=[permissions.AllowAny], ) urlpatterns = [ path('schema/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-wallet-api'), path('admin/', admin.site.urls), path('api/', include('api.urls')), ]
sheirand/Wallet
core/urls.py
urls.py
py
743
python
en
code
0
github-code
36
[ { "api_name": "drf_yasg.views.get_schema_view", "line_number": 7, "usage_type": "call" }, { "api_name": "drf_yasg.openapi.Info", "line_number": 8, "usage_type": "call" }, { "api_name": "drf_yasg.openapi", "line_number": 8, "usage_type": "name" }, { "api_name": "dr...
42576586601
"""" Detecção de Relógio """ import cv2 classificador = cv2.CascadeClassifier('cascades\\relogios.xml') imagem = cv2.imread('outros\\relogio2.jpg') imagemcinsa = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY) detectado = classificador.detectMultiScale(imagemcinsa, scaleFactor= 1.01, minSize=(10,10), minNeighbors=10) for (x, y, l, a) in detectado: cv2.rectangle(imagem, (x, y), (x + l, y + a), (0, 0, 255), 2) cv2.imshow('itens',imagem) cv2.waitKey()
alans96/PythonProject
Computer Vision/1 Detecção de Faces com Python e OpenCV/6 exe.py
6 exe.py
py
459
python
pt
code
0
github-code
36
[ { "api_name": "cv2.CascadeClassifier", "line_number": 6, "usage_type": "call" }, { "api_name": "cv2.imread", "line_number": 8, "usage_type": "call" }, { "api_name": "cv2.cvtColor", "line_number": 9, "usage_type": "call" }, { "api_name": "cv2.COLOR_BGR2GRAY", "...
22355060265
import re from collections import ChainMap from os import environ from pathlib import Path from subprocess import run import pytest import yaml here = Path(__file__).absolute().parent tests_dir = here.parent root = tests_dir.parent # Need to be in root for docker context tmp_dockerfile = Path(root / "Dockerfile.mlrun-test-nb") with (here / "Dockerfile.test-nb").open() as fp: dockerfile_template = fp.read() docker_tag = "mlrun/test-notebook" def mlrun_api_configured(): config_file_path = here / "test-notebooks.yml" with config_file_path.open() as fp: config = yaml.safe_load(fp) return config["env"].get("MLRUN_DBPATH") is not None def iterate_notebooks(): if not mlrun_api_configured(): return [] config_file_path = here / "test-notebooks.yml" with config_file_path.open() as fp: config = yaml.safe_load(fp) general_env = config["env"] for notebook_test_config in config["notebook_tests"]: # fill env keys that reference the general env test_env = {} for key, value in notebook_test_config.get("env", {}).items(): match = re.match(r"^\$\{(?P<env_var>.*)\}$", value) if match is not None: env_var = match.group("env_var") env_var_value = general_env.get(env_var) if env_var_value is None: raise ValueError( f"Env var {env_var} references general env, but it does not exist there" ) test_env[key] = env_var_value else: test_env[key] = value notebook_test_config["env"] = test_env yield pytest.param( notebook_test_config, id=notebook_test_config["notebook_name"] ) def args_from_env(env): external_env = {} for env_var_key in environ: if env_var_key.startswith("MLRUN_"): external_env[env_var_key] = environ[env_var_key] env = ChainMap(env, external_env) args, cmd = [], [] for name in env: value = env[name] args.append(f"ARG {name}") cmd.extend(["--build-arg", f"{name}={value}"]) args = "\n".join(args) return args, cmd @pytest.mark.skipif( not mlrun_api_configured(), reason="This is an integration test, add the needed environment variables in test-notebooks.yml " "to run it", ) @pytest.mark.parametrize("notebook", iterate_notebooks()) def test_notebook(notebook): path = f'./examples/{notebook["notebook_name"]}' args, args_cmd = args_from_env(notebook["env"]) deps = [] for dep in notebook.get("pip", []): deps.append(f"RUN python -m pip install --upgrade {dep}") pip = "\n".join(deps) code = dockerfile_template.format(notebook=path, args=args, pip=pip) with tmp_dockerfile.open("w") as out: out.write(code) cmd = ( ["docker", "build", "--file", str(tmp_dockerfile), "--tag", docker_tag] + args_cmd + ["."] ) out = run(cmd, cwd=root) assert out.returncode == 0, "cannot build"
mlrun/mlrun
tests/integration/test_notebooks.py
test_notebooks.py
py
3,076
python
en
code
1,129
github-code
36
[ { "api_name": "pathlib.Path", "line_number": 10, "usage_type": "call" }, { "api_name": "pathlib.Path", "line_number": 14, "usage_type": "call" }, { "api_name": "yaml.safe_load", "line_number": 23, "usage_type": "call" }, { "api_name": "yaml.safe_load", "line_n...
11580789914
import re import chatterbot from chatterbot.trainers import ListTrainer from chatterbot import ChatBot import logging logger = logging.getLogger() logger.setLevel(logging.ERROR) f = open('E:\\ProjectWork\\ImranV.1.0\\dataset.txt','r') train_data = [] for line in f: m = re.search('(Q:|A:)?(.+)', line) if m: train_data.append(m.groups()[1]) chatbot = ChatBot( "Terminal", storage_adapter="chatterbot.storage.SQLStorageAdapter", #allows the chat bot to connect to SQL databases input_adapter="chatterbot.input.TerminalAdapter", #allows a user to type into their terminal to communicate with the chat bot. logic_adapters=['chatterbot.logic.BestMatch','chatterbot.logic.MathematicalEvaluation',], output_adapter="chatterbot.output.TerminalAdapter", # print chatbot responce #database="../database.db" # specify the path to the database that the chat bot will use database_uri='sqlite:///database.sqlite3' ) trainer = ListTrainer(chatbot) trainer.train(train_data) print("Type your question here...") while True: try: chatbot_input = chatbot.get_response(input("Type here: ")) print(chatbot_input) # Press ctrl-c or ctrl-d to exit except(KeyboardInterrupt, EOFError, SystemExit): break
AakashMaheedar1998/ChatBot
Chatbot2.py
Chatbot2.py
py
1,320
python
en
code
0
github-code
36
[ { "api_name": "logging.getLogger", "line_number": 6, "usage_type": "call" }, { "api_name": "logging.ERROR", "line_number": 7, "usage_type": "attribute" }, { "api_name": "re.search", "line_number": 13, "usage_type": "call" }, { "api_name": "chatterbot.ChatBot", ...
9627005158
import numpy as np import pandas as pd from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from PyQt5 import QtGui from PyQt5.QtWidgets import * import sys from PIL import Image from wordCloud.WC import Ui_MainWindow from wordcloud import WordCloud from wordcloud import ImageColorGenerator from collections import Counter from konlpy.tag import Hannanum import matplotlib.pyplot as plt from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas class Main(QMainWindow, Ui_MainWindow): def __init__(self): super().__init__() self.setupUi(self) self.lines = "" # 연설문 self.nowlang = self.lang.currentText() self.eg_wordlist = [] self.kr_wordlist = [] self.mask = None self.canvas = None self.textbutton.clicked.connect(self.choseText) self.imgbutton.clicked.connect(self.choseImage) self.langbutton.clicked.connect(self.choselang) def clearAll(self): self.lines = "" self.plainTextEdit.clear() for i in reversed(range(self.verticalLayout.count())): self.verticalLayout.itemAt(i).widget().setParent(None) # layout비우는 방법 for i in reversed(range(self.verticalLayout_2.count())): self.verticalLayout_2.itemAt(i).widget().setParent(None) def choselang(self): self.nowlang = self.lang.currentText() def choseImage(self): for i in reversed(range(self.verticalLayout_2.count())): self.verticalLayout_2.itemAt(i).widget().setParent(None) fileName, _ = QFileDialog.getOpenFileName(self, '불러올 img file을 선택하세요.', '', 'img Files(*.png)') if fileName: self.mask = np.array(Image.open(fileName)) if self.nowlang == "영어": self.makeImgWordCloud(self.eg_wordlist) else: self.makeImgWordCloud(self.kr_wordlist) self.label_2.setPixmap(QtGui.QPixmap(fileName).scaled(400, 300)) def choseText(self): self.clearAll() fileName, _ = QFileDialog.getOpenFileName(self, '불러올 txt file을 선택하세요.', '', 'txt Files(*.txt)') self.label.setText(fileName.split("/")[-1].split(".")[0] + " WordCloud") if fileName: f = open(fileName, "r", encoding="cp949") if self.nowlang == "영어": self.lines = f.readlines()[0] f.close() self.makeEgWordList() else: self.lines = f.readlines() f.close() self.makeKrWordList() def makeEgWordList(self): tokenizer = RegexpTokenizer("[\w]+") # word 단위로 구분하라 stop_words = stopwords.words("english") # 단어는 자주 등장하지만 실제 의미 분석에는 의미 없는단어 words = self.lines.lower() tokens = tokenizer.tokenize(words) stopped_tokens = [i for i in list(tokens) if not i in stop_words] self.eg_wordlist = [i for i in stopped_tokens if len(i) > 1] self.makeTop20Word(self.eg_wordlist) self.makeWordCloud(self.eg_wordlist) def flatten(self, l): flatList = [] for elem in l: if type(elem) == list: for e in elem: flatList.append(e) else: flatList.append(elem) return flatList def makeKrWordList(self): hannanum = Hannanum() temp = [] for i in range(len(self.lines)): temp.append(hannanum.nouns(self.lines[i])) word_list = self.flatten(temp) self.kr_wordlist = pd.Series([x for x in word_list if len(x) > 1]) self.makeTop20Word(self.kr_wordlist) self.makeWordCloud(self.kr_wordlist) def makeTop20Word(self, wordlist): keys = pd.Series(wordlist).value_counts().head(20).keys() values = pd.Series(wordlist).value_counts().head(20).values for i in range(len(keys)): self.plainTextEdit.appendPlainText("{} : {}개".format(keys[i], values[i])) def makeWordCloud(self, wordlist): font_path = '/Library/Fonts/AppleGothic.ttf' wordcloud = WordCloud(font_path=font_path, width=800, height=800, background_color="white") count = Counter(wordlist) wordcloud = wordcloud.generate_from_frequencies(count) def __array__(self): return self.to_array() def to_array(self): return np.array(self.to_image()) array = wordcloud.to_array() fig = plt.figure() plt.imshow(array, interpolation="bilinear") self.canvas = FigureCanvas(fig) self.canvas.draw() self.verticalLayout.addWidget(self.canvas) self.canvas.show() def makeImgWordCloud(self, wordlist): font_path = '/Library/Fonts/AppleGothic.ttf' count = Counter(wordlist) wc = WordCloud(font_path=font_path, mask=self.mask, background_color="white") wc = wc.generate_from_frequencies(count) image_color = ImageColorGenerator(self.mask) fig = plt.figure(figsize=(8, 8)) plt.imshow(wc.recolor(color_func=image_color), interpolation="bilinear") plt.axis("off") self.canvas = FigureCanvas(fig) self.canvas.draw() self.verticalLayout_2.addWidget(self.canvas) self.canvas.show() if __name__ == '__main__': app = QApplication(sys.argv) you_viewer_main = Main() you_viewer_main.show() app.exec_()
LeeDong-Min/WordCloud
text_mining(moon_and_trump).py
text_mining(moon_and_trump).py
py
5,583
python
en
code
0
github-code
36
[ { "api_name": "wordCloud.WC.Ui_MainWindow", "line_number": 27, "usage_type": "name" }, { "api_name": "numpy.array", "line_number": 61, "usage_type": "call" }, { "api_name": "PIL.Image.open", "line_number": 61, "usage_type": "call" }, { "api_name": "PIL.Image", ...
21398256786
# /usr/bin/python # -*- coding: utf-8 -*- """ This program is to: reconstruct sentences from a given data file CS137B, programming assignment #1, Spring 2015 """ import re __author__ = 'Keigh Rim' __date__ = '2/1/2015' __email__ = 'krim@brandeis.edu' if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument( "--i", help="name of a data file" ) parser.add_argument( "--o", help="name of the output file" ) args = parser.parse_args() path = "../dataset/" sent = "" tags = "" with open(path+args.i) as in_file, open("../" + args.o, 'w') as out_file: for line in in_file: if re.search(r"^\s+$", line): sent += "\n" tags += "\n" out_file.write(sent) out_file.write(tags) out_file.write("\n") sent = "" tags = "" else: sent += line.split("\t")[1] + "\t" tags += line.split("\t")[2] + "\t"
keighrim/bananaNER
scripts/sent_reconst.py
sent_reconst.py
py
1,087
python
en
code
1
github-code
36
[ { "api_name": "argparse.ArgumentParser", "line_number": 18, "usage_type": "call" }, { "api_name": "re.search", "line_number": 34, "usage_type": "call" } ]
16154335818
from django import forms from django.utils.translation import ugettext_lazy as _ from django.core.validators import EmailValidator from django.conf import settings from django.core.mail import EmailMessage from django.template.loader import get_template from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Field, Layout, Submit # Form for contacting Web-CDI team. Asks for basic contact information and test ID. Simple format. class ContactForm(forms.Form): contact_name = forms.CharField(label=_("Your Name"), required=True, max_length=51) contact_email = forms.EmailField( label=_("Your Email Address"), required=True, max_length=201, validators=[EmailValidator()], ) contact_id = forms.CharField( label=_("Your Test URL"), required=True, max_length=101 ) content = forms.CharField( label=_("What would you like to tell us?"), required=True, widget=forms.Textarea(attrs={"cols": 80, "rows": 6}), max_length=1001, ) def __init__(self, *args, **kwargs): self.redirect_url = kwargs.pop("redirect_url", "") super().__init__(*args, **kwargs) self.fields["contact_id"].initial = self.redirect_url self.helper = FormHelper() self.helper.form_class = "form-horizontal" self.helper.label_class = "col-lg-3" self.helper.field_class = "col-lg-9" self.helper.layout = Layout( Field("contact_name"), Field("contact_email"), Field("contact_id", css_class="form-control-plaintext"), Field("content"), Div( Submit("submit", _("Submit")), css_class="col-lg-offset-3 col-lg-9 text-center", ), ) def send_email(self): cleaned_data = self.cleaned_data template = get_template("cdi_forms/administration_contact_email_template.txt") context = { "contact_name": cleaned_data['contact_name'], "contact_id": cleaned_data['contact_id'], "contact_email": cleaned_data['contact_email'], "form_content": cleaned_data['content'], } content = template.render(context) email = EmailMessage( "New contact form submission", content, settings.CONTACT_EMAIL, [settings.USER_ADMIN_EMAIL], headers={"Reply-To": cleaned_data['contact_email']}, ) email.send()
langcog/web-cdi
webcdi/cdi_forms/forms/contact_form.py
contact_form.py
py
2,511
python
en
code
7
github-code
36
[ { "api_name": "django.forms.Form", "line_number": 14, "usage_type": "attribute" }, { "api_name": "django.forms", "line_number": 14, "usage_type": "name" }, { "api_name": "django.forms.CharField", "line_number": 15, "usage_type": "call" }, { "api_name": "django.for...
40536503890
import requests import json import os import _G from datetime import datetime import utils PREV_NEWS_FILE = '.mtd_prevnews.json' NEWS_URL = os.getenv('MTD_NEWS_URL') WEBHOOK_URL = os.getenv('MTD_WEBHOOK_URL') MTD_NEWS_TAG = { 1: 'MAINTENANCE', 2: 'UPDATE', 3: 'GACHA', 4: 'EVENT', 5: 'CAMPAIGN', 6: 'BUG', 7: 'MISC', } MTD_NEWS_ICON = { 1: 'https://cdn-icons-png.flaticon.com/512/777/777081.png', 2: 'https://cdn.icon-icons.com/icons2/1508/PNG/512/updatemanager_104426.png', 3: 'https://cdn-icons-png.flaticon.com/512/4230/4230567.png', 4: 'https://cdn-icons-png.flaticon.com/512/4285/4285436.png', 5: 'https://cdn-icons-png.flaticon.com/512/3867/3867424.png', 6: 'https://www.iconsdb.com/icons/preview/red/error-7-xxl.png', 7: 'https://cdn-icons-png.flaticon.com/512/1827/1827301.png' } MTD_NEWS_COLOR = { 1: 0xfc3aef, 2: 0x5299f7, 3: 0xfad73c, 4: 0x50faf4, 5: 0xff5cb0, 6: 0xdb043e, 7: 0xcccccc, } MTD_VOCAB_JP = { 'NEWS_TAG': { 1: 'メンテナンス', 2: 'アップデート', 3: 'ガチャ', 4: 'イベント', 5: 'キャンペーン', 6: '不具合', 7: 'その他', } } def get_webhook_url(): global WEBHOOK_URL return WEBHOOK_URL def get_news_data(): return requests.get(NEWS_URL).json()['newsList'] def get_old_news(): ret = {} if not os.path.exists(PREV_NEWS_FILE): ret = get_news_data() ret = sorted(ret, key=lambda o: -o['id']) with open(PREV_NEWS_FILE, 'w') as fp: json.dump(ret, fp) else: with open(PREV_NEWS_FILE, 'r') as fp: ret = json.load(fp) return ret async def update(): news = {} try: news = get_news_data() news = sorted(news, key=lambda o: -o['id']) except Exception as err: utils.handle_exception(err) return if not news or 'service unavailable' in news[0]['message'].lower(): _G.log_warning("News data endpoint failure:") if news: _G.log_warning(news[0]['message']) return olds = get_old_news() o_cksum = 0 _G.log_debug("Checking MTD news") if olds: o_cksum = int(datetime.fromisoformat(olds[0]['postedAt']).timestamp()) n_cksum = int(datetime.fromisoformat(news[0]['postedAt']).timestamp()) if o_cksum > n_cksum: _G.log_warning(f"Old news newer than latest news ({o_cksum} > {n_cksum})") elif o_cksum == n_cksum: _G.log_debug("No news, skip") return _G.log_info("Gathering MTD news") ar = [] for n in news: if not olds or n['id'] > olds[0]['id']: ar.insert(0, n) else: break for a in ar: try: send_message(a) except Exception as err: utils.handle_exception(err) with open(PREV_NEWS_FILE, 'w') as fp: json.dump(news, fp) def send_message(obj): payload = {} payload['embeds'] = [{ 'author': { 'name': MTD_VOCAB_JP['NEWS_TAG'][obj['tag']], 'icon_url': MTD_NEWS_ICON[obj['tag']], }, 'title': f"**{obj['title']}**", 'description': f"<t:{int(datetime.fromisoformat(obj['postedAt']).timestamp())}>", 'color': MTD_NEWS_COLOR[obj['tag']], 'fields': [] }] # this will fail if total length is over 6000 for msg in utils.chunk(obj['message'], 1000): payload['embeds'][0]['fields'].append({ 'name': " \u200b", # zero-width space 'value': msg }) return requests.post(get_webhook_url(), json=payload) def init(): pass def reload(): pass
ken1882/RD_Terminator_3k
module/mtd_news.py
mtd_news.py
py
3,622
python
en
code
0
github-code
36
[ { "api_name": "os.getenv", "line_number": 10, "usage_type": "call" }, { "api_name": "os.getenv", "line_number": 11, "usage_type": "call" }, { "api_name": "requests.get", "line_number": 60, "usage_type": "call" }, { "api_name": "os.path.exists", "line_number": ...
22136785531
import os import time import json import torch import random import warnings import torchvision import numpy as np import pandas as pd import pathlib from utils import * from data import HumanDataset from data import process_df from data import process_submission_leakdata_full from data import process_loss_weight from data import process_together_labels from tqdm import tqdm from config import config from datetime import datetime from models.model import * from torch import nn, optim from collections import OrderedDict from torch.autograd import Variable from torch.utils.data.sampler import WeightedRandomSampler from torch.utils.data import DataLoader from torch.optim import lr_scheduler from sklearn.model_selection import train_test_split from timeit import default_timer as timer from sklearn.metrics import f1_score from PIL import Image import matplotlib.pyplot as plt # 1. set random seed random.seed(2050) np.random.seed(2050) torch.manual_seed(2050) torch.cuda.manual_seed_all(2050) os.environ["CUDA_VISIBLE_DEVICES"] = "0" torch.backends.cudnn.benchmark = True warnings.filterwarnings('ignore') index_class_dict = { 0: "Nucleoplasm", 1: "Nuclear membrane", 2: "Nucleoli", 3: "Nucleoli fibrillar center", 4: "Nuclear speckles", 5: "Nuclear bodies", 6: "Endoplasmic reticulum", 7: "Golgi apparatus", 8: "Peroxisomes", 9: "Endosomes", 10: "Lysosomes", 11: "Intermediate filaments", 12: "Actin filaments", 13: "Focal adhesion sites", 14: "Microtubules", 15: "Microtubule ends", 16: "Cytokinetic bridge", 17: "Mitotic spindle", 18: "Microtubule organizing center", 19: "Centrosome", 20: "Lipid droplets", 21: "Plasma membrane", 22: "Cell junctions", 23: "Mitochondria", 24: "Aggresome", 25: "Cytosol", 26: "Cytoplasmic bodies", 27: "Rods & rings" } def check(check_loader, model, folds, val_data_list): model.cuda() model.eval() count = 0 wrong_id = [] wrong_class = [] true_target = [] wrong_target = [] true_name = [] wrong_name = [] pred = [] for i, (image, target) in enumerate(tqdm(check_loader)): with torch.no_grad(): image = image.cuda(non_blocking=True) y_pred = model(image) label = y_pred.sigmoid().cpu().data.numpy() label_orig = label.copy().reshape((-1)) ll = label.copy().reshape((-1)) ll = -ll ll.sort() ll = -ll threshold = config.threshold # if threshold < ll[3]: # threshold = ll[3] label = label >= threshold label = label.reshape(-1) target = np.array(target) target = target.reshape(-1) flag = True for j in range(len(label)): if label[j] != target[j]: flag = False break if not flag or flag: count += 1 name = val_data_list.iloc[i].Id wrong_img_path = os.path.join(config.train_data, name) target1 = ' '.join(list([str(k) for k in np.nonzero(target)])) label1 = ' '.join(list([str(k) for k in np.nonzero(label)])) label1_name = '-&-'.join(list([index_class_dict[k] for k in np.nonzero(label)])) label_orig = ' '.join(list(str('%1.2f' % k) for k in label_orig)) wrong_id.append(str(name)) wrong_class.append(str(flag)) true_target.append(target1) wrong_target.append(label1) pred.append(label_orig) images = np.zeros(shape=(512, 512, 3), dtype=np.float) r = Image.open(wrong_img_path + "_red.png") g = Image.open(wrong_img_path + "_green.png") b = Image.open(wrong_img_path + "_blue.png") y = Image.open(wrong_img_path + "_yellow.png") images[:, :, 0] = np.array(r) / 2 + np.array(y) / 2 images[:, :, 1] = g images[:, :, 2] = b images = images.astype(np.uint8) f0 = plt.figure(0, figsize=(20, 25)) f0.suptitle('%s True:%s Pred:%s Pred_name%s' % (str(flag), target1, label1, label1_name)) ax1 = plt.subplot2grid((5, 4), (0, 0), fig=f0) ax2 = plt.subplot2grid((5, 4), (0, 1)) ax3 = plt.subplot2grid((5, 4), (0, 2)) ax4 = plt.subplot2grid((5, 4), (0, 3)) ax5 = plt.subplot2grid((5, 4), (1, 0), rowspan=4, colspan=4) ax1.imshow(np.array(r), cmap="Reds") ax1.set_title("true:") ax2.imshow(np.array(g), cmap="Greens") ax2.set_title("pred:") ax3.imshow(np.array(b), cmap="Blues") ax4.imshow(np.array(y), cmap="Oranges") ax5.imshow(images) plt.waitforbuttonpress(0) plt.close(f0) if wrong_id is not []: df = pd.DataFrame({ 'Id': wrong_id, 'True': wrong_class, 'True_Target': true_target, 'Pred_Target': wrong_target, 'pred': pred }) df.to_csv('wrong_classification.csv') def main(): fold = config.fold model = get_net() model.cuda() best_model = torch.load( "%s/%s_fold_%s_model_best_%s.pth.tar" % (config.best_models, config.model_name, str(fold), config.best)) model.load_state_dict(best_model["state_dict"]) train_files = pd.read_csv(config.train_csv) external_files = pd.read_csv(config.external_csv) test_files = pd.read_csv(config.test_csv) all_files, test_files, weight_log = process_df(train_files, external_files, test_files) train_data_list, val_data_list = train_test_split(all_files, test_size=0.13, random_state=2050) val_data_list = val_data_list[val_data_list['is_external'] == 0] check_gen = HumanDataset(val_data_list, augument=False, mode="train") check_loader = DataLoader(check_gen, 1, shuffle=False, pin_memory=True, num_workers=6) check(check_loader, model, fold, val_data_list) if __name__ == "__main__": main()
felixchen9099/kaggle_human_protein
my_utils/wrong_classification.py
wrong_classification.py
py
6,274
python
en
code
31
github-code
36
[ { "api_name": "random.seed", "line_number": 35, "usage_type": "call" }, { "api_name": "numpy.random.seed", "line_number": 36, "usage_type": "call" }, { "api_name": "numpy.random", "line_number": 36, "usage_type": "attribute" }, { "api_name": "torch.manual_seed", ...
70992284585
import json, hashlib, hmac, requests def json_encode(data): return json.dumps(data, separators=(',', ':'), sort_keys=True) def sign(data, secret): j = json_encode(data) print('Signing payload: ' + j) h = hmac.new(secret, msg=j.encode(), digestmod=hashlib.sha256) return h.hexdigest() class bitkub_caller: def __init__(self, config): self.API_HOST = 'https://api.bitkub.com' self.API_KEY = config['API_KEY'] self.API_SECRET.extend(map(ord, config['API_SECRET'])) self.API_SECRET = bytearray(config['API_SECRET'].encode()) self.header = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-BTK-APIKEY': self.API_KEY, } def create_payload(self, data = None): signature = sign(data, secret=self.API_SECRET) data['sig'] = signature return data def get_json_response(self, path, payload = None): try: r = requests.get(url = self.API_HOST + path, headers=self.header, data=json_encode(payload)) response = r.json() return response except Exception as e: print(e) return None def post_json_response(self, path, payload = None): try: r = requests.post(url = self.API_HOST + path, headers=self.header, data=json_encode(payload)) print(r.content) response = r.json() return response except Exception as e: print(e) return None def get_server_timestamp(self): try: response = requests.get(self.API_HOST + '/api/servertime') ts = int(response.text) return ts except Exception as e: print(e) return 0 def get_status(self): path = '/api/status' response = self.get_json_response(path) print(response) def get_wallet(self): path = '/api/market/wallet' ts = self.get_server_timestamp() data = { 'ts': ts } payload = self.create_payload(data) response = self.post_json_response(path, payload) print(response) def get_balance(self): path = '/api/market/balances' ts = self.get_server_timestamp() data = { 'ts': ts } payload = self.create_payload(data) print(payload) response = self.post_json_response(path, payload) print(response)
YamatoWestern/investment-bot
bitkub_helpers/bitkub_caller.py
bitkub_caller.py
py
2,601
python
en
code
0
github-code
36
[ { "api_name": "json.dumps", "line_number": 4, "usage_type": "call" }, { "api_name": "hmac.new", "line_number": 9, "usage_type": "call" }, { "api_name": "hashlib.sha256", "line_number": 9, "usage_type": "attribute" }, { "api_name": "requests.get", "line_number"...