max_stars_repo_path
stringlengths
3
269
max_stars_repo_name
stringlengths
4
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.05M
score
float64
0.23
5.13
int_score
int64
0
5
crimsobot/cogs/mystery.py
the-garlic-os/crimsoBOT
0
12763351
import asyncio import discord from discord.ext import commands from crimsobot.bot import CrimsoBOT from crimsobot.utils import tarot from crimsobot.utils import tools as c from crimsobot.utils.tarot import Deck, Suit class Mystery(commands.Cog): def __init__(self, bot: CrimsoBOT): self.bot = bot @commands.group(invoke_without_command=True, brief='Delve into the mysteries of tarot.') async def tarot(self, ctx: commands.Context) -> None: """Do you seek wisdom and guidance? Unveil the Mysteries of the past, the present, and the future with a tarot reading. A brief meaning of each card appears next to its name. Meditate deeply upon the words of wise crimsoBOT, and all shall become clear... You may choose to have a specific question in mind before you ask for your cards. However, taking a reading without a question in mind may help coax from you the reason you seek the tarot's guidance. """ # if no subcommand provided, give a three-card reading await self.ppf(ctx) @tarot.command(name='one', brief='Get a single reading.') @commands.cooldown(3, 300, commands.BucketType.user) async def one(self, ctx: commands.Context, spread: str = 'one') -> None: """This single-card reading is your answer to any question you may have.""" fp, descriptions = await tarot.reading(spread) filename = 'reading.png' f = discord.File(fp, 'reading.png') embed = c.crimbed( title="{}'s reading".format(ctx.author), descr=None, attachment=filename, footer='Type ">tarot card" for more on a specific card.', ) card_tuple = descriptions[0] embed.add_field(name=card_tuple[0], value='**{}**\n{}'.format(card_tuple[1], card_tuple[2])) await ctx.send(file=f, embed=embed) @tarot.command(name='ppf', brief='Past, present, and future.') @commands.cooldown(3, 300, commands.BucketType.user) async def ppf(self, ctx: commands.Context, spread: str = 'ppf') -> None: """This three-card spread is read from left to right to explore your past, present, and future.""" fp, descriptions = await tarot.reading(spread) filename = 'reading.png' f = discord.File(fp, filename) embed = c.crimbed( title="{}'s reading".format(ctx.author), descr=None, attachment=filename, footer='Type ">tarot card" for more on a specific card.', ) for card_tuple in descriptions: embed.add_field(name=card_tuple[0], value='**{}**\n{}'.format(card_tuple[1], card_tuple[2])) await ctx.send(file=f, embed=embed) @tarot.command(name='five', brief='Look deeper into your Reason and Potential.') @commands.cooldown(3, 300, commands.BucketType.user) async def five(self, ctx: commands.Context, spread: str = 'five') -> None: """This spread delves deeper into the present, exploring your Reason for seeking guidance. The Future card speaks toward the outcome should you stay on your current path. The Potential card looks toward the outcome should you change paths.""" fp, descriptions = await tarot.reading(spread) filename = 'reading.png' f = discord.File(fp, filename) embed = c.crimbed( title="{}'s reading".format(ctx.author), descr=None, attachment=filename, footer='Type ">tarot card" for more on a specific card.', ) for card_tuple in descriptions: embed.add_field(name=card_tuple[0], value='**{}**\n{}'.format(card_tuple[1], card_tuple[2])) await ctx.send(file=f, embed=embed) @tarot.command(name='card', brief='Inspect an individual card.') async def card(self, ctx: commands.Context) -> None: """Inspect an individual tarot card. A longer description is given for each.""" # the suits suits = [s for s in Suit] suit_list = [] for idx, suit in enumerate(suits): suit_list.append('{}. {}'.format(idx + 1, suit)) # prompt 1 of 2: choose suit embed = c.crimbed( title='Choose a suit:', descr='\n'.join(suit_list), thumb_name='wizard', footer='Type the number to choose.' ) prompt_suit = await ctx.send(embed=embed) # define check for suit def suit_check(msg: discord.Message) -> bool: try: valid_choice = 0 < int(msg.content) <= len(suits) in_channel = msg.channel == ctx.message.channel is_author = msg.author == ctx.message.author return valid_choice and in_channel and is_author except ValueError: return False # wait for user to spcify suit try: msg = await self.bot.wait_for('message', check=suit_check, timeout=45) except asyncio.TimeoutError: await prompt_suit.delete() return await prompt_suit.delete() if msg is None: return suit_choice = int(msg.content) await msg.delete() # prompt 2 of 2: choose card in suit suit = suits[suit_choice - 1] cards = await Deck.get_cards_in_suit(suit) card_list = [] for card in cards: card_list.append('{}. {}'.format(card.number, card.name)) embed = c.crimbed( title='Choose a card:', descr='\n'.join(card_list), thumb_name='wizard', footer='Type the number to choose.', ) prompt_card = await ctx.send(embed=embed) # define check for card def card_check(msg: discord.Message) -> bool: try: card_numbers = [c.number for c in cards] valid_choice = int(msg.content) in card_numbers in_channel = msg.channel == ctx.message.channel is_author = msg.author == ctx.message.author return valid_choice and in_channel and is_author except ValueError: return False # wait for user to spcify suit try: msg = await self.bot.wait_for('message', check=card_check, timeout=20) except asyncio.TimeoutError: await prompt_card.delete() return await prompt_card.delete() if msg is None: return card_number = int(msg.content) await msg.delete() card = await Deck.get_card(suit, card_number) fp = await card.get_image_buff() filename = 'card.png' f = discord.File(fp, filename) embed = c.crimbed( title='**{}**'.format(card.name.upper()), descr='\n'.join([ '**Element:** {}'.format(card.element), '**Upright:** {}'.format(card.description_upright), '**Reversed:** {}'.format(card.description_reversed), '\n{}'.format(card.description_long), ]), attachment=filename, ) await ctx.send(file=f, embed=embed) def setup(bot: CrimsoBOT) -> None: bot.add_cog(Mystery(bot))
2.640625
3
sr/app/middleware/ebay.py
Vyto96/SRP
2
12763352
from flask import jsonify, redirect, request, session from . import middle import requests, os from urllib.parse import unquote, quote @middle.route('/ebay/get_token', methods=['POST', 'GET']) def ebay_auth(): url = os.environ.get('EBAY_RUNAME') return redirect(url) @middle.route('/ebay/get_token/response/', methods=['GET', 'POST']) def ebay_auth_code_response(): # POST REQ per chiedere il token url = 'https://api.ebay.com/identity/v1/oauth2/token' #HEADER headers = { 'Content-Type': "application/x-www-form-urlencoded", 'Authorization': os.environ.get('EBAY_B64_CREDENTIAL') } #BODY payload = { 'grant_type': 'authorization_code', 'code': request.args['code'], 'redirect_uri': os.environ.get('EBAY_URI') } r =requests.post(url, data=payload, headers=headers).json() return jsonify( r ) ################################################################################################################### # { # "access_token": "v^1.1#i^1#p^3#r^1...XzMjRV4xMjg0", # "expires_in": 7200, # "refresh_token": "v^1.1#i^1#p^3#r^1...zYjRV4xMjg0", # "refresh_token_expires_in": 47304000, # "token_type": "User Access Token" # } # { # "access_token": "v^1.1#i ... AjRV4yNjA=", # "expires_in": 7200, # "token_type":"User Access Token" # } @middle.route('/ebay/refresh_token', methods=['POST']) def ebay_refresh_token(): refresh_token = request.form['refresh_token'] url = 'https://api.ebay.com/identity/v1/oauth2/token' headers = { 'Content-Type': "application/x-www-form-urlencoded", 'Authorization': os.environ.get('EBAY_B64_CREDENTIAL') } #BODY payload = { 'grant_type': 'refresh_token', 'refresh_token': refresh_token, 'scope': os.environ.get('EBAY_SCOPE_LIST') } resp = requests.post(url, data=payload, headers=headers).json() return jsonify( access_token=resp['access_token'] ) @middle.route('/ebay/get_report') def ebay_get_report(): tk = request.headers.get('token') if tk: mktp = request.args['marketplace'] start_date = request.args['start_date'] end_date = request.args['end_date'] url_api = 'https://api.ebay.com/sell/analytics/v1/traffic_report' auth = 'Bearer ' + tk headers = { 'Authorization': auth } dim = 'DAY' params = { "filter": 'marketplace_ids:{' + mktp + '},date_range:[' + start_date + '..' + end_date +']', "dimension": dim, "metric": "LISTING_VIEWS_TOTAL,TRANSACTION,SALES_CONVERSION_RATE" } response = requests.get(url_api, headers=headers, params=params) r = response.json() if 'errors' in r.keys(): # error che indica l'aggiornamento del token return jsonify(error='ERRORE: ' + r.get('errors')[0]['message'] , error_code=401) start_report = r['startDate'][:10] end_report = r['endDate'][:10] report = [] for i in r['records']: date = i['dimensionValues'][0]['value'] date = date[:4] + '/' + date[4:6] + '/' + date[6:8] tot_views = i['metricValues'][0]['value'] transactions = i['metricValues'][1]['value'] scr = i['metricValues'][2]['value'] #SALES_CONVERSION_RATE report.append({ 'date': date, 'tot_views': tot_views, 'transactions': transactions, 'scr': scr }) return jsonify( start_report=start_report, end_report=end_report, report=report) else: return jsonify(error='token non ricevuto' , error_code=401)
2.71875
3
preprocess_stamp_aug_zebra.py
AlamiMejjati/neurips18_hierchical_image_manipulation
0
12763353
import os import glob from shutil import copy2 from PIL import Image import json import numpy as np import argparse import shutil from skimage import io from tqdm import tqdm class NpEncoder(json.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() else: return super(NpEncoder, self).default(obj) def copy_file(src, dst): if os.path.exists(dst): os.rmdir(dst) shutil.copytree(src, dst) def construct_box(inst_root, label_root, dst): inst_list = os.listdir(inst_root) cls_list = os.listdir(label_root) for inst, cls in zip(*(inst_list, cls_list)): inst_map = Image.open(os.path.join(inst_root, inst)) # inst_map = Image.open(inst) inst_map = np.array(inst_map, dtype=np.int32) cls_map = Image.open(os.path.join(label_root, cls)) # cls_map = Image.open(cls) cls_map = np.array(cls_map, dtype=np.int32) H, W = inst_map.shape # get a list of unique instances inst_info = {'imgHeight':H, 'imgWidth':W, 'objects':{}} inst_ids = np.unique(inst_map) for iid in inst_ids: if int(iid) <=0: # filter out non-instance masks continue ys,xs = np.where(inst_map==iid) ymin, ymax, xmin, xmax = \ ys.min(), ys.max(), xs.min(), xs.max() cls_label = np.median(cls_map[inst_map==iid]) inst_info['objects'][str(iid)] = {'bbox': [xmin, ymin, xmax, ymax], 'cls':int(cls_label)} # write a file to path filename = os.path.splitext(os.path.basename(inst))[0] savename = os.path.join(dst, filename + '.json') with open(savename, 'w') as f: json.dump(inst_info, f, cls=NpEncoder) print('wrote a bbox summary of %s to %s' % (inst, savename)) def copy_label(src_path, dst_path1, dst_path2): for img_name in tqdm(os.listdir(src_path)): if '.png' in img_name: img = io.imread(os.path.join(src_path, img_name)) img[img == 255] = 30 io.imsave(os.path.join(dst_path1, img_name), img) img = img.astype('uint16') img[img == 30] = 30*1000 io.imsave(os.path.join(dst_path2, img_name), img) def process_files(source_base_path, target_base_pth, subset, COCO_path): dst_path = {} for name in ['img','label','inst','bbox']: cur_path = os.path.join(target_base_pth, subset + '_' + name) if not os.path.exists(cur_path): os.makedirs(cur_path) dst_path[name] = cur_path print('process label and inst copy') copy_label(source_base_path, dst_path['label'], dst_path['inst']) ### copy_file(dst_path['label'], dst_path['inst']) print('process img copy') if COCO_path: copy_img_file(source_base_path, dst_path['img'], COCO_path+'/'+subset+'2017') construct_box(dst_path['inst'], dst_path['label'], dst_path['bbox']) def copy_img_file(source_base_path, target_base_path, COCO_path): print({target_base_path}) for filepath in tqdm(os.listdir(source_base_path)): if ('.png' in filepath) or ('.jpg' in filepath): basename = os.path.basename(filepath).split('.')[0] filename = basename.split('_')[0] indexid = basename.split('_')[1] if os.path.isfile(COCO_path + '/' + filename + '.jpg'): os.symlink(COCO_path + '/' + filename + '.jpg', target_base_path + '/' + filename+'_'+indexid+'.jpg') else: print('File %s.jpg not Found. Please check mannually.' %filename) # organize image if __name__ == '__main__': parser = argparse.ArgumentParser(description='List the content of a folder') parser.add_argument('-s', '--subset', help='class for training the model', type=str) parser.add_argument('-d', '--datapath',default='/home/yam28/Documents/phdYoop/datasets/COCO', type=str) args = parser.parse_args() source_base_path_train = 'dataset/train/' + args.subset source_base_path_train_aug = 'dataset/train/' + args.subset+'_silvia' source_base_path_valid = 'dataset/val/' + args.subset target_base_pth = 'datasets/stamp_' + args.subset + '_aug' COCO_path = args.datapath process_files(source_base_path_train_aug, target_base_pth, 'train', None)
2.3125
2
backend/kale/tests/assets/kfp_dsl/pipeline_parameters_and_metrics.py
adamjm/kale
0
12763354
import kfp.dsl as dsl import json import kfp.components as comp from collections import OrderedDict from kubernetes import client as k8s_client def create_matrix(d1: int, d2: int): pipeline_parameters_block = ''' d1 = {} d2 = {} '''.format(d1, d2) block1 = ''' import numpy as np ''' block2 = ''' rnd_matrix = np.random.rand(d1, d2) ''' block3 = ''' from kale.utils import kfp_utils as _kale_kfp_utils _kale_kfp_metrics = { "d1": d1, "d2": d2 } _kale_kfp_utils.generate_mlpipeline_metrics(_kale_kfp_metrics) ''' data_saving_block = ''' # -----------------------DATA SAVING START--------------------------------- from kale.marshal import utils as _kale_marshal_utils _kale_marshal_utils.set_kale_data_directory("/marshal") _kale_marshal_utils.save(rnd_matrix, "rnd_matrix") # -----------------------DATA SAVING END----------------------------------- ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (pipeline_parameters_block, block1, block2, block3, data_saving_block) html_artifact = _kale_run_code(blocks) with open("/create_matrix.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('create_matrix') def sum_matrix(): data_loading_block = ''' # -----------------------DATA LOADING START-------------------------------- from kale.marshal import utils as _kale_marshal_utils _kale_marshal_utils.set_kale_data_directory("/marshal") _kale_marshal_utils.set_kale_directory_file_names() rnd_matrix = _kale_marshal_utils.load("rnd_matrix") # -----------------------DATA LOADING END---------------------------------- ''' block1 = ''' import numpy as np ''' block2 = ''' sum_result = rnd_matrix.sum() ''' block3 = ''' from kale.utils import kfp_utils as _kale_kfp_utils _kale_kfp_metrics = { "sum-result": sum_result } _kale_kfp_utils.generate_mlpipeline_metrics(_kale_kfp_metrics) ''' # run the code blocks inside a jupyter kernel from kale.utils.jupyter_utils import run_code as _kale_run_code from kale.utils.kfp_utils import \ update_uimetadata as _kale_update_uimetadata blocks = (data_loading_block, block1, block2, block3, ) html_artifact = _kale_run_code(blocks) with open("/sum_matrix.html", "w") as f: f.write(html_artifact) _kale_update_uimetadata('sum_matrix') create_matrix_op = comp.func_to_container_op(create_matrix) sum_matrix_op = comp.func_to_container_op(sum_matrix) @dsl.pipeline( name='hp-test-rnd', description='' ) def auto_generated_pipeline(booltest='True', d1='5', d2='6', strtest='test'): pvolumes_dict = OrderedDict() volume_step_names = [] volume_name_parameters = [] marshal_vop = dsl.VolumeOp( name="kale_marshal_volume", resource_name="kale-marshal-pvc", modes=dsl.VOLUME_MODE_RWM, size="1Gi" ) volume_step_names.append(marshal_vop.name) volume_name_parameters.append(marshal_vop.outputs["name"].full_name) pvolumes_dict['/marshal'] = marshal_vop.volume volume_step_names.sort() volume_name_parameters.sort() create_matrix_task = create_matrix_op(d1, d2)\ .add_pvolumes(pvolumes_dict)\ .after() step_limits = {'nvidia.com/gpu': '2'} for k, v in step_limits.items(): create_matrix_task.container.add_resource_limit(k, v) create_matrix_task.container.working_dir = "/kale" create_matrix_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update({'mlpipeline-metrics': '/mlpipeline-metrics.json'}) output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update({'create_matrix': '/create_matrix.html'}) create_matrix_task.output_artifact_paths.update(output_artifacts) dep_names = create_matrix_task.dependent_names + volume_step_names create_matrix_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: create_matrix_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) sum_matrix_task = sum_matrix_op()\ .add_pvolumes(pvolumes_dict)\ .after(create_matrix_task) sum_matrix_task.container.working_dir = "/kale" sum_matrix_task.container.set_security_context( k8s_client.V1SecurityContext(run_as_user=0)) output_artifacts = {} output_artifacts.update({'mlpipeline-metrics': '/mlpipeline-metrics.json'}) output_artifacts.update( {'mlpipeline-ui-metadata': '/mlpipeline-ui-metadata.json'}) output_artifacts.update({'sum_matrix': '/sum_matrix.html'}) sum_matrix_task.output_artifact_paths.update(output_artifacts) dep_names = sum_matrix_task.dependent_names + volume_step_names sum_matrix_task.add_pod_annotation( "kubeflow-kale.org/dependent-templates", json.dumps(dep_names)) if volume_name_parameters: sum_matrix_task.add_pod_annotation( "kubeflow-kale.org/volume-name-parameters", json.dumps(volume_name_parameters)) if __name__ == "__main__": pipeline_func = auto_generated_pipeline pipeline_filename = pipeline_func.__name__ + '.pipeline.tar.gz' import kfp.compiler as compiler compiler.Compiler().compile(pipeline_func, pipeline_filename) # Get or create an experiment and submit a pipeline run import kfp client = kfp.Client() experiment = client.create_experiment('hp-tuning') # Submit a pipeline run from kale.utils.kfp_utils import generate_run_name run_name = generate_run_name('hp-test-rnd') run_result = client.run_pipeline( experiment.id, run_name, pipeline_filename, {})
2.140625
2
VPhys_MET.py
JCCPort/Tests
0
12763355
<filename>VPhys_MET.py import pandas as pd import numpy as np import scipy as sc import math import numba as nb
1.289063
1
image_registration/matrix.py
nehagoyal1994/mito
0
12763356
<gh_stars>0 import cv2, math, imutils import numpy as np import os def matrixHomographyAligned(ptsA, ptsB, img, tmp, maskImg, maskTmp): # compute the homography matrix between the two sets of matched points (H, mask) = cv2.findHomography(ptsA, ptsB, method=cv2.RANSAC) # use the homography matrix to align the images (h, w) = tmp.shape[:2] aligned = cv2.warpPerspective(img, H, (w, h)) aligned_mask = cv2.warpPerspective(maskImg, H, (w, h)) return aligned, aligned_mask def matrixAffineAligned(ptsA, ptsB, img, tmp, maskImg, maskTmp): # compute the affine matrix between the two sets of matched points (H, mask) = cv2.estimateAffinePartial2D(ptsA, ptsB) # use the homography matrix to align the images (h, w) = tmp.shape[:2] aligned = cv2.warpAffine(img, H, (w, h)) aligned_mask = cv2.warpAffine(maskImg, H, (w, h)) return aligned, aligned_mask
2.859375
3
psp/caget.py
slaclab/psp
0
12763357
<reponame>slaclab/psp<filename>psp/caget.py<gh_stars>0 #!/usr/bin/env python import pyca from Pv import Pv import sys import time from options import Options def caget(pvname): pv = Pv(pvname) pv.connect(1.) pv.get(False, 1.) pv.disconnect() return pv.value if __name__ == '__main__': options = Options(['pvnames'], ['connect_timeout','get_timeout'], ['ctrl', 'hex']) try: options.parse() except Exception, msg: options.usage(str(msg)) sys.exit() pvnames = options.pvnames.split() ctrl = options.ctrl is not None if options.connect_timeout is not None: connect_timeout = float(options.connect_timeout) else: connect_timeout = 1.0 if options.get_timeout is not None: get_timeout = float(options.get_timeout) else: get_timeout = 1.0 for pvname in pvnames: try: pv = Pv(pvname) pv.connect(connect_timeout) pv.get(ctrl, get_timeout) if ctrl: print "%-30s " %(pv.name), pv.data else: if pv.status == pyca.NO_ALARM: ts = time.localtime(pv.secs+pyca.epoch) tstr = time.strftime("%Y-%m-%d %H:%M:%S", ts) if options.hex is not None: print "%-30s %08x.%08x" %(pv.name, pv.secs, pv.nsec), pv.value else: print "%-30s %s.%09d" %(pv.name, tstr, pv.nsec), pv.value else: print "%-30s %s %s" %(pv.name, pyca.severity[pv.severity], pyca.alarm[pv.status]) except pyca.pyexc, e: print 'pyca exception: %s' %(e) except pyca.caexc, e: print 'channel access exception: %s' %(e)
2.203125
2
app/__init__.py
rilder-almeida/projeto_case_enfase
0
12763358
from .core import get_dataset
1.03125
1
src/main.py
chilin0525/model-layer-profiling
0
12763359
from . import argv import os import sys import json import csv from . import dlprof_parser from .show_gpu_info import show_gpu from .profiling_command import * def to_dict(result): tmp = dict() tmp["summary"] = list() for i in result: tmp["summary"].append( i.to_dict() ) return tmp def write2file(filename,fileformat,result): if(fileformat=="json"): result = to_dict(result) with open(filename+'.json', 'w+', encoding='utf-8') as f: json.dump(result, f, ensure_ascii=False, indent=4) elif(fileformat=="csv"): with open(filename+'.csv', 'w+', encoding='UTF8') as f: writer = csv.writer(f) title = ["op type","gpu duration", "api call start", "kernel name"] writer.writerow(title) for i in result: writer.writerow(i.to_list()) else: tmp = sys.stdout sys.stdout = open(filename, "w+") for i in result: i.printall() sys.stdout = tmp def rm_log(verbose:bool): if(verbose): os.system("rm -rf log/") def main(): args = argv.argparsing() gpu = show_gpu(False) if(args.function=="gpuinfo"): for i in gpu: i.print_info() elif(args.function=="profile"): command = generate_command(args.model_type, args.gpu_idx,args.command) os.system(command) log_file_name = "log/dlprof_iteration.json" dlprof_result = dlprof_parser.parsing(log_file_name) write2file(args.output_filename, args.format, dlprof_result) rm_log(args.log) if __name__ == "__main__": main()
2.78125
3
stix2/v20/vocab.py
frank7y/cti-python-stix2
277
12763360
""" STIX 2.0 open vocabularies and enums """ ATTACK_MOTIVATION_ACCIDENTAL = "accidental" ATTACK_MOTIVATION_COERCION = "coercion" ATTACK_MOTIVATION_DOMINANCE = "dominance" ATTACK_MOTIVATION_IDEOLOGY = "ideology" ATTACK_MOTIVATION_NOTORIETY = "notoriety" ATTACK_MOTIVATION_ORGANIZATIONAL_GAIN = "organizational-gain" ATTACK_MOTIVATION_PERSONAL_GAIN = "personal-gain" ATTACK_MOTIVATION_PERSONAL_SATISFACTION = "personal-satisfaction" ATTACK_MOTIVATION_REVENGE = "revenge" ATTACK_MOTIVATION_UNPREDICTABLE = "unpredictable" ATTACK_MOTIVATION = [ ATTACK_MOTIVATION_ACCIDENTAL, ATTACK_MOTIVATION_COERCION, ATTACK_MOTIVATION_DOMINANCE, ATTACK_MOTIVATION_IDEOLOGY, ATTACK_MOTIVATION_NOTORIETY, ATTACK_MOTIVATION_ORGANIZATIONAL_GAIN, ATTACK_MOTIVATION_PERSONAL_GAIN, ATTACK_MOTIVATION_PERSONAL_SATISFACTION, ATTACK_MOTIVATION_REVENGE, ATTACK_MOTIVATION_UNPREDICTABLE, ] ATTACK_RESOURCE_LEVEL_INDIVIDUAL = "individual" ATTACK_RESOURCE_LEVEL_CLUB = "club" ATTACK_RESOURCE_LEVEL_CONTEST = "contest" ATTACK_RESOURCE_LEVEL_TEAM = "team" ATTACK_RESOURCE_LEVEL_ORGANIZATION = "organization" ATTACK_RESOURCE_LEVEL_GOVERNMENT = "government" ATTACK_RESOURCE_LEVEL = [ ATTACK_RESOURCE_LEVEL_INDIVIDUAL, ATTACK_RESOURCE_LEVEL_CLUB, ATTACK_RESOURCE_LEVEL_CONTEST, ATTACK_RESOURCE_LEVEL_TEAM, ATTACK_RESOURCE_LEVEL_ORGANIZATION, ATTACK_RESOURCE_LEVEL_GOVERNMENT, ] HASHING_ALGORITHM_MD5 = "MD5" HASHING_ALGORITHM_MD6 = "MD6" HASHING_ALGORITHM_RIPEMD_160 = "RIPEMD-160" HASHING_ALGORITHM_SHA_1 = "SHA-1" HASHING_ALGORITHM_SHA_224 = "SHA-224" HASHING_ALGORITHM_SHA_256 = "SHA-256" HASHING_ALGORITHM_SHA_384 = "SHA-384" HASHING_ALGORITHM_SHA_512 = "SHA-512" HASHING_ALGORITHM_SHA3_224 = "SHA3-224" HASHING_ALGORITHM_SHA3_256 = "SHA3-256" HASHING_ALGORITHM_SHA3_384 = "SHA3-384" HASHING_ALGORITHM_SHA3_512 = "SHA3-512" HASHING_ALGORITHM_SSDEEP = "ssdeep" HASHING_ALGORITHM_WHIRLPOOL = "WHIRLPOOL" HASHING_ALGORITHM = [ HASHING_ALGORITHM_MD5, HASHING_ALGORITHM_MD6, HASHING_ALGORITHM_RIPEMD_160, HASHING_ALGORITHM_SHA_1, HASHING_ALGORITHM_SHA_224, HASHING_ALGORITHM_SHA_256, HASHING_ALGORITHM_SHA_384, HASHING_ALGORITHM_SHA_512, HASHING_ALGORITHM_SHA3_224, HASHING_ALGORITHM_SHA3_256, HASHING_ALGORITHM_SHA3_384, HASHING_ALGORITHM_SHA3_512, HASHING_ALGORITHM_SSDEEP, HASHING_ALGORITHM_WHIRLPOOL, ] IDENTITY_CLASS_INDIVIDUAL = "individual" IDENTITY_CLASS_GROUP = "group" IDENTITY_CLASS_ORGANIZATION = "organization" IDENTITY_CLASS_CLASS = "class" IDENTITY_CLASS_UNKNOWN = "unknown" IDENTITY_CLASS = [ IDENTITY_CLASS_INDIVIDUAL, IDENTITY_CLASS_GROUP, IDENTITY_CLASS_ORGANIZATION, IDENTITY_CLASS_CLASS, IDENTITY_CLASS_UNKNOWN, ] INDICATOR_LABEL_ANOMALOUS_ACTIVITY = "anomalous-activity" INDICATOR_LABEL_ANONYMIZATION = "anonymization" INDICATOR_LABEL_BENIGN = "benign" INDICATOR_LABEL_COMPROMISED = "compromised" INDICATOR_LABEL_MALICIOUS_ACTIVITY = "malicious-activity" INDICATOR_LABEL_ATTRIBUTION = "attribution" INDICATOR_LABEL = [ INDICATOR_LABEL_ANOMALOUS_ACTIVITY, INDICATOR_LABEL_ANONYMIZATION, INDICATOR_LABEL_BENIGN, INDICATOR_LABEL_COMPROMISED, INDICATOR_LABEL_MALICIOUS_ACTIVITY, INDICATOR_LABEL_ATTRIBUTION, ] INDUSTRY_SECTOR_AGRICULTURE = "agriculture" INDUSTRY_SECTOR_AEROSPACE = "aerospace" INDUSTRY_SECTOR_AUTOMOTIVE = "automotive" INDUSTRY_SECTOR_COMMUNICATIONS = "communications" INDUSTRY_SECTOR_CONSTRUCTION = "construction" INDUSTRY_SECTOR_DEFENCE = "defence" INDUSTRY_SECTOR_EDUCATION = "education" INDUSTRY_SECTOR_ENERGY = "energy" INDUSTRY_SECTOR_ENTERTAINMENT = "entertainment" INDUSTRY_SECTOR_FINANCIAL_SERVICES = "financial-services" INDUSTRY_SECTOR_GOVERNMENT_NATIONAL = "government-national" INDUSTRY_SECTOR_GOVERNMENT_REGIONAL = "government-regional" INDUSTRY_SECTOR_GOVERNMENT_LOCAL = "government-local" INDUSTRY_SECTOR_GOVERNMENT_PUBLIC_SERVICES = "government-public-services" INDUSTRY_SECTOR_HEALTHCARE = "healthcare" INDUSTRY_SECTOR_HOSPITALITY_LEISURE = "hospitality-leisure" INDUSTRY_SECTOR_INFRASTRUCTURE = "infrastructure" INDUSTRY_SECTOR_INSURANCE = "insurance" INDUSTRY_SECTOR_MANUFACTURING = "manufacturing" INDUSTRY_SECTOR_MINING = "mining" INDUSTRY_SECTOR_NON_PROFIT = "non-profit" INDUSTRY_SECTOR_PHARMACEUTICALS = "pharmaceuticals" INDUSTRY_SECTOR_RETAIL = "retail" INDUSTRY_SECTOR_TECHNOLOGY = "technology" INDUSTRY_SECTOR_TELECOMMUNICATIONS = "telecommunications" INDUSTRY_SECTOR_TRANSPORTATION = "transportation" INDUSTRY_SECTOR_UTILITIES = "utilities" INDUSTRY_SECTOR = [ INDUSTRY_SECTOR_AGRICULTURE, INDUSTRY_SECTOR_AEROSPACE, INDUSTRY_SECTOR_AUTOMOTIVE, INDUSTRY_SECTOR_COMMUNICATIONS, INDUSTRY_SECTOR_CONSTRUCTION, INDUSTRY_SECTOR_DEFENCE, INDUSTRY_SECTOR_EDUCATION, INDUSTRY_SECTOR_ENERGY, INDUSTRY_SECTOR_ENTERTAINMENT, INDUSTRY_SECTOR_FINANCIAL_SERVICES, INDUSTRY_SECTOR_GOVERNMENT_NATIONAL, INDUSTRY_SECTOR_GOVERNMENT_REGIONAL, INDUSTRY_SECTOR_GOVERNMENT_LOCAL, INDUSTRY_SECTOR_GOVERNMENT_PUBLIC_SERVICES, INDUSTRY_SECTOR_HEALTHCARE, INDUSTRY_SECTOR_HOSPITALITY_LEISURE, INDUSTRY_SECTOR_INFRASTRUCTURE, INDUSTRY_SECTOR_INSURANCE, INDUSTRY_SECTOR_MANUFACTURING, INDUSTRY_SECTOR_MINING, INDUSTRY_SECTOR_NON_PROFIT, INDUSTRY_SECTOR_PHARMACEUTICALS, INDUSTRY_SECTOR_RETAIL, INDUSTRY_SECTOR_TECHNOLOGY, INDUSTRY_SECTOR_TELECOMMUNICATIONS, INDUSTRY_SECTOR_TRANSPORTATION, INDUSTRY_SECTOR_UTILITIES, ] MALWARE_LABEL_ADWARE = "adware" MALWARE_LABEL_BACKDOOR = "backdoor" MALWARE_LABEL_BOT = "bot" MALWARE_LABEL_DDOS = "ddos" MALWARE_LABEL_DROPPER = "dropper" MALWARE_LABEL_EXPLOIT_KIT = "exploit-kit" MALWARE_LABEL_KEYLOGGER = "keylogger" MALWARE_LABEL_RANSOMWARE = "ransomware" MALWARE_LABEL_REMOTE_ACCESS_TROJAN = "remote-access-trojan" MALWARE_LABEL_RESOURCE_EXPLOITATION = "resource-exploitation" MALWARE_LABEL_ROGUE_SECURITY_SOFTWARE = "rogue-security-software" MALWARE_LABEL_ROOTKIT = "rootkit" MALWARE_LABEL_SCREEN_CAPTURE = "screen-capture" MALWARE_LABEL_SPYWARE = "spyware" MALWARE_LABEL_TROJAN = "trojan" MALWARE_LABEL_VIRUS = "virus" MALWARE_LABEL_WORM = "worm" MALWARE_LABEL = [ MALWARE_LABEL_ADWARE, MALWARE_LABEL_BACKDOOR, MALWARE_LABEL_BOT, MALWARE_LABEL_DDOS, MALWARE_LABEL_DROPPER, MALWARE_LABEL_EXPLOIT_KIT, MALWARE_LABEL_KEYLOGGER, MALWARE_LABEL_RANSOMWARE, MALWARE_LABEL_REMOTE_ACCESS_TROJAN, MALWARE_LABEL_RESOURCE_EXPLOITATION, MALWARE_LABEL_ROGUE_SECURITY_SOFTWARE, MALWARE_LABEL_ROOTKIT, MALWARE_LABEL_SCREEN_CAPTURE, MALWARE_LABEL_SPYWARE, MALWARE_LABEL_TROJAN, MALWARE_LABEL_VIRUS, MALWARE_LABEL_WORM, ] REPORT_LABEL_THREAT_REPORT = "threat-report" REPORT_LABEL_ATTACK_PATTERN = "attack-pattern" REPORT_LABEL_CAMPAIGN = "campaign" REPORT_LABEL_IDENTITY = "identity" REPORT_LABEL_INDICATOR = "indicator" REPORT_LABEL_INTRUSION_SET = "intrusion-set" REPORT_LABEL_MALWARE = "malware" REPORT_LABEL_OBSERVED_DATA = "observed-data" REPORT_LABEL_THREAT_ACTOR = "threat-actor" REPORT_LABEL_TOOL = "tool" REPORT_LABEL_VULNERABILITY = "vulnerability" REPORT_LABEL = [ REPORT_LABEL_THREAT_REPORT, REPORT_LABEL_ATTACK_PATTERN, REPORT_LABEL_CAMPAIGN, REPORT_LABEL_IDENTITY, REPORT_LABEL_INDICATOR, REPORT_LABEL_INTRUSION_SET, REPORT_LABEL_MALWARE, REPORT_LABEL_OBSERVED_DATA, REPORT_LABEL_THREAT_ACTOR, REPORT_LABEL_TOOL, REPORT_LABEL_VULNERABILITY, ] THREAT_ACTOR_LABEL_ACTIVIST = "activist" THREAT_ACTOR_LABEL_COMPETITOR = "competitor" THREAT_ACTOR_LABEL_CRIME_SYNDICATE = "crime-syndicate" THREAT_ACTOR_LABEL_CRIMINAL = "criminal" THREAT_ACTOR_LABEL_HACKER = "hacker" THREAT_ACTOR_LABEL_INSIDER_ACCIDENTAL = "insider-accidental" THREAT_ACTOR_LABEL_INSIDER_DISGRUNTLED = "insider-disgruntled" THREAT_ACTOR_LABEL_NATION_STATE = "nation-state" THREAT_ACTOR_LABEL_SENSATIONALIST = "sensationalist" THREAT_ACTOR_LABEL_SPY = "spy" THREAT_ACTOR_LABEL_TERRORIST = "terrorist" THREAT_ACTOR_LABEL = [ THREAT_ACTOR_LABEL_ACTIVIST, THREAT_ACTOR_LABEL_COMPETITOR, THREAT_ACTOR_LABEL_CRIME_SYNDICATE, THREAT_ACTOR_LABEL_CRIMINAL, THREAT_ACTOR_LABEL_HACKER, THREAT_ACTOR_LABEL_INSIDER_ACCIDENTAL, THREAT_ACTOR_LABEL_INSIDER_DISGRUNTLED, THREAT_ACTOR_LABEL_NATION_STATE, THREAT_ACTOR_LABEL_SENSATIONALIST, THREAT_ACTOR_LABEL_SPY, THREAT_ACTOR_LABEL_TERRORIST, ] THREAT_ACTOR_ROLE_AGENT = "agent" THREAT_ACTOR_ROLE_DIRECTOR = "director" THREAT_ACTOR_ROLE_INDEPENDENT = "independent" THREAT_ACTOR_ROLE_INFRASTRUCTURE_ARCHITECT = "infrastructure-architect" THREAT_ACTOR_ROLE_INFRASTRUCTURE_OPERATOR = "infrastructure-operator" THREAT_ACTOR_ROLE_MALWARE_AUTHOR = "malware-author" THREAT_ACTOR_ROLE_SPONSOR = "sponsor" THREAT_ACTOR_ROLE = [ THREAT_ACTOR_ROLE_AGENT, THREAT_ACTOR_ROLE_DIRECTOR, THREAT_ACTOR_ROLE_INDEPENDENT, THREAT_ACTOR_ROLE_INFRASTRUCTURE_ARCHITECT, THREAT_ACTOR_ROLE_INFRASTRUCTURE_OPERATOR, THREAT_ACTOR_ROLE_MALWARE_AUTHOR, THREAT_ACTOR_ROLE_SPONSOR, ] THREAT_ACTOR_SOPHISTICATION_NONE = "none" THREAT_ACTOR_SOPHISTICATION_MINIMAL = "minimal" THREAT_ACTOR_SOPHISTICATION_INTERMEDIATE = "intermediate" THREAT_ACTOR_SOPHISTICATION_ADVANCED = "advanced" THREAT_ACTOR_SOPHISTICATION_EXPERT = "expert" THREAT_ACTOR_SOPHISTICATION_INNOVATOR = "innovator" THREAT_ACTOR_SOPHISTICATION_STRATEGIC = "strategic" THREAT_ACTOR_SOPHISTICATION = [ THREAT_ACTOR_SOPHISTICATION_NONE, THREAT_ACTOR_SOPHISTICATION_MINIMAL, THREAT_ACTOR_SOPHISTICATION_INTERMEDIATE, THREAT_ACTOR_SOPHISTICATION_ADVANCED, THREAT_ACTOR_SOPHISTICATION_EXPERT, THREAT_ACTOR_SOPHISTICATION_INNOVATOR, THREAT_ACTOR_SOPHISTICATION_STRATEGIC, ] TOOL_LABEL_DENIAL_OF_SERVICE = "denial-of-service" TOOL_LABEL_EXPLOITATION = "exploitation" TOOL_LABEL_INFORMATION_GATHERING = "information-gathering" TOOL_LABEL_NETWORK_CAPTURE = "network-capture" TOOL_LABEL_CREDENTIAL_EXPLOITATION = "credential-exploitation" TOOL_LABEL_REMOTE_ACCESS = "remote-access" TOOL_LABEL_VULNERABILITY_SCANNING = "vulnerability-scanning" TOOL_LABEL = [ TOOL_LABEL_DENIAL_OF_SERVICE, TOOL_LABEL_EXPLOITATION, TOOL_LABEL_INFORMATION_GATHERING, TOOL_LABEL_NETWORK_CAPTURE, TOOL_LABEL_CREDENTIAL_EXPLOITATION, TOOL_LABEL_REMOTE_ACCESS, TOOL_LABEL_VULNERABILITY_SCANNING, ]
1.765625
2
chat/discord/discordprivatemessagingserver.py
squahtx/hal9000
0
12763361
from base import InternedCollection from base import InternedNamedCollection from chat import ChatServer from .discordchatchannel import DiscordChatChannel from .discorduser import DiscordUser class DiscordPrivateMessagingServer(ChatServer): def __init__(self, chatService, client): super(DiscordPrivateMessagingServer, self).__init__(chatService) self.client = client self._channels = InternedNamedCollection(lambda x: DiscordChatChannel(self.chatService, self, x), lambda x: x.id) self._users = InternedCollection(lambda x: DiscordUser(self.chatService, self, x), lambda x: x.id) # IServer # Identity @property def id(self): return "PM" @property def globalId(self): return "Discord." + self.id @property def name(self): return "Private Messages" # Server # Channels @property def channelCount(self): return len(self.channels) @property def channels(self): self.updateChannels() return self._channels def getChannelById(self, id): return self.channels.get(id) def getChannelByName(self, name): return self.channels.getByName(name) # Users @property def userCount(self): return len(self.users) @property def users(self): return self._users def getUserById(self, id): return self.usersById.get(id) @property def localUser(self): return self.users.intern(self.client.user) # DiscordPrivateMessagingServer # Internal def updateChannels(self): self._channels.update(self.client.private_channels)
2.546875
3
ipfe/data.py
michaelborck/ipfe
3
12763362
<filename>ipfe/data.py """Additional test images. For more images, see - http://sipi.usc.edu/database/database.php """ import numpy as np from scipy import ndimage from skimage.io import imread import os.path as _osp data_dir = _osp.abspath(_osp.dirname(__file__)) + "/data" def load(f): """Load an image file located in the data directory. Parameters ---------- f : string File name. Returns ------- img : ndarray Image loaded from skimage.data_dir. """ return imread(_osp.join(data_dir, f)) def stinkbug(): """24-bit RGB PNG image of a stink bug Notes ----- This image was downloaded from Matplotlib tutorial <http://matplotlib.org/users/image_tutorial.html> No known copyright restrictions, released into the public domain. """ return load("stinkbug.png") def nuclei(): """Gray-level "cell nuclei" image used for blob processing. Notes ----- This image was downloaded from Pythonvision Basic Tutorial <http://pythonvision.org/media/files/images/dna.jpeg> No known copyright restrictions, released into the public domain. """ return load("nuclei.png") def baboon(): """Baboon. Notes ----- This image was downloaded from the Signal and Image Processing Institute at the University of Southern California. <http://sipi.usc.edu/database/database.php?volume=misc&image=11#top> No known copyright restrictions, released into the public domain. """ return load("baboon.png") def city_depth(): """City depth map. Notes ----- No known copyright restrictions, released into the public domain. """ return load("city_depth.png") def city(): """City. Notes ----- This image was generate form the Earthmine datas set of Perth, Australia. This image is copyright earthmine. """ return load("city.png") def aerial(): """Aerial Sna Diego (shelter Island). Notes ----- This image was downloaded from the Signal and Image Processing Institute at the University of Southern California. <http://sipi.usc.edu/database/database.php?volume=aerials&image=10#top> No known copyright restrictions, released into the public domain. """ return load("aerial.png") def peppers(): """Peppers. Notes ----- This image was downloaded from the Signal and Image Processing Institute at the University of Southern California. <http://sipi.usc.edu/database/database.php?volume=misc&image=11#top> No known copyright restrictions, released into the public domain. """ return load("peppers.png") def sign(): """Sign. """ return load("sign.png") def microstructure(l=256): """Synthetic binary data: binary microstructure with blobs. Parameters ---------- l: int, optional linear size of the returned image Code fragment from scikit-image Medial axis skeletonization see: <http://scikit-image.org/docs/dev/auto_examples/plot_medial_transform.html> No known copyright restrictions, released into the public domain. """ n = 5 x, y = np.ogrid[0:l, 0:l] mask = np.zeros((l, l)) generator = np.random.RandomState(1) points = l * generator.rand(2, n ** 2) mask[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 mask = ndimage.gaussian_filter(mask, sigma=l / (4. * n)) return mask def noisy_blobs(noise=True): """Synthetic binary data: four circles with noise. Parameters ---------- noise: boolean, optional include noise in image Code fragment from 'Image manipulation and processing using Numpy and Scipy' <http://www.tp.umu.se/~nylen/fnm/pylect/advanced/image_processing/index.html> No known copyright restrictions, released into the public domain. """ np.random.seed(1) n = 10 l = 256 blob = np.zeros((l, l)) points = l * np.random.random((2, n ** 2)) blob[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 blob = ndimage.gaussian_filter(blob, sigma=l / (4. * n)) if noise: mask = (blob > blob.mean()).astype(np.float) mask += 0.1 * blob blob = mask + 0.2 * np.random.randn(*mask.shape) return blob def noisy_circles(noise=True): """Synthetic binary data: four circles with noise. Parameters ---------- noise: boolean, optional include noise in image Code fragment from 'Image manipulation and processing using Numpy and Scipy' <http://www.tp.umu.se/~nylen/fnm/pylect/advanced/image_processing/index.html> No known copyright restrictions, released into the public domain. """ l = 100 x, y = np.indices((l, l)) center1 = (28, 24) center2 = (40, 50) center3 = (67, 58) center4 = (24, 70) radius1, radius2, radius3, radius4 = 16, 14, 15, 14 circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1 ** 2 circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2 ** 2 circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3 ** 2 circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4 ** 2 # 4 circles image = circle1 + circle2 + circle3 + circle4 if noise: image = image.astype(float) image += 1 + 0.2 * np.random.randn(*image.shape) return image def noisy_square(noise=True): """Synthetic binary data: square with noise. Parameters ---------- noise: boolean, optional include noise in image Code fragment from scikit-image 'Canny edge detector'. see: <http://scikit-image.org/docs/dev/auto_examples/plot_canny.html> Also in 'Image manipulation and processing using Numpy and Scipy' <http://www.tp.umu.se/~nylen/fnm/pylect/advanced/image_processing/index.html> No known copyright restrictions, released into the public domain. """ # Generate noisy image of a square im = np.zeros((128, 128)) im[32:-32, 32:-32] = 1 im = ndimage.rotate(im, 15, mode='constant') im = ndimage.gaussian_filter(im, 4) im += 0.2 * np.random.random(im.shape) if noise: im = im.astype(float) im += 0.2 * np.random.random(im.shape) return im def mri(): """MRI. Notes ----- This image was created/downloaded from the Matplotlib using the following: dfile= cbook.get_sample_data('s1045.ima', asfileobj=False) im = np.fromstring(file(dfile, 'rb').read(), np.uint16).astype(float) im.shape = 256, 256 im2 = im.astype(float)/float(im.max()) imsave('mri.png',im2) Code frament from 'pylab_examples example code: mri_with_eeg.py' <http://matplotlib.org/examples/pylab_examples/mri_with_eeg.html> No known copyright restrictions, released into the public domain. """ return load("mri.png") def cells(): """Cells From in 'Image manipulation and processing using Numpy and Scipy' section 2.6.6 Measuring object properties <http://www.tp.umu.se/~nylen/fnm/pylect/advanced/image_processing/index.html> No known copyright restrictions, released into the public domain. """ np.random.seed(1) n = 10 l = 256 im = np.zeros((l, l)) points = l * np.random.random((2, n ** 2)) im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 im = ndimage.gaussian_filter(im, sigma=l / (4. * n)) return im def cross(): """Synthetic binary data showing a cross Code fragment from scikit-image: <http://scikit-image.org/docs/dev/auto_examples/plot_hough_transform.html#example-plot-hough-transform-py> No known copyright restrictions, released into the public domain. """ image = np.zeros((100, 100)) idx = np.arange(25, 75) image[idx[::-1], idx] = 255 image[idx, idx] = 255 return image def misc(): """Synthetic binary data Code fragment from scikit-image: <http://scikit-image.org/docs/0.7.0/api/skimage.transform.hough_transform.html> No known copyright restrictions, released into the public domain. """ image = np.zeros((100, 150), dtype=bool) image[30, :] = 1 image[:, 65] = 1 image[35:45, 35:50] = 1 for i in range(90): image[i, i] = 1 image += np.random.random(image.shape) > 0.95 return image def random(same=False): """Synthetic binary data Released into the public domain. """ # Generate standardized random data if same: np.random.seed(seed=1234) else: np.random.seed() return np.random.randint(0, 255, size=(256, 256)) def overlapping_circles(): """Synthetic binary data Generate a binary image with two overlapping circles Released into the public domain. """ x, y = np.indices((80, 80)) x1, y1, x2, y2 = 28, 28, 44, 52 r1, r2 = 16, 20 mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1 ** 2 mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2 ** 2 image = np.logical_or(mask_circle1, mask_circle2) return image
2.5
2
null_model.py
CSB-IG/BioNetworkInference_ModularAnalysis
0
12763363
#written by <NAME> import sys import itertools import random import math import networkx as nx def gnp_random_graph(p, diccionario, m, directed=False): if directed: G=nx.DiGraph() else: G=nx.Graph() G.add_nodes_from(diccionario) if p<=0: return G if p>=1: return nx.complete_graph(n,create_using=G) while(G.number_of_edges() < int(m)): a,b = random.sample(diccionario, 2) a = a.strip() b = b.strip() if (a != b): if random.random() < p: if ((G.has_edge(diccionario[a],diccionario[b]) == False) and (G.has_edge(diccionario[b],diccionario[a]) == False)): G.add_edge(diccionario[a],diccionario[b]) return G ##------------------------------------------------------------------------------------------------------------------------------------------## def gnp_random_graph2(diccionario, m, directed=False): if directed: G=nx.DiGraph() else: G=nx.Graph() G.add_nodes_from(diccionario) n = G.number_of_nodes() #p = float(float(n)/float(m)) p = 2*float(m)/float(n*(n-1)) if p<=0: return G if p>=1: return nx.complete_graph(n,create_using=G) while(G.number_of_edges() < int(m)): a,b = random.sample(diccionario, 2) a = a.strip() b = b.strip() if (a != b): if random.random() < p: if ((G.has_edge(a,b) == False) and (G.has_edge(b,a) == False)): G.add_edge(a,b) return G ##------------------------------------------------------------------------------------------------------------------------------------------## def gnp_random_graph3(diccionario, m, directed=False): if directed: G=nx.DiGraph() else: G=nx.Graph() G.add_nodes_from(diccionario) n = G.number_of_nodes() #p = float(float(n)/float(m)) p = 2*float(m)/float(n*(n-1)) if p<=0: return G if p>=1: return nx.complete_graph(n,create_using=G) #random.seed(seed) if G.is_directed(): edges=itertools.permutations(range(n),2) else: edges=itertools.combinations(range(n),2) for a,b in edges: u=diccionario.keys()[diccionario.values().index(a+1)] v=diccionario.keys()[diccionario.values().index(b+1)] if random.random() < p: G.add_edge(u,v) return G ############################################################################################################################## red = sys.argv[1] sep = sys.argv[2] form = sys.argv[3] tipo = sys.argv[4] diccionario = {} genesDIC = [] izq = [] der = [] name = red.split('.') output = name[0]+'_NullModel.net' SALIDA = open(output,"w") if (sep == "cma"): sep = "," elif (sep == "tab"): sep = "\t" elif (sep == "spa"): sep = " " interacciones = open(red).readlines() print "Lineas interacciones (SIF) = ", len(interacciones) k = 0 tmp="---" for i in interacciones: genes = i.split(sep) #print genes a=genes[0].strip() b=genes[1].strip() c=genes[2].strip() if (form == "nIn"): if (genes[0].strip() not in genesDIC): genesDIC.append(genes[0].strip()) if (genes[2].strip() not in genesDIC): genesDIC.append(genes[2].strip()) elif (form == "nnI"): if (genes[0].strip() not in genesDIC): genesDIC.append(genes[0].strip()) if (genes[1].strip() not in genesDIC): genesDIC.append(genes[1].strip()) SALIDA.write("%s %s \n" % ("*Vertices", len(genesDIC))) i = 1 for n in genesDIC: n = n.strip() diccionario[n] = i SALIDA.write('%s "%s" \n' % (i,n)) i+=1 if (tipo == '1'): p=float(raw_input("p enlace = ")) m0=float(raw_input("aristas m = ")) G = gnp_random_graph(p,diccionario,m0) elif(tipo == '2'): m0=float(raw_input("aristas m = ")) G = gnp_random_graph2(diccionario,m0) elif(tipo == '3'): m0 = len(interacciones) G = gnp_random_graph3(diccionario,m0) output2 = name[0]+'_NullModel.sif' SIF = open(output2,"w") print "Nodos = ", G.number_of_nodes() print "Edges sin repetidos ni selfloops = ", G.number_of_edges() SALIDA.write("%s %s \n" % ("*Edges", G.number_of_edges())) for e in G.edges(): ed = G.get_edge_data(*e) #SALIDA.write("%s %s %s \n" % (e[0],e[1],ed['w'])) #SALIDA.write("%s %s %s \n" % (e[0],e[1],1)) SALIDA.write("%s %s %s \n" % (diccionario[e[0]],diccionario[e[1]],1)) SIF.write("%s\t%s\t%s\n" % (e[0],"pp",e[1])) SALIDA.close() #SIF.write("------\n") if not nx.is_connected(G): print "Componentes = ",nx.number_connected_components(G) for g in nx.connected_components(G): #print g if len(g) <= 2: for n in g: #SIF.write("%s\t%s\t%s\n" % (n,"pp",n)) SIF.write("%s\n" % n) SIF.close()
3.03125
3
guiding.py
StarlightHunter/galaxydslr
0
12763364
""" PHD2 guider helper """ from thirdparty.phd2guider import Guider as PHD2Guider class GuiderHelper: guider = None def connect(self, hostname="localhost"): if self.guider is None: self.guider = PHD2Guider(hostname) self.guider.Connect() def disconnect(self): if self.guider is not None: self.guider.Disconnect() self.guider = None def start_dither(self, dither_px, settle_px, settle_time, settle_timeout): if self.guider is not None: self.guider.Dither(dither_px, settle_px, settle_time, settle_timeout) else: raise Exception("The guider is not connected") def check_settled(self): settling = self.guider.CheckSettling() if settling.Done: if settling.Error: raise Exception(settling.Error) return True, settling return False, settling
2.671875
3
django/utils/migration_helpers.py
Haakenlid/tassen
16
12763365
from django.core import serializers from django.db import connection from psycopg2 import sql def reset_primary_key_index(table, col='id'): """Sets the postgres primary key index to one larger than max""" query = sql.SQL( '''SELECT setval( pg_get_serial_sequence(%(table)s, %(col)s), coalesce(max({col}), 1) ) FROM {table}''' ).format( col=sql.Identifier(col), table=sql.Identifier(table) ) with connection.cursor() as cursor: cursor.execute(query, dict(table=table, col=col)) def load_fixture(fixture_file): """load all items from fixture file""" def _load(apps, schema_editor): original_apps = serializers.python.apps serializers.python.apps = apps tables = set() try: with open(fixture_file) as fixture: objects = serializers.deserialize( 'json', fixture, ignorenonexistent=True ) for obj in objects: obj.save() tables.add(obj.object._meta.db_table) finally: serializers.python.apps = original_apps for table in tables: reset_primary_key_index(table) return _load def unload_fixture(appname, models=()): def _unload(apps, schema_editor): """Brutally deleting all entries for this model...""" for modelname in models: model = apps.get_model(appname, modelname) model.objects.all().delete() reset_primary_key_index(model._meta.db_table) return _unload
2.453125
2
SourceCode/Module13/PartB/taxi.py
hackettccp/CIS106SampleCode
2
12763366
<reponame>hackettccp/CIS106SampleCode #Imports the Bus and Car object from bus import Bus from car import Car """ Taxi Object. """ #Class Header class Taxi(Bus, Car) : #Initializer def __init__(self, make_in, model_in, year_in, riders_in , doors_in) : Bus.__init__(self, make_in, model_in, year_in, riders_in) Car.__init__(self, make_in, model_in, year_in, doors_in) self.meter = 5.0 #Retrieves the meter def getmeter(self) : return self.meter
3.03125
3
pycbio/hgdata/binnerSA.py
diekhans/read-through-analysis
0
12763367
# Copyright 2006-2012 <NAME> """ Version of Binner class that works with sqlalchemy """ from .rangeFinder import Binner from sqlalchemy import and_, or_ class BinnerSA(Binner): """generate sqlalchemy query to find overlapping ranges using bin numbers""" @staticmethod def getOverlappingSqlExpr(seqCol, binCol, startCol, endCol, seq, start, end): """General sqlalchemy experssion to select for overlaps with the specified range. Columns are SA column objects. Returns an and__ object""" # build bin parts parts = [] for bins in Binner.getOverlappingBins(start, end): if bins[0] == bins[1]: parts.append(binCol == bins[0]) else: parts.append(and_(binCol >= bins[0], binCol <= bins[1])) return and_(seqCol == seq, startCol < end, endCol > start, or_(*parts))
2.703125
3
dctorch/functional.py
GallagherCommaJack/dctorch
0
12763368
import torch import scipy.fft import numpy as np from functools import lru_cache @lru_cache() def compute_dct_mat(n: int, device: str, dtype: torch.dtype) -> torch.Tensor: m = scipy.fft.dct(np.eye(n), norm="ortho") return torch.tensor(m, device=device, dtype=dtype) @lru_cache() def compute_idct_mat(n: int, device: str, dtype: torch.dtype) -> torch.Tensor: m = scipy.fft.idct(np.eye(n), norm="ortho") return torch.tensor(m, device=device, dtype=dtype) def dct(t: torch.Tensor) -> torch.Tensor: m = compute_dct_mat(t.shape[-2], device=t.device, dtype=t.dtype) return torch.einsum("...id,ij->jd", t, m) def idct(t: torch.Tensor) -> torch.Tensor: m = compute_idct_mat(t.shape[-2], device=t.device, dtype=t.dtype) return torch.einsum("...id,ij->jd", t, m) def dct2(t: torch.Tensor) -> torch.Tensor: h, w = t.shape[-2:] mh = compute_dct_mat(h, device=t.device, dtype=t.dtype) mw = compute_dct_mat(w, device=t.device, dtype=t.dtype) return torch.einsum("...hw,hi,wj->...ij", t, mh, mw) def idct2(t: torch.Tensor) -> torch.Tensor: h, w = t.shape[-2:] mh = compute_idct_mat(h, device=t.device, dtype=t.dtype) mw = compute_idct_mat(w, device=t.device, dtype=t.dtype) return torch.einsum("...hw,hi,wj->...ij", t, mh, mw) def dct3(t: torch.Tensor) -> torch.Tensor: l, h, w = t.shape[-3:] ml = compute_dct_mat(l, device=t.device, dtype=t.dtype) mh = compute_dct_mat(h, device=t.device, dtype=t.dtype) mw = compute_dct_mat(w, device=t.device, dtype=t.dtype) return torch.einsum("...lhw,li,hj,wk->...ijk", t, ml, mh, mw) def idct3(t: torch.Tensor) -> torch.Tensor: l, h, w = t.shape[-3:] ml = compute_idct_mat(l, device=t.device, dtype=t.dtype) mh = compute_idct_mat(h, device=t.device, dtype=t.dtype) mw = compute_idct_mat(w, device=t.device, dtype=t.dtype) return torch.einsum("...lhw,li,hj,wk->...ijk", t, ml, mh, mw)
2.28125
2
htmlmin/tests/test_decorator.py
Embed-Engineering/django-htmlmin
389
12763369
<filename>htmlmin/tests/test_decorator.py # Copyright 2013 django-htmlmin authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import unittest from django.test.client import Client class TestDecorator(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client() def test_should_minify_the_content_of_a_view_decorated(self): response = self.client.get('/min') minified = b'<html><head></head><body><p>Hello world! :D' + \ b'</p><div>Copyright 3000</div></body></html>' self.assertEquals(minified, response.content) def should_not_touch_the_content_of_an_undecorated_view(self): expected = ''' <html> <body> <p>Hello world! :D</p> <div>Copyright 3000</div> </body> </html> ''' response = self.client.get('/raw') self.assertEquals(expected, response.content) def test_minify_response_should_be_false_in_not_minified_views(self): response = self.client.get('/not_min') self.assertEquals(False, response.minify_response)
2.640625
3
merge.py
willyrv/SSPSC_vs_StSI
1
12763370
<gh_stars>1-10 #!/usr/bin/env python OUTPUT_FILENAME = "output" TOTAL_OF_FILES = 2 if __name__ == "__main__": # make an array of files of size 100 results = [] for i in range(1, TOTAL_OF_FILES+1): a = open("./{}{}.txt".format(OUTPUT_FILENAME, i), 'r') text = a.read() a.close() text = text.split('\n') results.append(text[1:-2]) text = "Original_variable | real_parameters | number_of_observations | log-likelihood_of_real_params | Estim_params_T2_SSPSC | log-likelihood_T2_SSPSC | p-value_T2_SSPSC | Estim_params_T2_StSI | log-likelihood_T2_StSI | p-value_T2_StSI | AIC_selected_model | AIC_relative_prob\n" for line in range(len(results[0])): for i in range(TOTAL_OF_FILES): text+=(i+1).__str__() + ' | ' + results[i][line]+'\n' a = open('100exp_OUTPUT', 'w') a.write(text) a.close()
2.671875
3
virtualEnvironment/lib/python2.7/site-packages/twine/cli.py
tnkteja/myhelp
0
12763371
<filename>virtualEnvironment/lib/python2.7/site-packages/twine/cli.py # Copyright 2013 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import argparse import pkg_resources import setuptools import requests import pkginfo import twine def _registered_commands(group='twine.registered_commands'): return list(pkg_resources.iter_entry_points(group=group)) def dep_versions(): return 'pkginfo: {0}, requests: {1}, setuptools: {2}'.format( pkginfo.Installed(pkginfo).version, # __version__ is always defined but requests does not always have # PKG-INFO to read from requests.__version__, setuptools.__version__, ) def dispatch(argv): registered_commands = _registered_commands() parser = argparse.ArgumentParser(prog="twine") parser.add_argument( "--version", action="version", version="%(prog)s version {0} ({1})".format(twine.__version__, dep_versions()), ) parser.add_argument( "command", choices=[c.name for c in registered_commands], ) parser.add_argument( "args", help=argparse.SUPPRESS, nargs=argparse.REMAINDER, ) args = parser.parse_args(argv) command = args.command for registered_command in registered_commands: if registered_command.name == command: break else: print("{0} is not a valid command.".format(command)) raise SystemExit(True) main = registered_command.load() main(args.args)
2.15625
2
exe0403.py
juniorpedroso/Curso-Intensivo-de-Python
0
12763372
# Exercício 4.3 - List Comprehensions numbers = [value for value in range(1, 21)] print(numbers)
3.46875
3
pygimli/physics/SIP/siptools.py
baender/gimli
224
12763373
<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- """pygimli functions for dc resistivity / SIP data.""" # TODO Please sort the content into SIP package! import pylab as P import numpy as N import pygimli as pg from pygimli.utils import rndig def astausgleich(ab2org, mn2org, rhoaorg): """shifts the branches of a dc sounding to generate a matching curve.""" ab2 = P.asarray(ab2org) mn2 = P.asarray(mn2org) rhoa = P.asarray(rhoaorg) um = P.unique(mn2) for i in range(len(um) - 1): r0, r1 = [], [] ac = P.intersect1d(ab2[mn2 == um[i]], ab2[mn2 == um[i + 1]]) for a in ac: r0.append(rhoa[(ab2 == a) * (mn2 == um[i])][0]) r1.append(rhoa[(ab2 == a) * (mn2 == um[i + 1])][0]) if len(r0) > 0: fak = P.mean(P.array(r0) / P.array(r1)) print(fak) if P.isfinite(fak) and fak > 0.: rhoa[mn2 == um[i + 1]] *= fak return rhoa # formerly pg as vector def loadSIPallData(filename, outnumpy=False): """load SIP data with the columns ab/2,mn/2,rhoa and PHI with the corresponding frequencies in the first row.""" if outnumpy: A = N.loadtxt(filename) fr = A[0, 3:] ab2 = A[1:, 0] mn2 = A[1:, 1] rhoa = A[1:, 2] PHI = A[1:, 3:] else: A = pg.Matrix() pg.loadMatrixCol(A, 'sch/dc.ves') ndata = A.cols() ab2 = A[0](1, ndata) mn2 = A[1](1, ndata) rhoa = A[2](1, ndata) PHI = pg.Matrix() fr = [] for i in range(3, A.rows()): fr.append(A[i][0]) PHI.push_back(A[i](1, ndata)) return ab2, mn2, rhoa, PHI, fr def makeSlmData(ab2, mn2, rhoa=None, filename=None): """generate a pygimli data container from ab/2 and mn/2 array.""" data = pg.DataContainer() data.resize(len(ab2)) pos = N.unique(N.hstack((ab2, mn2))) for elx in N.hstack((-pos[::-1], pos)): data.createElectrode(elx, 0., 0.) if filename is not None: f = open(filename, 'w') f.write(str(len(pos) * 2) + '\n#x y z\n') for elx in N.hstack((-pos[::-1], pos)): f.write(str(elx) + '\t0\t0\n') f.write(str(len(ab2)) + '\n#a\tb\tm\tn\tk\trhoa\n') lpos = len(pos) iab = pos.searchsorted(ab2) imn = pos.searchsorted(mn2) if (filename is not None) & (rhoa is None): rhoa = N.ones(len(ab2)) for i in range(len(iab)): # print -pos[iab[i]], -pos[imn[i]], pos[imn[i]], pos[iab[i]] k = (ab2[i]**2 - mn2[i]**2) * N.pi / mn2[i] / 2.0 if filename is not None: f.write(str(lpos - iab[i]) + '\t' + str(lpos + iab[i] + 1) + '\t') f.write(str(lpos - imn[i]) + '\t' + str(lpos + imn[i] + 1) + '\t') f.write(str(rndig(k, 4)) + '\t' + str(rhoa[i]) + '\n') data.createFourPointData(i, int(lpos - iab[i]), int(lpos + iab[i] + 1), int(lpos - imn[i]), int(lpos + imn[i] + 1)) if filename is not None: f.close() data.set('rhoa', pg.asvector(rhoa)) return data def showsounding(ab2, rhoa, resp=None, mn2=None, islog=True, xlab=None): """ Display a sounding curve (rhoa over ab/2) and an additional response. """ if xlab is None: xlab = r'$\rho_a$ in $\Omega$m' ab2a = N.asarray(ab2) rhoa = N.asarray(rhoa) if mn2 is None: if islog: l1 = P.loglog(rhoa, ab2, 'rx-', label='observed') else: l1 = P.semilogy(rhoa, ab2, 'rx-', label='observed') P.hold(True) if resp is not None: if islog: l2 = P.loglog(resp, ab2, 'bo-', label='simulated') else: l2 = P.semilogy(resp, ab2, 'bo-', label='simulated') P.legend((l1, l2), ('obs', 'sim'), loc=0) else: for unmi in N.unique(mn2): if islog: l1 = P.loglog(rhoa[mn2 == unmi], ab2a[mn2 == unmi], 'rx-', label='observed') else: l1 = P.semilogy(rhoa[mn2 == unmi], ab2a[mn2 == unmi], 'rx-', label='observed') P.hold(True) if resp is not None: l2 = P.loglog(resp[mn2 == unmi], ab2a[mn2 == unmi], 'bo-', label='simulated') P.legend((l1, l2), ('obs', 'sim')) P.axis('tight') P.ylim((max(ab2), min(ab2))) locs = P.yticks()[0] if len(locs) < 2: locs = N.hstack((min(ab2), locs, max(ab2))) else: locs[0] = max(locs[0], min(ab2)) locs[-1] = min(locs[-1], max(ab2)) a = [] for l in locs: a.append('%g' % rndig(l)) P.yticks(locs, a) locs = P.xticks()[0] a = [] for l in locs: a.append('%g' % rndig(l)) P.xticks(locs, a) P.grid(which='both') P.xlabel(xlab) P.ylabel('AB/2 in m') # P.legend() P.show() return def showsip1ddata(PHI, fr, ab2, mn2=None, cmax=None, ylab=True, cbar=True): """display SIP phase data as image plot.""" P.cla() ax = P.gca() pal = P.cm.get_cmap() pal.set_under('w') pal.set_bad('w') if isinstance(PHI, pg.Vector): PHI = N.asarray(PHI) im = P.imshow(PHI.reshape((len(ab2), len(fr))), interpolation='nearest', cmap=pal) if cmax is None: cmax = N.max(PHI) im.set_clim((0., cmax)) ax.xaxis.set_label_position('top') P.xlabel('f in Hz') a = [] df = 1 for f in fr[::df]: a.append("%g" % rndig(f)) P.xticks(N.arange(0, len(fr), df), a) xtl = ax.get_xticklabels() for i, xtli in enumerate(xtl): xtli.set_rotation('vertical') if ylab: a = [] yla = 'AB/2' if mn2 is None: for i in range(len(ab2)): a.append(str(ab2[i])) else: yla = yla + '-MN/2' for i in range(len(ab2)): a.append('%g%g' % (rndig(ab2[i]), rndig(mn2[i]))) P.yticks(N.arange(len(ab2)), a) P.ylabel(yla + ' in m') if cbar: P.colorbar(aspect=40, shrink=0.6) P.ylim((len(ab2) - 0.5, -0.5)) P.show() P.ylim((len(ab2) - 0.5, -0.5)) return def showsip1dmodel(M, tau, thk, res=None, z=None, cmin=None, cmax=None, islog=True): """ Display an SIP Debye block model as image. """ if z is None: z = N.cumsum(N.hstack((0., thk))) P.cla() pal = P.cm.get_cmap() pal.set_under('w') pal.set_bad('w') if isinstance(M, pg.Vector): M = N.asarray(M) if islog: M = N.log10(M) M = M.reshape((len(z), len(tau))) im = P.imshow(M, interpolation='nearest', cmap=pal) if cmax is None: cmax = N.max(M) if cmax is None: cmax = N.max(M) im.set_clim((cmin, cmax)) a = [] for t in tau[::2]: a.append("%g" % rndig(t * 1000, 2)) P.xticks(N.arange(0, len(tau), 2), a) a = [] for zi in z: a.append(str(zi)) P.yticks(N.arange(len(z)) - 0.5, a) P.xlabel(r'$\tau$ in ms') P.ylabel('z in m') P.ylim((len(z) - 0.5, -0.5)) P.colorbar(orientation='horizontal', aspect=40, shrink=0.6) if res is not None: xl = P.xlim()[1] for i in range(len(res)): P.text(xl, i, r' %g $\Omega$m' % rndig(res[i], 2)) lgm = N.zeros((len(z), 1)) tch = N.zeros((len(z), 1)) lgt = N.log(tau) if islog: M = 10**M for n in range(len(M)): m = N.abs(M[n]) tch[n] = N.sum(m) lgm[n] = N.exp(N.sum(m * lgt) / N.sum(m)) tpos = N.interp(N.log(lgm), N.log(tau), N.arange(len(tau))) P.plot(tpos, N.arange(len(z)), 'w*') P.title('logarithmized spectral chargeability') P.show() return lgm, tch class DebyeModelling(pg.core.ModellingBase): """forward operator for Debye decomposition.""" def __init__(self, fvec, tvec=None, zero=False, verbose=False): if tvec is None: tvec = N.logspace(-4, 0, 5) mesh = pg.meshtools.createMesh1D(len(tvec)) if zero: mesh.cell(0).setMarker(-1) mesh.cell(len(tvec) - 1).setMarker(1) pg.core.ModellingBase.__init__(self, mesh, verbose) self.f_ = pg.asvector(fvec) self.t_ = tvec self.zero_ = zero def response(self, par): """phase spectrum as function of spectral chargeabilities.""" y = pg.Vector(len(self.f_), 0.0) for (t, p) in zip(self.t_, par): wt = self.f_ * 2.0 * P.pi * t y = y + wt / (wt * wt + 1.) * p return y def DebyeDecomposition(fr, phi, maxfr=None, tv=None, verbose=False, zero=False, err=0.25e-3, lam=10., blocky=False): """Debye decomposition of a phase spectrum.""" if maxfr is not None: idx = (fr <= maxfr) & (phi >= 0.) phi1 = phi[idx] fr1 = fr[idx] print("using frequencies from ", N.min(fr), " to ", N.max(fr), "Hz") else: phi1 = phi fr1 = fr if tv is None: tmax = 1. / N.min(fr1) / 2. / N.pi * 4. tmin = 1. / N.max(fr1) / 2. / N.pi / 8. tvec = N.logspace(N.log10(tmin), N.log10(tmax), 30) else: tvec = tv f = DebyeModelling(fr1, tvec, zero=zero) tvec = f.t_ tm = pg.trans.TransLog() start = pg.Vector(len(tvec), 1e-4) if zero: f.region(-1).setConstraintType(0) # smoothness f.region(0).setConstraintType(1) # smoothness f.region(1).setConstraintType(0) # min length f.regionManager().setInterRegionConstraint(-1, 0, 1.) f.regionManager().setInterRegionConstraint(0, 1, 1.) f.region(-1).setTransModel(tm) f.region(0).setTransModel(tm) f.region(1).setTransModel(tm) f.region(-1).setModelControl(1000.) f.region(1).setModelControl(1000.) else: f.regionManager().setConstraintType(1) # smoothness inv = pg.Inversion(pg.asvector(phi1 * 1e-3), f, verbose) inv.setAbsoluteError(pg.Vector(len(fr1), err)) inv.setLambda(lam) inv.setModel(start) inv.setBlockyModel(blocky) if zero: inv.setReferenceModel(start) else: inv.setTransModel(tm) mvec = inv.run() resp = inv.response() return tvec, mvec, N.array(resp) * 1e3, idx class DoubleColeColeModelling(pg.core.ModellingBase): """ Modelling using two Cole-Cole terms """ def __init__(self, mesh, fvec, si=1.0, verbose=False): pg.core.ModellingBase.__init__(self, mesh, verbose) self.f_ = fvec self.si_ = si def response(self, par): """yields phase response response of double Cole Cole model.""" y = pg.Vector(self.f_.size(), 0.0) wti = self.f_ * par[1] * 2.0 * P.pi wte = self.f_ * par[4] * 2.0 * P.pi for i in range(0, y.size()): cpI = 1. / (N.power(wti[i] * 1j, par[2]) + 1.) cpE = 1. / (N.power(wte[i] * 1j, par[5]) + 1.) y[i] = - N.imag(cpI) * par[0] - N.imag(cpE) * par[3] * self.si_ # y[i] = - par[0] - N.imag(cpE) * par[3] * self.si_ return y def ReadAndRemoveEM(filename, readsecond=False, doplot=False, dellast=True, ePhi=0.5, ePerc=1., lam=2000.): """ Read res1file and remove EM effects using a double-Cole-Cole model fr,rhoa,phi,dphi = ReadAndRemoveEM(filename, readsecond/doplot bools) """ fr, rhoa, phi, drhoa, dphi = read1resfile(filename, readsecond, dellast=dellast) # forward problem mesh = pg.meshtools.createMesh1D(1, 6) # 6 independent parameters f = DoubleColeColeModelling(mesh, pg.asvector(fr), phi[2] / abs(phi[2])) f.regionManager().loadMap("region.control") model = f.createStartVector() # inversion inv = pg.Inversion(phi, f, True, False) inv.setAbsoluteError(phi * ePerc * 0.01 + ePhi / 1000.) inv.setRobustData(True) # inv.setCWeight(pg.Vector(6, 1.0)) # wozu war das denn gut? inv.setMarquardtScheme(0.8) inv.setLambda(lam) inv.setModel(model) erg = inv.run() inv.echoStatus() chi2 = inv.chi2() mod0 = pg.Vector(erg) mod0[0] = 0.0 # set IP term to zero to obtain pure EM term emphi = f.response(mod0) resid = (phi - emphi) * 1000. if doplot: s = "IP: m= " + str(rndig(erg[0])) + " t=" + str(rndig(erg[1])) + \ " c =" + str(rndig(erg[2])) s += " EM: m= " + str(rndig(erg[3])) + " t=" + str(rndig(erg[4])) + \ " c =" + str(rndig(erg[5])) fig = P.figure(1) fig.clf() ax = P.subplot(111) P.errorbar( fr, phi * 1000., yerr=dphi * 1000., fmt='x-', label='measured') ax.set_xscale('log') P.semilogx(fr, emphi * 1000., label='EM term (CC)') P.errorbar(fr, resid, yerr=dphi * 1000., label='IP term') ax.set_yscale('log') P.xlim((min(fr), max(fr))) P.ylim((0.1, max(phi) * 1000.)) P.xlabel('f in Hz') P.ylabel(r'-$\phi$ in mrad') P.grid(True) P.title(s) P.legend(loc=2) # ('measured','2-cole-cole','residual')) fig.show() return N.array(fr), N.array(rhoa), N.array(resid), N.array( phi) * 1e3, dphi, chi2, N.array(emphi) * 1e3
2.3125
2
xmlutil/__init__.py
yangaound/xmlutil
0
12763374
# -*- coding: utf-8 -*- ''' Source: https://github.com/yangaound/xmlutil Created on 2016年12月24日 @author: albin ''' import re import abc import itertools from collections import defaultdict try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict import petl try: from lxml import etree except ImportError: from xml.etree import cElementTree as etree except ImportError: from xml.etree import ElementTree as etree __version__ = '1.0.0' namespace_pattern = re.compile(r"{.+}") def parse(filename, *args, **kwargs): """factory method, return a new instance of XMLNode""" element = etree.parse(filename, *args, **kwargs).getroot() return XMLNode(element) def get_tag(element): """return the element's local name""" return re.sub(namespace_pattern, '', element.tag) def get_namespace(element): """return the element's namespace""" return re.sub(get_tag(element), '', element.tag) class BridgeNode(object): __metaclass__ = abc.ABCMeta def __init__(self, element): """Abstract class, it wraps an element as a implementor :type element: ``lxml.etree.Element`` or ``xml.etree.ElementTree.Element`` """ if element is None: raise TypeError("Argument 'element' should be an instance of lxml.etree.Element or xml.etree.ElementTree.Element") self.element = element @abc.abstractmethod def to_dicts(self, **kwargs): """expands the wrapped element tree into a ``sequence``. :return: ``list<dict>``""" def to_table(self, inclusive_tags=(), exclusive_tags=(), duplicate_tags=(), with_element=False, with_attrib=False, ): dicts = self.to_dicts(duplicate_tags=duplicate_tags, with_element=with_element, with_attrib=with_attrib, ) table = dicts2table(dicts) if inclusive_tags: header = [field for tag in inclusive_tags for field in table.header() if (tag == field) or field.startswith(tag + '_')] table = table.cut(*header) elif exclusive_tags: header = [field for tag in exclusive_tags for field in table.header() if (tag == field) or field.startswith(tag + '_')] table = table.cutout(*header) return table def findall(self, expression, **kwargs): """Wraps the result of executing expression into a ``GroupNode`` and return it""" return self._execute_expression(self.element, 'findall', expression, **kwargs) def xpath(self, expression, **kwargs): """Wraps the result of executing expression into a ``GroupNode`` and return it""" return self._execute_expression(self.element, 'xpath', expression, **kwargs) def _execute_expression(self, target_node, func_name, expression, **kwargs): """executes expression over target_node methods named func_name""" func = getattr(target_node, func_name) elements = func(expression, **kwargs) return GroupNode((XMLNode(e) for e in elements)) def join(self, other, key=None, **petl_kwargs): """join this node and other node as a ``RelatedNode`` """ return self.relate(other, 'join', key=key, **petl_kwargs) def crossjoin(self, other, **petl_kwargs): """crossjoin this node and other node as a ``RelatedNode`` """ return self.relate(other, 'crossjoin', **petl_kwargs) def relate(self, other, relation, **petl_kwargs): """relate this node and other node as a ``RelatedNode`` over relation. relation is a function name of petl package""" return RelatedNode(self, other, relation, **petl_kwargs) def tag(self): return get_tag(self.element) def namespace(self): return get_namespace(self.element) def nsmap(self, sub=None): nsmap = self.element.nsmap return dict((k if k else sub, v) for k, v in nsmap.items()) def __repr__(self): return "<%s %s at 0x%x>" % (self.__class__.__name__, self.tag(), id(self)) class EmptyNode(BridgeNode): """This class just use to relates another nodes""" def __init__(self): pass def to_dicts(self, **kwargs): """implement""" return [] def __repr__(self): return "<%s %s at 0x%x>" % (self.__class__.__name__, 'None', id(self)) class XMLNode(BridgeNode): """This class wraps an instance of ``lxml.etree.Element`` or ``xml.etree.ElementTree.Element`` as a implementor""" def to_dicts(self, **kwargs): """implement""" dicts = DFSExpansion(self.element, **kwargs).expand() return dicts def remove(self): parent = self.element.getparent() parent.remove(self.element) def find(self, expression, **kwargs): element = self.element.find(expression, **kwargs) return XMLNode(element) class GroupNode(BridgeNode, list): def __init__(self, nodes): """This class wraps a not empty collection :type nodes: ``Iterator<? extends xmlutil.BridgeNode>`` """ self.extend(nodes) BridgeNode.__init__(self, self[0].element) def to_dicts(self, **kwargs): """implement""" dicts = [] for node in self: dicts.extend(node.to_dicts(**kwargs)) return dicts def _execute_expression(self, _, func_name, expression, **kwargs): """overwrite""" nodes = [] for node in self: nodes.extend(BridgeNode._execute_expression(self, node, func_name, expression, **kwargs)) return GroupNode(nodes) def remove(self): for node in self: node.remove() class RelatedNode(BridgeNode): def __init__(self, this, other, relation, **kwargs): """This class wraps 2 node over their relation :type this: ``? extends xmlutil.BridgeNode`` :type other: ``? extends xmlutil.BridgeNode`` :type relation: a function name of package ``petl`` """ super(RelatedNode, self).__init__(other.element) self.this = this self.other = other self.relation = relation self.kwargs = kwargs def to_dicts(self, **kwargs): """implement""" return self.to_table(**kwargs).dicts() def to_table(self, **kwargs): """overwrite""" this_table = dicts2table(self.this.to_dicts(**kwargs)) other_table = dicts2table(self.other.to_dicts(**kwargs)) if this_table.nrows() == 0: # self.this is a EmptyNode table = other_table else: table = getattr(this_table, self.relation)(other_table, **self.kwargs) return table def _execute_expression(self, _, func_name, expression, **kwargs): """overwrite""" nodes1 = BridgeNode._execute_expression(self, self.this, func_name, expression, **kwargs) nodes2 = BridgeNode._execute_expression(self, self.other, func_name, expression, **kwargs) return GroupNode(itertools.chain(nodes1, nodes2)) def dicts2table(dicts): """transform dicts into a ``petl.util.base.Table``""" return petl.wrap(petl.fromdicts(dicts)) if dicts else petl.empty() class DFSExpansion(object): """depth first search element tree and expands it into a ``sequence`` of ``dict`` E.g., >>> expansion = DFSExpansion(element) >>> dicts = expansion.expand() >>> for dic in dicts: >>> print dic """ def __init__(self, element, duplicate_tags=(), with_element=False, with_attrib=False): """ :type element: ``lxml.etree.Element`` or ``xml.etree.cElementTree.Element`` :param duplicate_tags: elements with these tag will be renamed and added to a dictionary :param with_element: the values of dictionaries contains of element if True otherwise contains of element's text. :param with_attrib: element that's attribute is not empty will be added to dictionaries if with_attrib is Tr """ self.element = element self.duplicate_tags = duplicate_tags self.duplicate_tags_counter = None self.with_element = with_element self.with_attrib = with_attrib self.dicts = list() self.buffer_tags = list() self.buffer_dict = OrderedDict() def expand(self): self._reset_duplicate_tags_counter() self._expand(self.element) return self.dicts def _expand(self, element, level=0): tag, text = get_tag(element), element.text.strip() if element.text else None if text: # element.text is not empty: self._buffer(tag, text, element) elif element.attrib and self.with_attrib: # element.attribute is not empty and need to fetch it self._buffer(tag, text, element, with_attrib=True) for e in element: self._expand(e, level + 1) if level == 0: self._insert(tag) def _buffer(self, tag, text, element, with_attrib=False): if self.buffer_dict.get(tag) is not None: if self.duplicate_tags and tag in self.duplicate_tags: self.duplicate_tags_counter[tag] += 1 tag = tag + '_' + str(self.duplicate_tags_counter[tag]) else: self._insert(tag) self.buffer_tags.append(tag) buffering = element if self.with_element else (element.attrib if with_attrib else text) self.buffer_dict.update({tag: buffering}) def _reset_duplicate_tags_counter(self): self.duplicate_tags_counter = defaultdict(int) def _insert(self, duplicate_tag): self._reset_duplicate_tags_counter() self.dicts.append(self.buffer_dict.copy()) try: idx = self.buffer_tags.index(duplicate_tag) except ValueError: idx = len(self.buffer_tags) for tag in self.buffer_tags[idx:]: self.buffer_dict.has_key(tag) and self.buffer_dict.update({tag: None}) self.buffer_tags = self.buffer_tags[:idx]
2.40625
2
examples/__init__.py
gelijergensen/PermutationImportance
4
12763375
<gh_stars>1-10 """These are just examples of using the various methods in PermutationImportance"""
1.140625
1
explorebg/explore_auth/forms.py
bvoytash/Quiz-Application
0
12763376
<gh_stars>0 from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField from importlib._common import _ UserModel = get_user_model() class SignUpForm(UserCreationForm): class Meta: model = UserModel fields = ('email', 'password1', '<PASSWORD>') class SignInForm(AuthenticationForm): username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True, 'style': 'font-size: medium; border: solid; border-color:green; border-radius: 10px; width 30px; height: 36px', 'placeholder': '<NAME>', })) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autofocus': True, 'style': 'font-size: medium; border: solid; border-color:green; border-radius: 10px; width 30px; height: 36px', 'placeholder': 'парола', }))
2.21875
2
config.py
the-data-science-union/dsu-mlpp
0
12763377
import os from os.path import join, dirname from dotenv import load_dotenv from pymongo import MongoClient import pymysql.cursors dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) client = MongoClient('localhost', 27017, username='admin', password="<PASSWORD>") sql_client = lambda db: pymysql.connect(host = 'localhost', user='root', password='<PASSWORD>', database=db)
2.09375
2
xiuhong_ms_hbond_code/Stable-MCCE/bin/pymccelib.py
caixiuhong/Develop-MCCE
0
12763378
<reponame>caixiuhong/Develop-MCCE #!/usr/bin/env python import logging class Env: def __init__(self): # hard code values self.tpl = {} self.atomnames = {} self.radius = {} self.charge = {} return def load_ftpl(self, fname): """Load a ftpl file""" # default string values, or defined as below float_values = ["EXTRA", "SCALING"] int_values = [] logging.info("Loading ftpl file %s" % fname) lines = open(fname).readlines() for line in lines: line = line.split("#")[0] fields = line.split(":") if len(fields) != 2: continue key_string = fields[0].strip() keys = key_string.split(",") keys = [x.strip().strip("\"") for x in keys] keys = [x for x in keys if x] keys = tuple(keys) value_string = fields[1].strip() if keys[0] in float_values: self.tpl[keys] = float(value_string) elif keys[0] in int_values: self.tpl[keys] = int(value_string) else: self.tpl[keys] = value_string # Make an atom list in the natural order of CONNECT record. if keys[0] == "CONNECT": atom = keys[1] conf = keys[2] if conf in self.atomnames: self.atomnames[conf].append(atom) else: self.atomnames[conf] = [atom] return class Atom: def __init__(self): self.atomname = "" self.confname = "" self.resname = "" self.on = False self.iatom = "0" return class Conformer: def __init__(self): self.confname = "" self.resname = "" self.atoms = [] return class Residue: def __init__(self): self.resname = [] self.conformers = [] return class Protein: """Protein structure""" def __init__(self): self.residues = [] return def pdb2mcce(self, pdb): """Convert pdb to mcce pdb""" atom_exceptions = [" H2 ", " OXT", " HXT"] mccelines = [] lines = [x for x in open(pdb).readlines() if x[:6] == "ATOM " or x[:6] == "HETATM"] icount = 0 previous_resid = () possible_confs = [] for line in lines: # pdb line atomname = line[12:16] resname = line[17:20] chainid = line[21] seqnum = int(line[22:26]) icode = line[26] xyz = line[30:54] current_resid = (resname, chainid, seqnum, icode) # mcce line, need to add conf_number, radius, charge, conf_type, conf_history if current_resid != previous_resid: possible_confs = [x.strip() for x in env.tpl[("CONFLIST", resname)].split(",")] logging.info("Identified a new residue %s: %s" % (resname, ", ".join(possible_confs))) previous_resid = current_resid Found = False for confname in possible_confs: if atomname in env.atomnames[confname]: conf_type = confname[3:5] conf_number = possible_confs.index(confname) cname = confname Found = True break if not Found: # this atom is not found in all conformers if atomname not in atom_exceptions: print("Atom \"%s\" in pdb file %s can not be assigned to any conformer" % (atomname, pdb)) continue key = ("RADIUS", cname, atomname) if key in env.tpl: radius_str = env.tpl[key] rad, _, _ = radius_str.split(",") rad = float(rad) else: rad = 0.0 key = ("CHARGE", cname, atomname) if key in env.tpl: charge_str = env.tpl[key] crg = float(charge_str) else: crg = 0.0 conf_history = "________" newline = "ATOM %5d %4s %s %c%4d%c%03d%s%8.3f %8.3f %s%s\n" % \ (icount, atomname, resname, chainid, seqnum, icode, conf_number, xyz, rad, crg, conf_type, conf_history) mccelines.append(newline) icount += 1 return mccelines env = Env()
2.8125
3
Trading_Strategies/ML/GA_ESN.py
mikimaus78/ml_monorepo
51
12763379
<reponame>mikimaus78/ml_monorepo import pandas as pd import numpy as np from Features import * def fitness(S, T, Close) : F = pd.Series(0.0, index=Close.index) if S.count() == 0: print "No signal to evaluate" return 1e10 for i in range(len(T)) : if (i == 0) or (i == len(T)-1): continue Close_j = Close[T.index[i-1]:T.index[i+1]] S_j = S[Close_j.index[1:-1]].dropna() if T[i] == 1: # buying point score = 0 if S_j.count() == 0 or sum(S_j) == 0: # case c: missing opportunities score = max(Close_j[1:-1]) - Close[T.index[i]] else: for j in range(S_j.count()) : if S_j[j] == 1: # case a: buying signal score += Close[S_j.index[j]] - Close[T.index[i]] if (S_j[j] == -1) : #and (abs(Close[S_j.index[j]] - Close[T.index[i]])/Close[T.index[i]] < 0.05) : # case b: selling signal score += (max(Close_j) - Close[T.index[i]]) score /= S_j.count() else : # selling point #S_j = S[T.index[i-1]:T.index[i+1]] if S_j.count() == 0 or sum(S_j) == 0: # case c: missing opportunities score = Close[T.index[i]] - min(Close_j[1:-1]) else: for j in range(S_j.count()) : if S_j[j] == -1: # case a: buying signal score += Close[T.index[i]] - Close[S_j.index[j]] if (S_j[j] == 1): #and (abs(Close[S_j.index[j]] - Close[T.index[i]])/Close[T.index[i]] < 0.05) : # case b: selling signal score += (Close[T.index[i]] - min(Close_j)) score /= S_j.count() F[T.index[i]] = score return F.sum() def ConfirmEP(data, delta_t, delta_p): peak, valley, _ ,_ = CycleIndicator.ExtremePoints(data) peak_confirmed = np.zeros(peak.shape) valley_confirmed = np.zeros(valley.shape) T = len(peak) i = 0 while(i <= T - 1) : # print "i={i}".format(i=i) confirmed= 0 if peak[i] == 1: # print "peak={i}:price={p}:to confirm".format(i=i, p=data[i]) for j in xrange(i+1,T) : if valley[j] == 1: # print "valley={j}:price={p}".format(j=j, p=data[j]) if (j-i) > delta_t and (data[i] - data[j]) /data[i] > delta_p : # print "peak={i}:price={p}:confirmed".format(i=i, p=data[i]) peak_confirmed[i] = 1 confirmed = 1 i=j break if peak[j] == 1: if data[j] > data[i] : i=j # print "peak={j}:price={p}:to reconfirm".format(j=j, p=data[j]) continue if confirmed == 0: # print "all peaks are confirmed:exit" break elif valley[i] == 1: # print "valley={i}:price={p}:to confirm".format(i=i, p=data[i]) for j in xrange(i+1, len(valley) + 1): if peak[j] == 1: # print "peak={j}:price={p}".format(j=j, p=data[j]) if (j-i) > delta_t and (data[j] - data[i])/data[i] > delta_p: # print "valley={i}:price={p}:confirmed".format(i=i, p=data[i]) valley_confirmed[i] = 1 confirmed = 1 i = j break if valley[j] == 1: if data[j] < data[i]: i = j # print "valley={j}:price={p}:to reconfirm".format(j=j, p=data[j]) continue if confirmed == 0: # print "all peaks are confirmed:exit" break else: i += 1 # print "--------------------------" return peak_confirmed, valley_confirmed, valley_confirmed - peak_confirmed def MovingAverageSystem(params, *args) : ''' based on Baba2004 paper, the Moving average system will generate Golden-cross and dea-cross trade signals based on the system below. ''' a = params[0] / 10.0 b = params[1] / 10.0 c = params[2] #/ 10.0 a_ = params[3] / 10.0 b_ = params[4] / 10.0 c_ = params[5] #/ 10.0 M = int(params[6] + 2) N = int(params[7] /100.0 * (300 - M - 1) + M + 1) C = args[0] sma1 = pd.rolling_mean(C, M) sma2 = pd.rolling_mean(C, N) Z = sma1 - sma2 crossover = pd.Series(0, index=Z.index) for i in range(len(Z)) : if i == 0: continue if (Z[i-1] < 0) and (Z[i] > 0): crossover[i] = 1 if (Z[i-1] > 0) and (Z[i] < 0): crossover[i] = -1 crossover = crossover.where(crossover <>0).dropna().copy() trade = pd.Series(0, index=Z.index) for i in range(len(Z)): if i == 0: continue cr_j = crossover[:Z.index[i]] if cr_j.count() == 0: continue index_s = cr_j.index[-1] index_e = Z.index[i] z_j = Z[index_s:index_e] if Z[i] >= 0 : MZt = max(z_j) if (MZt > b*c) and (Z[i] < min(MZt/a, c)) : trade[i] = 1 if Z[i] < 0: MWt = max(-1*z_j) if (MWt > b_*c_) and (-1*Z[i] < min(MWt/a_, c_)) : trade[i] = -1 return trade def SimpleMASystem(params, C) : ''' based on Baba2004 paper, the Moving average system will generate Golden-cross and dea-cross trade signals based on the system below. ''' M = int(params[0] + 2) N = int(params[1] /100.0 * (300 - M - 1) + M + 1) l_up = params[2] / 100.0 l_down = params[3] / 100.0 w_up = int(params[4] + 5) w_down = int(params[5] + 5) sma1 = pd.rolling_mean(C, M) sma2 = pd.rolling_mean(C, N) Z = sma1 - sma2 crossover = pd.Series(0, index=Z.index) for i in range(len(Z)) : if i == 0: continue if (Z[i-1] < 0) and (Z[i] > 0): if Z[i] > l_up * np.max(Z[i-w_up:i]) : crossover[i] = 1 if (Z[i-1] > 0) and (Z[i] < 0): if Z[i] < l_down * np.min(Z[i-w_down:i]): crossover[i] = -1 crossover = crossover.where(crossover <>0).dropna().copy() return crossover def RSI_system(params, C) : ''' based on Baba2004 paper, the Moving average system will generate Golden-cross and dea-cross trade signals based on the system below. ''' thres_ob = int(params[0]/2) + 50 thres_os = int(params[1]/2) p = (100-thres_ob) * params[2] / 100 q = thres_os * params[3] / 100 period = int(params[4]) + 5 rsi = ta.RSI(C.values, period) trade = pd.Series(0.0, index=C.index) last_ob = 0 last_os = 0 for i in range(len(rsi)) : if i < period - 1: continue if rsi[i] > thres_ob and rsi[i-1] < thres_ob: last_ob = i if last_ob <> 0: thres_sell = thres_ob + p * (i-last_ob) if rsi[i] < thres_sell : trade[i] = -1 last_ob = 0 if rsi[i] < thres_os and rsi[i-1] > thres_os : last_os = i if last_os <> 0: thres_buy = thres_os - q * (i-last_ob) if rsi[i] > thres_buy: trade[i] = 1 last_os = 0 trade = trade.where(trade<>0).dropna().copy() return trade def Hybrid_System(params, C) : params1 = params[:5] params2 = params[5:] trade1 = RSI_system(params1, C) trade2 = SimpleMASystem(params2, C)\ trade = pd.DataFrame(0.0, index=C.index) + trade1 + trade2 trade[trade >= 1] = 1 trade[trade <= -1] = -1 trade = trade.where(trade<>0).dropna().copy() return trade # def evaluate(individual, Close=Close, delta_t=5, delta_p=0.05) : # (Close, delta_t, delta_p) = args[0] # # _, _, Trade = ConfirmEP(Close, delta_t, delta_p) # Trade = pd.Series(Trade, index=Close.index ) # T = Trade.where(Trade<>0).dropna().copy() # Signal = MovingAverageSystem(individual, Close) # S = Signal.where(Signal<>0).dropna().copy() # # fit = fitness(S, T, Close) # print "fitness={f}".format(f=fit) # # return fit import Quandl if __name__ == "__main__" : df_tlt = Quandl.get('GOOG/NYSE_SPY', authtoken='<KEY>') Close = df_tlt['Close'] import array import random import numpy as np import pandas as pd from deap import algorithms from deap import base from deap import creator from deap import tools import matplotlib from ML.Features import * # df_funds = pd.read_csv('data/NAV_5ETFs.csv') # # Close = pd.Series(df_funds['zz 500'].values, index=df_funds['Date']) # Close = Close[-3000:-1000] df_funds = pd.read_csv('data/NAV_5ETFs.csv') Close = pd.Series(df_funds['zz 500'].values, index=df_funds['Date']).dropna() * 100 delta_t = 5 delta_p = 0.15 _, _, Trade = ConfirmEP(Close, delta_t, delta_p) # peak, valley, _, _ = CycleIndicator.ExtremePoints(Close) # Trade = valley - peak Trade = pd.Series(Trade, index=Close.index ) individual = [24.80688574431058, 13.308847279590141, 64, 96, 76.48226618166598, 57, 33.565571859346065, 84.09699171247095, 24.80688574431058, 13.308847279590141, 64, 96, 76.48226618166598, 57, 33.565571859346065, 84.09699171247095] Signal = MovingAverageSystem(individual, Close) T = Trade.where(Trade<>0).dropna().copy() T1 = Trade.where(Trade==1).dropna().copy() print fitness(T*0, T, Close) def evaluate(individual, Close=Close, T=T) : # Signal = MovingAverageSystem(individual, Close) Signal = Hybrid_System(individual, Close) S = Signal.where(Signal<>0)[:T.index[-1]].dropna().copy() fit = fitness(S, T, Close) print "fitness={f}:individual={i}".format(f=fit, i=individual) print "------------------------------------" return fit, evaluate(individual) toolbox = base.Toolbox() creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness=creator.FitnessMin) toolbox = base.Toolbox() toolbox.register("attr_uni", random.uniform, 0, 100) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_uni, 11) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register('evaluate', evaluate) toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mutate", tools.mutUniformInt, low=0, up=100, indpb=0.5) toolbox.register("select", tools.selTournament, tournsize=50) import multiprocessing pool = multiprocessing.Pool() toolbox.register("map", pool.map) pop = toolbox.population(n=10000) pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=100)
2.46875
2
pai-management/k8sPaiLibrary/maintaintool/docker-config-update.py
luoch/pai
2
12763380
<filename>pai-management/k8sPaiLibrary/maintaintool/docker-config-update.py # Copyright (c) Microsoft Corporation # All rights reserved. # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and # to permit persons to whom the Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING # BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import sys import json import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-s', '--src-json', dest="src_json", required=True, help="The json with the data you wanna write") parser.add_argument('-d', '--dst-json', dest="dst_json", required=True, help="The json with the data you wanna update") args = parser.parse_args() with open(args.src_json, "r") as jsonFile: src_data = json.load(jsonFile) with open(args.dst_json, "r") as jsonFile: dst_data = json.load(jsonFile) for conf_key in src_data: dst_data[conf_key] = src_data[conf_key] changed = True with open(args.dst_json, 'w') as jsonFile: json.dump(dst_data, jsonFile)
1.789063
2
Finals Practice/23.py
ikramulkayes/Python_season2
0
12763381
<filename>Finals Practice/23.py def func(word): word = word.split(", ") dic = {"Magic":[],"Normal":[]} for elm in word: decide = "" first = elm[0] first = int(first) sum1 = 0 for sval in elm[1::]: sum1 += int(sval) if first == sum1: decide = "Magic" else: decide = "Normal" dic[decide].append(int(elm)) fdic = {} for key,val in dic.items(): fdic[key] = tuple(val) return fdic word = input("Enter your numbers: ") print(func(word))
4.0625
4
elib/strings.py
MasterEnderman/EnderLib
1
12763382
from elib import * class strings(enderlib): pass class stringsUnification(strings): pass class stringsUnificationSettings(stringsUnification): head = """#priority {} import crafttweaker.item.IItemStack; import crafttweaker.item.IIngredient; import crafttweaker.liquid.ILiquidDefinition; import crafttweaker.liquid.ILiquidStack; import crafttweaker.oredict.IOreDict; import crafttweaker.oredict.IOreDictEntry; global modPriority as int[string] = {};\n\n""" class stringsUnificationTools(stringsUnification): head = """#loader contenttweaker #priority {} import mods.contenttweaker.VanillaFactory; import mods.contenttweaker.Fluid; import mods.contenttweaker.Color; import mods.contenttweaker.Item; import mods.contenttweaker.LocalizedNameSupplier; import mods.contenttweaker.ResourceLocation;\n\n""" bodyFinite = """var {} as Item = VanillaFactory.createItem("{}"); {}.setLocalizedNameSupplier(function(itemStack) {{return "{}";}}); {}.maxDamage = {}; {}.register();\n\n""" bodyInfinite = """var {} as Item = VanillaFactory.createItem("{}"); {}.setLocalizedNameSupplier(function(itemStack) {{return "{}";}}); {}.register();\n\n""" class stringsUnificationCompat(stringsUnification): class jei(stringsUnification): head = """#modloaded jei #priority {} import crafttweaker.item.IItemStack; import crafttweaker.item.IIngredient; import crafttweaker.liquid.ILiquidDefinition; import crafttweaker.liquid.ILiquidStack; import crafttweaker.oredict.IOreDict; import crafttweaker.oredict.IOreDictEntry; import mods.jei.JEI; import scripts._UNIFICATION.{}functions.getOreDict; import scripts._UNIFICATION.{}functions.getModlist; import scripts._UNIFICATION.{}functions.findFirstItem; import scripts._UNIFICATION.{}options.JEIMASTER; import scripts._UNIFICATION.{}options.JEIOres;\n\n""" body = """if (JEIMASTER) { cleanJEI(getModlist()); } function cleanJEI(modlist as string[]) { for metal in metalsToUnify { for type in typesToUnify.keys { jeiHide(findFirstItem(modlist,type,metal),type,metal); } if (JEIOres) { jeiHide(findFirstItem(modlist,"ore",metal),"ore",metal); } } } function jeiHide(filter as IItemStack, type as string, metal as string) { for item in getOreDict(type,metal).items { if (item.definition.owner != filter.definition.owner) { JEI.removeAndHide(item); } } }""" class tconstruct(stringsUnification): head = """#modloaded modtweaker tconstruct #priority {} import crafttweaker.item.IItemStack; import crafttweaker.item.IIngredient; import crafttweaker.liquid.ILiquidDefinition; import crafttweaker.liquid.ILiquidStack; import crafttweaker.oredict.IOreDict; import crafttweaker.oredict.IOreDictEntry; import mods.tconstruct.Alloy; import mods.tconstruct.Casting; import mods.tconstruct.Melting; import scripts._UNIFICATION.{}functions.getFluid; import scripts._UNIFICATION.{}functions.getOreDict; import scripts._UNIFICATION.{}functions.getModlist; import scripts._UNIFICATION.{}functions.getItemString; import scripts._UNIFICATION.{}functions.findFirstItem; import scripts._UNIFICATION.{}options.TiCoMASTER; import scripts._UNIFICATION.{}options.TiCoRemoveRecipes; import scripts._UNIFICATION.{}options.TiCoAddRecipes; import scripts._UNIFICATION.{}options.TiCoCastRemoveRecipes; import scripts._UNIFICATION.{}options.TiCoCastAddRecipes; import scripts._UNIFICATION.{}options.TiCoCastGear; import scripts._UNIFICATION.{}options.TiCoCastPlate; import scripts._UNIFICATION.{}options.TiCoCastNugget; import scripts._UNIFICATION.{}options.TiCoCastIngot; import scripts._UNIFICATION.{}options.TiCoMultiplierGear; import scripts._UNIFICATION.{}options.TiCoMultiplierPlate;\n\n""" body = """if (TiCoMASTER) { removeTiCoRecipes(); addTiCoCastingRecipes(getModlist()); } function removeTiCoRecipes() { for metal in metalsToUnify { if (TiCoRemoveRecipes & TiCoCastRemoveRecipes) { for type in typesToUnify.keys { for item in getOreDict(type,metal).items { if (type == "block") { Casting.removeBasinRecipe(item); } if (type == "ingot" | type == "gear" | type == "plate" | type == "nugget") { Casting.removeTableRecipe(item); } } } } } } function addTiCoCastingRecipes(modlist as string[]) { for metal in metalsToUnify { if (TiCoAddRecipes & TiCoCastAddRecipes) { Casting.addBasinRecipe( findFirstItem(modlist,"block",metal), null, getFluid(metal), unification_liquidToIngot * 9 ); Casting.addTableRecipe( findFirstItem(modlist,"ingot",metal), getItemString(TiCoCastIngot), getFluid(metal), unification_liquidToIngot ); Casting.addTableRecipe( findFirstItem(modlist,"nugget",metal), getItemString(TiCoCastNugget), getFluid(metal), unification_liquidToIngot / 9 ); Casting.addTableRecipe( findFirstItem(modlist,"plate",metal), getItemString(TiCoCastPlate), getFluid(metal), unification_liquidToIngot * TiCoMultiplierPlate ); Casting.addTableRecipe( findFirstItem(modlist,"gear",metal), getItemString(TiCoCastGear), getFluid(metal), unification_liquidToIngot * TiCoMultiplierGear ); } } }""" class immersiveengineering(stringsUnification): head = """#modloaded immersiveengineering #priority {} import crafttweaker.item.IItemStack; import crafttweaker.item.IIngredient; import crafttweaker.liquid.ILiquidDefinition; import crafttweaker.liquid.ILiquidStack; import crafttweaker.oredict.IOreDict; import crafttweaker.oredict.IOreDictEntry; import mods.immersiveengineering.AlloySmelter; import mods.immersiveengineering.ArcFurnace; import mods.immersiveengineering.BlastFurnace; import mods.immersiveengineering.Crusher; import mods.immersiveengineering.MetalPress; import scripts._UNIFICATION.{}functions.getOreDict; import scripts._UNIFICATION.{}functions.getModlist; import scripts._UNIFICATION.{}functions.getItemString; import scripts._UNIFICATION.{}functions.findFirstItem; import scripts._UNIFICATION.{}options.IEMASTER; import scripts._UNIFICATION.{}options.IESlagItem; import scripts._UNIFICATION.{}options.IEArcFurnaceRemoveRecipes; import scripts._UNIFICATION.{}options.IEArcFurnaceAddRecipes; import scripts._UNIFICATION.{}options.IEArcFurnaceEnergy; import scripts._UNIFICATION.{}options.IEArcFurnaceAddSmelt; import scripts._UNIFICATION.{}options.IEArcFurnaceTimeSmelt; import scripts._UNIFICATION.{}options.IEArcFurnaceAddOre; import scripts._UNIFICATION.{}options.IEArcFurnaceTimeOre; import scripts._UNIFICATION.{}options.IEArcFurnaceMultiplierOre; import scripts._UNIFICATION.{}options.IEArcFurnaceAddSteel; import scripts._UNIFICATION.{}options.IEArcFurnaceTimeSteel; import scripts._UNIFICATION.{}options.IEArcFurnaceAddAlloy; import scripts._UNIFICATION.{}options.IEArcFurnaceTimeAlloy; import scripts._UNIFICATION.{}options.IEBlastFurnaceRemoveRecipes; import scripts._UNIFICATION.{}options.IEBlastFurnaceAddRecipes; import scripts._UNIFICATION.{}options.IEBlastFurnaceTime; import scripts._UNIFICATION.{}options.IECrusherRemoveRecipes; import scripts._UNIFICATION.{}options.IECrusherAddRecipes; import scripts._UNIFICATION.{}options.IECrusherEnergy; import scripts._UNIFICATION.{}options.IECrusherMultiplier; import scripts._UNIFICATION.{}options.IEKilnRemoveRecipes; import scripts._UNIFICATION.{}options.IEKilnAddRecipes; import scripts._UNIFICATION.{}options.IEKilnTime; import scripts._UNIFICATION.{}options.IEMetalPressRemoveRecipes; import scripts._UNIFICATION.{}options.IEMetalPressAddRecipes; import scripts._UNIFICATION.{}options.IEMetalPressEnergy; import scripts._UNIFICATION.{}options.IEMetalPressMoldPlate; import scripts._UNIFICATION.{}options.IEMetalPressMoldPlateAmountInput; import scripts._UNIFICATION.{}options.IEMetalPressMoldPlateAmountOutput; import scripts._UNIFICATION.{}options.IEMetalPressMoldStick; import scripts._UNIFICATION.{}options.IEMetalPressMoldStickAmountInput; import scripts._UNIFICATION.{}options.IEMetalPressMoldStickAmountOutput; import scripts._UNIFICATION.{}options.IEMetalPressMoldGear; import scripts._UNIFICATION.{}options.IEMetalPressMoldGearAmountInput; import scripts._UNIFICATION.{}options.IEMetalPressMoldGearAmountOutput;\n\n""" body = """ if (IEMASTER) { removeIERecipes(); addIECrusherRecipes(getModlist()); addIEKilnRecipes(getModlist()); addIEMetalPressRecipes(getModlist()); addIEArcFurnaceRecipes(getModlist()); addIEBlastFurnaceRecipes(getModlist()); } function removeIERecipes() { for metal in metalsToUnify { if (IECrusherRemoveRecipes) { for item in getOreDict("dust",metal).items { Crusher.removeRecipe(item); } } if (alloyDict.keys in metal & IEKilnRemoveRecipes) { for item in getOreDict("ingot",metal).items { AlloySmelter.removeRecipe(item); } } if (IEMetalPressRemoveRecipes) { for item in getOreDict("plate",metal).items { MetalPress.removeRecipe(item); } for item in getOreDict("stick",metal).items { MetalPress.removeRecipe(item); } for item in getOreDict("gear",metal).items { MetalPress.removeRecipe(item); } } if (IEArcFurnaceRemoveRecipes) { for item in getOreDict("ingot",metal).items { ArcFurnace.removeRecipe(item); } } } if (IEBlastFurnaceRemoveRecipes) { for item in getOreDict("ingot","steel").items { BlastFurnace.removeRecipe(item); } for item in getOreDict("block","steel").items { BlastFurnace.removeRecipe(item); } } } function addIECrusherRecipes(modlist as string[]) { for metal in metalsToUnify { if (IECrusherAddRecipes) { if (getOreDict("ore",metal).items.length >= 1 & getOreDict("dust",metal).items.length >= 1) { Crusher.addRecipe(findFirstItem(modlist,"dust",metal) * IECrusherMultiplier,getOreDict("ore",metal),IECrusherEnergy); } if (getOreDict("ingot",metal).items.length >= 1 & getOreDict("dust",metal).items.length >= 1) { Crusher.addRecipe(findFirstItem(modlist,"dust",metal),getOreDict("ingot",metal),IECrusherEnergy); } } } } function addIEKilnRecipes(modlist as string[]) { for metal in alloyDict.keys { var alloyInputs as string[] = []; var amount as int = 0; for input, quantity in alloyDict[metal] { alloyInputs += input; amount += quantity; } if (alloyInputs.length == 2 & IEKilnAddRecipes) { AlloySmelter.addRecipe( findFirstItem(modlist,"ingot",metal) * amount, getOreDict("ingot",alloyInputs[0]) * alloyDict[metal][alloyInputs[0]], getOreDict("ingot",alloyInputs[1]) * alloyDict[metal][alloyInputs[1]], IEKilnTime ); AlloySmelter.addRecipe( findFirstItem(modlist,"ingot",metal) * amount, getOreDict("dust",alloyInputs[0]) * alloyDict[metal][alloyInputs[0]], getOreDict("dust",alloyInputs[1]) * alloyDict[metal][alloyInputs[1]], IEKilnTime ); AlloySmelter.addRecipe( findFirstItem(modlist,"ingot",metal) * amount, getOreDict("dust",alloyInputs[0]) * alloyDict[metal][alloyInputs[0]], getOreDict("ingot",alloyInputs[1]) * alloyDict[metal][alloyInputs[1]], IEKilnTime ); AlloySmelter.addRecipe( findFirstItem(modlist,"ingot",metal) * amount, getOreDict("ingot",alloyInputs[0]) * alloyDict[metal][alloyInputs[0]], getOreDict("dust",alloyInputs[1]) * alloyDict[metal][alloyInputs[1]], IEKilnTime ); } } } function addIEMetalPressRecipes(modlist as string[]) { for metal in metalsToUnify { if (getOreDict("ingot",metal).items.length >= 1 & getOreDict("plate",metal).items.length >= 1 & IEMetalPressAddRecipes) { MetalPress.addRecipe( findFirstItem(modlist,"plate",metal) * IEMetalPressMoldPlateAmountOutput, getOreDict("ingot",metal), getItemString(IEMetalPressMoldPlate), IEMetalPressEnergy, IEMetalPressMoldPlateAmountInput ); } if (getOreDict("ingot",metal).items.length >= 1 & getOreDict("stick",metal).items.length >= 1 & IEMetalPressAddRecipes) { MetalPress.addRecipe( findFirstItem(modlist,"stick",metal) * IEMetalPressMoldStickAmountOutput, getOreDict("ingot",metal), getItemString(IEMetalPressMoldStick), IEMetalPressEnergy, IEMetalPressMoldStickAmountInput ); } if (getOreDict("ingot",metal).items.length >= 1 & getOreDict("gear",metal).items.length >= 1 & IEMetalPressAddRecipes) { MetalPress.addRecipe( findFirstItem(modlist,"gear",metal) * IEMetalPressMoldGearAmountOutput, getOreDict("ingot",metal), getItemString(IEMetalPressMoldGear), IEMetalPressEnergy, IEMetalPressMoldGearAmountInput ); } } } function addIEArcFurnaceRecipes(modlist as string[]) { for metal in metalsToUnify { if (IEArcFurnaceAddRecipes & IEArcFurnaceAddSmelt & getOreDict("ingot",metal).items.length >= 1 & getOreDict("dust",metal).items.length >= 1) { ArcFurnace.addRecipe( findFirstItem(modlist,"ingot",metal), getOreDict("dust",metal), null, IEArcFurnaceTimeSmelt, IEArcFurnaceEnergy ); } if (IEArcFurnaceAddRecipes & IEArcFurnaceAddOre & getOreDict("ingot",metal).items.length >= 1 & getOreDict("ore",metal).items.length >= 1) { ArcFurnace.addRecipe( findFirstItem(modlist,"ingot",metal) * IEArcFurnaceMultiplierOre, getOreDict("ore",metal), getItemString(IESlagItem), IEArcFurnaceTimeOre, IEArcFurnaceEnergy, [], "Ores" ); } } for metal in alloyDict.keys { var alloyInputs as string[] = []; var amount as int = 0; for input, quantity in alloyDict[metal] { alloyInputs += input; amount += quantity; } if (alloyInputs.length == 2 & IEArcFurnaceAddAlloy & getOreDict("ingot",metal).items.length >= 1) { ArcFurnace.addRecipe( findFirstItem(modlist,"ingot",metal) * amount, getOreDict("ingot",alloyInputs[0]) * alloyDict[metal][alloyInputs[0]], null, IEArcFurnaceTimeAlloy, IEArcFurnaceEnergy, [ getOreDict("ingot",alloyInputs[1]) * alloyDict[metal][alloyInputs[1]] ], "Alloying" ); ArcFurnace.addRecipe( findFirstItem(modlist,"ingot",metal) * amount, getOreDict("dust",alloyInputs[0]) * alloyDict[metal][alloyInputs[0]], null, IEArcFurnaceTimeAlloy, IEArcFurnaceEnergy, [ getOreDict("dust",alloyInputs[1]) * alloyDict[metal][alloyInputs[1]] ], "Alloying" ); ArcFurnace.addRecipe( findFirstItem(modlist,"ingot",metal) * amount, getOreDict("dust",alloyInputs[0]) * alloyDict[metal][alloyInputs[0]], null, IEArcFurnaceTimeAlloy, IEArcFurnaceEnergy, [ getOreDict("ingot",alloyInputs[1]) * alloyDict[metal][alloyInputs[1]] ], "Alloying" ); ArcFurnace.addRecipe( findFirstItem(modlist,"ingot",metal) * amount, getOreDict("ingot",alloyInputs[0]) * alloyDict[metal][alloyInputs[0]], null, IEArcFurnaceTimeAlloy, IEArcFurnaceEnergy, [ getOreDict("dust",alloyInputs[1]) * alloyDict[metal][alloyInputs[1]] ], "Alloying" ); } } if (IEArcFurnaceAddRecipes & IEArcFurnaceAddSteel & getOreDict("ingot","steel").items.length >= 1) { ArcFurnace.addRecipe( findFirstItem(modlist,"ingot","steel"), getOreDict("ingot","iron"), getItemString(IESlagItem), IEArcFurnaceTimeSteel, IEArcFurnaceEnergy, [ getOreDict("dust","coke") ] ); ArcFurnace.addRecipe( findFirstItem(modlist,"ingot","steel"), getOreDict("dust","iron"), getItemString(IESlagItem), IEArcFurnaceTimeSteel, IEArcFurnaceEnergy, [ getOreDict("dust","coke") ] ); } } function addIEBlastFurnaceRecipes(modlist as string[]) { if (IEBlastFurnaceAddRecipes & getOreDict("ingot","steel").items.length >= 1) { BlastFurnace.addRecipe( findFirstItem(modlist,"ingot","steel"), getOreDict("ingot","iron"), IEBlastFurnaceTime, getItemString(IESlagItem) ); } if (IEBlastFurnaceAddRecipes & getOreDict("block","steel").items.length >= 1) { BlastFurnace.addRecipe( findFirstItem(modlist,"block","steel"), getOreDict("block","iron"), IEBlastFurnaceTime * 9, getItemString(IESlagItem) ); } }""" class stringsUnificationOptions(stringsUnification): head = """#priority {} import crafttweaker.item.IItemStack; import crafttweaker.item.IIngredient; import crafttweaker.liquid.ILiquidDefinition; import crafttweaker.liquid.ILiquidStack; import crafttweaker.oredict.IOreDict; import crafttweaker.oredict.IOreDictEntry;\n\n""" master = """// Enable Unification Scripts? static UNIFICATIONMASTER as bool = {}; static UNIFICATIONremoveRecipes as bool = {}; static UNIFICATIONfurnace as bool = {}; static UNIFICATIONcrafting as bool = {};\n\n""" tools = """// Use tools in recipes? static useTools as bool = {};\n\n""" jei = """//JEI static JEIMASTER as bool = {}; static JEIOres as bool = {};\n\n""" immersiveengineering = """//Immersive Engineering static IEMASTER as bool = {}; static IESlagItem as string = "{}"; static IECrusherRemoveRecipes as bool = {}; static IECrusherAddRecipes as bool = {}; static IECrusherEnergy as int = {}; static IECrusherMultiplier as int = {}; static IEKilnRemoveRecipes as bool = {}; static IEKilnAddRecipes as bool = {}; static IEKilnTime as int = {}; static IEMetalPressRemoveRecipes as bool = {}; static IEMetalPressAddRecipes as bool = {}; static IEMetalPressEnergy as int = {}; static IEMetalPressMoldPlate as string = "{}"; static IEMetalPressMoldPlateAmountInput as int = {}; static IEMetalPressMoldPlateAmountOutput as int = {}; static IEMetalPressMoldStick as string = "{}"; static IEMetalPressMoldStickAmountInput as int = {}; static IEMetalPressMoldStickAmountOutput as int = {}; static IEMetalPressMoldGear as string = "{}"; static IEMetalPressMoldGearAmountInput as int = {}; static IEMetalPressMoldGearAmountOutput as int = {}; static IEArcFurnaceRemoveRecipes as bool = {}; static IEArcFurnaceAddRecipes as bool = {}; static IEArcFurnaceEnergy as int = {}; static IEArcFurnaceAddSmelt as bool = {}; static IEArcFurnaceTimeSmelt as int = {}; static IEArcFurnaceAddOre as bool = {}; static IEArcFurnaceTimeOre as int = {}; static IEArcFurnaceMultiplierOre as int = {}; static IEArcFurnaceAddSteel as bool = {}; static IEArcFurnaceTimeSteel as int = {}; static IEArcFurnaceAddAlloy as bool = {}; static IEArcFurnaceTimeAlloy as int = {}; static IEBlastFurnaceRemoveRecipes as bool = {}; static IEBlastFurnaceAddRecipes as bool = {}; static IEBlastFurnaceTime as int = {};\n\n""" tconstruct = """// Tinker's Construct static TiCoMASTER as bool = {}; static TiCoRemoveRecipes as bool = {}; static TiCoAddRecipes as bool = {}; static TiCoCastRemoveRecipes as bool = {}; static TiCoCastAddRecipes as bool = {}; static TiCoCastGear as string = "{}"; static TiCoCastPlate as string = "{}"; static TiCoCastNugget as string = "{}"; static TiCoCastIngot as string = "{}"; static TiCoMultiplierGear as int = {}; static TiCoMultiplierPlate as int = {};\n\n""" class stringsUnificationScript(stringsUnification): head = """#priority {} import crafttweaker.item.IItemStack; import crafttweaker.item.IIngredient; import crafttweaker.liquid.ILiquidDefinition; import crafttweaker.liquid.ILiquidStack; import crafttweaker.oredict.IOreDict; import crafttweaker.oredict.IOreDictEntry; import scripts._UNIFICATION.{}functions.getModlist; import scripts._UNIFICATION.{}functions.removeAllRecipes; import scripts._UNIFICATION.{}functions.addFurnaceRecipes; import scripts._UNIFICATION.{}functions.addCraftingRecipes; import scripts._UNIFICATION.{}options.UNIFICATIONMASTER; import scripts._UNIFICATION.{}options.UNIFICATIONremoveRecipes; import scripts._UNIFICATION.{}options.UNIFICATIONfurnace; import scripts._UNIFICATION.{}options.UNIFICATIONcrafting;\n""" body = """ if (UNIFICATIONMASTER) { if (UNIFICATIONremoveRecipes) { removeAllRecipes(); } if (UNIFICATIONfurnace) { addFurnaceRecipes(getModlist()); } if (UNIFICATIONcrafting) { addCraftingRecipes(getModlist()); } }""" class stringsUnificationFunctions(stringsUnification): head = """#priority {} import crafttweaker.item.IItemStack; import crafttweaker.item.IIngredient; import crafttweaker.liquid.ILiquidDefinition; import crafttweaker.liquid.ILiquidStack; import crafttweaker.oredict.IOreDict; import crafttweaker.oredict.IOreDictEntry; import scripts._UNIFICATION.{}options.useTools; // External Variables global unification_recipeCheck as bool = true; global unification_liquidToIngot as int = {};""" body = """ // Functions function toString(item as IIngredient) as string { return item.commandString.replace("<","").replace(">",""); } function getOreDict(dict as string, material as string) as IIngredient { if (dict == "null" | material == "null") { return null; } else { return oreDict.get(dict~material.substring(0,1).toUpperCase()~material.substring(1).toLowerCase()); } } function getItem(mod as string, item as string) as IItemStack { return itemUtils.getItem(mod~":"~item); } function getItemAny(mod as string, item as string) as IItemStack { return itemUtils.getItem(mod~":"~item,32767); } function getItemMeta(mod as string, item as string, meta as int) as IItemStack { return itemUtils.getItem(mod~":"~item,meta); } function getItemString(input as string) as IItemStack { var counter as int = 0; var star as int = 0; var mod as string = ""; var item as string = ""; var meta as string = ""; for symbol in getArrayString(input) { if (symbol == ":") { counter += 1; } if (symbol == "*") { star += 1; } if (counter == 0 & symbol != ":") { mod += symbol; } if (counter == 1 & symbol != ":") { item += symbol; } if (counter == 2 & symbol != ":") { meta += symbol; } } if (star >= 1) { return getItemAny(mod,item); } if (counter == 1) { return getItem(mod,item); } else { return getItemMeta(mod,item,meta as int); } } function getArrayString(line as string) as string[] { var array as string[] = []; for i in 0 .. line.length { array += line[i]; } return array; } function getFluid(fluid as string) as ILiquidStack { var bucket as IItemStack = <minecraft:bucket>; if (fluid == "water") { bucket = <minecraft:water_bucket>; } if (fluid == "lava") { bucket = <minecraft:lava_bucket>; } if (fluid != "lava" & fluid != "water") { bucket = <forge:bucketfilled>.withTag({FluidName: fluid, Amount: 1000}); } for liquid in bucket.liquids { return liquid.definition * 1; } } function getBucket(fluid as string, bucket as IItemStack) as IItemStack { return bucket.withTag({FluidName: fluid, Amount: 1000}); } function getBucketDefault(fluid as string) as IItemStack { if (fluid == "water") { return <minecraft:water_bucket>; } if (fluid == "lava") { return <minecraft:lava_bucket>; } if (fluid != "water" & fluid != "lava") { return getBucket(fluid, <forge:bucketfilled>); } } function getModlist() as string[] { return sortBig(modPriority); } function removeAllRecipes() { for metal in metalsToUnify { for type in typesToUnify.keys { recipes.remove(getOreDict(type,metal)); } furnace.remove(getOreDict("ingot",metal)); furnace.remove(getOreDict("nugget",metal)); } } function findFirstItem(modlist as string[], type as string, metal as string) as IItemStack { for mod in modlist { for item in getOreDict(type,metal).items { if (mod == item.definition.owner) { return item; } } } } function addFurnaceRecipes(modlist as string[]) { for metal in metalsToUnify { if (getOreDict("ore",metal).items.length >= 1) { furnace.addRecipe(findFirstItem(modlist, "ingot", metal), getOreDict("ore",metal)); } if (getOreDict("dust",metal).items.length >= 1) { furnace.addRecipe(findFirstItem(modlist, "ingot", metal), getOreDict("dust",metal)); } } } function addCraftingRecipes(modlist as string[]) { for metal in metalsToUnify { for type, data in typesToUnify { if (getOreDict(type,metal).items.length >= 1) { for amount, data_2 in data { var index as int = 0; for craft in data_2 { unification_recipeCheck = true; registerRecipe(modlist,index,type,metal,amount,craft); index += 1; } } } else { print("[UNIFICATION] Did not find an Item for "~type~"_"~metal); } } } } function registerRecipe(modlist as string[], index as int, type as string, metal as string, amount as int, craft as string[][]) { var recipe = getRecipeArray(index,type,metal,amount,craft); if (unification_recipeCheck) { var name as string = "unification_"~type~"_"~metal~"_"~amount~"_"~index; recipes.addShaped(name,findFirstItem(modlist, type, metal) * amount,recipe); } } function getRecipeArray(index as int, type as string, metal as string, amount as int, grid as string[][]) as IIngredient[][] { var shape = getShape(grid); if (shape == "100-000-000") { return [ [checkIngredient(amount,index,0,0,type,metal)] ]; } if (shape == "111-111-111") { return [ [checkIngredient(amount,index,0,0,type,metal),checkIngredient(amount,index,0,1,type,metal),checkIngredient(amount,index,0,2,type,metal)], [checkIngredient(amount,index,1,0,type,metal),checkIngredient(amount,index,1,1,type,metal),checkIngredient(amount,index,1,2,type,metal)], [checkIngredient(amount,index,2,0,type,metal),checkIngredient(amount,index,2,1,type,metal),checkIngredient(amount,index,2,2,type,metal)] ]; } if (shape == "110-110-000") { return [ [checkIngredient(amount,index,0,0,type,metal),checkIngredient(amount,index,0,1,type,metal)], [checkIngredient(amount,index,1,0,type,metal),checkIngredient(amount,index,1,1,type,metal)] ]; } if (shape == "100-100-100") { return [ [checkIngredient(amount,index,0,0,type,metal)], [checkIngredient(amount,index,1,0,type,metal)], [checkIngredient(amount,index,2,0,type,metal)] ]; } if (shape == "100-100-000") { return [ [checkIngredient(amount,index,0,0,type,metal)], [checkIngredient(amount,index,1,0,type,metal)] ]; } print("[UNIFICATION] Did not found a matching recipe array template for "~type~"!"); } function getShape(grid as string[][]) as string { var space1 as int = 0; var space2 as int = 0; var space3 as int = 0; var space4 as int = 0; var space5 as int = 0; var space6 as int = 0; var space7 as int = 0; var space8 as int = 0; var space9 as int = 0; if (grid.length >= 1) { if (grid[0].length >= 1) { space1 = 1; } if (grid[0].length >= 2) { space2 = 1; } if (grid[0].length >= 3) { space3 = 1; } if (grid.length >= 2) { if (grid[1].length >= 1) { space4 = 1; } if (grid[1].length >= 2) { space5 = 1; } if (grid[1].length >= 3) { space6 = 1; } if (grid.length >= 3) { if (grid[2].length >= 1) { space7 = 1; } if (grid[2].length >= 2) { space8 = 1; } if (grid[2].length >= 3) { space9 = 1; } } } } return space1~space2~space3~"-"~space4~space5~space6~"-"~space7~space8~space9; } function checkIngredient(amount as int, index as int, pos1 as int, pos2 as int, type as string, metal as string) as IIngredient { if (typesToUnify[type][amount][index][pos1][pos2] == "null") { return null; } if (typesToUnify[type][amount][index][pos1][pos2] in "FLUID_") { return getBucketDefault(typesToUnify[type][amount][index][pos1][pos2].substring(6)); } if (typesToUnify[type][amount][index][pos1][pos2] in "UNI_") { if (useTools) { return unificationTools[typesToUnify[type][amount][index][pos1][pos2]]; } else { return null; } } if (typesToUnify[type][amount][index][pos1][pos2] in ":") { return itemUtils.getItem(typesToUnify[type][amount][index][pos1][pos2]); } else { if (getOreDict(typesToUnify[type][amount][index][pos1][pos2],metal).items.length >= 1) { return getOreDict(typesToUnify[type][amount][index][pos1][pos2],metal); } else { unification_recipeCheck = false; } } } function sortBig(list as int[string]) as string[] { var nums as int[] = []; var nums_mod as int[] = []; var sort as int[] = []; var mods as string[] = []; var i as int = 0; for mod, prio in list { if (loadedMods in mod) { nums += prio; } } nums_mod = nums; while (nums.length != 0) { nums = []; for entry in nums_mod { if (entry != i) { nums += entry; } } i = 0; for entry in nums { if (entry > i) { i = entry; } } sort += i; nums_mod = nums; } for entry in sort { for key, value in list { if (entry == value) { mods += key; } } } return mods; } function sortSmall(list as int[string]) as string[] { var nums as int[] = []; var nums_mod as int[] = []; var sort as int[] = []; var mods as string[] = []; var i as int = 0; for mod, prio in list { if (loadedMods in mod) { nums += prio; } } nums_mod = nums; while (nums.length != 0) { nums = []; for entry in nums_mod { if (entry != i) { nums += entry; } } i = 2147483; for entry in nums { if (entry < i) { i = entry; } } sort += i; nums_mod = nums; } for entry in sort { for key, value in list { if (entry == value) { mods += key; } } } return mods; }"""
2.28125
2
Aula 21 funcoes parte 2 exe 01.py
luizgarcindo/exercicio-curso-gustavo-guanabara
0
12763383
<filename>Aula 21 funcoes parte 2 exe 01.py def contador(i,f,p): """ Faz a contagem e mostra na tela :param i: inicio da contagem :param f: fim da contagem :param p: passo da contagem :return: sem retorno """ c=i while c<=f: print(f'{c} ', end='') c +=p print('FIMMM') contador(2,10,2) help(contador)
3.765625
4
psgan/solver.py
liuyaohua2017/PSGAN
0
12763384
<reponame>liuyaohua2017/PSGAN<filename>psgan/solver.py #!/usr/bin/python # -*- encoding: utf-8 -*- import os import os.path as osp pwd = osp.split(osp.realpath(__file__))[0] import time import datetime import torch from torch import nn from torchvision.transforms import ToPILImage from torchvision.utils import save_image import torch.nn.init as init from torch.autograd import Variable from torchgpipe import GPipe from ops.loss_added import GANLoss from ops.histogram_loss import HistogramLoss import tools.plot as plot_fig from . import net from .preprocess import PreProcess from concern.track import Track class Solver(Track): def __init__(self, config, device="cpu", data_loader=None, inference=False): self.G = net.Generator() if inference: self.G.load_state_dict(torch.load(inference, map_location=torch.device(device))) self.G = self.G.to(device).eval() return self.start_time = time.time() self.checkpoint = config.MODEL.WEIGHTS self.log_path = config.LOG.LOG_PATH self.result_path = os.path.join(self.log_path, config.LOG.VIS_PATH) self.snapshot_path = os.path.join(self.log_path, config.LOG.SNAPSHOT_PATH) self.log_step = config.LOG.LOG_STEP self.vis_step = config.LOG.VIS_STEP if device=='cuda': self.snapshot_step = config.LOG.SNAPSHOT_STEP // torch.cuda.device_count() else: self.snapshot_step = config.LOG.SNAPSHOT_STEP // 1 # Data loader self.data_loader_train = data_loader self.img_size = config.DATA.IMG_SIZE self.num_epochs = config.TRAINING.NUM_EPOCHS self.num_epochs_decay = config.TRAINING.NUM_EPOCHS_DECAY self.g_lr = config.TRAINING.G_LR self.d_lr = config.TRAINING.D_LR self.g_step = config.TRAINING.G_STEP self.beta1 = config.TRAINING.BETA1 self.beta2 = config.TRAINING.BETA2 self.lambda_idt = config.LOSS.LAMBDA_IDT self.lambda_A = config.LOSS.LAMBDA_A self.lambda_B = config.LOSS.LAMBDA_B self.lambda_his_lip = config.LOSS.LAMBDA_HIS_LIP self.lambda_his_skin = config.LOSS.LAMBDA_HIS_SKIN self.lambda_his_eye = config.LOSS.LAMBDA_HIS_EYE self.lambda_vgg = config.LOSS.LAMBDA_VGG # Hyper-parameteres self.d_conv_dim = config.MODEL.D_CONV_DIM self.d_repeat_num = config.MODEL.D_REPEAT_NUM self.norm = config.MODEL.NORM self.device = device self.build_model() super(Solver, self).__init__() # For generator def weights_init_xavier(self, m): classname = m.__class__.__name__ if classname.find('Conv') != -1: init.xavier_normal(m.weight.data, gain=1.0) elif classname.find('Linear') != -1: init.xavier_normal(m.weight.data, gain=1.0) def print_network(self, model, name): num_params = 0 for p in model.parameters(): num_params += p.numel() print(name) print(model) print("The number of parameters: {}".format(num_params)) def de_norm(self, x): out = (x + 1) / 2 return out.clamp(0, 1) def build_model(self): # self.G = net.Generator() # 构建两个判别器(二分类器) D_X, D_Y self.D_A = net.Discriminator(self.img_size, self.d_conv_dim, self.d_repeat_num, self.norm) self.D_B = net.Discriminator(self.img_size, self.d_conv_dim, self.d_repeat_num, self.norm) # 初始化网络参数,apply为从nn.module继承 self.G.apply(self.weights_init_xavier) self.D_A.apply(self.weights_init_xavier) self.D_B.apply(self.weights_init_xavier) # 从checkpoint文件中加载网络参数 self.load_checkpoint() # 循环一致性损失Cycle consistency loss self.criterionL1 = torch.nn.L1Loss() # 感知损失Perceptual loss self.criterionL2 = torch.nn.MSELoss() if self.device=='cuda': self.criterionGAN = GANLoss(use_lsgan=True, tensor=torch.cuda.FloatTensor) else: self.criterionGAN = GANLoss(use_lsgan=True, tensor=torch.FloatTensor) self.vgg = net.vgg16(pretrained=True) # 妆容损失makeup loss self.criterionHis = HistogramLoss() # Optimizers 优化器,迭代优化生成器和判别器的参数 self.g_optimizer = torch.optim.Adam(self.G.parameters(), self.g_lr, [self.beta1, self.beta2]) self.d_A_optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, self.D_A.parameters()), self.d_lr, [self.beta1, self.beta2]) self.d_B_optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, self.D_B.parameters()), self.d_lr, [self.beta1, self.beta2]) # Print networks self.print_network(self.G, 'G') self.print_network(self.D_A, 'D_A') self.print_network(self.D_B, 'D_B') if torch.cuda.is_available(): self.device = "cuda" if torch.cuda.device_count() > 1: self.G = nn.DataParallel(self.G) self.D_A = nn.DataParallel(self.D_A) self.D_B = nn.DataParallel(self.D_B) self.vgg = nn.DataParallel(self.vgg) self.criterionHis = nn.DataParallel(self.criterionHis) self.criterionGAN = nn.DataParallel(self.criterionGAN) self.criterionL1 = nn.DataParallel(self.criterionL1) self.criterionL2 = nn.DataParallel(self.criterionL2) self.criterionGAN = nn.DataParallel(self.criterionGAN) self.G.cuda() self.vgg.cuda() self.criterionHis.cuda() self.criterionGAN.cuda() self.criterionL1.cuda() self.criterionL2.cuda() self.D_A.cuda() self.D_B.cuda() def load_checkpoint(self): G_path = os.path.join(self.checkpoint, 'G.pth') if os.path.exists(G_path): self.G.load_state_dict(torch.load(G_path, map_location=torch.device(self.device))) print('loaded trained generator {}..!'.format(G_path)) D_A_path = os.path.join(self.checkpoint, 'D_A.pth') if os.path.exists(D_A_path): self.D_A.load_state_dict(torch.load(D_A_path, map_location=torch.device(self.device))) print('loaded trained discriminator A {}..!'.format(D_A_path)) D_B_path = os.path.join(self.checkpoint, 'D_B.pth') if os.path.exists(D_B_path): self.D_B.load_state_dict(torch.load(D_B_path, map_location=torch.device(self.device))) print('loaded trained discriminator B {}..!'.format(D_B_path)) def generate(self, org_A, ref_B, lms_A=None, lms_B=None, mask_A=None, mask_B=None, diff_A=None, diff_B=None, gamma=None, beta=None, ret=False): """org_A is content, ref_B is style""" res = self.G(org_A, ref_B, mask_A, mask_B, diff_A, diff_B, gamma, beta, ret) return res # mask attribute: 0:background 1:face 2:left-eyebrown 3:right-eyebrown 4:left-eye 5: right-eye 6: nose # 7: upper-lip 8: teeth 9: under-lip 10:hair 11: left-ear 12: right-ear 13: neck def test(self, real_A, mask_A, diff_A, real_B, mask_B, diff_B): cur_prama = None with torch.no_grad(): cur_prama = self.generate(real_A, real_B, None, None, mask_A, mask_B, diff_A, diff_B, ret=True) fake_A = self.generate(real_A, real_B, None, None, mask_A, mask_B, diff_A, diff_B, gamma=cur_prama[0], beta=cur_prama[1]) fake_A = fake_A.squeeze(0) # normalize min_, max_ = fake_A.min(), fake_A.max() fake_A.add_(-min_).div_(max_ - min_ + 1e-5) return ToPILImage()(fake_A.cpu()) def train(self): # The number of iterations per epoch self.iters_per_epoch = len(self.data_loader_train) # Start with trained model if exists g_lr = self.g_lr d_lr = self.d_lr start = 0 for self.e in range(start, self.num_epochs): # epoch for self.i, (source_input, reference_input) in enumerate(self.data_loader_train): # batch # image, mask, dist image_s, image_r = source_input[0].to(self.device), reference_input[0].to(self.device) mask_s, mask_r = source_input[1].to(self.device), reference_input[1].to(self.device) dist_s, dist_r = source_input[2].to(self.device), reference_input[2].to(self.device) self.track("data") # ================== Train D ================== # # training D_A, D_A aims to distinguish class B 判断是否是“真reference” y # Real out = self.D_A(image_r) self.track("D_A") d_loss_real = self.criterionGAN(out, True) self.track("D_A_loss") # Fake # 利用生成网络生成fake_y fake_A = self.G(image_s, image_r, mask_s, mask_r, dist_s, dist_r) self.track("G") # 判别网络的输入,判别网络的损失 requires_grad=False fake_A = Variable(fake_A.data).detach() out = self.D_A(fake_A) self.track("D_A_2") d_loss_fake = self.criterionGAN(out, False) self.track("D_A_loss_2") # Backward + Optimize # 判别器网络反向传播,更新网络参数 d_loss = (d_loss_real.mean() + d_loss_fake.mean()) * 0.5 self.d_A_optimizer.zero_grad() d_loss.backward(retain_graph=False) ##retain_graph=False 释放计算图 self.d_A_optimizer.step() # Logging self.loss = {} self.loss['D-A-loss_real'] = d_loss_real.mean().item() # training D_B, D_B aims to distinguish class A 判断是否是“真source” x # Real out = self.D_B(image_s) d_loss_real = self.criterionGAN(out, True) # Fake 利用生成网络生成fake_x self.track("G-before") fake_B = self.G(image_r, image_s, mask_r, mask_s, dist_r, dist_s) self.track("G-2") fake_B = Variable(fake_B.data).detach() out = self.D_B(fake_B) d_loss_fake = self.criterionGAN(out, False) # Backward + Optimize d_loss = (d_loss_real.mean() + d_loss_fake.mean()) * 0.5 self.d_B_optimizer.zero_grad() d_loss.backward(retain_graph=False) self.d_B_optimizer.step() # Logging self.loss['D-B-loss_real'] = d_loss_real.mean().item() # self.track("Discriminator backward") # ================== Train G ================== # if (self.i + 1) % self.g_step == 0: # identity loss assert self.lambda_idt > 0 # G should be identity if ref_B or org_A is fed idt_A = self.G(image_s, image_s, mask_s, mask_s, dist_s, dist_s) idt_B = self.G(image_r, image_r, mask_r, mask_r, dist_r, dist_r) loss_idt_A = self.criterionL1(idt_A, image_s) * self.lambda_A * self.lambda_idt loss_idt_B = self.criterionL1(idt_B, image_r) * self.lambda_B * self.lambda_idt # loss_idt loss_idt = (loss_idt_A + loss_idt_B) * 0.5 # loss_idt = loss_idt_A * 0.5 # self.track("Identical") # GAN loss D_A(G_A(A)) # fake_A in class B, # 生成器对抗损失 L_G^adv fake_A = self.G(image_s, image_r, mask_s, mask_r, dist_s, dist_r) pred_fake = self.D_A(fake_A) g_A_loss_adv = self.criterionGAN(pred_fake, True) # GAN loss D_B(G_B(B)) fake_B = self.G(image_r, image_s, mask_r, mask_s, dist_r, dist_s) pred_fake = self.D_B(fake_B) g_B_loss_adv = self.criterionGAN(pred_fake, True) # self.track("Generator forward") # color_histogram loss # 各局部颜色直方图损失 Makeup loss g_A_loss_his = 0 g_B_loss_his = 0 g_A_lip_loss_his = self.criterionHis( fake_A, image_r, mask_s[:, 0], mask_r[:, 0] ) * self.lambda_his_lip g_B_lip_loss_his = self.criterionHis( fake_B, image_s, mask_r[:, 0], mask_s[:, 0] ) * self.lambda_his_lip g_A_loss_his += g_A_lip_loss_his g_B_loss_his += g_B_lip_loss_his g_A_skin_loss_his = self.criterionHis( fake_A, image_r, mask_s[:, 1], mask_r[:, 1] ) * self.lambda_his_skin g_B_skin_loss_his = self.criterionHis( fake_B, image_s, mask_r[:, 1], mask_s[:, 1] ) * self.lambda_his_skin g_A_loss_his += g_A_skin_loss_his g_B_loss_his += g_B_skin_loss_his g_A_eye_loss_his = self.criterionHis( fake_A, image_r, mask_s[:, 2], mask_r[:, 2] ) * self.lambda_his_eye g_B_eye_loss_his = self.criterionHis( fake_B, image_s, mask_r[:, 2], mask_s[:, 2] ) * self.lambda_his_eye g_A_loss_his += g_A_eye_loss_his g_B_loss_his += g_B_eye_loss_his # self.track("Generator histogram") # cycle loss # fake_A: fake_x/source rec_A = self.G(fake_A, image_s, mask_s, mask_s, dist_s, dist_s) rec_B = self.G(fake_B, image_r, mask_r, mask_r, dist_r, dist_r) g_loss_rec_A = self.criterionL1(rec_A, image_s) * self.lambda_A g_loss_rec_B = self.criterionL1(rec_B, image_r) * self.lambda_B # self.track("Generator recover") # vgg loss # Perceptual loss vgg_s = self.vgg(image_s) vgg_s = Variable(vgg_s.data).detach() vgg_fake_A = self.vgg(fake_A) g_loss_A_vgg = self.criterionL2(vgg_fake_A, vgg_s) * self.lambda_A * self.lambda_vgg # self.track("Generator vgg") vgg_r = self.vgg(image_r) vgg_r = Variable(vgg_r.data).detach() vgg_fake_B = self.vgg(fake_B) g_loss_B_vgg = self.criterionL2(vgg_fake_B, vgg_r) * self.lambda_B * self.lambda_vgg loss_rec = (g_loss_rec_A + g_loss_rec_B + g_loss_A_vgg + g_loss_B_vgg) * 0.5 # loss_rec = (g_loss_rec_A + g_loss_A_vgg) * 0.5 # Combined loss g_loss = (g_A_loss_adv + g_B_loss_adv + loss_rec + loss_idt + g_A_loss_his + g_B_loss_his).mean() # g_loss = (g_A_loss_adv + loss_rec + loss_idt + g_A_loss_his).mean() self.g_optimizer.zero_grad() g_loss.backward(retain_graph=False) self.g_optimizer.step() # self.track("Generator backward") # Logging self.loss['G-A-loss-adv'] = g_A_loss_adv.mean().item() self.loss['G-B-loss-adv'] = g_A_loss_adv.mean().item() self.loss['G-loss-org'] = g_loss_rec_A.mean().item() self.loss['G-loss-ref'] = g_loss_rec_B.mean().item() self.loss['G-loss-idt'] = loss_idt.mean().item() self.loss['G-loss-img-rec'] = (g_loss_rec_A + g_loss_rec_B).mean().item() self.loss['G-loss-vgg-rec'] = (g_loss_A_vgg + g_loss_B_vgg).mean().item() self.loss['G-loss-img-rec'] = g_loss_rec_A.mean().item() self.loss['G-loss-vgg-rec'] = g_loss_A_vgg.mean().item() self.loss['G-A-loss-his'] = g_A_loss_his.mean().item() # Print out log info if (self.i + 1) % self.log_step == 0: self.log_terminal() #plot the figures for key_now in self.loss.keys(): plot_fig.plot(key_now, self.loss[key_now]) #save the images if (self.i) % self.vis_step == 0: print("Saving middle output...") self.vis_train([image_s, image_r, fake_A, rec_A, mask_s[:, :, 0], mask_r[:, :, 0]]) # Save model checkpoints if (self.i) % self.snapshot_step == 0: self.save_models() if (self.i % 100 == 99): plot_fig.flush(self.log_path) plot_fig.tick() # Decay learning rate if (self.e+1) > (self.num_epochs - self.num_epochs_decay): g_lr -= (self.g_lr / float(self.num_epochs_decay)) d_lr -= (self.d_lr / float(self.num_epochs_decay)) self.update_lr(g_lr, d_lr) print('Decay learning rate to g_lr: {}, d_lr:{}.'.format(g_lr, d_lr)) def update_lr(self, g_lr, d_lr): for param_group in self.g_optimizer.param_groups: param_group['lr'] = g_lr for param_group in self.d_A_optimizer.param_groups: param_group['lr'] = d_lr for param_group in self.d_B_optimizer.param_groups: param_group['lr'] = d_lr def save_models(self): if not osp.exists(self.snapshot_path): os.makedirs(self.snapshot_path) torch.save( self.G.state_dict(), os.path.join( self.snapshot_path, '{}_{}_G.pth'.format(self.e + 1, self.i + 1))) torch.save( self.D_A.state_dict(), os.path.join( self.snapshot_path, '{}_{}_D_A.pth'.format(self.e + 1, self.i + 1))) torch.save( self.D_B.state_dict(), os.path.join( self.snapshot_path, '{}_{}_D_B.pth'.format(self.e + 1, self.i + 1))) def vis_train(self, img_train_list): # saving training results mode = "train_vis" img_train_list = torch.cat(img_train_list, dim=3) result_path_train = osp.join(self.result_path, mode) if not osp.exists(result_path_train): os.makedirs(result_path_train) save_path = os.path.join(result_path_train, '{}_{}_fake.jpg'.format(self.e, self.i)) save_image(self.de_norm(img_train_list.data), save_path, normalize=True) def log_terminal(self): elapsed = time.time() - self.start_time elapsed = str(datetime.timedelta(seconds=elapsed)) log = "Elapsed [{}], Epoch [{}/{}], Iter [{}/{}]".format( elapsed, self.e+1, self.num_epochs, self.i+1, self.iters_per_epoch) for tag, value in self.loss.items(): log += ", {}: {:.4f}".format(tag, value) print(log) def to_var(self, x, requires_grad=True): if torch.cuda.is_available(): x = x.cuda() if not requires_grad: return Variable(x, requires_grad=requires_grad) else: return Variable(x)
1.820313
2
pyPack/HTML_constantes.py
slozano54/projetDNB
1
12763385
<reponame>slozano54/projetDNB #!/usr/bin/python3 #-*- coding: utf8 -*- # @author : <NAME> """ Générer les parties communes aux fichiers HTML. On met les constantes dans des chaînes. """ pass docTypeHead = ( """ <!doctype html> <html lang=\"fr\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>DNB-APMEP-MATHALEA</title> </head> """ ) style = ( """ <style> </style> """ ) docTypeHeadStyle = ( """ <!doctype html> <html lang=\"fr\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Projet DNB APMEP MATHALEA</title> <style> .navButton { display: inline-block; border-radius: 4px; background-color: #ff7f00; color: #FFFFFF; text-align: center; font-size: 1rem; padding: 0.75rem; width: auto; transition: all 0.5s; margin: 0.3rem; } .navButton { font-weight: bold; } .navButton { border: none; cursor: pointer; } .navButton span { cursor: pointer; display: inline-block; position: relative; transition: 0.5s; } .navButton span:after { content: '\\00bb'; position: absolute; opacity: 0; top: 0; right: -1.25rem; transition: 0.5s; } .navButton:hover span { padding-right: 1.5rem; } .navButton:hover span:after { opacity: 1; right: 0; } </style> </head> """ ) barreDeNavigation = ( """ <h1>PROJET DNB APMEP MATHALEA</h1> <hr> <h4>Source des données : <a href=\"https://www.apmep.fr/-Brevet-289-sujets-tous-corriges-\" target=\"_blank\">https://www.apmep.fr/-Brevet-289-sujets-tous-corriges-</a></h4> <hr> <a class="navButton" href=\"index.html\" target=\"_self\"><span>Accueil</span></a> <a class="navButton" href=\"../docs/pyPack/index.html\" target=\"_blank\"><span>Documentation</span></a> <hr> """ )
2.03125
2
03_linked_list.py
mwizasimbeye11/algorithms_in_python
1
12763386
<filename>03_linked_list.py<gh_stars>1-10 class Node: def __init__(self, data): self.data = data # Assign the data here self.next = None # Set next to None by default. class LinkedList: def __init__(self): self.head = None # Display the list. Linked list traversal. def display(self): temp = self.head display = "" while temp: display+=(str(temp.data)+" -> ") temp = temp.next display+="None" print(display) def push(self, data): # Create the new node before we insert it at the beginning of the LL new_node = Node(data) # Assign the next pointer to the head new_node.next = self.head # Move the head pointer to the new node. self.head = new_node def append(self, data): # Inserting data at the end of the linked list. new_node = Node(data) if self.head == None: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node def insert(self, previous_node, data): if previous_node == None: return # Create a new node with new data new_node = Node(data) new_node.next = previous_node.next previous_node.next = new_node # Tests # Initialize linked list llist = LinkedList() # Create some nodes. llist.push(2) llist.push(3) llist.push(4) llist.append(1) llist.display()
4.28125
4
evalto/reducer/reducer.py
jsoldani/ship-to
0
12763387
import os import errno import sys from pyswip import Prolog # function for reducing a topology to a term "l(type,dir,term1,term2)" def reduce(outputFile): # load Prolog program "reducer" prolog = Prolog() prolog.consult("prolog/reducer.pl") # check well-formedness violating = list(prolog.query("violatingWellFormedness(L1,L2)")) violating1 = violating[0]["L1"] violating2 = violating[0]["L2"] if len(violating1) > 0 or len(violating2) > 0: # print violations (if any) print("ERROR: topology is not well-formed because") for n in violating1: print("- node " + str(n) + " violates condition (i) of well-formedness") for n in violating2: print("- node " + str(n) + " violates condition (ii) of well-formedness") exit(2) # compute first possible solution (if any) results = list(prolog.query("loop(R)", maxresult=1)) if len(results) > 0: # if solvable, save first result result = results[0]["R"] else: # otherwise, return error message for non well-formed topology print("ERROR: something went wrong...is topology rooted?") exit(2) # create "output" folder (if not existing yet) try: os.mkdir("output") except Exception as e: if e.errno != errno.EEXIST: print(e) # output term on "outputFile" outputFileWithFolder = "output/" + outputFile output = open(outputFileWithFolder,"w") output.write(result) def main(args): # check command line arguments if len(args) < 1: print("usage: reducer.py <outputFile>") exit(2) # reduce topology and output on file reduce(args[0]) main(sys.argv[1:])
2.796875
3
docsbox/docs/tasks.py
Harshad2294/docsbox
0
12763388
import os import shutil import datetime from pylokit import Office from wand.image import Image from tempfile import NamedTemporaryFile, TemporaryDirectory from rq import get_current_job from docsbox import app, rq from docsbox.docs.utils import make_zip_archive, make_thumbnails @rq.job(timeout=app.config["REDIS_JOB_TIMEOUT"]) def remove_file(path): """ Just removes a file. Used for deleting original files (uploaded by user) and result files (result of converting) """ return os.remove(path) @rq.job(timeout=app.config["REDIS_JOB_TIMEOUT"]) def process_document(filename, path, options, meta): current_task = get_current_job() with Office(app.config["LIBREOFFICE_PATH"]) as office: # acquire libreoffice lock with office.documentLoad(path) as original_document: # open original document print ("PATH : ", str(path)) with TemporaryDirectory() as tmp_dir: # create temp dir where output'll be stored for fmt in options["formats"]: # iterate over requested formats current_format = app.config["SUPPORTED_FORMATS"][fmt] #output_path = os.path.join(tmp_dir, current_format["path"]) output_path = os.path.join(tmp_dir, filename+"."+current_format["path"]) original_document.saveAs(output_path, fmt=current_format["fmt"]) if options.get("thumbnails", None): is_created = False if meta["mimetype"] == "application/pdf": pdf_path = path elif "pdf" in options["formats"]: pdf_path = os.path.join(tmp_dir, filename+".pdf") else: pdf_tmp_file = NamedTemporaryFile() pdf_path = pdf_tmp_file.name original_document.saveAs(filename+".pdf", fmt="pdf") is_created = True image = Image(filename=pdf_path, resolution=app.config["THUMBNAILS_DPI"]) if is_created: pdf_tmp_file.close() thumbnails = make_thumbnails(image, tmp_dir, options["thumbnails"]["size"]) result_path, result_url = make_zip_archive(current_task.id, tmp_dir) remove_file.schedule( datetime.timedelta(seconds=app.config["RESULT_FILE_TTL"]), result_path ) return result_url
2.609375
3
apps/consultants/urls.py
kradalby/kavik
0
12763389
from django.conf.urls import patterns, include, url urlpatterns = patterns('apps.consultants.views', url(r'^maillist/$', 'maillist', name='maillist'), url(r'^vcf/$', 'vcf', name='vcf'), url(r'^maillist/(?P<team_id>[0-9]{2}|(tl))/$', 'maillist', name='maillist'), )
1.679688
2
actions/video.py
paulomcnally/pi-voice
1
12763390
<reponame>paulomcnally/pi-voice import subprocess class Video: @staticmethod def run(): subprocess.run(['sh', '/home/pi/pi-voice/actions/video.sh'])
2.046875
2
papermerge/core/serializers/content_type.py
papermerge/papermerge-core
45
12763391
<filename>papermerge/core/serializers/content_type.py from django.contrib.auth.models import ContentType from rest_framework_json_api import serializers class ContentTypeSerializer(serializers.ModelSerializer): class Meta: model = ContentType resource_name = 'content-types' fields = ('id', 'model',)
1.703125
2
code/KL_UCB/KL_UCB.py
christopher-salomon-smith/vip-mab
0
12763392
<filename>code/KL_UCB/KL_UCB.py import numpy as np import scipy.stats as sps import matplotlib.pyplot as plt import math class KL_UCB: ''' Representation of a single agent bandit problem and a method to run the KL_UCB algorithm on this problem Attributes ---------- T: The number of time steps the KL_UCB algorithm will run for. arm_distributions: A list of scipy.stats probability distributions bounded on [0,1] means: A list of arm means. Extracted from arm_distributions M: Number of arms. Extracted from length of arm_distributions regret: A 1xT numpy ndarray of the expected regret from the most recent algorithm run ''' def __init__(self, T, arm_distributions): ''' Construct a single agent bandit problem instance Parameters ---------- T: The number of time steps the KL_UCB algorithm will run for. arm_distributions: A list of scipy.stats probability distributions bounded on [0,1]. Raises ------ ValueError If T is not a positive integer. If the support for any arm distribution is not in [0,1]. ''' if (T < 1 or type(T) is not int): raise ValueError('T must be a positive integer') if (any(d.support()[0] < 0 or d.support()[1] > 1 for d in arm_distributions)): raise ValueError('distribution support must lie in [0,1]') self.T = T self.arm_distributions = arm_distributions self.means = [d.mean() for d in arm_distributions] self.M = len(arm_distributions) self.regret = None def KL(self, p, q): ''' Compute Kullback-Leibler divergence between Bernoulli distributions of parameters p and q. Note that we can use this even when arm distributions are not Bernoulli. In this case, p and q are the means of their respective distributions. ''' if (math.isclose(p, 0) and math.isclose(q, 0)) or (math.isclose(p, 1) and math.isclose(q, 1)) or (p >= 1 and q >= 1): return 0 elif math.isclose(q, 0) or math.isclose(q, 1) or q <= 0 or q >= 1: return np.inf elif math.isclose(p, 0) or p <= 0: return np.inf elif p >= 1: return 0 else: return p*np.log(p/q) + (1-p)*np.log((1-p)/(1-q)) def dKL(self, p, q): ''' Compute the derivative of the Bernoulli Kullback-Leibler divergence between p and q, with respect to q. ''' return (p-q)/(q*(q - 1.0)) def newton(self, N, S, k, t, precision = 1e-3, max_iterations=20, epsilon=1e-6): ''' Calculate upper confidence bound via newton's method WARNING: This function works in that it efficiently finds greatest approx zero to f in (0,1). However, KL-UCB technically specifies that the returned value of q should be such that f(q) <= 0. The q's returned by this function seemingly always satisfy f(q)>=0. Enforcing f(q) <= 0 does not work (times out) because f(q) converges to 0 from the right. If this is unacceptable, maybe look into other root finding methods like bisection. Parameters ---------- N: A numpy ndarray holding the number of times each arm has been played up until time t. S: A numpy ndarray holding the cumulative reward received from each arm up until time t. k: The arm index we are computing an upper confidence bound for. t: The current time step. precision: Arbitrarily small convergence threshold max_iterations: Limit on number of iterations Newton's method should run epsilon: A miscellaneous arbitrarily small limit Return ------ An upper confidence bound for the given parameters. Should technically be within [0,1], see warning. ''' p = S[k]/N[k] # from paper delta = 0.1 # arbitrary small positive offset q = p + delta # initial guess. if p==q, then dKL=0 and we never move anywhere converged = False for n in range(max_iterations): #if (p / q <= 0 or (1-p)/(1-q) <= 0): # sanity check for log domain errors # print(f'log error: p={p}, q={q}, n={n}') # wish to find greatest val of q in (0,1) that gets f closest to zero from below f = self.KL(p, q) - np.log(t+1)/N[k] df = self.dKL(p, q) # derivative of f is just derivative of KL if abs(df) < epsilon: # check denominator not too small break # NOTE: graph KL function to see that largest zero (what we want) is >= p. qnew = max(p+delta, min(q - (f / df), 1-epsilon)) # chris: my approach for keeping q in (p,1) # print(f'q={q}, f(q)={f}, qnew={qnew}, precision={precision} n={n}') if(abs(f) < precision and abs(qnew - q) < precision): # check for early convergence converged = True # print(f'converged at {n} iterations') break q = qnew # if(not converged): print("Did not converge") return q def plot_regret(self): ''' Plots regret of last run vs theoretical regret bounds Note: make sure KL_UCB.run() was called before calling this method ''' optimal_arm = np.argmax(self.means) time_axis = list(range(self.T)) coeff = 0 for i in range(self.M): if (i != optimal_arm): coeff += (self.means[optimal_arm] - self.means[i]) / (self.KL(self.means[i], self.means[optimal_arm])) theoretical_regret_bounds = [coeff * np.log(t+1) for t in time_axis] # not sure if allowed to do this bc of lim sup, seems like it works tho plt.plot(time_axis, theoretical_regret_bounds, '--') plt.plot(time_axis, self.regret) plt.show() def run(self): ''' Run the KL_UCB algorithm on the bandit problem instance held by self Return ------ A list of length self.T with expected regret at each time t ''' N = np.zeros(self.M) # keeps track of number of times arm k has been chosen S = np.zeros(self.M) # keeps track of cumulative sum of rewards for arm k # data structures just for plotting regret optimal_arm = np.argmax(self.means) exp_cum_rwd = [0 for t in range(self.T)] # exp_cum_rwd[t] is expected cumulative reward at time t for t in range(self.M): N[t] = 1 S[t] = self.arm_distributions[t].rvs() exp_cum_rwd[t] = exp_cum_rwd[t-1] + self.means[t] if t != 0 else self.means[t] # t is index of chosen arm here for t in range(self.M, self.T): a = np.argmax([self.newton(N, S, arm, t) for arm in range(self.M)]) #argmax part of line 6 of algorithm 1 r = self.arm_distributions[a].rvs() N[a] = N[a] + 1 S[a] = S[a] + r exp_cum_rwd[t] = exp_cum_rwd[t-1] + self.means[a] optimal_exp_cum_rwd = [(t+1) * self.means[optimal_arm] for t in range(self.T)] regret = np.asarray(optimal_exp_cum_rwd) - np.asarray(exp_cum_rwd) # see definition of regret self.regret = regret return regret # # test run # T = 1000 # rwd_means = [.2, .3, .4, .5, .6] # distributions = [sps.uniform(loc=rwd_means[i] - .1, scale=0.2) for i in range(len(rwd_means))] # kl = KL_UCB(T, distributions) # kl.run() # kl.plot_regret()
3.28125
3
src/test.py
MasayukiNagai/VersUS
2
12763393
# test script import os import logging from Handlers.SeqHandler import * from Handlers.ClinVarHandler import * from Handlers.BLASTHandler import * from Handlers.CADDHandler import * from Handlers.VEPHandler import * from Handlers.FileHandler import * from VersUS import * gene_file = './data/gene/HumanEnzWithEC.csv' seq_dir = './data/fasta_sequences' blast_path = './ncbi/blast/bin' blast_input = './data/blast/vus_blast.fasta' blast_output = './data/blast/blast_results.xml' cadd_input = '/Users/moon/DePauw/ITAP/VersUS/src/data/CADD/cadd_input.vcf.gz' cadd_output = '/Users/moon/DePauw/ITAP/VersUS/src/data/CADD/CADD_scores.tar.gz' vep_input = './data/vep/vep_vus_input.tsv' vep_output = './data/vep/vep_vus_results.tsv' # seqHandler = SeqHandler(gene_file, seq_dir) # clinvarHandler = ClinVarHandler() # blastHandler = BLASTHandler(blast_input, blast_output) caddHandler = CADDHandler(cadd_input, cadd_output) # vepHandler = VEPHandler(vep_input, vep_output) # versus = VersUS() # print('---------- read Gene File ----------') # genes_dict = seqHandler.readHumanGenesEC() # print('---------- VariationParser ----------') # clinvar_file = './data/clinvar/ClinVarVariationRelease_00-latest_weekly.xml' # # clinvar_file = './data/clinvar/clinvar_tail_5.xml' # vus_dict = clinvarHandler.readClinVarVariationsXML(clinvar_file, genes_dict) # print('---------- write to TSV ----------') # header = ('gene_id', 'gene_name', 'clinical_significance', 'EC_number', 'missense_variation', 'NP_accession', 'ClinVar_accession', 'chr', 'start', 'stop', 'referenceAllele', 'alternateAllele') # outfile_path = './data/VUS.tsv' # versus.write_to_tsv(vus_dict, header, outfile_path) # print('********** read TSV **********') # tsv_path = './data/VUS.tsv' # vus_dict = versus.read_tsv_to_dict(tsv_path) # print(f'The number of VUS: {len(vus_dict)}') # print(vus_dict[0]) # print('---------- make sequence dict ----------') # seq_dir_path = './data/fasta_sequences' # seq_dict = seqHandler.make_seq_dict() # print(next(iter(seq_dict.keys()))) # print('---------- add seq to vus_dict ----------') # seq_range = 12 # vus_dict, unfound_seq = seqHandler.add_seq_to_dict(vus_dict, seq_range) # print(f'NP numbers missing their seq: {(unfound_seq)}') # print('---------- get unfound sequences ----------') # seq_dict = seqHandler.fetch_seq(unfound_seq) # vus_dict, unfound_seq = seqHandler.add_seq_to_dict(vus_dict, seq_dict) # print(f'NP numbers missing their seq: {(unfound_seq)}') # print('---------- write to TSV ----------') # header = ('gene_id', 'gene_name', 'clinical_significance', 'EC_number', 'missense_variation', 'NP_accession', 'ClinVar_accession', 'chr', 'start', 'stop', 'referenceAllele', 'alternateAllele', 'FASTA_window') # outfile_path = './data/VUS.tsv' # versus.write_to_tsv(vus_dict, header, outfile_path) # print('********** read TSV **********') # tsv_path = './data/VUS.tsv' # vus_dict = versus.read_tsv_to_dict(tsv_path) # print(f'The number of VUS: {len(vus_dict)}') # print(vus_dict[0]) # print('---------- make a fasta file for blast ----------') # blastHandler.make_fasta_for_blast(vus_dict) # print('Done') # print('---------- run BLAST ----------') # blastHandler.blast_locally() # print('---------- read BLAST results ----------') # blast_dict = blastHandler.readBlastXML() # print('---------- add BLAST results to VUS_dict ----------') # vus_dict = blastHandler.add_blast_results(vus_dict, blast_dict) # header = ('gene_id', 'gene_name', 'clinical_significance', 'EC_number', 'missense_variation', 'NP_accession', 'ClinVar_accession', 'chr', 'start', 'stop', 'referenceAllele', 'alternateAllele', 'FASTA_window', 'pdb_ID', 'BLAST_evalue', 'hit_from', 'hit_to') # vus_blast_path = './data/VUS_with_blast.tsv' # versus.write_to_tsv(vus_dict, header, vus_blast_path) print('********** read TSV **********') tsv_path = './data/VUS_with_blast.tsv' vus_dict = read_tsv_to_dict(tsv_path) print(f'The number of VUS: {len(vus_dict)}') print(vus_dict[0]) print('---------- make_tsv_for_CADD ----------') caddHandler.make_tsv_for_CADD(vus_dict) print('Done') # print('---------- get CADD scores from its website ----------') # cadd_results = '/Users/moon/DePauw/ITAP/ClinvarSorting/data/CADD/GRCh38-v1.4.tsv.gz' # caddHandler.get_CADD_scores() # print('---------- read CADD results ----------') # cadd_results = './data/CADD/GRCh38-v1.4.tsv.gz' # cadd_dict = caddHandler.read_CADD_results() # print('---------- add CADD results ----------') # vus_dict = caddHandler.add_cadd_results(vus_dict) # header = ('gene_id', 'gene_name', 'clinical_significance', 'EC_number', 'missense_variation', 'NP_accession', 'ClinVar_accession', 'CADD_score', 'chr', 'start', 'stop', 'referenceAllele', 'alternateAllele', 'FASTA_window', 'pdb_ID', 'BLAST_evalue', 'hit_from', 'hit_to') # vus_blast_cadd_path = './data/VUS_with_blast_cadd.tsv' # versus.write_to_tsv(vus_dict, header, vus_blast_cadd_path) # print('********** read TSV **********') # tsv_path = './data/VUS_with_blast_cadd.tsv' # vus_dict = versus.read_tsv_to_dict(tsv_path) # print(f'The number of VUS: {len(vus_dict)}') # print(vus_dict[0]) # print('---------- make_tsv_for_VEP ----------') # vepHandler.make_tsv_for_vep(vus_dict) # print('Done') # print('---------- run vep ----------') # vepHandler.vep_locally() # print('---------- make ordered_dict for VEP ----------') # vus_ordered_dict = vepHandler.make_ordered_vus_dict_for_vep(vus_dict) # print('---------- make_tsv_ordered_for_VEP ----------') # vepHandler.make_tsv_ordered_for_vep(vus_ordered_dict) # print('Done') # print('---------- read VEP output ----------') # vep_dict = vepHandler.read_vep_output() # print('---------- add VEP output ----------') # vus_dict = vepHandler.add_vep_output(vus_dict) # header = ('gene_id', 'gene_name', 'clinical_significance', 'EC_number', 'missense_variation', 'NP_accession', 'ClinVar_accession', 'gnomAD_AF', 'CADD_score', 'chr', 'start', 'stop', 'referenceAllele', 'alternateAllele', 'FASTA_window', 'pdb_ID', 'BLAST_evalue', 'hit_from', 'hit_to') # vus_blast_cadd_path = './data/VUS_with_blast_cadd_vep.tsv' # versus.write_to_tsv(vus_dict, header, vus_blast_cadd_path) # logger = logging.getLogger('test_logger') # logger.setLevel(logging.DEBUG) # fh = logging.FileHandler('test.log') # fh.setLevel(logging.DEBUG) # fh_formatter = logging.Formatter('[%(asctime)s] %(levelname)s %(filename)s %(funcName)s : %(message)s') # fh.setFormatter(fh_formatter) # # creates a file handler that logs messages above INFO level # sh = logging.StreamHandler() # sh.setLevel(logging.DEBUG) # sh_formatter = logging.Formatter('[%(asctime)s] %(levelname)s : %(message)s', '%Y-%m-%d %H:%M:%S') # sh.setFormatter(sh_formatter) # # add the handlers to logger # logger.addHandler(fh) # logger.addHandler(sh) # logger.debug('What up, this is DEBUG') # logger.info('Hi, this is INFO') # logger.warning('Well, this is WARNING') # from test2 import log # log() # blast_input = './data/blast/vus_blast.fasta' # blast_output = './data/blast/blast_result_short.xml' # blastHandler = BLASTHandler(blast_path, blast_input, blast_output) # blast_results = blastHandler.readBlastXML() # print(blast_results) # cadd_input = os.path.abspath('./data/CADD/CADD_sample_input.vcf') # cadd_output = os.path.abspath('./data/CADD/CADD_sample_output.vcf') # caddHandler = CADDHandler(cadd_input, cadd_output) # caddHandler.get_CADD_scores()
2.109375
2
checkAllEps.py
stummyhurt/noTBA-scripterx
2
12763394
import asyncio from helpers import get_db import importlib import json import logging import sys from datetime import datetime from os import path from queue import Queue import requests from alive_progress import alive_bar from checkEp import check_episode dir = path.split(path.abspath(__file__))[0] # logging setup logging.StreamHandler() async def main(): if not api_token or not base_url: logging.critical('Either your api_token or base_url is blank!') sys.exit() api_json = {"X-Emby-Token": api_token} headers={"user-agent": "mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/81.0.4044.138 safari/537.36"} headers.update(api_json) years = datetime.now().year if len(sys.argv)==1 else None if sys.argv[1].lower() in ['all','none'] else sys.argv[1] logging.warning(f'Years={years}') raw_data = { 'IncludeItemTypes': 'Episode', 'Years': years, 'Recursive': True, 'IsMissing': False, } def get_items(params): res = requests.get(f'{base_url}/Items', params=params, headers=headers) try: data = json.loads(res.text) except json.decoder.JSONDecodeError: print(res.text) return [] items = [] for item in data.get('Items'): id = item.get("Id") items.append(id) return items ids = [] if not check_thumbs: for q in ['Episode ', 'TBA']: raw_data.update({'NameStartsWith': q}) ids += get_items(raw_data) if check_thumbs: ids = get_items(raw_data) logging.warning(f'Checking {len(ids)} ids!') with alive_bar(len(ids), bar='blocks', spinner='dots_waves2') as bar: db = get_db() async def run_with_progress(id): await check_episode(id, db) bar() # Optimal qsize limit might be 8 # 3 = 59.9 # 5 = 61.4 # 7 = 58.5 # 8 = 64 # 9 = 59.5 # 10 = 57.6 ps = Queue() for id in ids: while ps.qsize() > limit_concurrent_requests: await ps.get() ps.put(asyncio.create_task(run_with_progress(id))) while not ps.empty(): await ps.get() db.close() if __name__ == '__main__': conf = importlib.import_module('config') if path.isfile(f'{dir}/config_local.py'): conf = importlib.import_module('config_local') api_token = conf.api_token base_url = conf.base_url check_thumbs = conf.check_thumbs limit_concurrent_requests = conf.limit_concurrent_requests asyncio.run(main())
2.28125
2
packageopt/repositories/implementations/vola_repo.py
nspostnov/for-article-optimal-position-liquidation
0
12763395
from ..abstract_base_classes import RepoABC from ...models.vola import Vola __all__ = ['VolaRepo'] class VolaRepo(RepoABC): def __init__(self, volatablecruder): self._volatablecruder = volatablecruder def get(self, key): vola = Vola() vola.set_key(key) return self._volatablecruder.get(vola) def set(self, vola): self._volatablecruder.update(vola)
2.359375
2
Exercises/grade_determiner.py
Peabody29/Python_Projects-ST
0
12763396
"""This program takes a score between 0.0 and 1.0 and returns an appropriate grade for score inputted""" try: grade = float(input('Enter your score: ')) if grade < 0.6: print('Your score', grade, 'is F') elif 0.6 <= grade <= 0.7: print('Your score', grade, 'is D') elif 0.7 <= grade <= 0.8: print('Your score', grade, 'is C') elif 0.8 <= grade <= 0.9: print('Your score', grade, 'is B') elif 0.9 <= grade <= 1.0: print('Your score', grade, 'is A') elif grade > 1.0: print('Your score', grade, 'is out of range') except: print('Bad score')
4.34375
4
Cloudfn/semana_scrapper.py
orangebacked/GCP_references
0
12763397
import requests from lxml import html import pandas as pd import datetime from lxml import etree import google.cloud.storage import re from google.cloud import bigquery import html as hhhh from functools import reduce def scrapping(article): r1 = requests.get('https://www.semana.com{}'.format(article)) tree = html.fromstring(r1.content) content = tree.xpath('.//div[@id="contentItem"]') text_content = etree.tostring(content[0], pretty_print=True) text_content = hhhh.unescape(str(text_content)) text_content = re.sub(r"<.{0,200}>","",text_content) text_content = text_content.replace("\\n", "").replace("\r", "").replace("b'", "") date = tree.xpath('.//span[@class="date"]/text()')[0] date = date.replace("|", "") date = date.strip() list_date = date.split(" ") list_date[1] if list_date[2] == "PM": hour = str(int(list_date[1].split(":")[0]) + 12) + ":" + list_date[1].split(":")[1] + ":" + list_date[1].split(":")[2] else: hour = list_date[1] date = list_date[0].replace("/", "-").split("-") date = date[-1] + "-" + date[0] + "-" + date[1] tag = tree.xpath('.//a[@itemprop="articleSection"]/text()')[0] tag= hhhh.unescape(str(tag)) title = tree.xpath('.//h1[@class="tittleArticuloOpinion"]/text()')[0] title = title.strip() title = hhhh.unescape(str(title)) item_id = int(tree.xpath('.//input[@id="itemId"]/@value')[0]) timestamp = str(datetime.datetime.utcnow()) row = [str(title), str(date), str(hour), str(tag), str(text_content), item_id, timestamp] return row def loop_req(): r = requests.get('https://www.semana.com') tree = html.fromstring(r.content) list_articles = tree.xpath('.//a[contains(@class,"article-h-link")]/@href') ## in order to create the df dflist = [] for n,article in enumerate(list_articles): try: row = scrapping(article) upload_to_bq(row) row_l = [x for x in row] dflist.append(row_l) print(n) except: print(n,'fail') pass df=pd.DataFrame(dflist,columns=["title", "date", "hour", "tag", "text_content", "item_id", "timestamp"]) return df def upload_to_bq(row): # Instantiates a client bigquery_client = bigquery.Client() dataset_ref = bigquery_client.dataset('news_scrapping') table_ref = dataset_ref.table('semana') table = bigquery_client.get_table(table_ref) rows_to_insert = [row] errors = bigquery_client.insert_rows(table, rows_to_insert) print(errors) assert errors == [] def upload_bucket(csv): client = google.cloud.storage.Client() bucket = client.get_bucket('newscrapp') now = datetime.datetime.now() y = now.year m = now.month d = now.day h = now.hour blob = bucket.blob('semana/{}-{}-{}-{}.csv'.format(y, m, d, h)) blob.upload_from_string(csv) def scrapper(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`. """ request_json = request.get_json() if request.args and 'message' in request.args: return request.args.get('message') elif request_json and 'message' in request_json: return request_json['message'] else: df = loop_req() df.drop_duplicates(inplace = True) csv = df.to_csv() upload_bucket(csv) # pandas_gbq.to_gbq(df, 'news_scrapping.semana', project_id="servisentimen-servipolitics", if_exists='append') return csv
2.953125
3
app/config.py
RyanHartje/base_flask
0
12763398
# You can gen a bcrypt hash here: ## http://bcrypthashgenerator.apphb.com/ pwhash = 'bcrypt' # You can generate salts and other secrets with openssl # For example: # $ openssl rand -hex 16 # 1ca632d8567743f94352545abe2e313d salt = "<PASSWORD>" secret_key = 'fe65757e00193b8bc2e18444fa51d873' mongo_db = 'mydatabase' mongo_host = 'localhost' mongo_port = 27017 user_enable_registration = True user_enable_tracking = True user_from_email = "<EMAIL>" user_register_email_subject = "Thank you for signing up" mail_url = "mail.yoursite.com" mail_port = "25" mail_SSL = False mail_TLS = False mail_user = "username_goes_here" mail_pass = "<PASSWORD>"
1.6875
2
data/yaml2json.py
six-two/react_cv
0
12763399
<filename>data/yaml2json.py #!/usr/bin/env python3 import json import os import sys import time # external: pip3 install PyYAML import yaml SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) os.chdir(SCRIPT_DIR) def readYaml(inputPath): try: with open(inputPath, "r") as inputStream: return yaml.safe_load(inputStream) except Exception as ex: print(" Error parsing yaml file ".center(80, "=")) print(ex) sys.exit(1) def writeJson(outputPath, data): with open(outputPath, "w") as output: json.dump(data, output, indent=2, sort_keys=True) def yaml2json(inputFile, outputFile): data = readYaml(inputFile) writeJson(outputFile, data) def create_build_metadata_file(outputFile): from datetime import datetime now = datetime.now().strftime("%Y-%m-%d") writeJson(outputFile, { "build_date": now, }) print("Created {}".format(outputFile)) if __name__ == "__main__": FILE_NAMES = ["timeline", "labels", "ratings"] IN_DIR = "." OUT_DIR = "../src/app/data" # Convert the yaml files for fileName in FILE_NAMES: inputFile = os.path.join(IN_DIR, fileName + ".yaml") outputFile = os.path.join(OUT_DIR, fileName + ".json") print("{} -> {}".format(inputFile, outputFile)) yaml2json(inputFile, outputFile) # Create a file withe the last updated and similar infos path_build_json = os.path.join(OUT_DIR, "build.json") create_build_metadata_file(path_build_json)
2.96875
3
opentelemetry-api/src/opentelemetry/_metrics/instrument.py
ekmixon/opentelemetry-python
1
12763400
# Copyright The OpenTelemetry Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # pylint: disable=too-many-ancestors # type: ignore from abc import ABC, abstractmethod from collections import abc as collections_abc from logging import getLogger from typing import ( Callable, Generator, Generic, Iterable, Optional, TypeVar, Union, ) # pylint: disable=unused-import; needed for typing and sphinx from opentelemetry import _metrics as metrics from opentelemetry._metrics.measurement import Measurement _TInstrumentCallback = Callable[[], Iterable[Measurement]] _TInstrumentCallbackGenerator = Generator[Iterable[Measurement], None, None] TCallback = Union[_TInstrumentCallback, _TInstrumentCallbackGenerator] InstrumentT = TypeVar("InstrumentT", bound="Instrument") _logger = getLogger(__name__) class Instrument(ABC): @abstractmethod def __init__(self, name, unit="", description=""): pass # FIXME check that the instrument name is valid # FIXME check that the unit is 63 characters or shorter # FIXME check that the unit contains only ASCII characters class _ProxyInstrument(ABC, Generic[InstrumentT]): def __init__(self, name, unit, description) -> None: self._name = name self._unit = unit self._description = description self._real_instrument: Optional[InstrumentT] = None def on_meter_set(self, meter: "metrics.Meter") -> None: """Called when a real meter is set on the creating _ProxyMeter""" # We don't need any locking on proxy instruments because it's OK if some # measurements get dropped while a real backing instrument is being # created. self._real_instrument = self._create_real_instrument(meter) @abstractmethod def _create_real_instrument(self, meter: "metrics.Meter") -> InstrumentT: """Create an instance of the real instrument. Implement this.""" class _ProxyAsynchronousInstrument(_ProxyInstrument[InstrumentT]): def __init__(self, name, callback, unit, description) -> None: super().__init__(name, unit, description) self._callback = callback class Synchronous(Instrument): pass class Asynchronous(Instrument): @abstractmethod def __init__( self, name, callback: TCallback, *args, unit="", description="", **kwargs ): super().__init__( name, *args, unit=unit, description=description, **kwargs ) if isinstance(callback, collections_abc.Callable): self._callback = callback elif isinstance(callback, collections_abc.Generator): self._callback = self._wrap_generator_callback(callback) # FIXME check that callback is a callable or generator @staticmethod def _wrap_generator_callback( generator_callback: _TInstrumentCallbackGenerator, ) -> _TInstrumentCallback: """Wraps a generator style callback into a callable one""" has_items = True def inner() -> Iterable[Measurement]: nonlocal has_items if not has_items: return [] try: return next(generator_callback) except StopIteration: has_items = False # FIXME handle the situation where the callback generator has # run out of measurements return [] return inner # FIXME check that callbacks return an iterable of Measurements class _Adding(Instrument): pass class _Grouping(Instrument): pass class _Monotonic(_Adding): pass class _NonMonotonic(_Adding): pass class Counter(_Monotonic, Synchronous): @abstractmethod def add(self, amount, attributes=None): # FIXME check that the amount is non negative pass class DefaultCounter(Counter): def __init__(self, name, unit="", description=""): super().__init__(name, unit=unit, description=description) def add(self, amount, attributes=None): return super().add(amount, attributes=attributes) class _ProxyCounter(_ProxyInstrument[Counter], Counter): def add(self, amount, attributes=None): if self._real_instrument: self._real_instrument.add(amount, attributes) def _create_real_instrument(self, meter: "metrics.Meter") -> Counter: return meter.create_counter(self._name, self._unit, self._description) class UpDownCounter(_NonMonotonic, Synchronous): @abstractmethod def add(self, amount, attributes=None): pass class DefaultUpDownCounter(UpDownCounter): def __init__(self, name, unit="", description=""): super().__init__(name, unit=unit, description=description) def add(self, amount, attributes=None): return super().add(amount, attributes=attributes) class _ProxyUpDownCounter(_ProxyInstrument[UpDownCounter], UpDownCounter): def add(self, amount, attributes=None): if self._real_instrument: self._real_instrument.add(amount, attributes) def _create_real_instrument(self, meter: "metrics.Meter") -> UpDownCounter: return meter.create_up_down_counter( self._name, self._unit, self._description ) class ObservableCounter(_Monotonic, Asynchronous): pass class DefaultObservableCounter(ObservableCounter): def __init__(self, name, callback, unit="", description=""): super().__init__(name, callback, unit=unit, description=description) class _ProxyObservableCounter( _ProxyAsynchronousInstrument[ObservableCounter], ObservableCounter ): def _create_real_instrument( self, meter: "metrics.Meter" ) -> ObservableCounter: return meter.create_observable_counter( self._name, self._callback, self._unit, self._description ) class ObservableUpDownCounter(_NonMonotonic, Asynchronous): pass class DefaultObservableUpDownCounter(ObservableUpDownCounter): def __init__(self, name, callback, unit="", description=""): super().__init__(name, callback, unit=unit, description=description) class _ProxyObservableUpDownCounter( _ProxyAsynchronousInstrument[ObservableUpDownCounter], ObservableUpDownCounter, ): def _create_real_instrument( self, meter: "metrics.Meter" ) -> ObservableUpDownCounter: return meter.create_observable_up_down_counter( self._name, self._callback, self._unit, self._description ) class Histogram(_Grouping, Synchronous): @abstractmethod def record(self, amount, attributes=None): pass class DefaultHistogram(Histogram): def __init__(self, name, unit="", description=""): super().__init__(name, unit=unit, description=description) def record(self, amount, attributes=None): return super().record(amount, attributes=attributes) class _ProxyHistogram(_ProxyInstrument[Histogram], Histogram): def record(self, amount, attributes=None): if self._real_instrument: self._real_instrument.record(amount, attributes) def _create_real_instrument(self, meter: "metrics.Meter") -> Histogram: return meter.create_histogram( self._name, self._unit, self._description ) class ObservableGauge(_Grouping, Asynchronous): pass class DefaultObservableGauge(ObservableGauge): def __init__(self, name, callback, unit="", description=""): super().__init__(name, callback, unit=unit, description=description) class _ProxyObservableGauge( _ProxyAsynchronousInstrument[ObservableGauge], ObservableGauge, ): def _create_real_instrument( self, meter: "metrics.Meter" ) -> ObservableGauge: return meter.create_observable_gauge( self._name, self._callback, self._unit, self._description )
1.84375
2
books/dongbin-na/part3_greedy/greedy_1.py
livlikwav/Algorithms
1
12763401
<gh_stars>1-10 ''' * 오름차순이 이므로 max를 체크할 필요가 없다. ''' N = int(input()) data = list(map(int, input().split())) data.sort() # debug print(N) print(data) result = 0 max = 0 count = 0 for num in data: if max == 0: max = num elif max < num: max = num count += 1 if max == count: result += 1 max = 0 count = 0 print(result) ''' 5 2 3 1 2 2 10 1 2 3 4 3 2 1 2 5 7 20 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 5 5 5 6 ''' ''' <Answer> n = int(input()) data = list(map(int, input().split())) data.sort() result = 0 # 총 그룹의 수 count = 0 # 현재 그룹에 포함된 모험가의 수 for i in data: count += 1 # 현재 그룹에 해당 모험가를 포함시키기 if count >= i: # 현재 그룹에 포함된 모험가의 수가 현재의 공포도 이상이라면, 그룹 결성 result += 1 # 총 그룹의 수 증가시키기 count = 0 # 현재 그룹에 포함된 모험가의 수 초기화 print(result) # 총 그룹의 수 출력 '''
3.109375
3
plot_charts.py
anuprulez/similar_galaxy_tools
2
12763402
<gh_stars>1-10 import matplotlib.pyplot as plt import numpy as np from pylab import * from matplotlib_venn import venn2 import json # Font close to Times New Roman # https://mondaybynoon.com/linux-font-equivalents-to-popular-web-typefaces/ FONT_SIZE = 26 plt.rcParams["font.family"] = "FreeSerif" plt.rc('text', usetex=True) plt.rcParams[ 'text.latex.preamble' ]=[r"\usepackage{amsmath}"] plt.rcParams[ "font.size" ] = FONT_SIZE colors_dict = dict() colors_dict[ "help_text" ] = 'C2' colors_dict[ "name_desc_edam" ] = 'C1' colors_dict[ "input_output" ] = 'C0' def read_files( file_path ): with open( file_path, 'r' ) as similarity_data: return json.loads( similarity_data.read() ) def plot_doc_tokens_mat( file_path_io, file_path_nd, file_path_ht ): fig, axes = plt.subplots( nrows=1, ncols=3 ) sub_titles = [ "Input \& output (a)", "Name \& description (b)", "Help text (c)" ] io_tools_tokens = read_files( file_path_io ) nd_tools_tokens = read_files( file_path_nd ) ht_tools_tokens = read_files( file_path_ht ) NEW_FONT_SIZE = FONT_SIZE io_tokens = list() for item in io_tools_tokens: a = list() for x in item: a.append( float( x ) ) io_tokens.append( a ) nd_tokens = list() for item in nd_tools_tokens: a = list() for x1 in item: a.append( float( x1 ) ) nd_tokens.append( a ) ht_tokens = list() for item in ht_tools_tokens: a = list() for x2 in item: a.append( float( x2 ) ) ht_tokens.append( a ) for col, axis in enumerate( axes ): heatmap1 = axes[ 0 ].imshow( io_tokens, cmap=plt.cm.Reds ) heatmap2 = axes[ 1 ].imshow( nd_tokens, cmap=plt.cm.Reds ) heatmap3 = axes[ 2 ].imshow( ht_tokens, cmap=plt.cm.Reds ) axes[ 0 ].set_title( sub_titles[ 0 ], fontsize = NEW_FONT_SIZE ) axes[ 1 ].set_title( sub_titles[ 1 ], fontsize = NEW_FONT_SIZE ) axes[ 2 ].set_title( sub_titles[ 2 ], fontsize = NEW_FONT_SIZE ) for tick in axes[ 0 ].xaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axes[ 1 ].xaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axes[ 2 ].xaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axes[ 0 ].yaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axes[ 1 ].yaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axes[ 2 ].yaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) axes[ 0 ].set_xlabel( "Tokens", fontsize = NEW_FONT_SIZE ) axes[ 1 ].set_xlabel( "100-dimensions", fontsize = NEW_FONT_SIZE ) axes[ 2 ].set_xlabel( "200-dimensions", fontsize = NEW_FONT_SIZE ) axes[ 0 ].set_ylabel( "Tools (documents)", fontsize = NEW_FONT_SIZE ) axes[ 1 ].set_ylabel( "Tools (documents)", fontsize = NEW_FONT_SIZE ) axes[ 2 ].set_ylabel( "Tools (documents)", fontsize = NEW_FONT_SIZE ) plt.suptitle( "Documents-tokens multi-dimensional matrices" ) fig.subplots_adjust( right = 0.75 ) cbar_ax = fig.add_axes( [ 0.8, 0.15, 0.02, 0.7 ] ) fig.colorbar( heatmap3, cax=cbar_ax ) plt.show() def plot_lr_drop( file_path ): tools_lr = read_files( file_path ) max_len = 0 lr_drop = list() for item in tools_lr: lr_drop = tools_lr[ item ] break plt.plot( lr_drop ) plt.ylabel( 'Gradient descent learning rate' ) plt.xlabel( 'Iterations' ) plt.title( 'Learning rates computed using time-based decay' ) plt.grid( True ) plt.show() def plot_correlation( similarity_matrices, title ): # plot correlation matrix NEW_FONT_SIZE = 22 fig, axes = plt.subplots( nrows=2, ncols=2 ) sources = [ "input_output", 'name_desc_edam', 'help_text', "optimal" ] titles_fullrank = [ "Input \& output (a)", "Name \& description (b)", "Help text (c)", "Weighted average (d)" ] row_lst = [ [ 0, 1 ], [ 2, 3 ] ] for row, axis in enumerate( axes ): mat1 = similarity_matrices[ row_lst[ row ][ 0 ] ] mat2 = similarity_matrices[ row_lst[ row ][ 1 ] ] heatmap = axis[ 0 ].imshow( mat1, cmap=plt.cm.Reds ) heatmap = axis[ 1 ].imshow( mat2, cmap=plt.cm.Reds ) axis[ 0 ].set_title( titles_fullrank[ row_lst[ row ][ 0 ] ], fontsize = NEW_FONT_SIZE ) axis[ 1 ].set_title( titles_fullrank[ row_lst[ row ][ 1 ] ], fontsize = NEW_FONT_SIZE ) for tick in axis[ 0 ].xaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axis[ 1 ].xaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axis[ 0 ].yaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axis[ 1 ].yaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) if row == 1: axis[ 0 ].set_xlabel( "Tools (documents)", fontsize = NEW_FONT_SIZE ) axis[ 1 ].set_xlabel( "Tools (documents)", fontsize = NEW_FONT_SIZE ) axis[ 0 ].set_ylabel( "Tools (documents)", fontsize = NEW_FONT_SIZE ) axis[ 1 ].set_ylabel( "Tools (documents)", fontsize = NEW_FONT_SIZE ) fig.subplots_adjust( right = 0.75 ) cbar_ax = fig.add_axes( [ 0.8, 0.15, 0.02, 0.7 ] ) fig.colorbar( heatmap, cax=cbar_ax ) plt.suptitle( title ) plt.show() def extract_correlation( file_path, title ): # extract correlation matrices from multiple sources sim_data = read_files( file_path ) tools_list = read_files( "data/tools_list.json" ) mat_size = len( sim_data ) sim_score_ht = np.zeros( [ mat_size, mat_size ] ) sim_score_nd = np.zeros( [ mat_size, mat_size ] ) sim_score_io = np.zeros( [ mat_size, mat_size ] ) sim_score_op = np.zeros( [ mat_size, mat_size ] ) similarity_matrices = list() for index, tool_name in enumerate( tools_list ): sources_sim = sim_data[ tool_name ] sim_score_ht[ index ] = sources_sim[ "help_text" ] sim_score_nd[ index ] = sources_sim[ "name_desc_edam" ] sim_score_io[ index ] = sources_sim[ "input_output" ] sim_score_op[ index ] = sources_sim[ "optimal" ] similarity_matrices.append( sim_score_io ) similarity_matrices.append( sim_score_nd ) similarity_matrices.append( sim_score_ht ) similarity_matrices.append( sim_score_op ) plot_correlation( similarity_matrices, title ) def plot_weights_distribution( file_path, title ): # plot weights distribution NEW_FONT_SIZE = FONT_SIZE weights_tools = read_files( file_path ) weights_io = list() weights_nd = list() weights_ht = list() for item in weights_tools: wts = weights_tools[ item ] weights_io.append( wts[ "input_output" ] ) weights_nd.append( wts[ "name_desc_edam" ] ) weights_ht.append( wts[ "help_text" ] ) fig, axes = plt.subplots( nrows=1, ncols=3 ) sources = [ "input_output", 'name_desc_edam', 'help_text', "optimal" ] sub_titles = [ "Input \& output (a)", "Name \& description (b)", "Help text (c)", "Weighted average (d)" ] for row, axis in enumerate( axes ): axes[ 0 ].plot( weights_io, color = colors_dict[ "input_output" ] ) axes[ 1 ].plot( weights_nd, color = colors_dict[ "name_desc_edam" ] ) axes[ 2 ].plot( weights_ht, color = colors_dict[ "help_text" ] ) axes[ 0 ].set_title( sub_titles[ 0 ], fontsize = NEW_FONT_SIZE ) axes[ 1 ].set_title( sub_titles[ 1 ], fontsize = NEW_FONT_SIZE ) axes[ 2 ].set_title( sub_titles[ 2 ], fontsize = NEW_FONT_SIZE ) for tick in axes[ 0 ].xaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axes[ 1 ].xaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axes[ 2 ].xaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axes[ 0 ].yaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axes[ 1 ].yaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) for tick in axes[ 2 ].yaxis.get_major_ticks(): tick.label.set_fontsize( NEW_FONT_SIZE ) axes[ 0 ].set_xlabel( "Tools (documents)", fontsize = NEW_FONT_SIZE ) axes[ 1 ].set_xlabel( "Tools (documents)", fontsize = NEW_FONT_SIZE ) axes[ 2 ].set_xlabel( "Tools (documents)", fontsize = NEW_FONT_SIZE ) axes[ 0 ].set_ylabel( "Weights", fontsize = NEW_FONT_SIZE ) plt.suptitle( title ) plt.show() def plot_gradient_drop( actual_gd_file_path ): actual_gd = read_files( actual_gd_file_path ) tools_len = len( actual_gd ) iterations = 100 actual_io = np.zeros( [ tools_len, iterations ] ) actual_nd = np.zeros( [ tools_len, iterations ] ) actual_ht = np.zeros( [ tools_len, iterations ] ) cumulative_gradient = np.zeros( [ tools_len, iterations ] ) for index_x, item_y in enumerate( actual_gd ): for index_y, y in enumerate( actual_gd[ item_y ] ): actual_io[ index_x ][ index_y ] = y[ "input_output" ] actual_nd[ index_x ][ index_y ] = y[ "name_desc_edam" ] actual_ht[ index_x ][ index_y ] = y[ "help_text" ] for tool_idx in range( tools_len ): for iteration in range( iterations ): cumulative_gradient[ tool_idx ][ iteration ] = np.sqrt( actual_io[ tool_idx ][ iteration ] ** 2 + actual_nd[ tool_idx ][ iteration ] ** 2 + actual_ht[ tool_idx ][ iteration ] ** 2 ) mean_cumulative_gradient = np.mean( cumulative_gradient, axis = 0 ) plt.plot( mean_cumulative_gradient, color='C0' ) plt.ylabel( 'Cumulative gradient' ) plt.xlabel( 'Iterations' ) plt.title( 'Cumulative gradient over iterations for all the tools attributes' ) plt.grid( True ) plt.show() def compute_cost( similarity_data, iterations ): cost_iterations = np.zeros( [ len( similarity_data ) - 1, iterations ] ) for index, tool in enumerate( similarity_data ): if "cost_iterations" in tool: cost_iterations[ index ][ : ] = tool[ "cost_iterations" ][ :iterations ] # compute mean cost occurred for each tool across iterations return np.mean( cost_iterations, axis=0 ) def plot_average_cost(): max_iter = 100 sim_mat = read_files( "data/similarity_matrix.json" ) cost = compute_cost( sim_mat, max_iter ) plt.plot( cost ) plt.ylabel( 'Mean squared error' ) plt.xlabel( 'Iterations' ) plt.title( 'Mean squared error over iterations for paragraph vectors approach' ) plt.grid( True ) plt.show() def plot_average_optimal_scores(): similarity_data = read_files( "data/similarity_matrix.json" ) ave_scores = np.zeros( [ len( similarity_data ) - 1, len( similarity_data ) - 1 ] ) opt_scores = np.zeros( [ len( similarity_data ) - 1, len( similarity_data ) - 1 ] ) for index, tool in enumerate( similarity_data ): if "average_similar_scores" in tool: ave_scores[ index ] = tool[ "average_similar_scores" ] if "optimal_similar_scores" in tool: opt_scores[ index ] = tool[ "optimal_similar_scores" ] plt.plot( np.mean( opt_scores, axis = 0 ) ) plt.plot( np.mean( ave_scores, axis = 0 ) ) plt.ylabel( 'Weighted average similarity scores' ) plt.xlabel( 'Tools' ) plt.title( 'Weighted similarity scores using uniform and optimal weights using paragraph vectors', fontsize=26 ) plt.legend( [ "Weights learnt using optimization", "Uniform weights" ], loc=4 ) plt.grid( True ) plt.show() plot_average_cost() plot_average_optimal_scores() '''plot_average_cost() plot_gradient_drop( "data/actual_gd_tools.json" ) plot_weights_distribution( "data/optimal_weights.json", "Distribution of weights for paragraph vectors approach" ) plot_doc_tokens_mat( "data/doc_vecs_io.json", "data/doc_vecs_nd.json", "data/doc_vecs_ht.json" ) extract_correlation( "data/similarity_scores_sources_optimal.json", "Similarity matrices for paragraph vectors approach" ) plot_lr_drop( "data/learning_rates.json" )'''
2.546875
3
main/gdalwarp.py
crschmidt/labs-rectifier
6
12763403
<reponame>crschmidt/labs-rectifier<gh_stars>1-10 from ctypes import CDLL, Structure, c_char_p, c_double, c_void_p, c_int, pointer try: libgdal = CDLL("libgdal.so") except OSError: try: libgdal = CDLL("libgdal1.so") except OSError: libgdal = CDLL("libgdal1.4.0.so.1") libgdal.CPLGetLastErrorMsg.restype = c_char_p libgdal.GDALCreateGCPTransformer.restype = c_void_p libgdal.GDALCreateTPSTransformer.restype = c_void_p class GDALError (Exception): def __init__ (self): Exception.__init__(self,libgdal.CPLGetLastErrorMsg()) class GCP (Structure): _fields_ = (("id", c_char_p), ("info", c_char_p), ("pixel", c_double), ("line", c_double), ("x", c_double), ("y", c_double), ("z", c_double)) def __init__ (self, pixel, line, x, y, z = 0.0): Structure.__init__(self) self.pixel = pixel self.line = line self.x = x self.y = y self.z = 0.0 class GCPTransformer (object): """ >>> gcps = [(4088.91092814, 2763.15406687, 72.8380250931, 19.0290564917), \ (4258.82959082, 2867.87138224, 72.8398275375, 19.0279205232), \ (3950.60503992, 3041.74164172, 72.8365015984, 19.0262368413), \ (258.654269972, 10952.7078168, 72.7933502197, 18.9384386463), \ (2182.50223829, 3045.2972624, 72.815387249, 19.0257905614), \ (5544.95430777, 2932.15961155, 72.8551268578, 19.0275553888)] >>> g = GCPTransformer(gcps) >>> g.transform(((3000,3000),)) [(72.825369665662336, 19.026545872405777)] """ _create = libgdal.GDALCreateGCPTransformer _destroy = libgdal.GDALDestroyGCPTransformer _transform = libgdal.GDALGCPTransform def __init__ (self, gcps, order = 0): gs = ( GCP * len(gcps) )() for (n, gcp) in enumerate(gcps): gs[n] = GCP(*gcp) self.transformer = self._create( len(gcps), gs, order, False ) if self.transformer is None: raise GDALError() def __del__ (self): if self.transformer: self._destroy(self.transformer) def transform (self, points, destToSource = False): assert self.transformer is not None result = pointer(c_int(0)) xs = (c_double * len(points))() for i in range(len(points)): xs[i] = points[i][0] ys = (c_double * len(points))() for i in range(len(points)): ys[i] = points[i][1] zs = (c_double * len(points))() for i in range(len(points)): zs[i] = 0.0 self._transform( self.transformer, int(destToSource), len(points), xs, ys, zs, result ) if not result[0]: raise GDALError() xformed = [(xs[i], ys[i]) for i in range(len(points))] return xformed class TPSTransformer (GCPTransformer): """ >>> gcps = [(4088.91092814, 2763.15406687, 72.8380250931, 19.0290564917), \ (4258.82959082, 2867.87138224, 72.8398275375, 19.0279205232), \ (3950.60503992, 3041.74164172, 72.8365015984, 19.0262368413), \ (258.654269972, 10952.7078168, 72.7933502197, 18.9384386463), \ (2182.50223829, 3045.2972624, 72.815387249, 19.0257905614), \ (5544.95430777, 2932.15961155, 72.8551268578, 19.0275553888)] >>> t = TPSTransformer(gcps) >>> t.transform(((3000,3000),)) [(72.82530263451811, 19.02654185747901)] """ _create = libgdal.GDALCreateTPSTransformer _destroy = libgdal.GDALDestroyTPSTransformer _transform = libgdal.GDALTPSTransform def __init__ (self, gcps): gs = ( GCP * len(gcps) )() for n, gcp in enumerate(gcps): gs[n] = GCP(*gcp) self.transformer = self._create( len(gcps), gs, False ) if self.transformer is None: raise GDALError() if __name__ == '__main__': import doctest doctest.testmod()
2.203125
2
src/main/python/client/PythonClient.py
mfentler-tgm/sew5-simple-user-database-mfentler-tgm
0
12763404
#from clientController import ClientController from client.clientController import ClientController from PyQt5 import QtCore, QtGui, QtWidgets import sys def main(): try: app = QtWidgets.QApplication([]) controller = ClientController() controller.show() app.exec_() except Exception as e: print(e) if __name__ == "__main__": main()
2.328125
2
day1.py
willjrh/Advent-of-code-21
0
12763405
import numpy as np def day_1(file: str): """Read in day 1 part 1 input and count increasing values""" with open(file) as f: data_in = f.read() # convert data to float data = [float(i) for i in data_in.split()] # Part 1 print(sum(np.diff(np.array(data)) > 0)) # Part 2 convolution = [] for i in range(len(data) - 2): convolution.append(data[i] + data[i + 1] + data[i + 2]) print(sum(np.diff(convolution) > 0)) pass def main(): day_1("inputs/day_1_1.txt") if __name__ == "__main__": main()
3.578125
4
wildlifecompliance/components/artifact/models.py
mintcoding/wildlifecompliance
0
12763406
from __future__ import unicode_literals import logging from django.db import models from django.contrib.gis.db import models from django.contrib.postgres.fields.jsonb import JSONField from django.db.models import Max from django.utils.encoding import python_2_unicode_compatible from ledger.accounts.models import EmailUser, RevisionedMixin from wildlifecompliance.components.organisations.models import Organisation from wildlifecompliance.components.call_email.models import CallEmail, Location from wildlifecompliance.components.main.models import ( CommunicationsLogEntry, UserAction, Document, ) from wildlifecompliance.components.users.models import RegionDistrict, CompliancePermissionGroup from wildlifecompliance.components.offence.models import Offence, Offender from wildlifecompliance.components.legal_case.models import ( LegalCase, BriefOfEvidence, ProsecutionBrief ) from wildlifecompliance.components.artifact.email import ( send_mail) from wildlifecompliance.components.main.email import prepare_mail from django.core.exceptions import ValidationError from wildlifecompliance.components.main.utils import FakeRequest logger = logging.getLogger(__name__) class Artifact(RevisionedMixin): STATUS_ACTIVE = 'active' STATUS_WAITING_FOR_DISPOSAL = 'waiting_for_disposal' STATUS_CLOSED = 'closed' STATUS_CHOICES = ( (STATUS_ACTIVE, 'Active'), (STATUS_WAITING_FOR_DISPOSAL, 'Waiting For Disposal'), (STATUS_CLOSED, 'Closed'), ) identifier = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, null=False, blank=False) artifact_date = models.DateField(null=True) artifact_time = models.TimeField(blank=True, null=True) number = models.CharField(max_length=50, blank=True, null=True) status = models.CharField( max_length=100, choices=STATUS_CHOICES, default='active' ) class Meta: app_label = 'wildlifecompliance' verbose_name = 'CM_Artifact' verbose_name_plural = 'CM_Artifacts' # Prefix "OB" char to DocumentArtifact number. def save(self, *args, **kwargs): super(Artifact, self).save(*args,**kwargs) if self.number is None: new_number_id = 'OB{0:06d}'.format(self.pk) self.number = new_number_id self.save() @property def object_type(self): object_type = None pa = PhysicalArtifact.objects.filter(artifact_ptr_id=self.id) da = DocumentArtifact.objects.filter(artifact_ptr_id=self.id) if pa: object_type = 'document_artifact' elif da: object_type = 'physical_artifact' return object_type @property def artifact_type(self): pa = PhysicalArtifact.objects.filter(artifact_ptr_id=self.id) if pa and pa.first().physical_artifact_type and pa.first().physical_artifact_type.artifact_type: return pa.first().physical_artifact_type.artifact_type da = DocumentArtifact.objects.filter(artifact_ptr_id=self.id) if da and da.first().document_type: document_type = da.first().document_type display_name = '' for choice in DocumentArtifact.DOCUMENT_TYPE_CHOICES: if document_type == choice[0]: display_name = choice[1] return display_name return '---' @property def get_related_items_identifier(self): return self.number @property def get_related_items_descriptor(self): return self.identifier def log_user_action(self, action, request=None): user_name = None if not request: return ArtifactUserAction.log_action(self, action) else: return ArtifactUserAction.log_action(self, action, request.user) # TODO - no longer required class DocumentArtifactType(models.Model): artifact_type = models.CharField(max_length=50) #schema = JSONField(null=True) version = models.SmallIntegerField(default=1, blank=False, null=False) description = models.CharField(max_length=255, blank=True, null=True) replaced_by = models.ForeignKey( 'self', on_delete=models.PROTECT, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) class Meta: app_label = 'wildlifecompliance' verbose_name = 'CM_DocumentArtifactType' verbose_name_plural = 'CM_DocumentArtifactTypes' unique_together = ('artifact_type', 'version') def __str__(self): return self.artifact_type class PhysicalArtifactType(models.Model): FOUND_OBJECT = 'found_object' SEIZED_OBJECT = 'seized_object' SURRENDERED_OBJECT = 'surrendered_object' TYPE_CHOICES = ( (FOUND_OBJECT, 'Found Object'), (SEIZED_OBJECT, 'Seized Object'), (SURRENDERED_OBJECT, 'Surrendered Object'), ) artifact_type = models.CharField(max_length=50, choices=TYPE_CHOICES, blank=False, null=False, unique=True) details_schema = JSONField(default=[{}]) storage_schema = JSONField(default=[{}]) version = models.SmallIntegerField(default=1, blank=False, null=False) description = models.CharField(max_length=255, blank=True, null=True) replaced_by = models.ForeignKey( 'self', on_delete=models.PROTECT, blank=True, null=True ) date_created = models.DateTimeField(auto_now_add=True, null=True) class Meta: app_label = 'wildlifecompliance' verbose_name = 'CM_PhysicalArtifactType' verbose_name_plural = 'CM_PhysicalArtifactTypes' unique_together = ('artifact_type', 'version') def __str__(self): display_name = '' for choice in PhysicalArtifactType.TYPE_CHOICES: if self.artifact_type == choice[0]: display_name = choice[1] return display_name class PhysicalArtifactDisposalMethod(models.Model): disposal_method = models.CharField(max_length=50) description = models.CharField(max_length=255, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) class Meta: app_label = 'wildlifecompliance' verbose_name = 'CM_PhysicalArtifactDisposalMethod' verbose_name_plural = 'CM_PhysicalArtifactDisposalMethods' #unique_together = ('artifact_type', 'version') def __str__(self): return '{}, {}'.format(self.disposal_method, self.description) class DocumentArtifact(Artifact): WITNESS_STATEMENT = 'witness_statement' RECORD_OF_INTERVIEW = 'record_of_interview' OFFICER_STATEMENT = 'officer_statement' EXPERT_STATEMENT = 'expert_statement' PHOTOGRAPH = 'photograph' VIDEO = 'video' SOUND = 'sound' OTHER = 'other' DOCUMENT_TYPE_CHOICES = ( (WITNESS_STATEMENT, 'Witness Statement'), (RECORD_OF_INTERVIEW, 'Record of Interview'), (OFFICER_STATEMENT, 'Officer Statement'), (EXPERT_STATEMENT, 'Expert Statement'), (PHOTOGRAPH, 'Photograph'), (VIDEO, 'Video'), (SOUND, 'Sound'), (OTHER, 'Other') ) document_type = models.CharField( max_length=30, choices=DOCUMENT_TYPE_CHOICES, ) legal_cases = models.ManyToManyField( LegalCase, through='DocumentArtifactLegalCases', through_fields=('document_artifact', 'legal_case'), related_name='legal_case_document_artifacts', ) statement = models.ForeignKey( 'self', related_name='document_artifact_statement', on_delete=models.PROTECT, blank=True, null=True ) person_providing_statement = models.ForeignKey( EmailUser, related_name='document_artifact_person_providing_statement', null=True, ) officer_interviewer = models.ForeignKey( EmailUser, related_name='document_artifact_officer_interviewer', null=True, ) people_attending = models.ManyToManyField( EmailUser, related_name='document_artifact_people_attending', ) offence = models.ForeignKey( Offence, related_name='document_artifact_offence', null=True, ) offender = models.ForeignKey( Offender, related_name='document_artifact_offender', null=True, ) class Meta: app_label = 'wildlifecompliance' verbose_name = 'CM_DocumentArtifact' verbose_name_plural = 'CM_DocumentArtifacts' @property def primary_legal_case(self): primary_case = None for legal_case in self.documentartifactlegalcases_set.all(): if legal_case.primary: primary_case = legal_case return primary_case @property def primary_legal_case_id(self): primary_case = None for legal_case in self.documentartifactlegalcases_set.all(): if legal_case.primary: primary_case = legal_case if primary_case: return primary_case.legal_case_id else: return None def close(self, request=None): # NOTE: close_record logic moved to can_close_legal_case self.status = self.STATUS_CLOSED self.log_user_action( ArtifactUserAction.ACTION_CLOSE.format(self.number), request) self.save() class DocumentArtifactLegalCasesManager(models.Manager): def create_with_primary(self, legal_case_id, document_artifact_id): qs = DocumentArtifactLegalCases.objects.filter(document_artifact_id=document_artifact_id) set_primary = True for doc in qs: if doc.primary: set_primary = False link = self.create(legal_case_id=legal_case_id, document_artifact_id=document_artifact_id, primary=set_primary) return link class DocumentArtifactLegalCases(models.Model): document_artifact = models.ForeignKey( DocumentArtifact, null=False) legal_case = models.ForeignKey( LegalCase, null=False) primary = models.BooleanField(default=False) objects = DocumentArtifactLegalCasesManager() class Meta: app_label = 'wildlifecompliance' verbose_name = 'CM_DocumentArtifactLegalCases' unique_together = ('document_artifact', 'legal_case') class BriefOfEvidenceDocumentArtifacts(models.Model): legal_case = models.ForeignKey( LegalCase, ) document_artifact = models.ForeignKey( DocumentArtifact, ) ticked = models.BooleanField(default=False) class Meta: app_label = 'wildlifecompliance' unique_together = ('document_artifact', 'legal_case') @property def label(self): return self.__str__() def __str__(self): label_text = '' if self.document_artifact.identifier: label_text = self.document_artifact.identifier else: label_text = self.document_artifact.number return label_text @property def hyperlink(self): hyperlink = '/internal/object/' + str(self.document_artifact.id) return hyperlink class ProsecutionBriefDocumentArtifacts(models.Model): legal_case = models.ForeignKey( LegalCase, ) document_artifact = models.ForeignKey( DocumentArtifact, ) ticked = models.BooleanField(default=False) class Meta: app_label = 'wildlifecompliance' unique_together = ('document_artifact', 'legal_case') @property def label(self): return self.__str__() def __str__(self): label_text = '' if self.document_artifact.identifier: label_text = self.document_artifact.identifier else: label_text = self.document_artifact.number return label_text @property def hyperlink(self): hyperlink = '/internal/object/' + str(self.document_artifact.id) return hyperlink class PhysicalArtifact(Artifact): physical_artifact_type = models.ForeignKey( PhysicalArtifactType, null=True ) legal_cases = models.ManyToManyField( LegalCase, through='PhysicalArtifactLegalCases', through_fields=('physical_artifact', 'legal_case'), related_name='legal_case_physical_artifacts', ) officer = models.ForeignKey( EmailUser, related_name='physical_artifact_officer', null=True, ) statement = models.ForeignKey( DocumentArtifact, related_name='physical_artifact_statement', on_delete=models.PROTECT, blank=True, null=True ) custodian = models.ForeignKey( EmailUser, related_name='physical_artifact_custodian', null=True, ) disposal_date = models.DateField(null=True) disposal_details = models.TextField(blank=True, null=True) disposal_method = models.ForeignKey( PhysicalArtifactDisposalMethod, null=True ) class Meta: app_label = 'wildlifecompliance' verbose_name = 'CM_PhysicalArtifact' verbose_name_plural = 'CM_PhysicalArtifacts' def add_legal_case(self, legal_case_id): try: legal_case_id_int = int(legal_case_id) except Exception as e: raise e legal_case = LegalCase.objects.get(id=legal_case_id_int) if legal_case: if not self.legal_case: self.legal_case = legal_case self.save() elif self.legal_case != legal_case: self.associated_legal_cases.add(legal_case) def dispose(self, request=None): print("dispose") disposal_date = request.data.get('disposal_date') disposal_method_id = request.data.get('disposal_method_id') disposal_details = request.data.get('disposal_details') self.disposal_date = disposal_date self.disposal_method_id = disposal_method_id self.disposal_details = disposal_details self.close(request) def close(self, request): # TODO: add logic to check for disposal date # NOTE: close_record logic moved to can_close_legal_case if not self.disposal_date: self.status = self.STATUS_WAITING_FOR_DISPOSAL email_data = prepare_mail(request=request, instance=self, workflow_entry=None, send_mail=send_mail, recipient_address=self.custodian_email) #prepare_mail(request=request, instance=self, workflow_entry=None, send_mail=send_mail) # write comms log based on email_data print("email_data") print(email_data) to = email_data.get('to', '') fromm = email_data.get('fromm', '') cc = email_data.get('cc', '') log_type = 'email' reference = email_data.get('reference', '') subject = email_data.get('subject', '') text = email_data.get('text', '') ArtifactCommsLogEntry.objects.create( artifact=self, to=to, fromm=fromm, cc=cc, log_type=log_type, reference=reference, subject=subject, text=text ) # action log self.log_user_action( ArtifactUserAction.ACTION_WAITING_FOR_DISPOSAL.format(self.number), request) else: self.status = self.STATUS_CLOSED # attempt to close parent ## self.log_user_action( ArtifactUserAction.ACTION_CLOSE.format(self.number), request) self.save() @property def data(self): """ returns a queryset of form data records attached to PhysicalArtifact (shortcut to PhysicalArtifactFormDataRecord related_name). """ return self.form_data_records.all() @property def details_schema(self): if self.physical_artifact_type: return self.physical_artifact_type.details_schema @property def storage_schema(self): if self.physical_artifact_type: return self.physical_artifact_type.storage_schema class PhysicalArtifactLegalCasesManager(models.Manager): def create_with_primary(self, legal_case_id, physical_artifact_id): qs = PhysicalArtifactLegalCases.objects.filter(physical_artifact_id=physical_artifact_id) set_primary = True for doc in qs: if doc.primary: set_primary = False link = self.create(legal_case_id=legal_case_id, physical_artifact_id=physical_artifact_id, primary=set_primary) return link class PhysicalArtifactLegalCases(models.Model): physical_artifact = models.ForeignKey( PhysicalArtifact, null=False) legal_case = models.ForeignKey( LegalCase, null=False) primary = models.BooleanField(default=False) used_within_case = models.BooleanField(default=False) sensitive_non_disclosable = models.BooleanField(default=False) objects = PhysicalArtifactLegalCasesManager() class Meta: app_label = 'wildlifecompliance' verbose_name = 'CM_PhysicalArtifactLegalCases' unique_together = ('physical_artifact', 'legal_case') class BriefOfEvidencePhysicalArtifacts(models.Model): legal_case = models.ForeignKey( LegalCase, ) physical_artifact = models.ForeignKey( PhysicalArtifact, ) ticked = models.BooleanField(default=False) reason_sensitive_non_disclosable = models.TextField(blank=True, null=True) class Meta: app_label = 'wildlifecompliance' unique_together = ('physical_artifact', 'legal_case') @property def label(self): return self.__str__() def __str__(self): label_text = '' if self.physical_artifact.identifier: label_text = self.physical_artifact.identifier else: label_text = self.physical_artifact.number return label_text @property def hyperlink(self): hyperlink = '/internal/object/' + str(self.physical_artifact.id) return hyperlink class ProsecutionBriefPhysicalArtifacts(models.Model): legal_case = models.ForeignKey( LegalCase, ) physical_artifact = models.ForeignKey( PhysicalArtifact, ) ticked = models.BooleanField(default=False) reason_sensitive_non_disclosable = models.TextField(blank=True, null=True) class Meta: app_label = 'wildlifecompliance' unique_together = ('physical_artifact', 'legal_case') @property def label(self): return self.__str__() def __str__(self): label_text = '' if self.physical_artifact.identifier: label_text = self.physical_artifact.identifier else: label_text = self.physical_artifact.number return label_text @property def hyperlink(self): hyperlink = '/internal/object/' + str(self.physical_artifact.id) return hyperlink @python_2_unicode_compatible class PhysicalArtifactFormDataRecord(models.Model): INSTANCE_ID_SEPARATOR = "__instance-" ACTION_TYPE_ASSIGN_VALUE = 'value' ACTION_TYPE_ASSIGN_COMMENT = 'comment' COMPONENT_TYPE_TEXT = 'text' COMPONENT_TYPE_TAB = 'tab' COMPONENT_TYPE_SECTION = 'section' COMPONENT_TYPE_GROUP = 'group' COMPONENT_TYPE_NUMBER = 'number' COMPONENT_TYPE_EMAIL = 'email' COMPONENT_TYPE_SELECT = 'select' COMPONENT_TYPE_MULTI_SELECT = 'multi-select' COMPONENT_TYPE_TEXT_AREA = 'text_area' COMPONENT_TYPE_TABLE = 'table' COMPONENT_TYPE_EXPANDER_TABLE = 'expander_table' COMPONENT_TYPE_LABEL = 'label' COMPONENT_TYPE_RADIO = 'radiobuttons' COMPONENT_TYPE_CHECKBOX = 'checkbox' COMPONENT_TYPE_DECLARATION = 'declaration' COMPONENT_TYPE_FILE = 'file' COMPONENT_TYPE_DATE = 'date' COMPONENT_TYPE_CHOICES = ( (COMPONENT_TYPE_TEXT, 'Text'), (COMPONENT_TYPE_TAB, 'Tab'), (COMPONENT_TYPE_SECTION, 'Section'), (COMPONENT_TYPE_GROUP, 'Group'), (COMPONENT_TYPE_NUMBER, 'Number'), (COMPONENT_TYPE_EMAIL, 'Email'), (COMPONENT_TYPE_SELECT, 'Select'), (COMPONENT_TYPE_MULTI_SELECT, 'Multi-Select'), (COMPONENT_TYPE_TEXT_AREA, 'Text Area'), (COMPONENT_TYPE_TABLE, 'Table'), (COMPONENT_TYPE_EXPANDER_TABLE, 'Expander Table'), (COMPONENT_TYPE_LABEL, 'Label'), (COMPONENT_TYPE_RADIO, 'Radio'), (COMPONENT_TYPE_CHECKBOX, 'Checkbox'), (COMPONENT_TYPE_DECLARATION, 'Declaration'), (COMPONENT_TYPE_FILE, 'File'), (COMPONENT_TYPE_DATE, 'Date'), ) physical_artifact = models.ForeignKey(PhysicalArtifact, related_name='form_data_records') field_name = models.CharField(max_length=512, blank=True, null=True) schema_name = models.CharField(max_length=256, blank=True, null=True) instance_name = models.CharField(max_length=256, blank=True, null=True) component_type = models.CharField( max_length=64, choices=COMPONENT_TYPE_CHOICES, default=COMPONENT_TYPE_TEXT) value = JSONField(blank=True, null=True) comment = models.TextField(blank=True, null=True) deficiency = models.TextField(blank=True, null=True) def __str__(self): return "Physical Artifact {id} record {field}: {value}".format( id=self.physical_artifact_id, field=self.field_name, value=self.value[:8] ) class Meta: app_label = 'wildlifecompliance' unique_together = ('physical_artifact', 'field_name',) @staticmethod def process_form(PhysicalArtifact, form_data, action=ACTION_TYPE_ASSIGN_VALUE): if action == PhysicalArtifactFormDataRecord.ACTION_TYPE_ASSIGN_COMMENT and\ not can_edit_comments and not can_edit_deficiencies: raise Exception( 'You are not authorised to perform this action!') for field_name, field_data in form_data.items(): schema_name = field_data.get('schema_name', '') component_type = field_data.get('component_type', '') value = field_data.get('value', '') comment = field_data.get('comment_value', '') deficiency = field_data.get('deficiency_value', '') instance_name = '' if PhysicalArtifactFormDataRecord.INSTANCE_ID_SEPARATOR in field_name: [parsed_schema_name, instance_name] = field_name.split( PhysicalArtifactFormDataRecord.INSTANCE_ID_SEPARATOR ) schema_name = schema_name if schema_name else parsed_schema_name form_data_record, created = PhysicalArtifactFormDataRecord.objects.get_or_create( physical_artifact_id=PhysicalArtifact.id, field_name=field_name ) if created: form_data_record.schema_name = schema_name form_data_record.instance_name = instance_name form_data_record.component_type = component_type if action == PhysicalArtifactFormDataRecord.ACTION_TYPE_ASSIGN_VALUE: form_data_record.value = value elif action == PhysicalArtifactFormDataRecord.ACTION_TYPE_ASSIGN_COMMENT: if can_edit_comments: form_data_record.comment = comment if can_edit_deficiencies: form_data_record.deficiency = deficiency form_data_record.save() class ArtifactCommsLogEntry(CommunicationsLogEntry): artifact = models.ForeignKey(Artifact, related_name='comms_logs') class Meta: app_label = 'wildlifecompliance' class ArtifactCommsLogDocument(Document): log_entry = models.ForeignKey( ArtifactCommsLogEntry, related_name='documents') _file = models.FileField(max_length=255) class Meta: app_label = 'wildlifecompliance' class ArtifactUserAction(models.Model): ACTION_CREATE_ARTIFACT = "Create object {}" ACTION_SAVE_ARTIFACT = "Save object {}" ACTION_CLOSE = "Close object {}" ACTION_WAITING_FOR_DISPOSAL = "Mark object {} as waiting for disposal" ACTION_ADD_WEAK_LINK = "Create manual link between {}: {} and {}: {}" ACTION_REMOVE_WEAK_LINK = "Remove manual link between {}: {} and {}: {}" who = models.ForeignKey(EmailUser, null=True, blank=True) when = models.DateTimeField(null=False, blank=False, auto_now_add=True) what = models.TextField(blank=False) artifact = models.ForeignKey(Artifact, related_name='action_logs') class Meta: app_label = 'wildlifecompliance' ordering = ('-when',) @classmethod def log_action(cls, artifact, action, user=None): return cls.objects.create( artifact=artifact, who=user, what=str(action) ) def __str__(self): return "{what} ({who} at {when})".format( what=self.what, who=self.who, when=self.when ) class ArtifactDocument(Document): artifact = models.ForeignKey( Artifact, related_name='documents') _file = models.FileField(max_length=255) input_name = models.CharField(max_length=255, blank=True, null=True) # after initial submit prevent document from being deleted can_delete = models.BooleanField(default=True) version_comment = models.CharField(max_length=255, blank=True, null=True) def delete(self): if self.can_delete: return super(ArtifactDocument, self).delete() class Meta: app_label = 'wildlifecompliance' class RendererDocument(Document): physical_artifact = models.ForeignKey( PhysicalArtifact, related_name='renderer_documents') _file = models.FileField(max_length=255) input_name = models.CharField(max_length=255, null=True, blank=True) class Meta: app_label = 'wildlifecompliance' class BriefOfEvidenceOtherStatements(models.Model): legal_case = models.ForeignKey( LegalCase, related_name='legal_case_boe_other_statements') person = models.ForeignKey( EmailUser, related_name='email_user_boe_other_statements', ) statement = models.ForeignKey( DocumentArtifact, related_name='statement_boe_other_statements', blank=True, null=True ) associated_doc_artifact = models.ForeignKey( DocumentArtifact, related_name='document_artifact_boe_other_statements', blank=True, null=True) ticked = models.BooleanField(default=False) children = models.ManyToManyField( 'self', related_name='parents', symmetrical=False) class Meta: app_label = 'wildlifecompliance' @property def label(self): return self.__str__() @property def hyperlink(self): if self.associated_doc_artifact: hyperlink = '/internal/object/' + str(self.associated_doc_artifact.id) elif self.statement: hyperlink = '/internal/object/' + str(self.statement.id) else: hyperlink = '/internal/users/' + str(self.person.id) return hyperlink @property def show(self): show = False # person if self.children.count(): # statement for child in self.children.all(): if child.children.count(): # associated_doc_artifact for grandchild in child.children.all(): if grandchild.ticked: show = True else: if child.ticked: show = True else: show = self.ticked return show def __str__(self): label_text = '' if not self.statement and not self.associated_doc_artifact: full_name = self.person.get_full_name() label_text = 'Person: ' + full_name elif not self.associated_doc_artifact: if self.statement.identifier: label_text = self.statement.artifact_type + ': ' + self.statement.identifier else: label_text = self.statement.artifact_type + ': ' + self.statement.number else: if self.associated_doc_artifact.identifier: label_text = 'Associated Document Object: ' + self.associated_doc_artifact.identifier else: label_text = 'Associated Document Object: ' + self.associated_doc_artifact.number return label_text class BriefOfEvidenceRecordOfInterview(models.Model): legal_case = models.ForeignKey( LegalCase, related_name='legal_case_boe_roi') offence = models.ForeignKey( Offence, related_name='offence_boe_roi') offender = models.ForeignKey( Offender, related_name='offender_boe_roi', blank=True, null=True) record_of_interview = models.ForeignKey( DocumentArtifact, related_name='record_of_interview_boe_roi', blank=True, null=True) associated_doc_artifact = models.ForeignKey( DocumentArtifact, related_name='document_artifact_boe_roi', blank=True, null=True) ticked = models.BooleanField(default=False) children = models.ManyToManyField( 'self', related_name='parents', symmetrical=False) class Meta: app_label = 'wildlifecompliance' @property def show(self): show = False # offence if self.children.count(): # offender for child in self.children.all(): if child.children.count(): # record_of_interview for grandchild in child.children.all(): if grandchild.children.count(): # associated_doc_artifact for greatgrandchild in grandchild.children.all(): if greatgrandchild.ticked: show = True else: if grandchild.ticked: show = True else: if child.ticked: show = True else: show = self.ticked return show @property def hyperlink(self): hyperlink = '' if not self.offender and not self.record_of_interview and not self.associated_doc_artifact: hyperlink = '/internal/offence/' + str(self.offence.id) elif not self.record_of_interview and not self.associated_doc_artifact: if self.offender.person: hyperlink = '/internal/users/' + str(self.offender.person.id) elif not self.associated_doc_artifact: hyperlink = '/internal/object/' + str(self.record_of_interview.id) else: hyperlink = '/internal/object/' + str(self.associated_doc_artifact.id) return hyperlink @property def label(self): return self.__str__() def __str__(self): label_text = '' if not self.offender and not self.record_of_interview and not self.associated_doc_artifact: if self.offence.identifier: label_text = 'Offence: ' + self.offence.identifier else: label_text = 'Offence: ' + self.offence.lodgement_number elif not self.record_of_interview and not self.associated_doc_artifact: label_text = 'Offender: ' + str(self.offender) elif not self.associated_doc_artifact: if self.record_of_interview.identifier: label_text = 'Record of Interview: ' + self.record_of_interview.identifier else: label_text = 'Record of Interview: ' + self.record_of_interview.number else: if self.associated_doc_artifact.identifier: label_text = 'Associated Document Object: ' + self.associated_doc_artifact.identifier else: label_text = 'Associated Document Object: ' + self.associated_doc_artifact.number return label_text class ProsecutionBriefOtherStatements(models.Model): legal_case = models.ForeignKey( LegalCase, related_name='legal_case_pb_other_statements') person = models.ForeignKey( EmailUser, related_name='email_user_pb_other_statements', ) statement = models.ForeignKey( DocumentArtifact, related_name='statement_pb_other_statements', blank=True, null=True ) associated_doc_artifact = models.ForeignKey( DocumentArtifact, related_name='document_artifact_pb_other_statements', blank=True, null=True) ticked = models.BooleanField(default=False) children = models.ManyToManyField( 'self', related_name='parents', symmetrical=False) class Meta: app_label = 'wildlifecompliance' @property def show(self): show = False # person if self.children.count(): # statement for child in self.children.all(): if child.children.count(): # associated_doc_artifact for grandchild in child.children.all(): if grandchild.ticked: show = True else: if child.ticked: show = True else: show = self.ticked return show @property def hyperlink(self): if self.associated_doc_artifact: hyperlink = '/internal/object/' + str(self.associated_doc_artifact.id) elif self.statement: hyperlink = '/internal/object/' + str(self.statement.id) else: hyperlink = '/internal/users/' + str(self.person.id) return hyperlink @property def label(self): return self.__str__() def __str__(self): label_text = '' if not self.statement and not self.associated_doc_artifact: full_name = self.person.get_full_name() label_text = 'Person: ' + full_name elif not self.associated_doc_artifact: if self.statement.identifier: label_text = self.statement.artifact_type + ': ' + self.statement.identifier else: label_text = self.statement.artifact_type + ': ' + self.statement.number else: if self.associated_doc_artifact.identifier: label_text = 'Associated Document Object: ' + self.associated_doc_artifact.identifier else: label_text = 'Associated Document Object: ' + self.associated_doc_artifact.number return label_text class ProsecutionBriefRecordOfInterview(models.Model): legal_case = models.ForeignKey( LegalCase, related_name='legal_case_pb_roi') offence = models.ForeignKey( Offence, related_name='offence_pb_roi') offender = models.ForeignKey( Offender, related_name='offender_pb_roi', blank=True, null=True) record_of_interview = models.ForeignKey( DocumentArtifact, related_name='record_of_interview_pb_roi', blank=True, null=True) associated_doc_artifact = models.ForeignKey( DocumentArtifact, related_name='document_artifact_pb_roi', blank=True, null=True) ticked = models.BooleanField(default=False) children = models.ManyToManyField( 'self', related_name='parents', symmetrical=False) class Meta: app_label = 'wildlifecompliance' @property def label(self): return self.__str__() @property def show(self): show = False # offence if self.children.count(): # offender for child in self.children.all(): if child.children.count(): # record_of_interview for grandchild in child.children.all(): if grandchild.children.count(): # associated_doc_artifact for greatgrandchild in grandchild.children.all(): if greatgrandchild.ticked: show = True else: if grandchild.ticked: show = True else: if child.ticked: show = True else: show = self.ticked return show @property def hyperlink(self): hyperlink = '' if not self.offender and not self.record_of_interview and not self.associated_doc_artifact: hyperlink = '/internal/offence/' + str(self.offence.id) elif not self.record_of_interview and not self.associated_doc_artifact: if self.offender.person: hyperlink = '/internal/users/' + str(self.offender.person.id) elif not self.associated_doc_artifact: hyperlink = '/internal/object/' + str(self.record_of_interview.id) else: hyperlink = '/internal/object/' + str(self.associated_doc_artifact.id) return hyperlink def __str__(self): label_text = '' if not self.offender and not self.record_of_interview and not self.associated_doc_artifact: if self.offence.identifier: label_text = 'Offence: ' + self.offence.identifier else: label_text = 'Offence: ' + self.offence.lodgement_number elif not self.record_of_interview and not self.associated_doc_artifact: label_text = 'Offender: ' + str(self.offender) elif not self.associated_doc_artifact: if self.record_of_interview.identifier: label_text = 'Record of Interview: ' + self.record_of_interview.identifier else: label_text = 'Record of Interview: ' + self.record_of_interview.number else: if self.associated_doc_artifact.identifier: label_text = 'Associated Document Object: ' + self.associated_doc_artifact.identifier else: label_text = 'Associated Document Object: ' + self.associated_doc_artifact.number return label_text import reversion reversion.register(Artifact, follow=['comms_logs', 'action_logs', 'documents']) reversion.register(DocumentArtifactType, follow=['documentartifacttype_set']) reversion.register(PhysicalArtifactType, follow=['physicalartifacttype_set', 'physicalartifact_set']) reversion.register(PhysicalArtifactDisposalMethod, follow=['physicalartifact_set']) #reversion.register(DocumentArtifact_people_attending, follow=[]) reversion.register(DocumentArtifact, follow=['comms_logs', 'action_logs', 'documents', 'document_artifact_statement', 'documentartifactlegalcases_set', 'briefofevidencedocumentartifacts_set', 'prosecutionbriefdocumentartifacts_set', 'physical_artifact_statement', 'statement_boe_other_statements', 'document_artifact_boe_other_statements', 'record_of_interview_boe_roi', 'document_artifact_boe_roi', 'statement_pb_other_statements', 'document_artifact_pb_other_statements', 'record_of_interview_pb_roi', 'document_artifact_pb_roi']) reversion.register(DocumentArtifactLegalCases, follow=[]) reversion.register(BriefOfEvidenceDocumentArtifacts, follow=[]) reversion.register(ProsecutionBriefDocumentArtifacts, follow=[]) reversion.register(PhysicalArtifact, follow=['comms_logs', 'action_logs', 'documents', 'physicalartifactlegalcases_set', 'briefofevidencephysicalartifacts_set', 'prosecutionbriefphysicalartifacts_set', 'form_data_records', 'renderer_documents']) reversion.register(PhysicalArtifactLegalCases, follow=['physical_artifact', 'legal_case']) reversion.register(BriefOfEvidencePhysicalArtifacts, follow=[]) reversion.register(ProsecutionBriefPhysicalArtifacts, follow=[]) reversion.register(PhysicalArtifactFormDataRecord, follow=[]) reversion.register(ArtifactCommsLogEntry, follow=['documents']) reversion.register(ArtifactCommsLogDocument, follow=[]) reversion.register(ArtifactUserAction, follow=[]) reversion.register(ArtifactDocument, follow=[]) reversion.register(RendererDocument, follow=[]) #reversion.register(BriefOfEvidenceOtherStatements_children, follow=[]) reversion.register(BriefOfEvidenceOtherStatements, follow=['parents']) #reversion.register(BriefOfEvidenceRecordOfInterview_children, follow=[]) reversion.register(BriefOfEvidenceRecordOfInterview, follow=['parents']) #reversion.register(ProsecutionBriefOtherStatements_children, follow=[]) reversion.register(ProsecutionBriefOtherStatements, follow=['parents']) #reversion.register(ProsecutionBriefRecordOfInterview_children, follow=[]) reversion.register(ProsecutionBriefRecordOfInterview, follow=['parents'])
1.671875
2
examples/python/corepy/typecheck.py
airgiser/ucb
1
12763407
<gh_stars>1-10 #!/usr/bin/python def displayNumType(val): print val, 'is', if isinstance(val, (int, long, float, complex)): print 'a number of type:', type(val).__name__ else: print 'not a number at all!' displayNumType(23) displayNumType(999999999999999999999L) displayNumType(23.3) displayNumType(-2+3.2j) displayNumType('string')
3.21875
3
examples/plotting/file/hover_glyph.py
g-parki/bokeh
15,193
12763408
from bokeh.models import HoverTool from bokeh.plotting import figure, output_file, show from bokeh.sampledata.glucose import data x = data.loc['2010-10-06'].index.to_series() y = data.loc['2010-10-06']['glucose'] # Basic plot setup p = figure(width=800, height=400, x_axis_type="datetime", tools="", toolbar_location=None, title='Hover over points') p.ygrid.grid_line_color = None p.background_fill_color = "#fafafa" p.line(x, y, line_dash="4 4", line_width=1, color='gray') cr = p.circle(x, y, size=20, fill_color="steelblue", alpha=0.1, line_color=None, hover_fill_color="midnightblue", hover_alpha=0.5, hover_line_color="white") p.add_tools(HoverTool(tooltips=None, renderers=[cr], mode='hline')) output_file("hover_glyph.html", title="hover_glyph.py example") show(p)
2.859375
3
shell-sort/python/main.py
NikitaKolotushkin/Basics-Algorithms
0
12763409
<filename>shell-sort/python/main.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- def shell_sort(list_: list) -> list: """Returns a sorted list, by shell sort method :param list_: The list to be sorted :type list_: list :rtype: list :return: Sorted list, by shell sort method """ half = len(list_) // 2 while half > 0: for i in range(half, len(list_)): tmp = list_[i] j = i while j >= half and list_[j - half] > tmp: list_[j] = list_[j - half] j -= half list_[j] = tmp half //= 2 return list_
4.21875
4
core/src/zeit/wochenmarkt/sources.py
rickdg/vivi
5
12763410
import zc.sourcefactory.contextual import zc.sourcefactory.source import zeit.cms.content.contentsource import zeit.cms.content.sources import zeit.wochenmarkt.interfaces import zope.interface import zope.schema.interfaces class RecipeCategoriesSource( zc.sourcefactory.contextual.BasicContextualSourceFactory): check_interfaces = zeit.wochenmarkt.interfaces.IRecipeCategoriesWhitelist name = 'categories' addform = 'zeit.wochenmarkt.add_contextfree' @zope.interface.implementer( zeit.wochenmarkt.interfaces.IRecipeCategoriesSource, zeit.cms.content.contentsource.IAutocompleteSource) class source_class(zc.sourcefactory.source.FactoredContextualSource): def get_check_types(self): """IAutocompleteSource, but not applicable for us""" return [] def __contains__(self, value): # We do not want to ask the whitelist again. return True def search(self, term): from zeit.wochenmarkt.interfaces import IRecipeCategoriesWhitelist categories = zope.component.getUtility(IRecipeCategoriesWhitelist) return categories.search(term) def getTitle(self, context, value): return value.name def getToken(self, context, value): return value.code recipeCategoriesSource = RecipeCategoriesSource() class IngredientsSource( zc.sourcefactory.contextual.BasicContextualSourceFactory): check_interfaces = zeit.wochenmarkt.interfaces.IIngredientsWhitelist name = 'ingredients' addform = 'zeit.wochenmarkt.add_contextfree' @zope.interface.implementer( zeit.wochenmarkt.interfaces.IIngredientsSource, zeit.cms.content.contentsource.IAutocompleteSource) class source_class(zc.sourcefactory.source.FactoredContextualSource): def get_check_types(self): """IAutocompleteSource, but not applicable for us""" return [] def __contains__(self, value): # We do not want to ask the whitelist again. return True def search(self, term): from zeit.wochenmarkt.interfaces import IIngredientsWhitelist ingredients = zope.component.getUtility(IIngredientsWhitelist) return ingredients.search(term) ingredientsSource = IngredientsSource()
1.71875
2
lldb/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteGPacket.py
bytesnake/Enzyme
0
12763411
from __future__ import print_function import gdbremote_testcase from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestGdbRemoteGPacket(gdbremote_testcase.GdbRemoteTestCaseBase): mydir = TestBase.compute_mydir(__file__) def run_test_g_packet(self): self.build() self.prep_debug_monitor_and_inferior() self.test_sequence.add_log_lines( ["read packet: $g#67", {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "register_bank"}}], True) self.connect_to_debug_monitor() context = self.expect_gdbremote_sequence() register_bank = context.get("register_bank") self.assertTrue(register_bank[0] != 'E') self.test_sequence.add_log_lines( ["read packet: $G" + register_bank + "#00", {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "G_reply"}}], True) context = self.expect_gdbremote_sequence() self.assertTrue(context.get("G_reply")[0] != 'E') @skipIfOutOfTreeDebugserver @debugserver_test def test_g_packet_debugserver(self): self.init_debugserver_test() self.run_test_g_packet()
1.96875
2
setup.py
danpeczek/ai-katie
0
12763412
import setuptools import os import re with open("README.rst", "r", encoding="utf-8") as fh: long_description = fh.read() def load_version(): """ Loads a file content """ filename = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "katie", "__init__.py")) with open(filename, "rt") as version_file: init_file = version_file.read() version = re.search(r"__version__ = '([0-9a-z.-]+)'", init_file).group(1) return version setuptools.setup(name='ai-katie', version=load_version(), description='Utility things for Data Science and AI', long_description=long_description, author='danpeczek', author_email='<EMAIL>', url='https://github.com/danpeczek/ai-katie', project_urls={ "Bug Tracker": "https://github.com/danpeczek/ai-katie/issues", }, install_requires=["torch", "numpy"], classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Topic :: Communications :: Email', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Scientific/Engineering :: Information Analysis' ], package_dir={"": "."}, packages=setuptools.find_packages(where="."), python_requires=">=3.6" )
1.742188
2
src/model/bert/bert.py
Twitter-Fake/twitter-fake
1
12763413
from util import get_dataset from sklearn.metrics import classification_report import numpy as np from keras.layers import Dense, Input, concatenate from keras.models import Model from keras import backend as K def recall_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def f1_m(y_true, y_pred): precision = precision_m(y_true, y_pred) recall = recall_m(y_true, y_pred) return 2*((precision*recall)/(precision+recall+K.epsilon())) def build_model(bert_dim=768, profile_dim=32): ''' bert network ''' bert_input = Input(shape=(bert_dim,)) bert_output = Dense(256, activation='relu')(bert_input) bert_output = Dense(256, activation='relu')(bert_output) bert_output = Dense(256, activation='relu')(bert_output) bert_output = Dense(32, activation='relu')(bert_output) ''' input for profile network ''' profile_input = Input(shape=(profile_dim,)) ''' model for combined features ''' x = concatenate([profile_input, bert_output]) output = Dense(32, activation='relu')(x) output = Dense(16, activation='relu')(output) output = Dense(1, activation='sigmoid')(output) model = Model(inputs=[profile_input, bert_input], outputs=[output]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc', f1_m]) return model if __name__ == "__main__": cross_val = None for i in range(5): ''' get data with bert embeddings ''' train_x, train_y, test_x, test_y = get_dataset('bert') ''' build neural network model ''' model = build_model() model.summary() train_split = np.hsplit(train_x, np.array([32, 800]))[:2] test_split = np.hsplit(test_x, np.array([32, 800]))[:2] model.fit(x=train_split, y=train_y, batch_size=32, shuffle=True, epochs=100) if cross_val == None: cross_val = model.evaluate(test_split, test_y) else: cross_val += model.evaluate(test_split, test_y) print([metric/5 for metric in cross_val]) model.save('bert_sent_parallel_cross_val.h5')
2.421875
2
GUIfiles/ui_mainWindow.py
NicolasJacson/cam2ascii
1
12763414
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'mainWindowWYIqrE.ui' ## ## Created by: Qt User Interface Compiler version 5.14.1 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide2.QtCore import (QCoreApplication, QMetaObject, QObject, QPoint, QRect, QSize, QUrl, Qt) from PySide2.QtGui import (QBrush, QColor, QConicalGradient, QCursor, QFont, QFontDatabase, QIcon, QLinearGradient, QPalette, QPainter, QPixmap, QRadialGradient) from PySide2.QtWidgets import * class Ui_CAM2ascii(object): def setupUi(self, CAM2ascii): if CAM2ascii.objectName(): CAM2ascii.setObjectName(u"CAM2ascii") CAM2ascii.resize(1280, 720) CAM2ascii.setMinimumSize(QSize(1280, 720)) CAM2ascii.setMaximumSize(QSize(1280, 720)) CAM2ascii.setWindowTitle(u"CAM2ascii") self.centralwidget = QWidget(CAM2ascii) self.centralwidget.setObjectName(u"centralwidget") self.loadingMenuFrame = QFrame(self.centralwidget) self.loadingMenuFrame.setObjectName(u"loadingMenuFrame") self.loadingMenuFrame.setGeometry(QRect(-1, -1, 1281, 721)) self.loadingMenuFrame.setStyleSheet(u"QFrame {\n" " \n" " background-color: rgb(47, 47, 47);\n" " color: white\n" "}") self.loadingMenuFrame.setFrameShape(QFrame.StyledPanel) self.loadingMenuFrame.setFrameShadow(QFrame.Raised) self.title = QLabel(self.loadingMenuFrame) self.title.setObjectName(u"title") self.title.setGeometry(QRect(0, 150, 1281, 121)) font = QFont() font.setPointSize(40) self.title.setFont(font) self.title.setStyleSheet(u"QLabel {\n" " color: rgb(255, 255, 255)\n" "}") self.title.setAlignment(Qt.AlignCenter) self.progressBar = QProgressBar(self.loadingMenuFrame) self.progressBar.setObjectName(u"progressBar") self.progressBar.setGeometry(QRect(280, 460, 720, 31)) self.progressBar.setStyleSheet(u"QProgressBar {\n" " border-radius : 10px;\n" " border-style: none;\n" " background-color: rgb(80, 80, 80);\n" " color:white;\n" " text-align: center;\n" "}\n" "\n" "QProgressBar::chunk {\n" " border-radius : 10px;\n" " background-color: qlineargradient(spread:pad, x1:0, y1:0.512, x2:1, y2:0.579227, stop:0 rgba(0, 153, 102, 255), stop:1 rgba(0, 104, 69, 255));\n" "}") self.progressBar.setValue(24) self.author = QLabel(self.loadingMenuFrame) self.author.setObjectName(u"author") self.author.setGeometry(QRect(1130, 700, 151, 21)) font1 = QFont() font1.setPointSize(8) self.author.setFont(font1) self.author.setStyleSheet(u"QLabel {\n" " color:white\n" "}") self.author.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter) self.author.setMargin(2) CAM2ascii.setCentralWidget(self.centralwidget) self.retranslateUi(CAM2ascii) QMetaObject.connectSlotsByName(CAM2ascii) # setupUi def retranslateUi(self, CAM2ascii): self.title.setText(QCoreApplication.translate("CAM2ascii", u"$> _", None)) self.author.setText(QCoreApplication.translate("CAM2ascii", u"Made by Eppah", None)) # retranslateUi
1.835938
2
sapp/pipeline/base_parser.py
MLH-Fellowship/sapp
1
12763415
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """Abstract Parser for Zoncolan like output""" import logging import pprint from collections import defaultdict from typing import ( Any, Dict, Iterable, List, NamedTuple, Set, TextIO, Tuple, Union, cast, ) import xxhash from ..analysis_output import AnalysisOutput, Metadata from . import ( DictEntries, DictKey, Optional, ParseConditionTuple, ParseIssueTuple, ParseType, PipelineStep, Summary, ) # if these imports have the same name we get a linter error try: import ujson as json except ImportError: import json # noqa log: logging.Logger = logging.getLogger("sapp") # The callable's json output can be found at the given sharded file and offset. # Used for debugging. class EntryPosition(NamedTuple): callable: str shard: int offset: int # pyre-ignore[2] # pyre-ignore[3] def log_trace_keyerror(func): # pyre-ignore[2] # pyre-ignore[3] # pyre-ignore[53] def wrapper(self, json, *args): try: return func(self, json, *args) except KeyError: # The most common problem with parsing json is not finding # a field you expect, so we'll catch those and log them, but move # on. log.exception( "Unable to parse trace for the following:\n%s", pprint.pformat(json) ) return ([], {}) return wrapper # pyre-ignore[2] # pyre-ignore[3] def log_trace_keyerror_in_generator(func): # pyre-ignore[2] # pyre-ignore[3] # pyre-ignore[53] def wrapper(self, json, *args): try: yield from func(self, json, *args) except KeyError: # The most common problem with parsing json is not finding # a field you expect, so we'll catch those and log them, but move # on. log.exception( "Unable to parse trace for the following:\n%s", pprint.pformat(json) ) return yield return wrapper class BaseParser(PipelineStep[AnalysisOutput, DictEntries]): """The parser takes a json file as input, and provides a simplified output for the Processor. """ def __init__(self, repo_dirs: Optional[List[str]] = None) -> None: """ repo_dirs: Possible absolute paths analyzed during the run. This is used to relativize paths in the input. These paths are NOT guaranteed to exist on the current machine disk! """ self.repo_dirs: List[str] = repo_dirs or [] def initialize(self, metadata: Optional[Metadata]) -> None: return # @abstractmethod def parse( self, input: AnalysisOutput ) -> Iterable[Union[ParseConditionTuple, ParseIssueTuple]]: """Must return objects with a 'type': ParseType field.""" raise NotImplementedError("Abstract method called!") # @abstractmethod def parse_handle( self, handle: TextIO ) -> Iterable[Union[ParseConditionTuple, ParseIssueTuple]]: """Must return objects with a 'type': ParseType field.""" raise NotImplementedError("Abstract method called!") def _analysis_output_to_parsed_tuples( self, input: AnalysisOutput ) -> Iterable[ Tuple[ParseType, DictKey, Union[ParseConditionTuple, ParseIssueTuple]] ]: entries = self.parse(input) for e in entries: if isinstance(e, ParseConditionTuple): typ = e.type key = (e.caller, e.caller_port) elif isinstance(e, ParseIssueTuple): typ = ParseType.ISSUE key = e.handle else: raise Exception("Unknown ParseType") yield typ, key, e def analysis_output_to_dict_entries( self, inputfile: AnalysisOutput, previous_issue_handles: Optional[AnalysisOutput], linemapfile: Optional[str], ) -> DictEntries: """Here we take input generators and return a dict with issues, preconditions, and postconditions separated. If there is only a single generator file, it's simple. If we also pass in a generator from a previous inputfile then there are a couple extra steps: 1. If an issue was seen in the previous inputfile then we won't return it, because it's not new. 2. In addition, we take an optional linemap file that maps for each filename, each new file line position to a list of old file line position. This is used to adjust handles to we can recognize when issues moved. """ issues: List[ParseIssueTuple] = [] previous_handles: Set[str] = set() conditions: Dict[ParseType, Dict[DictKey, List[ParseConditionTuple]]] = { ParseType.PRECONDITION: defaultdict(list), ParseType.POSTCONDITION: defaultdict(list), } # If we have a mapfile, create the map. if linemapfile: log.info("Parsing linemap file") with open(linemapfile, "r") as f: linemap = json.load(f) else: linemap = None # Save entry info from the parent analysis, if there is one. if previous_issue_handles: log.info("Parsing previous issue handles") for f in previous_issue_handles.file_handles(): handles = f.read().splitlines() previous_handles = set(filter(lambda h: not h.startswith("#"), handles)) log.info("Parsing analysis output...") for typ, key, e in self._analysis_output_to_parsed_tuples(inputfile): if typ == ParseType.ISSUE: e = cast(ParseIssueTuple, e) # We are only interested in issues that weren't in the previous # analysis. if not self._is_existing_issue(linemap, previous_handles, e, key): issues.append(e.interned()) elif typ == ParseType.PRECONDITION or typ == ParseType.POSTCONDITION: e = cast(ParseConditionTuple, e) conditions[typ][key].append(e.interned()) return { "issues": issues, "preconditions": conditions[ParseType.PRECONDITION], "postconditions": conditions[ParseType.POSTCONDITION], } def _is_existing_issue( self, linemap: Dict[str, Any], old_handles: Set[str], new_issue: ParseIssueTuple, new_handle: DictKey, ) -> bool: if new_handle in old_handles: return True if not linemap: return False filename = new_issue.filename old_map = linemap.get(filename, {}) old_lines = old_map.get(str(new_issue.line), []) # Once this works, we should remove the "relative" line from the handle # and use the absolute one to avoid having to map both the start of the # method and the line in the method. # Consider all possible old lines for old_line in old_lines: old_handle = BaseParser.compute_diff_handle( filename, old_line, new_issue.code ) if old_handle in old_handles: return True return False def run( self, input: AnalysisOutput, summary: Summary ) -> Tuple[DictEntries, Summary]: return ( self.analysis_output_to_dict_entries( input, summary.get("previous_issue_handles"), summary.get("old_linemap_file"), ), summary, ) @staticmethod def compute_master_handle( callable: str, line: int, start: int, end: int, code: int ) -> str: key = "{callable}:{line}|{start}|{end}:{code}".format( callable=callable, line=line, start=start, end=end, code=code ) return BaseParser.compute_handle_from_key(key) @staticmethod def compute_diff_handle(filename: str, old_line: int, code: int) -> str: """Uses the absolute line and ignores the callable/character offsets. Used only in determining whether new issues are old issues. """ key = "{filename}:{old_line}:{code}".format( filename=filename, old_line=old_line, code=code ) return BaseParser.compute_handle_from_key(key) @staticmethod def compute_handle_from_key(key: str) -> str: hash_gen = xxhash.xxh64() hash_gen.update(key.encode()) hash_ = hash_gen.hexdigest() return key[: 255 - len(hash_) - 1] + ":" + hash_ @staticmethod def is_supported(metadata: Metadata) -> bool: raise NotImplementedError("Subclasses should implement this!") # Instead of returning the actual json from the AnalysisOutput, we return # location information so it can be retrieved later. def get_json_file_offsets(self, input: AnalysisOutput) -> Iterable[EntryPosition]: raise NotImplementedError("get_json_file_offset not implemented") # Given a path and an offset, return the json in mostly-raw form. def get_json_from_file_offset( self, path: str, offset: int ) -> Optional[Dict[str, Any]]: raise NotImplementedError("get_json_from_file_offset not implemented")
1.914063
2
src/2-initialize.py
abroniewski/DBLP-Research-Paper-Graph-Modeling
0
12763416
<reponame>abroniewski/DBLP-Research-Paper-Graph-Modeling from utils import Neo4jConnection import time def delete_all_existing_nodes(): print(f"Deleting all existing nodes and edges.") tic = time.perf_counter() query_delete_all_existing_nodes = ''' MATCH (n) DETACH DELETE n ''' conn.query(query_delete_all_existing_nodes, db='neo4j') toc = time.perf_counter() print(f"Total time: {toc - tic:0.4f} seconds\n") def create_author_paper_collection_year(): print(f"Creating authors, papers, collections and years.") tic = time.perf_counter() query_create_author_paper_collection_year = ''' // CREATE NODES FOR AUTHORS AND PAPERS + EDGES FOR CONTRIBUTION // This works by using LOAD CSV to connect to the locally available .csv in the default /import folder of neo4j // Using MERGE, we check to see is a node called "paper" already exists. If so, we will add the info, if not // we will create a new node // We then UNWIND the array of authors, and again use MERGE to create a node for each authoer (if it doesn't exist) // Finally, we create an edge connecting each author to the current paper // NOTE: Using MERGE allows us to make sure we are not creating duplicate nodes for an author that has contributed // to multiple papers. // LEARNING: We cannot create labels for nodes or edges dynamically // LEARNING: trim() removes whitespace before and after // LEARNING: NEVER FORGET!!! You should be creating csv files for your nodes and your edges. Using pure CYPHER for // your loading is like using SQL on something that Python can to simply. It's not worth it.... Here we needed // to deal with multiple UNWINDs, resulting in CYPHER challenges we would not have encountered working in Python. LOAD CSV WITH HEADERS FROM 'file:///publications_processed.csv' AS row FIELDTERMINATOR ',' MERGE (y:Year {year: toInteger(row.publication_year)}) MERGE (collection:document_type {title:row.source_title, document_type:row.document_type}) WITH y, collection, row MERGE (collection)-[:IN_YEAR]->(y) MERGE (p:Paper {name: row.paper, article_no: toInteger(row.article_no)}) MERGE (p)-[:PUBLISHED_IN]->(y) MERGE (p)-[e:IN_COLLECTION]->(collection) MERGE (rg:ReviewGroup {group_id: toInteger(row.review_group)}) MERGE (p)-[:REVIEWED_BY]->(rg) WITH p, row UNWIND split(row.authors, ',') AS author MERGE (a:Author {name: trim(author)}) MERGE (a)-[r:CONTRIBUTED]->(p) ''' conn.query(query_create_author_paper_collection_year, db='neo4j') toc = time.perf_counter() print(f"Total time: {toc-tic:0.4f} seconds\n") def add_peer_review_group_authors(): print(f"Creating peer review groups with authors.") tic = time.perf_counter() query_add_peer_review_group_authors = ''' LOAD CSV WITH HEADERS FROM 'file:///publications_processed.csv' AS row FIELDTERMINATOR ',' MATCH (rg:ReviewGroup {group_id: toInteger(row.review_group)}) WITH row, rg UNWIND split(row.reviewers, ',') AS reviewer MATCH (a:Author {name: trim(reviewer)}) CREATE (a)-[:IN_REVIEW_GROUP]->(rg) ''' conn.query(query_add_peer_review_group_authors, db='neo4j') toc = time.perf_counter() print(f"Total time: {toc-tic:0.4f} seconds\n") def update_document_type_node_labels(): # To have the correct names for Proceeding and Journal nodes, we will use the previously # created node properties to set the label. This can be done easily with a few queries # because we have a small set of collection types. We start by setting an index on the # property "document_type" to improve performance as we will be cycling through properties # instead of nodes and relations. We then SET the node label for each type of collection we # have, and REMOVE the previous label and temporary "document_type" property. print(f"Updating document type node labels.") tic = time.perf_counter() query_set_document_type_index = ''' // We will need to cycle through all of the document_type nodes we created to pull the attribute // document_type out of the node and label the node with it. // We start by creating an INDEX on that property cycling through properties instead of taking // advantage of graph database ability to move through relationships is expensive. CREATE INDEX ON :document_type(document_type) ''' query_update_proceeding_node_labels = ''' MATCH (n:document_type {document_type:'Proceeding'}) SET n:Proceeding REMOVE n:document_type REMOVE n.document_type ''' query_update_journal_node_labels = ''' MATCH (n:document_type {document_type:'Journal'}) SET n:Journal REMOVE n:document_type REMOVE n.document_type ''' query_update_other_node_labels = ''' // Because this is the last node relabelling query being called, the only remaining nodes with this label // are those that have not already been renamed. These ones will all be named "Other". MATCH (n:document_type) SET n:Other REMOVE n:document_type REMOVE n.document_type ''' query_drop_document_type_index = ''' // Removing index for no longer required document_type DROP INDEX ON :document_type(document_type) ''' conn.query(query_set_document_type_index, db='neo4j') conn.query(query_update_proceeding_node_labels, db='neo4j') conn.query(query_update_journal_node_labels, db='neo4j') conn.query(query_update_other_node_labels, db='neo4j') conn.query(query_drop_document_type_index, db='neo4j') toc = time.perf_counter() print(f"Total time: {toc-tic:0.4f} seconds\n") def create_citations_edges(): print(f"Creating citation relationships.") tic = time.perf_counter() query_create_citations_edges = ''' // CREATE CITATIONS // We will MATCH on existing papers where the article name is the same as the article name // for the incoming row of data. Once matched, we will UNWIND the array of citations // in the "cited_by" column. We then MATCH on nodes that have the same article_no as the // paper from where the citation is originating. The last WITH statement only calls our // two matched papers and adds a [CITED] edge between them. // NOTE: When we create or MERGE, anything that has not already been matched will be created // as a new object. So we need to do all of our MATCHES before our MERGE and then we can pull // in the found objects using their aliases. LOAD CSV WITH HEADERS FROM 'file:///publications_processed.csv' AS row FIELDTERMINATOR ',' MATCH (p:Paper {name: row.paper}) WITH p, row UNWIND split(row.cited_by, ',') AS cited_by MATCH (p2:Paper {article_no: toInteger(cited_by)}) WITH p, p2 MERGE (p)<-[r:CITED]-(p2) ''' conn.query(query_create_citations_edges, db='neo4j') toc = time.perf_counter() print(f"Total time: {toc-tic:0.4f} seconds\n") def create_keywords_from_index_nodes(): #TODO: This keyword long is expensive. Can it be made faster by using a keyword index and matching on the index # instead of on the string? print(f"Creating keywords.") tic = time.perf_counter() query_create_keywords_from_index_nodes = ''' // LEARNING: when matching on indexes, always add toInteger as CSV LOAD reads everything in as a string. LOAD CSV WITH HEADERS FROM 'file:///publications_processed.csv' AS row FIELDTERMINATOR ',' WITH row UNWIND split(row.index_keywords, ';') AS kw MERGE (k:Keyword {keyword: toLower( trim(kw) )}) WITH row, k MATCH (p:Paper {article_no: toInteger(row.article_no)}) MERGE (p)-[r:TOPIC]->(k) ''' conn.query(query_create_keywords_from_index_nodes, db='neo4j') toc = time.perf_counter() print(f"Total time: {toc-tic:0.4f} seconds\n") ################################## # Main Program Run ################################## if __name__ == '__main__': conn = Neo4jConnection(uri="bolt://localhost:7687", user="neo4j", pwd="<PASSWORD>") print(f"\n**** Starting neo4j database initialization ****\n") main_tic = time.perf_counter() delete_all_existing_nodes() create_author_paper_collection_year() add_peer_review_group_authors() update_document_type_node_labels() create_citations_edges() create_keywords_from_index_nodes() main_toc = time.perf_counter() print(f"*** Initialization Complete. Total time: {main_toc - main_tic:0.4f} seconds ****")
3.046875
3
MHD/FEniCS/StabNS/NSpreconditioner.py
wathen/PhD
3
12763417
import petsc4py import sys petsc4py.init(sys.argv) from petsc4py import PETSc import numpy as np from dolfin import tic, toc class BaseMyPC(object): def setup(self, pc): pass def reset(self, pc): pass def apply(self, pc, x, y): raise NotImplementedError def applyT(self, pc, x, y): self.apply(pc, x, y) def applyS(self, pc, x, y): self.apply(pc, x, y) def applySL(self, pc, x, y): self.applyS(pc, x, y) def applySR(self, pc, x, y): self.applyS(pc, x, y) def applyRich(self, pc, x, y, w, tols): self.apply(pc, x, y) class NSPCD(BaseMyPC): def __init__(self, W, kspF, kspA, kspQ,Fp): self.W = W self.kspF = kspF self.kspA = kspA self.kspQ = kspQ self.Fp = Fp self.u_is = PETSc.IS().createGeneral(range(W.sub(0).dim())) self.p_is = PETSc.IS().createGeneral(range(W.sub(0).dim(),W.sub(0).dim()+W.sub(1).dim())) self.HiptmairIts = 0 self.CGits = 0 def create(self, pc): print "Create" def setUp(self, pc): A, P = pc.getOperators() if A.type != 'python': self.Bt = A.getSubMatrix(self.p_is,self.u_is) else: self.Bt = A.getPythonContext().getMatrix("Bt") print "setup" def apply(self, pc, x, y): # self.kspCurlCurl.setOperators(self.B) x1 = x.getSubVector(self.u_is) y1 = x1.duplicate() y11 = x1.duplicate() x2 = x.getSubVector(self.p_is) y2 = x2.duplicate() y3 = x2.duplicate() y4 = x2.duplicate() # tic() self.kspA.solve(x2,y2) self.Fp.mult(y2,y3) self.kspQ.solve(y3,y4) self.Bt.multTranspose(y4,y11) self.kspF.solve(x1+y11,y1) y.array = (np.concatenate([y1.array, -y4.array])) def ITS(self): return self.CGits, self.HiptmairIts , self.CGtime, self.HiptmairTime class NSLSC(BaseMyPC): def __init__(self, W, kspF, kspBQB, QB): self.QB = QB self.W = W self.kspF = kspF self.kspBQB = kspBQB self.u_is = PETSc.IS().createGeneral(range(W.sub(0).dim())) self.p_is = PETSc.IS().createGeneral(range(W.sub(0).dim(),W.sub(0).dim()+W.sub(1).dim())) def create(self, pc): print "Create" def setUp(self, pc): A, P= pc.getOperators() self.Bt = A.getSubMatrix(self.u_is,self.p_is) self.A = A.getSubMatrix(self.u_is,self.u_is) print "setup" def apply(self, pc, x, y): x1 = x.getSubVector(self.u_is) y1 = x1.duplicate() x2 = x.getSubVector(self.p_is) y2 = x2.duplicate() y3 = x1.duplicate() y4 = x1.duplicate() y5 = x2.duplicate() y6 = x2.duplicate() y7 = x1.duplicate() self.kspBQB.solve(x2, y2) self.QB.mult(y2,y3) self.A.mult(y3,y4) self.QB.multTranspose(y4,y5) self.kspBQB.solve(y5, y6) self.Bt.mult(y6,y7) self.kspF.solve(x1+y7,y1) y.array = (np.concatenate([y1.array, -y6.array]))
2.375
2
Core/Solvers/KDA/KDA_Solution_Class.py
zztcok/SNAC_PSNAC
1
12763418
<reponame>zztcok/SNAC_PSNAC import sys import os from pyomo.environ import * from pyomo.opt import SolverFactory import itertools from pyutilib.misc import Options import time as timer import pdb import gc import re class KDA: def __init__(self, model_data, solver, mipgap,solve_output, _opts, fixed_parameters={}, penval = 0): self.mipgap = mipgap self.solver = solver self._opts = _opts self.fixed_parameters = fixed_parameters self.model_type = model_data._data['model_type'][None][0] ### Process knapsack data if self.model_type == 'PRDP': from Core.Solvers.KDA import knapsack_item knapsack_data = knapsack_item.knapsack_data_processing(model_data) ### Solve knapsack solution = self.kda_solver(knapsack_data,model_data,solver,mipgap,solve_output, _opts, penval) self.output = solution def kda_solver(self, knapsack_data,model_data, solver, mipgap, solve_output, _opts, penval): ## Start Solution Timer start_time = timer.clock() problem_count = 0 output_directory = solve_output ## Set the number of time steps total ts = len(model_data._data['time_step'][None]) ### declare time time = 0 sp_solve= {} ex = {} #### Loop over all steps while time < ts: ##Set the parameters that are time specific if time == 0: ### Initialize Time Dependent Parameters ### Class wide parameters self.run_time = {} self.temp_dict = {} self.temp_item_selection = {} self.fixed_items = {} ### Method wide Parameters results_storage = {} item_monitor = {} sp_realizations = {} ### Declare Sub-Problem Name sub_problem = '0' ###Declare Max Duration max_duration = 0 ######################################################## ### Create Existance Vector (Model Specific) ######################################################## existance = {} if self.model_type == 'PRDP': from Core.Solvers.KDA.KDA_PRDP_Functions import initial_existance existance[('0',0)] = initial_existance(knapsack_data) ######################################################## ### Determine Fixed Parameters (Model Specific) ######################################################## if len(self.fixed_parameters) != 0: if self.model_type == 'PRDP': from Core.Solvers.KDA.KDA_PRDP_Functions import initial_fixed_parameters self.fixed_items[sub_problem] = initial_fixed_parameters(self.fixed_parameters,knapsack_data, model_data) else: self.fixed_items[sub_problem] = [] ### Increment problem counter problem_count += 1 ######################################################## ### Solve t=0 Problem Based on Solve Options ######################################################## if 'min_solve' in _opts: ##Solve using min_solve_solver self.min_solve_solver(knapsack_data, item_monitor, model_data,existance,output_directory,sub_problem,time,max_duration,penval) elif 'max_solve' in _opts: ### Solve using max_solve_solver self.max_solve_solver(knapsack_data, model_data,existance,output_directory,sub_problem,time,max_duration,penval) else: ### Solve using min_solve_solver self.min_solve_solver(knapsack_data, item_monitor, model_data,existance,output_directory,sub_problem,time,max_duration,penval) ### Store Solution results_storage[time] = dict(self.temp_item_selection) item_monitor[time] = dict(self.temp_dict) ### Increment time time += 1 else: ######################################################## ### Determine Sub-Problem Generation ######################################################## item_monitor[time] = {} for i in item_monitor[time-1]: ### THIS IS WHERE PARALLELIZATION SHOULD OCCUR finished_items = [] generate_subproblems = False ### Based on _opts determine whetherto generate sub-problems if 'min_solve' in _opts: ################################################ ### Determine Sub-Problems (Model Specific) ################################################ if self.model_type == 'PRDP': from Core.Solvers.KDA.KDA_PRDP_Functions import min_solve_sp_generation generate_subproblems, finished_items = min_solve_sp_generation(item_monitor,time,i) elif 'max_solve' in _opts: ################################################ ### Determine Sub-Problems (Model Specific) ################################################ if self.model_type == 'PRDP': from Core.Solvers.KDA.KDA_PRDP_Functions import max_solve_sp_generation generate_subproblems, finished_items = max_solve_sp_generation(item_monitor,time,i) else: ################################################ ### Determine Sub-Problems (Model Specific) ################################################ if self.model_type == 'PRDP': from Core.Solvers.KDA.KDA_PRDP_Functions import every_solve_sp_generation generate_subproblems,finished_items = every_solve_sp_generation(item_monitor,time,i) #################################################### ### Generate Sub-Problems #################################################### if generate_subproblems == True: if len(finished_items) > 0: ################################################ ### Model Specific Sub-Problem Generation ################################################ if self.model_type == 'PRDP': from Core.Solvers.KDA.KDA_PRDP_Functions import PRDP_SubProblem_Generation sp_realizations, sp_solve, item_monitor = PRDP_SubProblem_Generation(finished_items, i, time, item_monitor,sp_solve,sp_realizations) else: item_monitor[time][i] = item_monitor[time-1][i] ######################################################## ### Calculate Existance Vectors Items ######################################################## for i in item_monitor[time]: ### THIS IS ANOTHER PLACE FOR PARALLELIZATION #################################################### ### Model Specific Existance Vector Determiniation #################################################### if self.model_type == 'PRDP': from Core.Solvers.KDA.KDA_PRDP_Functions import non_initial_existance_vector existance = non_initial_existance_vector(i, time, model_data, existance, knapsack_data, item_monitor, _opts, sp_realizations, results_storage) ######################################################## ### Update Parameters and Solve Sub-Problems ######################################################## for i in item_monitor[time]: ### THIS IS ANOTHER PLACE FOR PARALLELIZATION #################################################### ### Determine if Solving is Needed #################################################### if self.model_type == 'PRDP': from Core.Solvers.KDA.KDA_PRDP_Functions import do_solve_calc do_solve = do_solve_calc(i, time, existance) if do_solve == 0: try: results_storage[time] except: results_storage[time] = {} results_storage[time][i] = () else: ################################################ ### Determine Sub-Problem Fixed Parameters (Model Specific) ################################################ if len(self.fixed_parameters) > 0: if self.model_type == 'PRDP': from Core.Solvers.KDA.KDA_PRDP_Functions import fixed_item_generator self.fixed_items[i] = fixed_item_generator(i,time,sp_realizations, knapsack_data, model_data, self.fixed_parameters) else: self.fixed_items[i] = [] ################################################ ### Minimum Solve ################################################ if 'min_solve' in _opts: ##Solve using min_solve_solver try: if time == sp_solve[i]: max_duration = 0 self.min_solve_solver(knapsack_data, item_monitor[time][i],model_data,existance,output_directory,i,time,max_duration,penval) ### Increment problem counter problem_count += 1 ## Create dictionary entry for temporary variable with the time key try: results_storage[time] except: results_storage[time] = {} results_storage[time][i] = self.Item_Selection item_monitor[time][i] += self.temp else: try: results_storage[time] except: results_storage[time] = {} results_storage[time][i] = () except: try: results_storage[time] except: results_storage[time] = {} results_storage[time][i] = () ################################################ ### Maximum Solve ################################################ elif 'max_solve' in _opts: ### If there are no active items solve the knapsack using data if item_monitor[time][i] == (): ### Solve using max_solve_solver self.max_solve_solver(knapsack_data,model_data,existance,output_directory,i,time,max_duration,penval) ### Increment problem counter problem_count += 1 try: results_storage[time] except: results_storage[time] = {} results_storage[time][i] = self.Item_Selection item_monitor[time][i] += self.temp else: try: results_storage[time] except: results_storage[time] = {} results_storage[time][i] = () ################################################ ### Everytime Solve ################################################ else: ### Solve using min_solve_solver self.min_solve_solver(knapsack_data, item_monitor[time][i],model_data,existance,output_directory,i,time,max_duration,penval) ### Increment problem counter problem_count += 1 ## Create dictionary entry for temporary variable with the time key try: results_storage[time] except: results_storage[time] = {} results_storage[time][i] = self.Item_Selection item_monitor[time][i] += self.temp ## Increment Time time += 1 finish_time = timer.clock() total_time = finish_time - start_time answers = self.results_format(sp_realizations, problem_count, results_storage, total_time) return answers def max_solve_solver(self, knapsack_data, model_data, existance, output_directory, sub_problem,time, max_duration,penval): ##Solver info opt = SolverFactory(self.solver) options = Options() opt.options.mip_tolerances_mipgap = self.mipgap ################################################################ ### Generate Model (Model Specific) ################################################################ if self.model_type == 'PRDP': ### Define Item List items = knapsack_data.ItemList ### Generate Model from Core.Solvers.KDA.KDA_PRDP_Functions import PRDP_Max_Solve_Model_Generator model = PRDP_Max_Solve_Model_Generator(knapsack_data, model_data, existance, sub_problem, time, max_duration, self._opts, penval) ### Initiate Timer st = timer.clock() ################################################################ ### Create Instance ################################################################ for items in self.fixed_items[sub_problem]: model.x[items[0]] = items[1] model.x[items[0]].fixed = True model.preprocess() ################################################################ ### Solve Model ################################################################ results = opt.solve(model) ### Take finish Time ft = timer.clock() ################################################################ ### Process Results ################################################################ ### Make Output Directory if 'quiet' not in self._opts: if not os.path.exists(output_directory): os.makedirs(output_directory) ## Load Results model.solutions.load_from(results) #### Save problem information if 'quiet' not in self._opts: save_file = "IntKs_" + str(sub_problem) + "_" + str(time) + ".json" results.write(filename = os.path.join(output_directory, save_file)) ### Create Performance variables for problem runtime and item management self.temp = () self.Item_Selection = () ## Store the items packed in the knapsack in temporary variable for i in items: if model.x[i].value == 1: ######################################################## ### Store Results (Model Specific) ######################################################## if self.model_type == 'PRDP': from Core.Solvers.KDA.KDA_PRDP_Functions import results_processing obj1, obj2 = results_processing(knapsack_data, model_data,i, time) ### Items Selected self.Item_Selection += (obj1,) ### Append item self.temp += (obj2,) if time == 0: self.temp_dict[sub_problem] = self.temp self.temp_item_selection[sub_problem] = self.Item_Selection ## Store solve time self.run_time[(sub_problem,time)] = ft - st def min_solve_solver(self, knapsack_data, active_item_list, model_data,existance,output_directory,sub_problem,time,max_duration,penval): ##Solver info opt = SolverFactory(self.solver) options = Options() opt.options.mip_tolerances_mipgap = self.mipgap ################################################################ ### Generate Model (Model Specific) ################################################################ if self.model_type == 'PRDP': ### Define Item List items = knapsack_data.ItemList ### Generate Model if 'greedy' in self._opts: from Core.Solvers.KDA.KDA_PRDP_Functions import PRDP_Min_Solve_Model_Generator_Greedy model = PRDP_Min_Solve_Model_Generator_Greedy(knapsack_data, model_data, active_item_list, existance, sub_problem, time, max_duration, self._opts, penval) else: from Core.Solvers.KDA.KDA_PRDP_Functions import PRDP_Min_Solve_Model_Generator model = PRDP_Min_Solve_Model_Generator(knapsack_data, model_data, active_item_list, existance, sub_problem, time, max_duration, self._opts, penval) ### Initiate Timer st = timer.clock() ################################################################ ### Create Instance ################################################################ for (i,j) in self.fixed_items[sub_problem]: model.x[i].value = j model.x[i].fixed = True model.preprocess() ################################################################ ### Solve Model ################################################################ results = opt.solve(model) ### Take finish Time ft = timer.clock() ################################################################ ### Process Results ################################################################ ### Make Output Directory if 'quiet' not in self._opts: if not os.path.exists(output_directory): os.makedirs(output_directory) ### Load Results model.solutions.load_from(results) #### Save problem information if 'quiet' not in self._opts: save_file = "IntKs_" + str(sub_problem) + "_" + str(time) + ".json" results.write(filename = os.path.join(output_directory, save_file)) ### Create Performance variables for problem runtime and item management self.temp = () self.Item_Selection = () ## Store the items packed in the knapsack in temporary variable for i in items: if model.x[i].value == 1: ######################################################## ### Store Results (Model Specific) ######################################################## if self.model_type == 'PRDP': from Core.Solvers.KDA.KDA_PRDP_Functions import results_processing obj1, obj2 = results_processing(knapsack_data, model_data,i,time) ### Items Selected self.Item_Selection += (obj1,) ### Append item self.temp += (obj2,) if time == 0: self.temp_dict[sub_problem] = self.temp self.temp_item_selection[sub_problem] = self.Item_Selection ## Store solve time self.run_time[(sub_problem,time)] = ft - st def results_format(self, sp_realizations, problem_count, results_storage, total_time): answer = {} answer['sub_problem_realizations'] = sp_realizations answer['problem_count'] = problem_count answer['results'] = results_storage answer['runtime'] = self.run_time answer['algorithm_time'] = total_time return answer
2.28125
2
skoda/sm5_evaluation.py
mmalekzadeh/privacy-autoencoder
18
12763419
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created in September 2017 @author: mmalekzadeh """ import numpy as np from keras.models import model_from_json from keras import backend as K def mcor(y_true, y_pred): #matthews_correlation y_pred_pos = K.round(K.clip(y_pred, 0, 1)) y_pred_neg = 1 - y_pred_pos y_pos = K.round(K.clip(y_true, 0, 1)) y_neg = 1 - y_pos tp = K.sum(y_pos * y_pred_pos) tn = K.sum(y_neg * y_pred_neg) fp = K.sum(y_neg * y_pred_pos) fn = K.sum(y_pos * y_pred_neg) numerator = (tp * tn - fp * fn) denominator = K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) return numerator / (denominator + K.epsilon()) def precision(y_true, y_pred): """Precision metric. Only computes a batch-wise average of precision. Computes the precision, a metric for multi-label classification of how many selected items are relevant. """ true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def recall(y_true, y_pred): """Recall metric. Only computes a batch-wise average of recall. Computes the recall, a metric for multi-label classification of how many relevant items are selected. """ true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall ### Global Variables ### ## Load Lists of Inferences all_inferences = np.load("all_inferences.npy") white_list = np.asarray(all_inferences[0].tolist()[0]) black_list = np.asarray(all_inferences[1].tolist()[0]) gray_list = np.asarray(all_inferences[2].tolist()[0]) num_classes = len(white_list)+len(black_list)+len(gray_list) ## Load Original Test Data of each list ## w -> white, b -> black, g -> gray o_w_test_data = np.load("data_test_white.npy") o_b_test_data = np.load("data_test_black.npy") o_g_test_data = np.load("data_test_gray.npy") o_w_test_data = np.reshape(o_w_test_data, (len(o_w_test_data), o_w_test_data.shape[1], o_w_test_data.shape[2], 1)) o_b_test_data = np.reshape(o_b_test_data, (len(o_b_test_data), o_b_test_data.shape[1], o_b_test_data.shape[2], 1)) o_g_test_data = np.reshape(o_g_test_data, (len(o_g_test_data), o_g_test_data.shape[1], o_g_test_data.shape[2], 1)) ## Load Transformed Test Data of each list tr_w_test_data = np.load("transformed_w_test_data.npy") tr_b_test_data = np.load("transformed_b_test_data.npy") tr_g_test_data = np.load("transformed_g_test_data.npy") ## Load Labels of each list w_test_label = np.load("label_test_white.npy") b_test_label = np.load("label_test_black.npy") g_test_label = np.load("label_test_gray.npy") ## Build one-hot codes for each list y_white = np.zeros((w_test_label.shape[0], num_classes)) for i in range(w_test_label.shape[0]): y_white[i, int(w_test_label[i])] = 1 y_black = np.zeros((b_test_label.shape[0], num_classes)) for i in range(b_test_label.shape[0]): y_black[i, int(b_test_label[i])] = 1 y_gray = np.zeros((g_test_label.shape[0], num_classes)) for i in range(g_test_label.shape[0]): y_gray[i, int(g_test_label[i])] = 1 # load json and create model json_file = open('server_cnn_model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model loaded_model.load_weights("server_cnn_model_weights.h5") print("Loaded model from disk") # evaluate loaded model on test data loaded_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy',precision ,recall]) ## Evaluate Original Data o_w_scores = loaded_model.evaluate(o_w_test_data, y_white, verbose=1) o_b_scores = loaded_model.evaluate(o_b_test_data, y_black, verbose=1) o_g_scores = loaded_model.evaluate(o_g_test_data, y_gray, verbose=1) ## Predict Original Data o_w_predict = loaded_model.predict(o_w_test_data, verbose=1) o_b_predict = loaded_model.predict(o_b_test_data, verbose=1) o_g_predict = loaded_model.predict(o_g_test_data, verbose=1) ## Evaluate Transformed Data tr_w_scores = loaded_model.evaluate(tr_w_test_data, y_white, verbose=1) tr_b_scores = loaded_model.evaluate(tr_b_test_data, y_black, verbose=1) tr_g_scores = loaded_model.evaluate(tr_g_test_data, y_gray, verbose=1) ## Predict Transformed Data tr_w_predict = loaded_model.predict(tr_w_test_data, verbose=1) tr_b_predict = loaded_model.predict(tr_b_test_data, verbose=1) tr_g_predict = loaded_model.predict(tr_g_test_data, verbose=1) print("\n ~~~ Result: F1-Socre on Original Data:") print("\n on white-listed: %.2f%%"% ((2*((o_w_scores[2]*o_w_scores[3])/(o_w_scores[2]+o_w_scores[3])))*100)) print("\n on black-listed %.2f%%"% ((2*((o_b_scores[2]*o_b_scores[3])/(o_b_scores[2]+o_b_scores[3])))*100)) print("\n on gray-listed %.2f%%"% ((2*((o_g_scores[2]*o_g_scores[3])/(o_g_scores[2]+o_g_scores[3])))*100)) print("\n ~~~ Result: F1-Socre on Transformed Data:") print("\n on white-listed: %.2f%%"% ((2*((tr_w_scores[2]*tr_w_scores[3])/(tr_w_scores[2]+tr_w_scores[3])))*100)) print("\n on black-listed %.2f%%"% ((2*((tr_b_scores[2]*tr_b_scores[3])/(tr_b_scores[2]+tr_b_scores[3])))*100)) print("\n on gray-listed %.2f%%"% ((2*((tr_g_scores[2]*tr_g_scores[3])/(tr_g_scores[2]+tr_g_scores[3])))*100)) # ########### Calculating Confusion Matrix ########### import itertools import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.GnBu): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", fontsize=18, color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') o_w_pred = np.argmax(o_w_predict,axis=1) o_b_pred = np.argmax(o_b_predict,axis=1) o_g_pred = np.argmax(o_g_predict,axis=1) tr_w_pred = np.argmax(tr_w_predict,axis=1) tr_b_pred = np.argmax(tr_b_predict,axis=1) tr_g_pred = np.argmax(tr_g_predict,axis=1) w_true = np.zeros(o_w_pred.shape[0]) b_true = np.zeros(o_b_pred.shape[0]) g_true = np.zeros(o_g_pred.shape[0]) for i in range(o_w_pred.shape[0]): w_true[i]= 1 if o_w_pred[i] in gray_list: o_w_pred[i]= 2 elif o_w_pred[i] in white_list: o_w_pred[i]= 1 else: o_w_pred[i]= 0 for i in range(o_b_pred.shape[0]): b_true[i]= 0 if o_b_pred[i] in gray_list: o_b_pred[i]= 2 elif o_b_pred[i] in white_list: o_b_pred[i]= 1 else: o_b_pred[i]= 0 for i in range(o_g_pred.shape[0]): g_true[i]= 2 if o_g_pred[i] in gray_list: o_g_pred[i]= 2 elif o_g_pred[i] in white_list: o_g_pred[i]= 1 else: o_g_pred[i]= 0 for i in range(tr_w_pred.shape[0]): if tr_w_pred[i] in gray_list: tr_w_pred[i]= 2 elif tr_w_pred[i] in white_list: tr_w_pred[i]= 1 else: tr_w_pred[i]= 0 for i in range(tr_b_pred.shape[0]): if tr_b_pred[i] in gray_list: tr_b_pred[i]= 2 elif tr_b_pred[i] in white_list: tr_b_pred[i]= 1 else: tr_b_pred[i]= 0 for i in range(tr_g_pred.shape[0]): if tr_g_pred[i] in gray_list: tr_g_pred[i]= 2 elif tr_g_pred[i] in white_list: tr_g_pred[i]= 1 else: tr_g_pred[i]= 0 class_names =["B", "W", "G"] ycf_test = np.append(w_true, g_true, axis=0) ycf_test = np.append(ycf_test, b_true, axis=0) ycf_o_pred = np.append(o_w_pred, o_g_pred, axis=0) ycf_o_pred = np.append(ycf_o_pred, o_b_pred, axis=0) ycf_tr_pred = np.append(tr_w_pred, tr_g_pred, axis=0) ycf_tr_pred = np.append(ycf_tr_pred, tr_b_pred, axis=0) ## Compute confusion matrix for Original Data o_cnf_matrix = confusion_matrix(ycf_test, ycf_o_pred) np.set_printoptions(precision=3) ## Plot non-normalized confusion matrix plot_confusion_matrix(o_cnf_matrix, classes=class_names, normalize=True, title='Confusion Matrix of Original Data') plt.savefig('OCF.pdf',bbox_inches='tight') plt.gcf().clear() ## Compute confusion matrix for Transformed Data tr_cnf_matrix = confusion_matrix(ycf_test, ycf_tr_pred) np.set_printoptions(precision=3) ## Plot non-normalized confusion matrix plot_confusion_matrix(tr_cnf_matrix, classes=class_names, normalize=True, title='Confusion Matrix of Transformed Data') plt.savefig('TrCF.pdf',bbox_inches='tight')
2.75
3
ctapipe/image/reducers.py
Pluto9th/ctapipe
0
12763420
""" Algorithms for the data volume reduction. """ from abc import abstractmethod from ctapipe.core import Component __all__ = [ 'DataVolumeReducer', ] class DataVolumeReducer(Component): """ Base component for data volume reducers. Parameters ---------- config : traitlets.loader.Config Configuration specified by config file or cmdline arguments. Used to set traitlet values. Set to None if no configuration to pass. tool : ctapipe.core.Tool Tool executable that is calling this component. Passes the correct logger to the component. Set to None if no Tool to pass. kwargs Attributes ---------- extracted_samples : ndarray Numpy array containing True where the samples lay within the integration window, and False where the samples lay outside. Has shape of (n_chan, n_pix, n_samples). peakpos : ndarray Numpy array of the peak position for each pixel. Has shape of (n_chan, n_pix). neighbours : list List of neighbours for each pixel. Changes per telescope. """ def __init__(self, config=None, parent=None, **kwargs): super().__init__(config=config, parent=parent, **kwargs) self._nchan = None self._npix = None self._nsamples = None self.extracted_samples = None self.peakpos = None self.neighbours = None @staticmethod def requires_neighbours(): """ Method used for callers of the ImageExtractor to know if the extractor requires knowledge of the pixel neighbours Returns ------- bool """ return False def check_neighbour_set(self): """ Check if the pixel neighbours has been set for the extractor Raises ------- ValueError If neighbours has not been set """ if self.requires_neighbours(): if self.neighbours is None: self.log.exception("neighbours attribute must be set") raise ValueError() @abstractmethod def reduce_waveforms(self, waveforms): """ Call the relevant functions to reduce the waveforms using a particular reducer. Parameters ---------- waveforms : ndarray Waveforms stored in a numpy array of shape (n_chan, n_pix, n_samples). Returns ------- reduced_waveforms : ndarray Reduced waveforms stored in a numpy array of shape (n_chan, n_pix, n_samples). """
2.59375
3
Code-Sleep-Python/Encryption-Techniques/AES/tables.py
shardul08/Code-Sleep-Python
420
12763421
sbox = [ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 ] sboxInv = [ 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D ] rCon = [ 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d ] vector_table = [2, 3, 1, 1, 1, 2, 3, 1, 1, 1, 2, 3, 3, 1, 1, 2] table_2 = [ 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e, 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, 0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e, 0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, 0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe, 0x1b, 0x19, 0x1f, 0x1d, 0x13, 0x11, 0x17, 0x15, 0x0b, 0x09, 0x0f, 0x0d, 0x03, 0x01, 0x07, 0x05, 0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31, 0x37, 0x35, 0x2b, 0x29, 0x2f, 0x2d, 0x23, 0x21, 0x27, 0x25, 0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51, 0x57, 0x55, 0x4b, 0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, 0x45, 0x7b, 0x79, 0x7f, 0x7d, 0x73, 0x71, 0x77, 0x75, 0x6b, 0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65, 0x9b, 0x99, 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85, 0xbb, 0xb9, 0xbf, 0xbd, 0xb3, 0xb1, 0xb7, 0xb5, 0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5, 0xdb, 0xd9, 0xdf, 0xdd, 0xd3, 0xd1, 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5, 0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5, 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5] table_3 = [ 0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17, 0x12, 0x11, 0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39, 0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, 0x21, 0x60, 0x63, 0x66, 0x65, 0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71, 0x50, 0x53, 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d, 0x44, 0x47, 0x42, 0x41, 0xc0, 0xc3, 0xc6, 0xc5, 0xcc, 0xcf, 0xca, 0xc9, 0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1, 0xf0, 0xf3, 0xf6, 0xf5, 0xfc, 0xff, 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1, 0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, 0xa9, 0xb8, 0xbb, 0xbe, 0xbd, 0xb4, 0xb7, 0xb2, 0xb1, 0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99, 0x88, 0x8b, 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81, 0x9b, 0x98, 0x9d, 0x9e, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86, 0x8f, 0x8c, 0x89, 0x8a, 0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6, 0xbf, 0xbc, 0xb9, 0xba, 0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2, 0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, 0xea, 0xcb, 0xc8, 0xcd, 0xce, 0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda, 0x5b, 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a, 0x6b, 0x68, 0x6d, 0x6e, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a, 0x3b, 0x38, 0x3d, 0x3e, 0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a, 0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a] table_9 = [ 0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77, 0x90, 0x99, 0x82, 0x8b, 0xb4, 0xbd, 0xa6, 0xaf, 0xd8, 0xd1, 0xca, 0xc3, 0xfc, 0xf5, 0xee, 0xe7, 0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c, 0xab, 0xa2, 0xb9, 0xb0, 0x8f, 0x86, 0x9d, 0x94, 0xe3, 0xea, 0xf1, 0xf8, 0xc7, 0xce, 0xd5, 0xdc, 0x76, 0x7f, 0x64, 0x6d, 0x52, 0x5b, 0x40, 0x49, 0x3e, 0x37, 0x2c, 0x25, 0x1a, 0x13, 0x08, 0x01, 0xe6, 0xef, 0xf4, 0xfd, 0xc2, 0xcb, 0xd0, 0xd9, 0xae, 0xa7, 0xbc, 0xb5, 0x8a, 0x83, 0x98, 0x91, 0x4d, 0x44, 0x5f, 0x56, 0x69, 0x60, 0x7b, 0x72, 0x05, 0x0c, 0x17, 0x1e, 0x21, 0x28, 0x33, 0x3a, 0xdd, 0xd4, 0xcf, 0xc6, 0xf9, 0xf0, 0xeb, 0xe2, 0x95, 0x9c, 0x87, 0x8e, 0xb1, 0xb8, 0xa3, 0xaa, 0xec, 0xe5, 0xfe, 0xf7, 0xc8, 0xc1, 0xda, 0xd3, 0xa4, 0xad, 0xb6, 0xbf, 0x80, 0x89, 0x92, 0x9b, 0x7c, 0x75, 0x6e, 0x67, 0x58, 0x51, 0x4a, 0x43, 0x34, 0x3d, 0x26, 0x2f, 0x10, 0x19, 0x02, 0x0b, 0xd7, 0xde, 0xc5, 0xcc, 0xf3, 0xfa, 0xe1, 0xe8, 0x9f, 0x96, 0x8d, 0x84, 0xbb, 0xb2, 0xa9, 0xa0, 0x47, 0x4e, 0x55, 0x5c, 0x63, 0x6a, 0x71, 0x78, 0x0f, 0x06, 0x1d, 0x14, 0x2b, 0x22, 0x39, 0x30, 0x9a, 0x93, 0x88, 0x81, 0xbe, 0xb7, 0xac, 0xa5, 0xd2, 0xdb, 0xc0, 0xc9, 0xf6, 0xff, 0xe4, 0xed, 0x0a, 0x03, 0x18, 0x11, 0x2e, 0x27, 0x3c, 0x35, 0x42, 0x4b, 0x50, 0x59, 0x66, 0x6f, 0x74, 0x7d, 0xa1, 0xa8, 0xb3, 0xba, 0x85, 0x8c, 0x97, 0x9e, 0xe9, 0xe0, 0xfb, 0xf2, 0xcd, 0xc4, 0xdf, 0xd6, 0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, 0x0e, 0x79, 0x70, 0x6b, 0x62, 0x5d, 0x54, 0x4f, 0x46] table_11 = [0x00, 0x0b, 0x16, 0x1d, 0x2c, 0x27, 0x3a, 0x31, 0x58, 0x53, 0x4e, 0x45, 0x74, 0x7f, 0x62, 0x69, 0xb0, 0xbb, 0xa6, 0xad, 0x9c, 0x97, 0x8a, 0x81, 0xe8, 0xe3, 0xfe, 0xf5, 0xc4, 0xcf, 0xd2, 0xd9, 0x7b, 0x70, 0x6d, 0x66, 0x57, 0x5c, 0x41, 0x4a, 0x23, 0x28, 0x35, 0x3e, 0x0f, 0x04, 0x19, 0x12, 0xcb, 0xc0, 0xdd, 0xd6, 0xe7, 0xec, 0xf1, 0xfa, 0x93, 0x98, 0x85, 0x8e, 0xbf, 0xb4, 0xa9, 0xa2, 0xf6, 0xfd, 0xe0, 0xeb, 0xda, 0xd1, 0xcc, 0xc7, 0xae, 0xa5, 0xb8, 0xb3, 0x82, 0x89, 0x94, 0x9f, 0x46, 0x4d, 0x50, 0x5b, 0x6a, 0x61, 0x7c, 0x77, 0x1e, 0x15, 0x08, 0x03, 0x32, 0x39, 0x24, 0x2f, 0x8d, 0x86, 0x9b, 0x90, 0xa1, 0xaa, 0xb7, 0xbc, 0xd5, 0xde, 0xc3, 0xc8, 0xf9, 0xf2, 0xef, 0xe4, 0x3d, 0x36, 0x2b, 0x20, 0x11, 0x1a, 0x07, 0x0c, 0x65, 0x6e, 0x73, 0x78, 0x49, 0x42, 0x5f, 0x54, 0xf7, 0xfc, 0xe1, 0xea, 0xdb, 0xd0, 0xcd, 0xc6, 0xaf, 0xa4, 0xb9, 0xb2, 0x83, 0x88, 0x95, 0x9e, 0x47, 0x4c, 0x51, 0x5a, 0x6b, 0x60, 0x7d, 0x76, 0x1f, 0x14, 0x09, 0x02, 0x33, 0x38, 0x25, 0x2e, 0x8c, 0x87, 0x9a, 0x91, 0xa0, 0xab, 0xb6, 0xbd, 0xd4, 0xdf, 0xc2, 0xc9, 0xf8, 0xf3, 0xee, 0xe5, 0x3c, 0x37, 0x2a, 0x21, 0x10, 0x1b, 0x06, 0x0d, 0x64, 0x6f, 0x72, 0x79, 0x48, 0x43, 0x5e, 0x55, 0x01, 0x0a, 0x17, 0x1c, 0x2d, 0x26, 0x3b, 0x30, 0x59, 0x52, 0x4f, 0x44, 0x75, 0x7e, 0x63, 0x68, 0xb1, 0xba, 0xa7, 0xac, 0x9d, 0x96, 0x8b, 0x80, 0xe9, 0xe2, 0xff, 0xf4, 0xc5, 0xce, 0xd3, 0xd8, 0x7a, 0x71, 0x6c, 0x67, 0x56, 0x5d, 0x40, 0x4b, 0x22, 0x29, 0x34, 0x3f, 0x0e, 0x05, 0x18, 0x13, 0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, 0xfb, 0x92, 0x99, 0x84, 0x8f, 0xbe, 0xb5, 0xa8, 0xa3] table_13 = [0x00, 0x0d, 0x1a, 0x17, 0x34, 0x39, 0x2e, 0x23, 0x68, 0x65, 0x72, 0x7f, 0x5c, 0x51, 0x46, 0x4b, 0xd0, 0xdd, 0xca, 0xc7, 0xe4, 0xe9, 0xfe, 0xf3, 0xb8, 0xb5, 0xa2, 0xaf, 0x8c, 0x81, 0x96, 0x9b, 0xbb, 0xb6, 0xa1, 0xac, 0x8f, 0x82, 0x95, 0x98, 0xd3, 0xde, 0xc9, 0xc4, 0xe7, 0xea, 0xfd, 0xf0, 0x6b, 0x66, 0x71, 0x7c, 0x5f, 0x52, 0x45, 0x48, 0x03, 0x0e, 0x19, 0x14, 0x37, 0x3a, 0x2d, 0x20, 0x6d, 0x60, 0x77, 0x7a, 0x59, 0x54, 0x43, 0x4e, 0x05, 0x08, 0x1f, 0x12, 0x31, 0x3c, 0x2b, 0x26, 0xbd, 0xb0, 0xa7, 0xaa, 0x89, 0x84, 0x93, 0x9e, 0xd5, 0xd8, 0xcf, 0xc2, 0xe1, 0xec, 0xfb, 0xf6, 0xd6, 0xdb, 0xcc, 0xc1, 0xe2, 0xef, 0xf8, 0xf5, 0xbe, 0xb3, 0xa4, 0xa9, 0x8a, 0x87, 0x90, 0x9d, 0x06, 0x0b, 0x1c, 0x11, 0x32, 0x3f, 0x28, 0x25, 0x6e, 0x63, 0x74, 0x79, 0x5a, 0x57, 0x40, 0x4d, 0xda, 0xd7, 0xc0, 0xcd, 0xee, 0xe3, 0xf4, 0xf9, 0xb2, 0xbf, 0xa8, 0xa5, 0x86, 0x8b, 0x9c, 0x91, 0x0a, 0x07, 0x10, 0x1d, 0x3e, 0x33, 0x24, 0x29, 0x62, 0x6f, 0x78, 0x75, 0x56, 0x5b, 0x4c, 0x41, 0x61, 0x6c, 0x7b, 0x76, 0x55, 0x58, 0x4f, 0x42, 0x09, 0x04, 0x13, 0x1e, 0x3d, 0x30, 0x27, 0x2a, 0xb1, 0xbc, 0xab, 0xa6, 0x85, 0x88, 0x9f, 0x92, 0xd9, 0xd4, 0xc3, 0xce, 0xed, 0xe0, 0xf7, 0xfa, 0xb7, 0xba, 0xad, 0xa0, 0x83, 0x8e, 0x99, 0x94, 0xdf, 0xd2, 0xc5, 0xc8, 0xeb, 0xe6, 0xf1, 0xfc, 0x67, 0x6a, 0x7d, 0x70, 0x53, 0x5e, 0x49, 0x44, 0x0f, 0x02, 0x15, 0x18, 0x3b, 0x36, 0x21, 0x2c, 0x0c, 0x01, 0x16, 0x1b, 0x38, 0x35, 0x22, 0x2f, 0x64, 0x69, 0x7e, 0x73, 0x50, 0x5d, 0x4a, 0x47, 0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, 0xff, 0xb4, 0xb9, 0xae, 0xa3, 0x80, 0x8d, 0x9a, 0x97] table_14 = [0x00, 0x0e, 0x1c, 0x12, 0x38, 0x36, 0x24, 0x2a, 0x70, 0x7e, 0x6c, 0x62, 0x48, 0x46, 0x54, 0x5a, 0xe0, 0xee, 0xfc, 0xf2, 0xd8, 0xd6, 0xc4, 0xca, 0x90, 0x9e, 0x8c, 0x82, 0xa8, 0xa6, 0xb4, 0xba, 0xdb, 0xd5, 0xc7, 0xc9, 0xe3, 0xed, 0xff, 0xf1, 0xab, 0xa5, 0xb7, 0xb9, 0x93, 0x9d, 0x8f, 0x81, 0x3b, 0x35, 0x27, 0x29, 0x03, 0x0d, 0x1f, 0x11, 0x4b, 0x45, 0x57, 0x59, 0x73, 0x7d, 0x6f, 0x61, 0xad, 0xa3, 0xb1, 0xbf, 0x95, 0x9b, 0x89, 0x87, 0xdd, 0xd3, 0xc1, 0xcf, 0xe5, 0xeb, 0xf9, 0xf7, 0x4d, 0x43, 0x51, 0x5f, 0x75, 0x7b, 0x69, 0x67, 0x3d, 0x33, 0x21, 0x2f, 0x05, 0x0b, 0x19, 0x17, 0x76, 0x78, 0x6a, 0x64, 0x4e, 0x40, 0x52, 0x5c, 0x06, 0x08, 0x1a, 0x14, 0x3e, 0x30, 0x22, 0x2c, 0x96, 0x98, 0x8a, 0x84, 0xae, 0xa0, 0xb2, 0xbc, 0xe6, 0xe8, 0xfa, 0xf4, 0xde, 0xd0, 0xc2, 0xcc, 0x41, 0x4f, 0x5d, 0x53, 0x79, 0x77, 0x65, 0x6b, 0x31, 0x3f, 0x2d, 0x23, 0x09, 0x07, 0x15, 0x1b, 0xa1, 0xaf, 0xbd, 0xb3, 0x99, 0x97, 0x85, 0x8b, 0xd1, 0xdf, 0xcd, 0xc3, 0xe9, 0xe7, 0xf5, 0xfb, 0x9a, 0x94, 0x86, 0x88, 0xa2, 0xac, 0xbe, 0xb0, 0xea, 0xe4, 0xf6, 0xf8, 0xd2, 0xdc, 0xce, 0xc0, 0x7a, 0x74, 0x66, 0x68, 0x42, 0x4c, 0x5e, 0x50, 0x0a, 0x04, 0x16, 0x18, 0x32, 0x3c, 0x2e, 0x20, 0xec, 0xe2, 0xf0, 0xfe, 0xd4, 0xda, 0xc8, 0xc6, 0x9c, 0x92, 0x80, 0x8e, 0xa4, 0xaa, 0xb8, 0xb6, 0x0c, 0x02, 0x10, 0x1e, 0x34, 0x3a, 0x28, 0x26, 0x7c, 0x72, 0x60, 0x6e, 0x44, 0x4a, 0x58, 0x56, 0x37, 0x39, 0x2b, 0x25, 0x0f, 0x01, 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d, 0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d]
1.023438
1
storm/base/pd.py
italiangrid/grinder-load-testsuite
0
12763422
<filename>storm/base/pd.py<gh_stars>0 from common import TestID, log_surl_call_result from eu.emi.security.authn.x509.impl import PEMCredential from exceptions import Exception from jarray import array from java.io import FileInputStream from javax.net.ssl import X509ExtendedKeyManager from net.grinder.plugin.http import HTTPRequest from net.grinder.script import Test from net.grinder.script.Grinder import grinder from org.italiangrid.srm.client import SRMClient, SRMClientFactory import random import traceback error = grinder.logger.error info = grinder.logger.info debug = grinder.logger.debug props = grinder.properties def pd(surls, token, client): debug("Requesting surl(s): %s" % surls) res = client.srmPd(surls, token) log_surl_call_result("pd", res) debug("pd done.") return res class TestRunner: def __call__(self, surls, token, client): if client is None: raise Exception("Please set a non-null SRM client!") test = Test(TestID.PD, "StoRM PD") test.record(pd) try: return pd(surls, token, client) except Exception: error("Error executing pd: %s" % traceback.format_exc()) raise
1.976563
2
json_handling.py
e-diamond/ac-flowers
0
12763423
import json class JSON: @staticmethod def readFromURL(url): import requests print("Downloading data...") response = requests.get(url) return json.loads(response.text) @staticmethod def readFromFile(filename): file = open(filename, "r") data = file.read() file.close() return json.loads(data) @classmethod def url2File(cls, url, filename): data = cls.readFromURL(url) print("Writing to file ", filename, "...") file = open(filename, "w") json.dump(data, file) file.close()
3.390625
3
opyapi/schema/validators/validate_datetime.py
dkraczkowski/opyapi
5
12763424
from datetime import datetime from typing import Optional from opyapi.schema.errors import NotWithinMaximumBoundaryError from opyapi.schema.errors import NotWithinMinimumBoundaryError from opyapi.schema.errors import ValidationError from opyapi.schema.formatters import format_datetime def validate_datetime( value: str, minimum: Optional[datetime] = None, maximum: Optional[datetime] = None ) -> None: try: datetime_value = format_datetime(value) except ValueError: raise ValidationError(f"Passed value {value} is not valid ISO 8601 datetime") if minimum and datetime_value < minimum: raise NotWithinMinimumBoundaryError( f"Passed date `{datetime_value}` is lower than set minimum value `{minimum}`." ) if maximum and datetime_value > maximum: raise NotWithinMaximumBoundaryError( f"Passed date `{datetime_value}` is greater than set maximum value `{maximum}`." ) __all__ = ["validate_datetime"]
3.03125
3
tests/test_parameterized_interface.py
DamonGeorge/Parameterized
0
12763425
import json from enum import Enum import pytest from parameterized import ParameterizedInterface @pytest.fixture def example_enum(): class TestEnum(Enum): ONE = 1 TWO = 2 THREE = 3 return TestEnum class TestParameterizedInterface: def test_abc(self, example_enum): class BadParent(ParameterizedInterface): def __init__(self): pass class BadBadChild(BadParent): def __init__(self): super().__init__() class GoodParent(ParameterizedInterface): _type_enum = example_enum def __init__(self): pass class BadChild(GoodParent): def __init__(self): super().__init__() class GoodChild(GoodParent): _type = example_enum.ONE def __init__(self): super().__init__() with pytest.raises(TypeError): t = BadParent() # pylint:disable=abstract-class-instantiated with pytest.raises(TypeError): t = BadBadChild() # pylint:disable=abstract-class-instantiated with pytest.raises(TypeError): t = BadChild() # pylint:disable=abstract-class-instantiated # this shouldn't error GoodChild()
2.625
3
telegraph/telenote.py
ds19991999/ONote
2
12763426
#!/usr/bin/env python # -*- coding:utf-8 -*- from .api import Telegraph class TeleNote(Telegraph): def __init__(self, access_token=None, reconnect_times=3, my_proxies=None, timeout=5, author_name=None, short_name=None, author_url=None): super().__init__(access_token, reconnect_times, my_proxies, timeout) self.author_name = author_name self.short_name = short_name self.author_url = author_url def create_new_article(self, url_path, content=[{"tag":"p","children":["Hello, world!"]}], return_content=True): response = self.create_page(title=url_path, content=content, author_name=self.author_name, author_url=self.author_url, return_content=return_content) return response["url"] def get_auth_url(self): fields = ["auth_url"] response = self.get_account_info(fields) return response["auth_url"] def create_my_account(self, replace_token=True): response = self.create_account(short_name=self.short_name, author_name=self.author_name, author_url=self.author_url, replace_token=replace_token) return response
2.703125
3
hw_5/util.py
YuguangTong/AY250-hw
0
12763427
<gh_stars>0 from urllib.request import urlopen from bs4 import BeautifulSoup import numpy as np import pandas as pd def is_number(s): """ check if a string represents an integer or float number parameter -------- s: a string return ------ return True iff S represents a number (int or float) """ try: float(s) return True except ValueError: return False def get_daily_data(y, m, d, icao): """ grab daily weather data for an airport from wunderground.com parameter --------- y: year m: month d: day ICAO: ICAO identification number for an airport return ------ a dictionary containing "Min Temperature": daily minimum temperature "Max Temperature": daily maximum temperature "Precipitation": daily precipitation "Max Humidity": daily maximum humidity "Min Humidify": daily minimum humidify """ # construct url from (y, m, d) url = "http://www.wunderground.com/history/airport/" + icao + '/'+\ str(y) + "/" + str(m) + "/" + str(d) + "/DailyHistory.html" page = urlopen(url) # parse html soup = BeautifulSoup(page, 'html5lib') # return dictionary daily_data = {'Min Temperature':'nan', 'Max Temperature':'nan', 'Precipitation':'nan', 'Maximum Humidity':'nan', 'Minimum Humidity':'nan'} # find rows in the main table all_rows = soup.find(id="historyTable").find_all('tr') for row in all_rows: # attempt to find item name try: item_name = row.findAll('td', class_='indent')[0].get_text() except Exception as e: # if run into error, skip this row continue # temperature and precipitation if item_name in ('Min Temperature','Max Temperature', 'Precipitation'): try: val = row.find_all('span', class_='wx-value')[0].get_text() except Exception as e: continue if is_number(val): daily_data[item_name] = val if item_name in ('Maximum Humidity', 'Minimum Humidity'): try: val = row.find_all('td')[1].get_text() except Exception as e: continue if is_number(val): daily_data[item_name] = val return daily_data def write2csv(time_range, icao_list, filename): """ scrape Weather Underground for weather info for airports listed in ICAO_LIST for the period in TIME_RANGE and write data into FILENAME parameter --------- time_range: a timestamp/datetime iterator icao_list: a list of standard 4 character strings representing a list of airports filename: name of the output file return ------ None output to file FILENAME """ f = open(filename, 'w') for date in time_range: for icao in icao_list: y, m, d = date.year, date.month, date.day # get data from Weather Underground daily_data = get_daily_data(y, m, d, icao) min_temp = daily_data['Min Temperature'] max_temp = daily_data['Max Temperature'] min_hum = daily_data['Minimum Humidity'] max_hum = daily_data['Maximum Humidity'] prec = daily_data['Precipitation'] str2write = ','.join([str(date), icao, min_temp, max_temp, \ min_hum, max_hum, prec]) str2write +='\n' # print(str(date), icao) f.write(str2write) # Done getting data! Close file. f.close() def fetch_df(date): """ build a pandas DataFrame holding weather data from a csv file specified by DATE parameter -------- date: pandas DatetimeIndex or python Datetime obj return ------ a DataFrame with the follwing info for 50 cities date, icao, min_temperature, max_temperature, min_humidity, max_humidity, precipitation """ filename = 'hw_5_data/weather_data/' + date.strftime('%Y') + '/'+ \ date.strftime('%Y%m%d')+'.csv' col_names = ('date', 'icao', 'min_temp', 'max_temp', 'min_hum', 'max_hum', 'prec') df = pd.read_csv(filename, header=None, names=col_names) return df def lat_lon_2_distance(lat1, lon1, lat2, lon2): """ return distance (in km) between two locations (lat1, lon1) and (lat2, lon2) parameter --------- lat1, lat2: latitude in degrees lon1, lon2: longitude in degrees return ------ distance in km """ from math import sin, cos, sqrt, atan2, radians # approximate radius of earth in km R = 6373.0 lat1 = radians(lat1) lon1 = radians(lon1) lat2 = radians(lat2) lon2 = radians(lon2) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = R * c return distance #-------------------------------------------------- # # NOT YET FINISHED BELOW # #-------------------------------------------------- def AIO_get_data_from_soup(soup): """ find the weather info from SOUP, a html parsed by the BeautifulSoup - Taken from function get_daily_data(y, m, d, icao) - reimplemented to use together with AsyncIO library to speedup IO parameter --------- soup: a html parsed by the BeautifulSoup return ------ same as get_daily_data """ # return dictionary daily_data = {'Min Temperature':'nan', 'Max Temperature':'nan', 'Precipitation':'nan', 'Maximum Humidity':'nan', 'Minimum Humidity':'nan'} # find rows in the main table all_rows = soup.find(id="historyTable").find_all('tr') for row in all_rows: # attempt to find item name try: item_name = row.findAll('td', class_='indent')[0].get_text() except Exception as e: # if run into error, skip this row continue # temperature and precipitation if item_name in ('Min Temperature','Max Temperature', 'Precipitation'): try: val = row.find_all('span', class_='wx-value')[0].get_text() except Exception as e: continue if is_number(val): daily_data[item_name] = val if item_name in ('Maximum Humidity', 'Minimum Humidity'): try: val = row.find_all('td')[1].get_text() except Exception as e: continue if is_number(val): daily_data[item_name] = val return daily_data
3.546875
4
python/convergdb/athena.py
ray-pan-bci/convergdb
10
12763428
from convergdb_logging import * from batch_control import * from athena import * from cloudwatch import * from glue import * from s3 import * from sns import * from spark_partitions import * from spark import * from state import * from string import Template def initiate_athena_query(query, database, s3_output, region, retries=3): for retry in range(0, retries): try: convergdb_log("asynchronously executing: " + query + " on database " + database + " to " + s3_output) client = boto3.client('athena', region_name = region) response = client.start_query_execution( QueryString=query, QueryExecutionContext={ 'Database': database }, ResultConfiguration={ 'OutputLocation': s3_output, } ) convergdb_log('Execution ID: ' + response['QueryExecutionId']) return response['QueryExecutionId'] except: convergdb_log("query failed") if retry == retries - 1: raise convergdb_log("retrying...") def wait_for_athena_query_execution(execution_id, region, retries = 3): client = boto3.client('athena', region_name = region) st = time.time() for retry in range(0,retries): try: while True: check = client.get_query_execution( QueryExecutionId = execution_id ) time.sleep(0.125) if check["QueryExecution"]["Status"]["State"] in ['SUCCEEDED','FAILED','CANCELLED']: if check["QueryExecution"]["Status"]["State"] == 'SUCCEEDED': break else: raise Exception("query for execution_id: " + execution_id + " failed") else: convergdb_log("still executing: " + execution_id) et = time.time() convergdb_log("query execution_id " + execution_id + " took " + str(et - st) +" seconds") return execution_id except: convergdb_log("query failed") if retry == retries - 1: raise convergdb_log("retrying...") def run_athena_query(query, database, s3_output, region, retries=3): return wait_for_athena_query_execution( initiate_athena_query( query, database, s3_output, region, retries ), region, retries ) def run_athena_query_async(query, database, s3_output, region, retries=3): initiate_athena_query( query, database, s3_output, region, retries ) def column_headers(response): headers = [] for col in response["ResultSet"]["ResultSetMetadata"]["ColumnInfo"]: d = {} d["name"] = col["Name"] d["type"] = col["Type"] headers.append(d) return headers def control_query_row_to_dict(row, headers): d = {} for i in range(len(headers)): this_field = headers[i]["name"] this_value = row["Data"][i]["VarCharValue"] if this_field == 'size': # header row will have value matching field name if this_value != 'size': d[this_field] = int(this_value) else: # handling for header row d[this_field] = this_value else: # otherwise return varchar value unchanged d[this_field] = this_value return d def row_to_dict(row, headers): d = {} for i in range(len(headers)): d[headers[i]["name"]] = row["Data"][i]["VarCharValue"] return d def athena_results_to_list(execution_id, region, dict_transform_function=row_to_dict): st = time.time() ret = [] client = boto3.client('athena', region_name = region) paginator = client.get_paginator('get_query_results') page_iterator = paginator.paginate( QueryExecutionId = execution_id ) for page in page_iterator: convergdb_log("next page") headers = column_headers(page) for row in page["ResultSet"]["Rows"]: ret.append(dict_transform_function(row, headers)) # the first row is coming back with the header... unacceptable! et = time.time() convergdb_log("query results gathering took " + str(et - st) +" seconds") return ret[1:len(ret)] def athena_query_to_list(query, database, s3_location, region, dict_transform_function=row_to_dict): id = run_athena_query( query, database, s3_location, region ) return athena_results_to_list( id, region, dict_transform_function ) def athena_results_csv_s3_path(execution_id, region): client = boto3.client('athena', region_name = region) resp = client.get_query_execution( QueryExecutionId = execution_id ) output = resp["QueryExecution"]["ResultConfiguration"]["OutputLocation"] return { 'bucket': output[5:len(output)].split('/',1)[0], 'key': output[5:len(output)].split('/',1)[1] } def tmp_results_location(structure): return "s3://" + structure["script_bucket"] + "/" + structure["deployment_id"] + "/tmp/" def athena_database_name(full_relation_name): return ('__').join(full_relation_name.split('.')[0:3]) def athena_table_name(full_relation_name): return full_relation_name.split('.')[3] def athena_describe_table(database, table, region): client = boto3.client('glue', region_name = region) t = client.get_table( DatabaseName = database, Name = table ) return t # expects a list for attributes as returned from get-table API def has_attribute(attributes, attribute_name): for a in attributes: if a['Name'] == attribute_name: return True return False # !PARTITIONS def msck_repair_table_async_params(structure): return [ "msck repair table " + athena_table_name(structure["full_relation_name"]), athena_database_name(structure["full_relation_name"]), tmp_results_location(structure), structure["region"] ] def msck_repair_table(structure): run_athena_query_async( "msck repair table " + athena_table_name(structure["full_relation_name"]), athena_database_name(structure["full_relation_name"]), tmp_results_location(structure), structure["region"] )
1.882813
2
Arase/MEPe/CalculatePADs.py
mattkjames7/Arase
0
12763429
<gh_stars>0 import numpy as np from .Read3D import Read3D from .GetPitchAngle import GetPitchAngle import DateTimeTools as TT import DateTimeTools as TT from scipy.stats import binned_statistic def CalculatePADs(Date,na=18,Verbose=True): ''' Calculates a pitch angle distribution of the differential energy flux data using the level 2 3dflux data. WARNING: This may not be exactly the same as level 3 data, also some level 2 data is missing the instrument orientation data required Inputs ====== Date : int Date to alcualte PAD for na : int Number of alpha (pitch angle) bins to create in the range 0 to 180 degrees Verbose: bool Display progress Returns ======= out : dict Contains a dict for each species ''' #this is the output dictionary out = {} #read the 3D data in data,meta = Read3D(Date) #calculate alpha alpha = GetPitchAngle(Date,data=data) #determine the size of the output arrays nt = data['Epoch'].size ne = data['FEDU_Energy'].size #get the dates/times Date,ut = TT.CDFEpochtoDate(data['epoch']) utc = TT.ContUT(Date,ut) #get the energy arrays (shape: (nt,ne)) Emid = data['FEDU_Energy'] lE = np.log10(Emid) dE = np.abs(lE[1:] - lE[:-1]) lEmin = np.append(lE[0]-dE[0]/2.0,lE[1:]-dE/2.0) lEmax = np.append(lE[:-1]+dE/2.0,lE[-1]+dE[-1]/2.0,) EMin = 10**lEmin EMax = 10**lEmax #get the alpha limits Alpha = np.linspace(0.0,180.0,na+1) #create 3D array for fluxes flux = np.zeros((nt,ne,na),dtype='float32') + np.nan #loop through each dimension (slow!) FLUX = data['FEDU'] bad = np.where(FLUX <= 0) FLUX[bad] = np.nan for i in range(0,nt): if Verbose: print('\r{:6.2f}%'.format(100.0*(i+1)/nt),end='') for j in range(0,ne): a = alpha[i].flatten() f = FLUX[i,:,j].flatten() good = np.where(np.isfinite(f))[0] if good.size > 0: flux[i,j],_,_ = binned_statistic(a[good],f[good],statistic='mean',bins=Alpha) if Verbose: print() tmp = {} tmp['Date'] = Date tmp['ut'] = ut tmp['utc'] = utc tmp['Emin'] = EMin tmp['Emax'] = EMax tmp['Alpha'] = Alpha tmp['Flux'] = flux out['eFlux'] = tmp return out
2.28125
2
2021/day_10/solution.py
krother/advent_of_code
3
12763430
<reponame>krother/advent_of_code<gh_stars>1-10 """ Syntax Scoring https://adventofcode.com/2021/day/10 """ MATCHES = { '<': '>', '(': ')', '{': '}', '[': ']' } ERROR_SCORE = { ')': 3, ']': 57, '}': 1197, '>': 25137, } AUTOCOMPLETE_SCORE = { ')': 1, ']': 2, '}': 3, '>': 4, } def find_error(line): """returns error score and remaining stack""" stack = [] for char in line: if char in '[({<': stack.append(char) else: m = stack.pop() match = MATCHES[m] if char != match: return ERROR_SCORE[char], [] return 0, stack def autocomplete(stack): prod = 0 for char in stack[::-1]: prod *= 5 prod += AUTOCOMPLETE_SCORE[MATCHES[char]] return prod def solve(data): total = 0 for line in data.strip().split('\n'): score, _ = find_error(line) total += score return total def solve2(data): autos = [] for line in data.strip().split('\n'): score, stack = find_error(line) if score == 0: autos.append(autocomplete(stack)) autos.sort() middle = len(autos) // 2 return autos[middle] if __name__ == '__main__': input_data = open('input_data.txt').read() result = solve(input_data) print(f'Example 1: {result}') # 268845 result = solve2(input_data) print(f'Example 2: {result}') # 4038824534
3.375
3
SLpackage/private/pacbio/pythonpkgs/pypeflow/lib/python2.7/site-packages/pypeflow/do_task.py
fanglab/6mASCOPE
5
12763431
#! python2.7 from . import do_support, util from .io import fix_relative_symlinks import argparse import copy import importlib import inspect import json import logging import os import pprint import re import string import sys import time from pipes import quote # shlex in python3.3+ DONE = 'done' STATUS = 'status' TIMEOUT = 30 LOG = logging.getLogger() DESCRIPTION = """Given a JSON description, call a python-function. """ EPILOG = """ The JSON looks like this: { "inputs": {"input-name": "filename"}, "outputs": {"output-name": "output-filename (relative)"}, "bash_template_fn": "template.sh", "parameters": {} } This program will run on the work host, and it will do several things: - Run in CWD. - Verify that inputs are available. (Wait til timeout if not.) - Possibly, cd to tmpdir and create symlinks from inputs. - Run the python-function. - Its module must be available (e.g. in PYTHONPATH). - Pass a kwd-dict of the union of inputs/outputs/parameters. - Ignore return-value. Expect exceptions. - Possibly, mv outputs from tmpdir to workdir. - Write exit-code into STATUS. - Touch DONE on success. """ """ (Someday, we might also support runnable Python modules, or even executables via execvp().) Note: qsub will *not* run this directly. There is a higher layer. """ def get_parser(): class _Formatter(argparse.RawDescriptionHelpFormatter, argparse.ArgumentDefaultsHelpFormatter): pass parser = argparse.ArgumentParser(description=DESCRIPTION, epilog=EPILOG, formatter_class=_Formatter, ) parser.add_argument('--timeout', type=int, default=TIMEOUT, help='How many seconds to wait for input files (and JSON) to exist. (default: %(default)s') parser.add_argument('--tmpdir', help='Root directory to run in. (Sub-dir name will be based on CWD.)') parser.add_argument('json_fn', help='JSON file, as per epilog.') return parser def wait_for(fn, timeout=None): if timeout is None: global TIMEOUT timeout = copy.copy(TIMEOUT) # just to be clear try: _wait_for(fn, timeout) except BaseException: LOG.exception('Was waiting for {!r}'.format(fn)) raise def _wait_for(fn, timeout): LOG.debug('Checking existence of {!r} with timeout={}'.format(fn, timeout)) dirname = os.path.dirname(fn) if os.path.exists(dirname): if not os.access(dirname, os.X_OK): raise Exception('Cannot x into dir {!r}'.format(dirname)) while not os.path.exists(fn): if timeout > 0: time.sleep(1) timeout -= 1 else: raise Exception('Timed out waiting for {!r}'.format(fn)) assert os.access(fn, os.R_OK), '{!r} not readable'.format(fn) def get_func(python_function): mod_name, func_name = os.path.splitext(python_function) func_name = func_name[1:] # skip dot mod = importlib.import_module(mod_name) func = getattr(mod, func_name) return func class OldTaskRunner(object): def __init__(self, inputs, outputs, parameters): for k,v in (inputs.items() + outputs.items()): setattr(self, k, v) self.parameters = parameters self.inputs = inputs self.outputs = outputs def run_python_func(func, inputs, outputs, parameters): if False: kwds = dict() kwds.update(inputs) kwds.update(outputs) kwds.update(parameters) func(**kwds) else: # old way, for now cwd = os.getcwd() parameters['cwd'] = cwd self = OldTaskRunner(inputs, outputs, parameters) func(self=self) script_fn = getattr(self, 'generated_script_fn', None) if script_fn is not None: do_support.run_bash(script_fn) def run_python(python_function_name, myinputs, myoutputs, parameters): func = get_func(python_function_name) try: run_python_func(func, myinputs, myoutputs, parameters) except TypeError: # Report the actual function spec. LOG.error('For function "{}", {}'.format(python_function_name, inspect.getargspec(func))) raise class Attrs(object): """This facilitates substitution of values in string. """ def __str__(self): # For this, all values must be strings. return ' '.join(f for f in self.kwds.values()) def __getattr__(self, name): # For this, values can be string, int, float, etc. if '*' in name: re_star = re.compile('^' + name.replace('*', '.*') + '$') result = (v for (k,v) in self.kwds.iteritems() if re_star.search(k)) elif 'ALL' == name: result = self.kwds.itervalues() else: result = [str(self.kwds[name])] return ' '.join(self.quote(v) for v in sorted(result)) def __init__(self, kwds, quote=quote): self.kwds = kwds self.quote = quote def sub(bash_template, myinputs, myoutputs, parameters): # Set substitution dict var_dict = dict() valid_parameters = {k:v for k,v in parameters.iteritems() if not k.startswith('_')} assert 'input' not in parameters assert 'output' not in parameters # input/output/params are the main values substituted in the subset of # snakemake which we support. var_dict['input'] = Attrs(myinputs) var_dict['output'] = Attrs(myoutputs) var_dict['params'] = Attrs(valid_parameters, quote=lambda x:x) fmtr = string.Formatter() return fmtr.vformat(bash_template, [], var_dict) def run_bash(bash_template, myinputs, myoutputs, parameters): # Like snakemake, we use bash "strict mode", but we add -vx. # http://redsymbol.net/articles/unofficial-bash-strict-mode/ prefix = """ IFS=$'\n\t' set -vxeuo pipefail hostname pwd date """ # Substitute try: task_lines = sub(bash_template, myinputs, myoutputs, parameters) except Exception: msg = """\ Failed to substitute var_dict inputs: {} outputs: {} parameters: {} into bash script: {} Possibly you forgot to use "input.foo" "output.bar" "params.fubar" etc. in your script? """.format(myinputs, myoutputs, parameters, bash_template) LOG.error(msg) raise postfix = """ date """ # Combine bash_content = prefix + task_lines + postfix # Write user_script.sh bash_fn = 'user_script.sh' with open(bash_fn, 'w') as ofs: ofs.write(bash_content) cmd = '/bin/bash {}'.format(bash_fn) util.system(cmd) def run_cfg_in_tmpdir(cfg, tmpdir, relpath): """ Accept 'inputs', 'outputs', 'parameters' in cfg. Relativize 'inputs' relative to relpath, unless running in tmpdir. ('outputs' are always relative to rundir.) If 'bash_template_fn' in cfg, then substitute and use it. """ inputs = cfg['inputs'] outputs = cfg['outputs'] parameters = cfg['parameters'] bash_template_fn = cfg['bash_template_fn'] for k,v in inputs.items(): if not os.path.isabs(v): inputs[k] = os.path.normpath(os.path.join(relpath, v)) if tmpdir: inputs[k] = os.path.abspath(inputs[k]) for fn in inputs.values(): wait_for(fn) wait_for(bash_template_fn) bash_template = open(bash_template_fn).read() myinputs = dict(inputs) myoutputs = dict(outputs) finaloutdir = os.getcwd() if tmpdir: import getpass user = getpass.getuser() pid = os.getpid() myrundir = '{tmpdir}/{user}/pypetmp/{finaloutdir}'.format(**locals()) util.rmdirs(myrundir) util.mkdirs(myrundir) # TODO(CD): Copy inputs w/ flock. else: myrundir = finaloutdir with util.cd(myrundir): if tmpdir: # Check again, in case we have the paths wrong. for fn in inputs.values(): wait_for(fn, 0) # TODO(CD): Write a script in wdir even when running in tmpdir (so we can see it on error). run_bash(bash_template, myinputs, myoutputs, parameters) if tmpdir: """ for k,v in outputs.iteritems(): cmd = 'mv -f {} {}'.format( os.path.join(myrundir, v), os.path.join(finaloutdir, v)) util.system(cmd) """ cmd = 'rsync -av {}/ {}; rm -rf {}'.format(myrundir, finaloutdir, myrundir) util.system(cmd) fix_relative_symlinks(finaloutdir, myrundir, recursive=True) for fn in cfg['outputs'].values(): wait_for(fn) def run(json_fn, timeout, tmpdir): if isinstance(timeout, int): global TIMEOUT TIMEOUT = timeout wait_for(json_fn) LOG.debug('Loading JSON from {!r}'.format(json_fn)) cfg = json.loads(open(json_fn).read()) LOG.debug(pprint.pformat(cfg)) rundir = os.path.normpath(os.path.dirname(json_fn)) with util.cd(rundir): run_cfg_in_tmpdir(cfg, tmpdir, '.') def main(): parser = get_parser() parsed_args = parser.parse_args(sys.argv[1:]) try: run(**vars(parsed_args)) except Exception: LOG.critical('Error in {} with args={!r}'.format(sys.argv[0], pprint.pformat(vars(parsed_args)))) raise if __name__ == "__main__": do_support.setup_simple_logging(**os.environ) LOG.debug('Running "{}"'.format(' '.join(sys.argv))) main()
2.5625
3
src/comparators/compare_functions/__init__.py
asd249180/similarity_and_matching
0
12763432
<gh_stars>0 from src.comparators.compare_functions.cka import cka from src.comparators.compare_functions.cca import cca from src.comparators.compare_functions.l2 import l2 from src.comparators.compare_functions.ps_inv import ps_inv from src.comparators.compare_functions.correlation import correlation from src.comparators.compare_functions.sq_sum import sq_sum from src.comparators.compare_functions.lr import lr from src.comparators.compare_functions.tsne import tsne from src.comparators.compare_functions.ls_orth import ls_orth from src.comparators.compare_functions.r2 import r2 from src.comparators.compare_functions.ls_sum import ls_sum from src.comparators.compare_functions.cka_torch import cka as cka_torch from src.comparators.compare_functions.lr_torch import lr as lr_torch def get_comparator_function(str_comparator): str_comparator = str_comparator.lower() dispatcher = { 'cka' : cka, 'cca' : cca, 'l2' : l2, 'ps_inv' : ps_inv, 'ls_orth' : ls_orth, 'corr' : correlation, 'sq_sum' : sq_sum, 'lr' : lr, 'r2' : r2, 'ls_sum' : ls_sum, 'lr_torch' : lr_torch, 'cka_torch' : cka_torch, } if str_comparator not in dispatcher: raise ValueError('{} is unknown comparator.'.format(str_comparator)) return dispatcher[str_comparator]
2.265625
2
lab_manager/urls.py
FlorianJa/Lab-Manager
0
12763433
<reponame>FlorianJa/Lab-Manager<filename>lab_manager/urls.py<gh_stars>0 from django.conf.urls import url from lab_manager import views app_name = 'lab_manager' urlpatterns = [ url(r'^api/printers$', views.fablab_printers), url(r'^api/printers/(?P<pk>[0-9]+)$', views.fablab_printers_detail), url(r'^api/filament/(?P<slug>[\w-]+)$', views.filament_usage_default), url(r'^api/filament$', views.filament_usage), url(r'^api/user$', views.user), url(r'^api/user/(?P<slug>[\w-]+)$', views.user_detail), url(r'^api/operating/(?P<pk>[0-9]+)$', views.operating_usage_default), url(r'^api/maintenance/(?P<pk>[0-9]+)$', views.maintenance), url(r'^api/printer/(?P<pk>[0-9]+)$', views.printer_usage_default), url(r'^api/usage$', views.usage), url(r'^api/usage/(?P<pk>[0-9]+)$', views.usage_detail) ]
1.773438
2
tests/test_beatmap.py
Vergenter/OsuPyParser
0
12763434
<reponame>Vergenter/OsuPyParser from osupyparser import OsuFile import time import unittest class TestBeatmap(unittest.TestCase): def test_basic_functionality(self): start = time.perf_counter() data = OsuFile("tests//testv2.osu").parse_file() end = time.perf_counter() self.assertTrue(data.__dict__) info = data.__dict__ for d, e in info.items(): print(f"{d}: {e}") print(f"Parsed in {round((end - start) * 1000, 2)}ms") def test_nested_tag(self): data = OsuFile("tests//testVersionInTag.osu").parse_file() self.assertTrue(data.__dict__) def test_utf8_BOM(self): data = OsuFile("tests//testLazerUTF8BOM.osu").parse_file() self.assertTrue(data.__dict__) if __name__ == '__main__': unittest.main()
2.671875
3
silx/opencl/test/test_sparse.py
physwkim/silx
2
12763435
<filename>silx/opencl/test/test_sparse.py #!/usr/bin/env python # coding: utf-8 # /*########################################################################## # # Copyright (c) 2018-2019 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # ###########################################################################*/ """Test of the sparse module""" import numpy as np import unittest import logging from itertools import product from ..common import ocl if ocl: import pyopencl.array as parray from silx.opencl.sparse import CSR try: import scipy.sparse as sp except ImportError: sp = None logger = logging.getLogger(__name__) def generate_sparse_random_data( shape=(1000,), data_min=0, data_max=100, density=0.1, use_only_integers=True, dtype="f"): """ Generate random sparse data where. Parameters ------------ shape: tuple Output data shape. data_min: int or float Minimum value of data data_max: int or float Maximum value of data density: float Density of non-zero elements in the output data. Low value of density mean low number of non-zero elements. use_only_integers: bool If set to True, the output data items will be primarily integers, possibly casted to float if dtype is a floating-point type. This can be used for ease of debugging. dtype: str or numpy.dtype Output data type """ mask = np.random.binomial(1, density, size=shape) if use_only_integers: d = np.random.randint(data_min, high=data_max, size=shape) else: d = data_min + (data_max - data_min) * np.random.rand(*shape) return (d * mask).astype(dtype) @unittest.skipUnless(ocl and sp, "PyOpenCl/scipy is missing") class TestCSR(unittest.TestCase): """Test CSR format""" def setUp(self): # Test possible configurations input_on_device = [False, True] output_on_device = [False, True] dtypes = [np.float32, np.int32, np.uint16] self._test_configs = list(product(input_on_device, output_on_device, dtypes)) def compute_ref_sparsification(self, array): ref_sparse = sp.csr_matrix(array) return ref_sparse def test_sparsification(self): for input_on_device, output_on_device, dtype in self._test_configs: self._test_sparsification(input_on_device, output_on_device, dtype) def _test_sparsification(self, input_on_device, output_on_device, dtype): current_config = "input on device: %s, output on device: %s, dtype: %s" % ( str(input_on_device), str(output_on_device), str(dtype) ) logger.debug("CSR: %s" % current_config) # Generate data and reference CSR array = generate_sparse_random_data(shape=(512, 511), dtype=dtype) ref_sparse = self.compute_ref_sparsification(array) # Sparsify on device csr = CSR(array.shape, dtype=dtype) if input_on_device: # The array has to be flattened arr = parray.to_device(csr.queue, array.ravel()) else: arr = array if output_on_device: d_data = parray.empty_like(csr.data) d_indices = parray.empty_like(csr.indices) d_indptr = parray.empty_like(csr.indptr) d_data.fill(0) d_indices.fill(0) d_indptr.fill(0) output = (d_data, d_indices, d_indptr) else: output = None data, indices, indptr = csr.sparsify(arr, output=output) if output_on_device: data = data.get() indices = indices.get() indptr = indptr.get() # Compare nnz = ref_sparse.nnz self.assertTrue( np.allclose(data[:nnz], ref_sparse.data), "something wrong with sparsified data (%s)" % current_config ) self.assertTrue( np.allclose(indices[:nnz], ref_sparse.indices), "something wrong with sparsified indices (%s)" % current_config ) self.assertTrue( np.allclose(indptr, ref_sparse.indptr), "something wrong with sparsified indices pointers (indptr) (%s)" % current_config ) def test_desparsification(self): for input_on_device, output_on_device, dtype in self._test_configs: self._test_desparsification(input_on_device, output_on_device, dtype) def _test_desparsification(self, input_on_device, output_on_device, dtype): current_config = "input on device: %s, output on device: %s, dtype: %s" % ( str(input_on_device), str(output_on_device), str(dtype) ) logger.debug("CSR: %s" % current_config) # Generate data and reference CSR array = generate_sparse_random_data(shape=(512, 511), dtype=dtype) ref_sparse = self.compute_ref_sparsification(array) # De-sparsify on device csr = CSR(array.shape, dtype=dtype, max_nnz=ref_sparse.nnz) if input_on_device: data = parray.to_device(csr.queue, ref_sparse.data) indices = parray.to_device(csr.queue, ref_sparse.indices) indptr = parray.to_device(csr.queue, ref_sparse.indptr) else: data = ref_sparse.data indices = ref_sparse.indices indptr = ref_sparse.indptr if output_on_device: d_arr = parray.empty_like(csr.array) d_arr.fill(0) output = d_arr else: output = None arr = csr.densify(data, indices, indptr, output=output) if output_on_device: arr = arr.get() # Compare self.assertTrue( np.allclose(arr.reshape(array.shape), array), "something wrong with densified data (%s)" % current_config ) def suite(): suite = unittest.TestSuite() suite.addTest( unittest.defaultTestLoader.loadTestsFromTestCase(TestCSR) ) return suite if __name__ == '__main__': unittest.main(defaultTest="suite")
1.578125
2
fiat/metric.py
chamhoo/Severstal
0
12763436
<filename>fiat/metric.py """ auther: leechh metric - large is better """ import tensorflow as tf def dice(): def metric(y_true, y_pred): smooth = 1e-8 y_true = tf.keras.backend.flatten(y_true) y_pred = tf.keras.backend.flatten(y_pred) intersection = tf.reduce_sum(tf.multiply(y_true, y_pred)) union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred) return ((2 * intersection) + smooth) / (union + smooth) return metric def mean_dice(axis=[1, 2]): def metric(y_true, y_pred): smooth = 1e-8 intersection = tf.reduce_sum(tf.multiply(y_true, y_pred), axis=axis) union = tf.reduce_sum(y_true, axis=axis) + tf.reduce_sum(y_pred, axis=axis) return tf.reduce_mean(((2 * intersection) + smooth) / (union + smooth)) return metric def metricfromname(metric_name, y_true, y_pred): # y_*: [batch, height, width, num_class] # dice if metric_name == 'dice': return dice()(y_true, y_pred) if metric_name == 'mean_dice': return mean_dice()(y_true, y_pred) else: assert False, 'metric function ISNOT exist'
2.515625
3
module/output_block.py
sc0ttms/SE-TFCN
9
12763437
<gh_stars>1-10 # -*- coding: utf-8 -*- import torch import torch.nn as nn from torchinfo import summary class OutputBlock(nn.Module): def __init__(self, num_channels): super().__init__() self.num_channels = num_channels self.net = nn.Sequential(nn.Conv2d(self.num_channels[0], self.num_channels[1], kernel_size=1), nn.PReLU()) def forward(self, inputs): # inputs [B, C, F, T] -> outputs [B, 1, F, T] outputs = self.net(inputs) return outputs if __name__ == "__main__": print(f"Test OutputBlock Module Start...") # get model model = OutputBlock([16, 1]) # get inputs inputs = torch.randn([2, 16, 256, 201]) # print network summary(model, input_size=inputs.shape) # forward outputs = model(inputs) print(f"Test OutputBlock Module End...") pass
3.03125
3
local_server/esconector.py
IoT-Vigilant/iotvigilant-cybercamp-2018
2
12763438
<filename>local_server/esconector.py #!/usr/bin/python3 """ ########################################### # IoT Vigilant Orchestrator ########################################### """ from elasticsearch import Elasticsearch import time es_host = "localhost" es_port = 9200 es_index = "rawdata" es_index_ml = "mloutput" es_doc_type = "ts" es = Elasticsearch([{'host': es_host, 'port': es_port}]) def get_n_packets(interval): interval = 60000 * interval queryUniqueMacs = { "query":{ "bool":{ "must":{ "range":{ "@timestamp":{ "gte":int(round(time.time() * 1000)) - interval, # ini date "lte":int(round(time.time() * 1000)), # end date "format":"epoch_millis" } } } } }, "aggs":{ "by_mac":{ "terms":{ "field":"MacOrigen" } } } } response = es.search(index = es_index, doc_type=es_doc_type, size='100', body = queryUniqueMacs) lista = response['aggregations']['by_mac']['buckets'] result_macs = [] results = [] for l in lista: result_macs.append( str(l['key'])) results.append(str(l['doc_count'])) return [result_macs,results] def get_metric_by_mac(interval,metric): interval = interval * 60000 queryUniqueMacs = { "query":{ "bool":{ "must":{ "range":{ "@timestamp":{ "gte":int(round(time.time() * 1000)) - interval, # ini date "lte":int(round(time.time() * 1000)), # end date "format":"epoch_millis" } } } } }, "aggs":{ "by_mac":{ "terms":{ "field":"MacOrigen" }, "aggs":{ "count_diff":{ "cardinality":{ "field":metric, }, } } } } } response = es.search(index = es_index, doc_type=es_doc_type, size='100', body = queryUniqueMacs) lista = response['aggregations']['by_mac']['buckets'] result_macs = [] results = [] for l in lista: result_macs.append( str(l['key'])) results.append(str(l['count_diff']['value'])) return [result_macs,results] def get_metrics(interval): macs = get_metric_by_mac(interval, "IpOrigen")[0] diff_srcips = get_metric_by_mac(interval, "IpOrigen")[1] diff_dstips = (get_metric_by_mac(interval, "IpDestino"))[1] diff_srcports = (get_metric_by_mac(interval, "PuertoOrigen"))[1] diff_dstports = (get_metric_by_mac(interval, "PuertoDestino"))[1] diff_layers = (get_metric_by_mac(interval, "layers"))[1] n_packets = (get_n_packets(interval))[1] return [macs,n_packets,diff_srcips,diff_dstips,diff_srcports,diff_dstports,diff_layers] def load_data(maclist,data,prob): for k,m in enumerate(maclist): body = { "@timestamp": int(round(time.time() * 1000)), "mac":m, "n_packets": data[k][0], "diff_srcips": data[k][1], "diff_dstips": data[k][2], "diff_srcports": data[k][3], "diff_dstports": data[k][4], "diff_layers": data[k][5], } if prob: body['prob'] = prob[k] response = es.index(index = es_index_ml, doc_type=es_doc_type, body = body) def get_bulk_pro_data(n): #gmm_model_size macs = [] n_packets = [] diff_srcips = [] diff_dstips = [] diff_srcports = [] diff_dstports = [] diff_layers = [] body = { "query": { "match_all": {} } } body_n = { "query":{ "bool":{ "must":{ "range":{ "@timestamp":{ "gte":int(round(time.time() * 1000)) - (n * 60000), # ini date "lte":int(round(time.time() * 1000)), # end date "format":"epoch_millis" } } } } } } result = es.search(index = es_index_ml, size = n,doc_type=es_doc_type, body = body_n)['hits']['hits'] for document in result: macs.append(document['_source']['mac']) n_packets.append(document['_source']['n_packets']) diff_srcips.append(document['_source']['diff_srcips']) diff_dstips.append(document['_source']['diff_dstips']) diff_srcports.append(document['_source']['diff_srcports']) diff_dstports.append(document['_source']['diff_dstports']) diff_layers.append(document['_source']['diff_layers']) return [macs,n_packets,diff_srcips,diff_dstips,diff_srcports,diff_dstports,diff_layers]
2.125
2
corehq/ex-submodules/couchforms/const.py
dimagilg/commcare-hq
471
12763439
TAG_TYPE = "#type" TAG_XML = "#xml" TAG_VERSION = "@version" TAG_UIVERSION = "@uiVersion" TAG_NAMESPACE = "@xmlns" TAG_NAME = "@name" TAG_META = "meta" TAG_FORM = 'form' ATTACHMENT_NAME = "form.xml" MAGIC_PROPERTY = 'xml_submission_file' RESERVED_WORDS = [TAG_TYPE, TAG_XML, TAG_VERSION, TAG_UIVERSION, TAG_NAMESPACE, TAG_NAME, TAG_META, ATTACHMENT_NAME, 'case', MAGIC_PROPERTY] DEVICE_LOG_XMLNS = 'http://code.javarosa.org/devicereport'
1.039063
1
rlschool/metamaze/test.py
HaojieSHI98/RLSchool
169
12763440
import gym import sys import rlschool.metamaze def test_2d_maze(max_iteration): print("Testing 2D Maze...") maze_env = gym.make("meta-maze-2D-v0", enable_render=False) cell_scale = 9 task = maze_env.sample_task(cell_scale=cell_scale) maze_env.set_task(task) iteration = 0 while iteration < max_iteration: iteration += 1 maze_env.reset() done=False sum_reward = 0 while not done: state, reward, done, _ = maze_env.step(maze_env.action_space.sample()) sum_reward += reward print("Episode is over! You got %.1f score."%sum_reward) if(sum_reward > 0.0): cell_scale += 2 # gradually increase the difficulty print("Increase the difficulty, cell_scale = %d"%cell_scale) task = maze_env.sample_task(cell_scale=cell_scale) maze_env.set_task(task) def test_3d_maze(max_iteration): print("Testing 3D Maze...") maze_env = gym.make("meta-maze-3D-v0", enable_render=False) cell_scale = 9 task = maze_env.sample_task(cell_scale=cell_scale, cell_size=2.0, wall_height=3.2) maze_env.set_task(task) iteration = 0 while iteration < max_iteration: iteration += 1 maze_env.reset() done=False sum_reward = 0 while not done: state, reward, done, _ = maze_env.step(maze_env.action_space.sample()) sum_reward += reward print("Episode is over! You got %.1f score."%sum_reward) if(sum_reward > 0.0): cell_scale += 2 # gradually increase the difficulty print("Increase the difficulty, cell_scale = %d"%cell_scale) task = maze_env.sample_task(cell_scale=cell_scale, cell_size=2.0, wall_height=3.2) maze_env.set_task(task) if __name__=="__main__": test_2d_maze(100) test_3d_maze(100)
3.53125
4
code/default/x_tunnel/local/heroku_front/host_manager.py
wuyongwen/XX-Net
0
12763441
import random import time from front_base.host_manager import HostManagerBase class HostManager(HostManagerBase): def __init__(self, logger, appids=[]): self.logger = logger self.appids = appids def set_appids(self, appids): self.appids = appids def get_sni_host(self, ip): if len(self.appids) == 0: self.logger.warn("no appid left") time.sleep(1) raise Exception("no appid left") return "", random.choice(self.appids) def remove(self, appid): try: self.appids.remove(appid) except: pass
2.421875
2
astropy/cosmology/__init__.py
jvictor42/astropy
0
12763442
<filename>astropy/cosmology/__init__.py<gh_stars>0 # Licensed under a 3-clause BSD style license - see LICENSE.rst """ astropy.cosmology contains classes and functions for cosmological distance measures and other cosmology-related calculations. See the `Astropy documentation <https://docs.astropy.org/en/latest/cosmology/index.html>`_ for more detailed usage examples and references. """ from . import core, flrw, funcs, units, utils from . import io # needed before 'realizations' # isort: split from . import realizations from .core import * from .flrw import * from .funcs import * from .realizations import * from .utils import * __all__ = (core.__all__ + flrw.__all__ # cosmology classes + realizations.__all__ # instances thereof + funcs.__all__ + utils.__all__) # utils
1.640625
2
lib/matplotlib/testing/compare.py
stefanv/matplotlib
1
12763443
<filename>lib/matplotlib/testing/compare.py #======================================================================= """ A set of utilities for comparing results. """ #======================================================================= import matplotlib from matplotlib.testing.noseclasses import ImageComparisonFailure import math import operator import os import numpy as np import shutil import subprocess import sys #======================================================================= __all__ = [ 'compare_float', 'compare_images', 'comparable_formats', ] #----------------------------------------------------------------------- def compare_float( expected, actual, relTol = None, absTol = None ): """Fail if the floating point values are not close enough, with the givem message. You can specify a relative tolerance, absolute tolerance, or both. """ if relTol is None and absTol is None: exMsg = "You haven't specified a 'relTol' relative tolerance " exMsg += "or a 'absTol' absolute tolerance function argument. " exMsg += "You must specify one." raise ValueError, exMsg msg = "" if absTol is not None: absDiff = abs( expected - actual ) if absTol < absDiff: expectedStr = str( expected ) actualStr = str( actual ) absDiffStr = str( absDiff ) absTolStr = str( absTol ) msg += "\n" msg += " Expected: " + expectedStr + "\n" msg += " Actual: " + actualStr + "\n" msg += " Abs Diff: " + absDiffStr + "\n" msg += " Abs Tol: " + absTolStr + "\n" if relTol is not None: # The relative difference of the two values. If the expected value is # zero, then return the absolute value of the difference. relDiff = abs( expected - actual ) if expected: relDiff = relDiff / abs( expected ) if relTol < relDiff: # The relative difference is a ratio, so it's always unitless. relDiffStr = str( relDiff ) relTolStr = str( relTol ) expectedStr = str( expected ) actualStr = str( actual ) msg += "\n" msg += " Expected: " + expectedStr + "\n" msg += " Actual: " + actualStr + "\n" msg += " Rel Diff: " + relDiffStr + "\n" msg += " Rel Tol: " + relTolStr + "\n" if msg: return msg else: return None #----------------------------------------------------------------------- # A dictionary that maps filename extensions to functions that map # parameters old and new to a list that can be passed to Popen to # convert files with that extension to png format. converter = { } def make_external_conversion_command(cmd): def convert(*args): cmdline = cmd(*args) oldname, newname = args pipe = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pipe.communicate() errcode = pipe.wait() if not os.path.exists(newname) or errcode: msg = "Conversion command failed:\n%s\n" % ' '.join(cmdline) if stdout: msg += "Standard output:\n%s\n" % stdout if stderr: msg += "Standard error:\n%s\n" % stderr raise IOError, msg return convert if matplotlib.checkdep_ghostscript() is not None: # FIXME: make checkdep_ghostscript return the command if sys.platform == 'win32': gs = 'gswin32c' else: gs = 'gs' cmd = lambda old, new: \ [gs, '-q', '-sDEVICE=png16m', '-dNOPAUSE', '-dBATCH', '-sOutputFile=' + new, old] converter['pdf'] = make_external_conversion_command(cmd) converter['eps'] = make_external_conversion_command(cmd) if matplotlib.checkdep_inkscape() is not None: cmd = lambda old, new: \ ['inkscape', '-z', old, '--export-png', new] converter['svg'] = make_external_conversion_command(cmd) def comparable_formats(): '''Returns the list of file formats that compare_images can compare on this system.''' return ['png'] + converter.keys() def convert(filename): ''' Convert the named file into a png file. Returns the name of the created file. ''' base, extension = filename.rsplit('.', 1) if extension not in converter: raise ImageComparisonFailure, "Don't know how to convert %s files to png" % extension newname = base + '_' + extension + '.png' if not os.path.exists(filename): raise IOError, "'%s' does not exist" % filename # Only convert the file if the destination doesn't already exist or # is out of date. if (not os.path.exists(newname) or os.stat(newname).st_mtime < os.stat(filename).st_mtime): converter[extension](filename, newname) return newname verifiers = { } def verify(filename): """ Verify the file through some sort of verification tool. """ if not os.path.exists(filename): raise IOError, "'%s' does not exist" % filename base, extension = filename.rsplit('.', 1) verifier = verifiers.get(extension, None) if verifier is not None: cmd = verifier(filename) pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pipe.communicate() errcode = pipe.wait() if errcode != 0: msg = "File verification command failed:\n%s\n" % ' '.join(cmd) if stdout: msg += "Standard output:\n%s\n" % stdout if stderr: msg += "Standard error:\n%s\n" % stderr raise IOError, msg # Turning this off, because it seems to cause multiprocessing issues if matplotlib.checkdep_xmllint() and False: verifiers['svg'] = lambda filename: [ 'xmllint', '--valid', '--nowarning', '--noout', filename] def crop_to_same(actual_path, actual_image, expected_path, expected_image): # clip the images to the same size -- this is useful only when # comparing eps to pdf if actual_path[-7:-4] == 'eps' and expected_path[-7:-4] == 'pdf': aw, ah = actual_image.size ew, eh = expected_image.size actual_image = actual_image.crop((aw/2-ew/2, ah/2-eh/2, aw/2+ew/2, ah/2+eh/2)) return actual_image, expected_image def compare_images( expected, actual, tol, in_decorator=False ): '''Compare two image files - not the greatest, but fast and good enough. = EXAMPLE # img1 = "./baseline/plot.png" # img2 = "./output/plot.png" # # compare_images( img1, img2, 0.001 ): = INPUT VARIABLES - expected The filename of the expected image. - actual The filename of the actual image. - tol The tolerance (a unitless float). This is used to determine the 'fuzziness' to use when comparing images. - in_decorator If called from image_comparison decorator, this should be True. (default=False) ''' try: from PIL import Image, ImageOps, ImageFilter except ImportError, e: msg = "Image Comparison requires the Python Imaging Library to " \ "be installed. To run tests without using PIL, then use " \ "the '--without-tag=PIL' command-line option.\n" \ "Importing PIL failed with the following error:\n%s" % e if in_decorator: raise NotImplementedError, e else: return msg verify(actual) # Convert the image to png extension = expected.split('.')[-1] if extension != 'png': actual = convert(actual) expected = convert(expected) # open the image files and remove the alpha channel (if it exists) expectedImage = Image.open( expected ).convert("RGB") actualImage = Image.open( actual ).convert("RGB") actualImage, expectedImage = crop_to_same(actual, actualImage, expected, expectedImage) # normalize the images expectedImage = ImageOps.autocontrast( expectedImage, 2 ) actualImage = ImageOps.autocontrast( actualImage, 2 ) # compare the resulting image histogram functions h1 = expectedImage.histogram() h2 = actualImage.histogram() rms = math.sqrt( reduce(operator.add, map(lambda a,b: (a-b)**2, h1, h2)) / len(h1) ) diff_image = os.path.join(os.path.dirname(actual), 'failed-diff-'+os.path.basename(actual)) expected_copy = 'expected-'+os.path.basename(actual) if ( (rms / 10000.0) <= tol ): if os.path.exists(diff_image): os.unlink(diff_image) if os.path.exists(expected_copy): os.unlink(expected_copy) return None save_diff_image( expected, actual, diff_image ) if in_decorator: shutil.copyfile( expected, expected_copy ) results = dict( rms = rms, expected = str(expected), actual = str(actual), diff = str(diff_image), ) return results else: # expected_copy is only for in_decorator case if os.path.exists(expected_copy): os.unlink(expected_copy) # old-style call from mplTest directory msg = " Error: Image files did not match.\n" \ " RMS Value: " + str( rms / 10000.0 ) + "\n" \ " Expected:\n " + str( expected ) + "\n" \ " Actual:\n " + str( actual ) + "\n" \ " Difference:\n " + str( diff_image ) + "\n" \ " Tolerance: " + str( tol ) + "\n" return msg def save_diff_image( expected, actual, output ): from PIL import Image expectedImage = Image.open( expected ).convert("RGB") actualImage = Image.open( actual ).convert("RGB") actualImage, expectedImage = crop_to_same(actual, actualImage, expected, expectedImage) expectedImage = np.array(expectedImage).astype(np.float) actualImage = np.array(actualImage).astype(np.float) assert expectedImage.ndim==actualImage.ndim assert expectedImage.shape==actualImage.shape absDiffImage = abs(expectedImage-actualImage) # expand differences in luminance domain absDiffImage *= 10 save_image_np = np.clip(absDiffImage,0,255).astype(np.uint8) save_image = Image.fromarray(save_image_np) save_image.save(output)
2.796875
3
pubsub/tests/unit/pubsub_v1/subscriber/test_policy_thread.py
alercunha/google-cloud-python
1
12763444
<gh_stars>1-10 # Copyright 2017, Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from concurrent import futures import queue import threading import grpc import mock import pytest from google.auth import credentials from google.cloud.pubsub_v1 import subscriber from google.cloud.pubsub_v1 import types from google.cloud.pubsub_v1.subscriber import _helper_threads from google.cloud.pubsub_v1.subscriber import message from google.cloud.pubsub_v1.subscriber.policy import thread def create_policy(**kwargs): creds = mock.Mock(spec=credentials.Credentials) client = subscriber.Client(credentials=creds) return thread.Policy(client, 'sub_name_c', **kwargs) def test_init(): policy = create_policy() policy._callback(None) def test_init_with_executor(): executor = futures.ThreadPoolExecutor(max_workers=25) policy = create_policy(executor=executor, queue=queue.Queue()) assert policy._executor is executor def test_close(): policy = create_policy() consumer = policy._consumer with mock.patch.object(consumer, 'stop_consuming') as stop_consuming: policy.close() stop_consuming.assert_called_once_with() assert 'callback request worker' not in policy._consumer.helper_threads @mock.patch.object(_helper_threads.HelperThreadRegistry, 'start') @mock.patch.object(threading.Thread, 'start') def test_open(thread_start, htr_start): policy = create_policy() with mock.patch.object(policy._consumer, 'start_consuming') as consuming: policy.open(mock.sentinel.CALLBACK) assert policy._callback is mock.sentinel.CALLBACK consuming.assert_called_once_with() htr_start.assert_called() thread_start.assert_called() def test_on_callback_request(): policy = create_policy() with mock.patch.object(policy, 'call_rpc') as call_rpc: policy.on_callback_request(('call_rpc', {'something': 42})) call_rpc.assert_called_once_with(something=42) def test_on_exception_deadline_exceeded(): policy = create_policy() exc = mock.Mock(spec=('code',)) exc.code.return_value = grpc.StatusCode.DEADLINE_EXCEEDED assert policy.on_exception(exc) is None def test_on_exception_other(): policy = create_policy() exc = TypeError('wahhhhhh') with pytest.raises(TypeError): policy.on_exception(exc) def test_on_response(): callback = mock.Mock(spec=()) # Set up the policy. policy = create_policy() policy._callback = callback # Set up the messages to send. messages = ( types.PubsubMessage(data=b'foo', message_id='1'), types.PubsubMessage(data=b'bar', message_id='2'), ) # Set up a valid response. response = types.StreamingPullResponse( received_messages=[ {'ack_id': 'fack', 'message': messages[0]}, {'ack_id': 'back', 'message': messages[1]}, ], ) # Actually run the method and prove that the callback was # called in the expected way. policy.on_response(response) assert callback.call_count == 2 for call in callback.mock_calls: assert isinstance(call[1][0], message.Message)
1.851563
2
escnn/nn/modules/nonlinearities/fourier_quotient.py
QUVA-Lab/escnn
4
12763445
<reponame>QUVA-Lab/escnn from escnn.group import * from escnn.gspaces import * from escnn.nn import FieldType from escnn.nn import GeometricTensor from ..equivariant_module import EquivariantModule import torch import torch.nn.functional as F from typing import List, Tuple, Any import numpy as np __all__ = ["QuotientFourierPointwise", "QuotientFourierELU"] def _build_kernel(G: Group, subgroup_id: Tuple, irrep: List[tuple]): kernel = [] X: HomSpace = G.homspace(subgroup_id) for irr in irrep: k = X._dirac_kernel_ft(irr, X.H.trivial_representation.id) # irr = G.irrep(*irr) # K *= np.sqrt(irr.size) kernel.append(k.T.reshape(-1)) kernel = np.concatenate(kernel) return kernel class QuotientFourierPointwise(EquivariantModule): def __init__(self, gspace: GSpace, subgroup_id: Tuple, channels: int, irreps: List, *grid_args, grid: List[GroupElement] = None, function: str = 'p_relu', inplace: bool=True, **grid_kwargs ): r""" Applies a Inverse Fourier Transform to sample the input features on a *quotient space* :math:`X`, apply the pointwise non-linearity in the spatial domain (Dirac-delta basis) and, finally, computes the Fourier Transform to obtain irreps coefficients. The quotient space used is isomorphic to :math:`X \cong G / H` where :math:`G` is ```gspace.fibergroup``` while :math:`H` is the subgroup of :math:`G` idenitified by ```subgroup_id```; see :meth:`~escnn.group.Group.subgroup` and :meth:`~escnn.group.Group.homspace` .. note:: This operation is only *approximately* equivariant and its equivariance depends on the sampling grid and the non-linear activation used, as well as the original band-limitation of the input features. The same function is applied to every channel independently. The input representation is preserved by this operation and, therefore, it equals the output representation. The class first constructs a band-limited quotient representation of ```gspace.fibergroup``` using :meth:`escnn.group.Group.spectral_quotient_representation`. The band-limitation of this representation is specified by ```irreps``` which should be a list containing a list of ids identifying irreps of ```gspace.fibergroup``` (see :attr:`escnn.group.IrreducibleRepresentation.id`). This representation is used to define the input and output field types, each containing ```channels``` copies of a feature field transforming according to this representation. A feature vector transforming according to such representation is interpreted as a vector of coefficients parameterizing a function over the group using a band-limited Fourier basis. To approximate the Fourier transform, this module uses a finite number of samples from the group. The set of samples to be used can be specified through the parameter ```grid``` or by the ```grid_args``` and ```grid_kwargs``` which will then be passed to the method :meth:`~escnn.group.Group.grid`. .. warning :: By definition, an homogeneous space is invariant under a right action of the subgroup :math:`H`. That means that a feature representing a function over a homogeneous space :math:`X \cong G/H`, when interpreted as a function over :math:`G` (as we do here when sampling), the function will be constant along each coset, i.e. :math:`f(gh) = f(g)` if :math:`g \in G, h\in H`. An approximately uniform sampling grid over :math:`G` creates an approximately uniform grid over :math:`G/H` through projection but might contain redundant elements (if the grid contains :math:`g 'in G`, any element :math:`gh` in the grid will be redundant). It is therefore advised to create a grid directly in the quotient space, e.g. using :meth:`escnn.group.SO3.sphere_grid`, :meth:`escnn.group.O3.sphere_grid`. We do not support yet a general method and interface to generate grids over any homogeneous space for any group, so you should check each group's methods. .. todo:: Mention the normalization of the transform we use Args: gspace (GSpace): the gspace describing the symmetries of the data. The Fourier transform is performed over the group ```gspace.fibergroup``` subgroup_id (tuple): identifier of the subgroup :math:`H` to construct the quotient space channels (int): number of independent fields in the input `FieldType` irreps (list): list of irreps' ids to construct the band-limited representation *grid_args: parameters used to construct the discretization grid grid (list, optional): list containing the elements of the group to use for sampling. Optional (default ``None``). function (str): the identifier of the non-linearity. It is used to specify which function to apply. By default (``'p_relu'``), ReLU is used. inplace (bool): applies the non-linear activation in-place. Default: `True` **grid_kwargs: keyword parameters used to construct the discretization grid """ assert isinstance(gspace, GSpace) super(QuotientFourierPointwise, self).__init__() self.space = gspace G: Group = gspace.fibergroup self.rho = G.spectral_quotient_representation(subgroup_id, *irreps, name=None) # the representation in input is preserved self.in_type = self.out_type = FieldType(self.space, [self.rho]*channels) # retrieve the activation function to apply if function == 'p_relu': self._function = F.relu_ if inplace else F.relu elif function == 'p_elu': self._function = F.elu_ if inplace else F.elu elif function == 'p_sigmoid': self._function = torch.sigmoid_ if inplace else F.sigmoid elif function == 'p_tanh': self._function = torch.tanh_ if inplace else F.tanh else: raise ValueError('Function "{}" not recognized!'.format(function)) kernel = _build_kernel(G, subgroup_id, irreps) assert kernel.shape[0] == self.rho.size kernel = kernel / np.linalg.norm(kernel) kernel = kernel.reshape(-1, 1) if grid is None: grid = G.grid(*grid_args, **grid_kwargs) A = np.concatenate( [ self.rho(g) @ kernel for g in grid ], axis=1 ).T eps = 1e-8 Ainv = np.linalg.inv(A.T @ A + eps * np.eye(self.rho.size)) @ A.T self.register_buffer('A', torch.tensor(A, dtype=torch.get_default_dtype())) self.register_buffer('Ainv', torch.tensor(Ainv, dtype=torch.get_default_dtype())) def forward(self, input: GeometricTensor) -> GeometricTensor: r""" Applies the pointwise activation function on the input fields Args: input (GeometricTensor): the input feature map Returns: the resulting feature map after the non-linearities have been applied """ assert input.type == self.in_type shape = input.shape x_hat = input.tensor.view(shape[0], len(self.in_type), self.rho.size, *shape[2:]) x = torch.einsum('bcf...,gf->bcg...', x_hat, self.A) y = self._function(x) y_hat = torch.einsum('bcg...,fg->bcf...', y, self.Ainv) y_hat = y_hat.reshape(*shape) return GeometricTensor(y_hat, self.out_type, input.coords) def evaluate_output_shape(self, input_shape: Tuple[int, ...]) -> Tuple[int, ...]: assert len(input_shape) >= 2 assert input_shape[1] == self.in_type.size b, c = input_shape[:2] spatial_shape = input_shape[2:] return (b, self.out_type.size, *spatial_shape) def check_equivariance(self, atol: float = 1e-4, rtol: float = 2e-2) -> List[Tuple[Any, float]]: c = self.in_type.size B = 64 x = torch.randn(B, c, *[3]*self.space.dimensionality) errors = [] # for el in self.space.testing_elements: for _ in range(50): el = self.space.fibergroup.sample() x1 = GeometricTensor(x.clone(), self.in_type) x2 = GeometricTensor(x.clone(), self.in_type).transform_fibers(el) out1 = self(x1).transform_fibers(el) out2 = self(x2) out1 = out1.tensor.view(B, len(self.in_type), self.rho.size, *out1.shape[2:]).detach().numpy() out2 = out2.tensor.view(B, len(self.in_type), self.rho.size, *out2.shape[2:]).detach().numpy() errs = np.linalg.norm(out1 - out2, axis=2).reshape(-1) errs[errs < atol] = 0. norm = np.sqrt(np.linalg.norm(out1, axis=2).reshape(-1) * np.linalg.norm(out2, axis=2).reshape(-1)) relerr = errs / norm # print(el, errs.max(), errs.mean(), relerr.max(), relerr.min()) assert relerr.mean()+ relerr.std() < rtol, \ 'The error found during equivariance check with element "{}" is too high: max = {}, mean = {}, std ={}' \ .format(el, relerr.max(), relerr.mean(), relerr.std()) errors.append((el, errs.mean())) return errors class QuotientFourierELU(QuotientFourierPointwise): def __init__(self, gspace: GSpace, subgroup_id: Tuple, channels: int, irreps: List, *grid_args, grid: List[GroupElement] = None, inplace: bool = True, **grid_kwargs ): r""" Applies a Inverse Fourier Transform to sample the input features on a quotient space, apply ELU point-wise in the spatial domain (Dirac-delta basis) and, finally, computes the Fourier Transform to obtain irreps coefficients. See :class:`~escnn.nn.QuotientFourierPointwise` for more details. Args: gspace (GSpace): the gspace describing the symmetries of the data. The Fourier transform is performed over the group ```gspace.fibergroup``` subgroup_id (tuple): identifier of the subgroup :math:`H` to construct the quotient space channels (int): number of independent fields in the input `FieldType` irreps (list): list of irreps' ids to construct the band-limited representation *grid_args: parameters used to construct the discretization grid grid (list, optional): list containing the elements of the group to use for sampling. Optional (default ``None``). inplace (bool): applies the non-linear activation in-place. Default: `True` **grid_kwargs: keyword parameters used to construct the discretization grid """ super(QuotientFourierELU, self).__init__(gspace, subgroup_id, channels, irreps, *grid_args, function='p_elu', inplace=inplace, grid=grid, **grid_kwargs)
2.125
2
caia/circrequests/steps/query_source_url.py
umd-lib/caia
0
12763446
<reponame>umd-lib/caia import logging from typing import List from caia.circrequests.circrequests_job_config import CircrequestsJobConfig from caia.core.http import http_get_request from caia.core.step import Step, StepResult logger = logging.getLogger(__name__) class QuerySourceUrl(Step): """ Queries the source url and stores a successful response. """ def __init__(self, job_config: CircrequestsJobConfig): self.job_config = job_config self.errors: List[str] = [] def execute(self) -> StepResult: source_url = self.job_config['source_url'] headers = {'Content-Type': 'application/json'} return http_get_request(source_url, headers) def __str__(self) -> str: fullname = f"{self.__class__.__module__}.{self.__class__.__name__}" return f"{fullname}@{id(self)}"
2.140625
2
cla_public/apps/base/tests/test_healthchecks.py
farrepa/cla_public
0
12763447
import unittest import mock import requests from cla_public import app from cla_public.apps.base import healthchecks class DiskSpaceHealthcheckTest(unittest.TestCase): @mock.patch("os.statvfs") def test_disk_space_check_reports_on_available_and_total_space(self, stat_mock): stat_mock.return_value.f_bavail = 50 * 1024 stat_mock.return_value.f_blocks = 100 * 1024 stat_mock.return_value.f_frsize = 1024 result = healthchecks.check_disk() self.assertDictContainsSubset({"available_percent": 50.0, "available_mb": 50.0, "total_mb": 100.0}, result) @mock.patch("os.statvfs") def test_disk_space_check_passes_when_more_than_2_percent_space_is_available(self, stat_mock): stat_mock.return_value.f_bavail = 3 * 1024 stat_mock.return_value.f_blocks = 100 * 1024 stat_mock.return_value.f_frsize = 1024 result = healthchecks.check_disk() self.assertDictContainsSubset({"status": "healthy", "available_percent": 3.0}, result) @mock.patch("os.statvfs") def test_disk_space_check_fails_when_less_than_2_percent_space_is_available(self, stat_mock): stat_mock.return_value.f_bavail = 2 * 1024 stat_mock.return_value.f_blocks = 100 * 1024 stat_mock.return_value.f_frsize = 1024 result = healthchecks.check_disk() self.assertDictContainsSubset({"status": "unhealthy", "available_percent": 2.0}, result) class BackendAPIHealthcheckTest(unittest.TestCase): def setUp(self): self.app = app.create_app("config/testing.py") self.app.test_request_context().push() @mock.patch("requests.get") def test_backend_check_fails_if_request_fails(self, request_mock): request_mock.side_effect = requests.exceptions.ConnectionError() result = healthchecks.check_backend_api() self.assertDictContainsSubset({"status": "unhealthy", "response": "ConnectionError"}, result) @mock.patch("requests.get") def test_backend_check_fails_if_backend_is_unhealthy(self, request_mock): request_mock.return_value.ok = False request_mock.return_value.json.return_value = {"status": "DOWN"} result = healthchecks.check_backend_api() self.assertDictContainsSubset({"status": "unhealthy", "response": {"status": "DOWN"}}, result) @mock.patch("requests.get") def test_backend_check_passes_if_backend_is_healthy(self, request_mock): request_mock.return_value.ok = True request_mock.return_value.json.return_value = {"status": "UP"} result = healthchecks.check_backend_api() self.assertDictContainsSubset({"status": "healthy", "response": {"status": "UP"}}, result) class HealthcheckEndpointTest(unittest.TestCase): check_disk = "cla_public.apps.base.healthchecks.check_disk" check_backend_api = "cla_public.apps.base.healthchecks.check_backend_api" def setUp(self): self.app = app.create_app("config/testing.py") self.app.test_request_context().push() self.client = self.app.test_client() def assert_response_is_service_unavailable(self): result = self.client.get("/healthcheck.json") self.assertEquals(requests.codes.service_unavailable, result.status_code) def test_healthcheck_returns_service_unavailable_if_any_or_all_checks_fail(self): with mock.patch(self.check_disk, return_value={"status": "unhealthy"}), mock.patch( self.check_backend_api, return_value={"status": "healthy"} ): self.assert_response_is_service_unavailable() with mock.patch(self.check_disk, return_value={"status": "healthy"}), mock.patch( self.check_backend_api, return_value={"status": "unhealthy"} ): self.assert_response_is_service_unavailable() with mock.patch(self.check_disk, return_value={"status": "unhealthy"}), mock.patch( self.check_backend_api, return_value={"status": "unhealthy"} ): self.assert_response_is_service_unavailable() def test_healthcheck_returns_ok_if_all_checks_pass(self): with mock.patch(self.check_disk, return_value={"status": "healthy"}), mock.patch( self.check_backend_api, return_value={"status": "healthy"} ): result = self.client.get("/healthcheck.json") self.assertEquals(requests.codes.ok, result.status_code)
2.59375
3
venv/Lib/site-packages/gevent/tests/test__monkey_ssl_warning3.py
asanka9/Quession-Discussion-App-Socket.Io-NLP
13
12763448
<reponame>asanka9/Quession-Discussion-App-Socket.Io-NLP import unittest import warnings import sys # All supported python versions now provide SSLContext. # We subclass without importing by name. Compare with # warning2.py import ssl class MySubclass(ssl.SSLContext): pass # This file should only have this one test in it # because we have to be careful about our imports # and because we need to be careful about our patching. class Test(unittest.TestCase): @unittest.skipIf(sys.version_info[:2] < (3, 6), "Only on Python 3.6+") def test_ssl_subclass_and_module_reference(self): from gevent import monkey self.assertFalse(monkey.saved) with warnings.catch_warnings(record=True) as issued_warnings: warnings.simplefilter('always') monkey.patch_all() monkey.patch_all() issued_warnings = [x for x in issued_warnings if isinstance(x.message, monkey.MonkeyPatchWarning)] self.assertEqual(1, len(issued_warnings)) message = str(issued_warnings[0].message) self.assertNotIn("Modules that had direct imports", message) self.assertIn("Subclasses (NOT patched)", message) # the gevent subclasses should not be in here. self.assertNotIn('gevent.', message) if __name__ == '__main__': unittest.main()
2.3125
2
sdk/managednetwork/azure-mgmt-managednetwork/azure/mgmt/managednetwork/models/connectivity_collection.py
yanfa317/azure-sdk-for-python
0
12763449
<filename>sdk/managednetwork/azure-mgmt-managednetwork/azure/mgmt/managednetwork/models/connectivity_collection.py # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class ConnectivityCollection(Model): """The collection of Connectivity related groups and policies within the Managed Network. Variables are only populated by the server, and will be ignored when sending a request. :ivar groups: The collection of connectivity related Managed Network Groups within the Managed Network :vartype groups: list[~azure.mgmt.managednetwork.v2019_06_01_pre.models.ManagedNetworkGroup] :ivar peerings: The collection of Managed Network Peering Policies within the Managed Network :vartype peerings: list[~azure.mgmt.managednetwork.v2019_06_01_pre.models.ManagedNetworkPeeringPolicy] """ _validation = { 'groups': {'readonly': True}, 'peerings': {'readonly': True}, } _attribute_map = { 'groups': {'key': 'groups', 'type': '[ManagedNetworkGroup]'}, 'peerings': {'key': 'peerings', 'type': '[ManagedNetworkPeeringPolicy]'}, } def __init__(self, **kwargs): super(ConnectivityCollection, self).__init__(**kwargs) self.groups = None self.peerings = None
1.84375
2
kikola/templatetags/json_tags.py
playpauseandstop/kikola
4
12763450
""" ============================= kikola.templatetags.json_tags ============================= Template filter to dumps Python var to JSON in templates. Installation ============ Just add ``kikola`` to ``INSTALLED_APPS`` var of your project settings. Filters ======= jsonify ------- Custom template filter ``jsonify`` based on `skam's snippet <http://www.djangosnippets.org/snippets/201/>`_ and comments for it. Don't forget to make resulted variable ``safe`` to use it inside textareas. Usage ~~~~~ In templates:: {% load json_tags %} <pre class="python">{{ var|safe }}</pre> <pre class="json">{{ var|jsonify|safe }}</pre> And when:: var = { 'bool': True, 'list': ['foo', 'bar'], 'string': 'bar', } Template renders as:: <pre class="python">{'list': ['foo', 'bar'], 'bool': True, 'string': 'bar'}</pre> <pre class="json">{"list": ["foo", "bar"], "bool": true, "string": "bar"}</pre> """ from django.core.serializers.json import DjangoJSONEncoder from django.template import Library from django.utils import simplejson register = Library() @register.filter def jsonify(obj, safe=False): return simplejson.dumps(obj, cls=DjangoJSONEncoder)
2.53125
3