hexsha
stringlengths
40
40
size
int64
1
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
239
max_stars_repo_name
stringlengths
5
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
239
max_issues_repo_name
stringlengths
5
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
239
max_forks_repo_name
stringlengths
5
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.03M
avg_line_length
float64
1
958k
max_line_length
int64
1
1.03M
alphanum_fraction
float64
0
1
acf6540065630cfc4441a3567d0a3817c2dc626e
286
py
Python
agilex/configuracion_agilex/doctype/estado_de_conservacion/estado_de_conservacion.py
Nirchains/agilex
04470873abdea5d0023a1ccadf02a932fb3e834b
[ "MIT" ]
null
null
null
agilex/configuracion_agilex/doctype/estado_de_conservacion/estado_de_conservacion.py
Nirchains/agilex
04470873abdea5d0023a1ccadf02a932fb3e834b
[ "MIT" ]
null
null
null
agilex/configuracion_agilex/doctype/estado_de_conservacion/estado_de_conservacion.py
Nirchains/agilex
04470873abdea5d0023a1ccadf02a932fb3e834b
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2019, Pedro Antonio Fernández Gómez and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class EstadodeConservacion(Document): pass
26
68
0.793706
acf654556b7014fdf8006f45410835b5e9c1cc12
981
py
Python
Criar_No.py
rafaelcalixto/PageRank
21545470c544186cf8b10a4862421215cc78f83d
[ "MIT" ]
null
null
null
Criar_No.py
rafaelcalixto/PageRank
21545470c544186cf8b10a4862421215cc78f83d
[ "MIT" ]
null
null
null
Criar_No.py
rafaelcalixto/PageRank
21545470c544186cf8b10a4862421215cc78f83d
[ "MIT" ]
null
null
null
import bs4 #Beautifulsoup class Criar_No: def criar(dados_html, url_no): no = {} no['titulo'] = None no['url'] = url_no no['links'] = [] no['ranking'] = 0 tags_html = bs4.BeautifulSoup(dados_html, 'lxml') #### lxml é uma dependência titulo = tags_html.find('title') subtitle = tags_html.find('h3') if titulo is not None: no['titulo'] = titulo.text else: no['titulo'] = 'Unknow' if subtitle is not None: for h3 in subtitle: if isinstance(h3, str) and len(h3) < 40: no['titulo'] += '-' + h3 print(no['titulo']) lista_links = tags_html.find_all('a', href = True) for cada_link in list(set(lista_links)): if 'http' in cada_link['href']: no['links'].append(cada_link['href']) return no
28.852941
59
0.476045
acf6549e9075108623d43644abd299116ee2ae41
1,235
py
Python
src/pynwb/ndx_franklab_novela/camera_device.py
NovelaNeuro/ndx-franklab-novela
d5b87f742cf5aeb2c88c6f3df699614ec3fb2328
[ "BSD-3-Clause" ]
null
null
null
src/pynwb/ndx_franklab_novela/camera_device.py
NovelaNeuro/ndx-franklab-novela
d5b87f742cf5aeb2c88c6f3df699614ec3fb2328
[ "BSD-3-Clause" ]
4
2021-03-18T22:34:00.000Z
2021-12-09T00:33:53.000Z
src/pynwb/ndx_franklab_novela/camera_device.py
NovelaNeuro/ndx-franklab-novela
d5b87f742cf5aeb2c88c6f3df699614ec3fb2328
[ "BSD-3-Clause" ]
2
2020-12-07T22:35:42.000Z
2021-02-17T18:55:07.000Z
from hdmf.utils import docval, call_docval_func, get_docval from pynwb import register_class from pynwb.device import Device @register_class('CameraDevice', 'ndx-franklab-novela') class CameraDevice(Device): """Represented as CameraDevice in NWB""" __nwbfields__ = ('meters_per_pixel', 'camera_name', 'model', 'lens') @docval(*get_docval(Device.__init__) + ( {'name': 'meters_per_pixel', 'type': float, 'doc': 'meters per pixel'}, {'name': 'camera_name', 'type': str, 'doc': 'name of camera'}, {'name': 'model', 'type': str, 'doc': 'model of this camera device'}, {'name': 'lens', 'type': str, 'doc': 'lens info'}, )) def __init__(self, **kwargs): super().__init__(**{kwargs_item: kwargs[kwargs_item] for kwargs_item in kwargs.copy() if kwargs_item not in ['meters_per_pixel', 'camera_name', 'model', 'lens'] }) call_docval_func(super(CameraDevice, self).__init__, kwargs) self.meters_per_pixel = kwargs['meters_per_pixel'] self.camera_name = kwargs['camera_name'] self.model = kwargs['model'] self.lens = kwargs['lens']
41.166667
102
0.597571
acf654fdbe8df6ec0b537f6ec0667c2a6aad1cec
6,501
py
Python
dewey/commands/base.py
sidebarchats/dewey
78e1f04f6de23e32a3e38c658d83bbb68993a6af
[ "MIT" ]
null
null
null
dewey/commands/base.py
sidebarchats/dewey
78e1f04f6de23e32a3e38c658d83bbb68993a6af
[ "MIT" ]
null
null
null
dewey/commands/base.py
sidebarchats/dewey
78e1f04f6de23e32a3e38c658d83bbb68993a6af
[ "MIT" ]
null
null
null
import os import pickle import subprocess import sys import yaml from clint import resources VALID_PLATFORMS = ["Windows", "MacOSX", "Linux"] class Brain(object): pass class DeweyCommand(object): def __init__(self): resources.init('sidebar', 'dewey') brain_pickle = resources.user.read('sidebar_config.ini') if brain_pickle: self.brain = pickle.loads(brain_pickle) else: self.brain = Brain() # Check for dewey.yml. if os.path.isfile("dewey.yml"): self.local = yaml.load(open("dewey.yml")) else: self.local = None def has_local_override(self, key): return self.local and key in self.local and len(self.local[key]) > 0 def answer_yes_or_no(self, question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is one of "yes" or "no". """ valid = {"yes":True, "y":True, "ye":True, "no":False, "n":False} if default == None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = raw_input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' "\ "(or 'y' or 'n').\n") def question(self, question): """Ask a question, with a default value.""" while True: sys.stdout.write(question) choice = None while not choice: choice = raw_input() return choice def question_with_default(self, question, default=None): """Ask a question, with a default value.""" prompt = "" if default: prompt = " [%s]" % default while True: sys.stdout.write(question + prompt) choice = raw_input() if default is not None and choice == '': return default else: choice def save(self): resources.user.write('sidebar_config.ini', pickle.dumps(self.brain)) def ensure_dev_setup(self): if not hasattr(self.brain, "username"): whoami = str(subprocess.check_output("whoami")).strip() resp = self.question_with_default( "Hi! I'm dewey, Sidebar's CLI. Looks like we haven't met before. Can you tell me your github username, so I can keep things tidy?", whoami ) self.brain.username = resp self.save() def set_platform(self, platform): assert platform in VALID_PLATFORMS self.platform = platform def run_pre(self, *args, **kwargs): if not self.platform: raise OSError("echo 'Dewey doesn't know your operating system. Sorry!'") if self.platform == "Windows": try: ret = self.pre_windows(*args, **kwargs) if ret: return ret except: pass return "" elif self.platform == "MacOSX": try: ret = self.pre_macosx(*args, **kwargs) if ret: return ret except: pass return "" elif self.platform == "Linux": try: ret = self.pre_unix(*args, **kwargs) if ret: return ret except: pass return "" else: raise OSError("echo 'Dewey doesn't know how to run pre for %s'" % self.platform) def pre_default(self, *args, **kwargs): raise NotImplementedError("Pre-command not written!") def pre_windows(self, *args, **kwargs): """Returns a string to execute on windows""" return self.pre_default(self, *args, **kwargs) def pre_macosx(self, *args, **kwargs): """Returns a string to execute on Mac OS X""" return self.pre_default(self, *args, **kwargs) def pre_unix(self, *args, **kwargs): """Returns a string to execute on unix""" return self.pre_default(self, *args, **kwargs) def run_command(self, *args, **kwargs): """Runs the body of the command (should not have current shell side effects.)""" pass def run_post(self, *args, **kwargs): if not self.platform: raise OSError("echo 'Dewey doesn't know your operating system. Sorry!'") if self.platform == "Windows": try: ret = self.post_windows(*args, **kwargs) if ret: return ret except: pass return "" elif self.platform == "MacOSX": try: ret = self.post_macosx(*args, **kwargs) if ret: return ret except: pass return "" elif self.platform == "Linux": try: ret = self.post_unix(*args, **kwargs) if ret: return ret except: pass return "" else: raise OSError("echo 'Dewey doesn't know how to run post for %s'" % self.platform) def post_default(self, *args, **kwargs): raise NotImplementedError("Post-command not written!") def post_windows(self, *args, **kwargs): """Returns a string to execute on windows""" return self.post_default(self, *args, **kwargs) def post_macosx(self, *args, **kwargs): """Returns a string to execute on Mac OS X""" return self.post_default(self, *args, **kwargs) def post_unix(self, *args, **kwargs): """Returns a string to execute on unix""" return self.post_default(self, *args, **kwargs)
32.668342
148
0.525919
acf655e6b913ac25e798654be7459fdb7a046a22
7,589
py
Python
services/places365-scene-recognition/service/serviceUtils.py
arturgontijo/dnn-model-services
b5b1453a1e933bdc79451f172873f31fb7fd9842
[ "MIT" ]
26
2018-12-14T20:02:07.000Z
2021-10-07T19:39:16.000Z
services/places365-scene-recognition/service/serviceUtils.py
arturgontijo/dnn-model-services
b5b1453a1e933bdc79451f172873f31fb7fd9842
[ "MIT" ]
73
2018-08-09T17:13:21.000Z
2022-03-12T00:03:16.000Z
services/places365-scene-recognition/service/serviceUtils.py
arturgontijo/dnn-model-services
b5b1453a1e933bdc79451f172873f31fb7fd9842
[ "MIT" ]
33
2018-10-24T10:45:48.000Z
2022-03-19T05:39:48.000Z
import logging import os import urllib.request from urllib.parse import urlparse import base64 import io from PIL import Image import time import re import argparse from service import registry logging.basicConfig( level=10, format="%(asctime)s - [%(levelname)8s] - %(name)s - %(message)s") log = logging.getLogger(os.path.basename(__file__)) def common_parser(script_name): parser = argparse.ArgumentParser(prog=script_name) service_name = os.path.splitext(os.path.basename(script_name))[0] parser.add_argument("--grpc-port", help="port to bind gRPC service to", default=registry[service_name]["grpc"], type=int, required=False) return parser def main_loop(grpc_handler, args): """From gRPC docs: Because start() does not block you may need to sleep-loop if there is nothing else for your code to do while serving.""" server = grpc_handler(port=args.grpc_port) server.start() try: while True: time.sleep(0.1) except KeyboardInterrupt: server.stop(0) def download(url, filename): """Downloads a file given its url and saves to filename.""" # Adds header to deal with images under https opener = urllib.request.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:9.0) Gecko/20100101 Firefox/10.0')] urllib.request.install_opener(opener) # Downloads the image try: urllib.request.urlretrieve(url, filename) except Exception: raise return def jpg_to_base64(jpgimg, open_file=False): """Encodes a jpg file into base64. Can receive either the already open jpg PIL Image or its path as input.""" if open_file: try: jpgimg = Image.open(jpgimg) except Exception as e: log.error(e) raise imgbuffer = io.BytesIO() try: jpgimg.save(imgbuffer, format='JPEG') except Exception as e: log.error(e) raise imgbytes = imgbuffer.getvalue() return base64.b64encode(imgbytes) def base64_to_jpg(base64img, output_file_path=""): """Decodes from base64 to jpg. If output_file_path is defined, saves the decoded image.""" decoded_jpg = base64.b64decode(base64img) jpg_bytes = io.BytesIO(decoded_jpg) image = Image.open(jpg_bytes) if output_file_path != "": # If image is PNG, convert to JPG if image.format == 'PNG': image = image.convert('RGB') image.save(output_file_path, format='JPEG') return decoded_jpg def clear_path(path): """ Deletes all files in a path. """ for file in os.listdir(path): file_path = os.path.join(path, file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) return def clear_file(file_path): """ Deletes a file given its path.""" try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) return def initialize_diretories(directories_list, clear_directories=True): """ Creates directories (or clears them if necesary).""" for directory in directories_list: if not os.path.exists(directory): os.makedirs(directory) else: if clear_directories: clear_path(directory) def get_file_index(save_dir, prefix): """ Gets number "x" of images of this type in the directory (so that the save path will be "prefix_x". Requires files named as follows: "*_xx.ext", e.g.: "contentimage_03.jpg", from which 03 would be extracted to return 04 as the index of the next file to be saved. This number resets to 0 at 99.""" file_index = 0 regex = prefix + r'([0-9]{2})\.([a-z]{3})' files = [f for f in os.listdir(save_dir) if os.path.isfile(os.path.join(save_dir, f))] if files: for file_name in files: regmatch = re.match(regex, file_name) if regmatch is not None: int_index = int(regmatch.group(1)) if int_index >= file_index: file_index = int_index + 1 # Circular list (up to 99) for files of each type. if file_index > 99: file_index = 0 file_index_str = str(file_index).zfill(2) return file_index_str def png_to_jpg(png_path, delete_original=True): """Opens a png image, creates a jpg image of the same name and optionally deletes the original png image. Returns: path to the jpg image.""" with Image.open(png_path) as png_img: jpg_img = png_img.convert('RGB') stripped_file_name = os.path.splitext(png_path)[0] jpg_path = stripped_file_name + ".jpg" jpg_img.save(jpg_path) if delete_original: clear_file(png_path) return jpg_path def treat_image_input(input_argument, save_dir, image_type): """ Gets image save path, downloads links or saves local images to temporary folder, deals with base64 inputs.""" # Gets index (numerical suffix) to save the image (so it multiple calls are allowed) file_index_str = get_file_index(save_dir, image_type + "_") # Assemble save path (still lacks extension) save_path = save_dir + '/' + image_type + "_" + file_index_str # If its a link, download if urlparse(input_argument).scheme in ('http', 'https'): log.debug("Treating image input as a url.") path = urlparse(input_argument).path file_ext = os.path.splitext(path)[1].lower() if file_ext not in ['.jpg', '.jpeg', '.png']: log.error('URL image extension not recognized. Should be .jpg, .jpeg or .png. ' 'Got {}. Trying to treat image as .jpg.'.format(file_ext)) save_path += ".jpg" else: save_path += file_ext log.debug("Downloading image under the path: {}".format(save_path)) try: download(input_argument, save_path) if file_ext == ".png": save_path = png_to_jpg(save_path, True) Image.open(save_path) except Exception: clear_file(save_path) raise # If its a local file elif os.path.isfile(input_argument): log.debug("Treating image input as a path to a local file.") try: image = Image.open(input_argument) except Exception: log.exception('Could not open image in treat_image_input') raise # Gets file extension if image.format == 'PNG': file_ext = ".png" elif image.format == 'JPEG' or image.format == 'JPG': file_ext = '.jpg' else: log.error("Input file extension not recognized!") return False save_path += file_ext # Save image to temp file image.save(save_path) # If it's not a local file, try to decode from base64 to jpg and save else: # TODO : check if always decoding base64 to JPG works. log.debug("Treating image input as base64.") # Extracting header if present if input_argument[0:4] == "data": file_ext = '.' + input_argument.split('/')[1].split(';')[0].lower() input_argument = input_argument.split(',')[1] else: file_ext = '.jpg' save_path += file_ext base64_to_jpg(input_argument, save_path) return save_path, file_index_str
33.431718
120
0.619976
acf6572d779a4d4c4454bc920ed65da8e1e53660
29,996
py
Python
tests/examples/minlplib/fo8.py
ouyang-w-19/decogo
52546480e49776251d4d27856e18a46f40c824a1
[ "MIT" ]
2
2021-07-03T13:19:10.000Z
2022-02-06T10:48:13.000Z
tests/examples/minlplib/fo8.py
ouyang-w-19/decogo
52546480e49776251d4d27856e18a46f40c824a1
[ "MIT" ]
1
2021-07-04T14:52:14.000Z
2021-07-15T10:17:11.000Z
tests/examples/minlplib/fo8.py
ouyang-w-19/decogo
52546480e49776251d4d27856e18a46f40c824a1
[ "MIT" ]
null
null
null
# MINLP written by GAMS Convert at 04/21/18 13:52:13 # # Equation counts # Total E G L N X C B # 274 1 0 273 0 0 0 0 # # Variable counts # x b i s1s s2s sc si # Total cont binary integer sos1 sos2 scont sint # 147 91 56 0 0 0 0 0 # FX 2 2 0 0 0 0 0 0 # # Nonzero counts # Total const NL DLL # 1137 1121 16 0 # # Reformulation has removed 1 variable and 1 equation from pyomo.environ import * model = m = ConcreteModel() m.b1 = Var(within=Binary,bounds=(0,1),initialize=0) m.b2 = Var(within=Binary,bounds=(0,1),initialize=0) m.b3 = Var(within=Binary,bounds=(0,1),initialize=0) m.b4 = Var(within=Binary,bounds=(0,1),initialize=0) m.b5 = Var(within=Binary,bounds=(0,1),initialize=0) m.b6 = Var(within=Binary,bounds=(0,1),initialize=0) m.b7 = Var(within=Binary,bounds=(0,1),initialize=0) m.b8 = Var(within=Binary,bounds=(0,1),initialize=0) m.b9 = Var(within=Binary,bounds=(0,1),initialize=0) m.b10 = Var(within=Binary,bounds=(0,1),initialize=0) m.b11 = Var(within=Binary,bounds=(0,1),initialize=0) m.b12 = Var(within=Binary,bounds=(0,1),initialize=0) m.b13 = Var(within=Binary,bounds=(0,1),initialize=0) m.b14 = Var(within=Binary,bounds=(0,1),initialize=0) m.b15 = Var(within=Binary,bounds=(0,1),initialize=0) m.b16 = Var(within=Binary,bounds=(0,1),initialize=0) m.b17 = Var(within=Binary,bounds=(0,1),initialize=0) m.b18 = Var(within=Binary,bounds=(0,1),initialize=0) m.b19 = Var(within=Binary,bounds=(0,1),initialize=0) m.b20 = Var(within=Binary,bounds=(0,1),initialize=0) m.b21 = Var(within=Binary,bounds=(0,1),initialize=0) m.b22 = Var(within=Binary,bounds=(0,1),initialize=0) m.b23 = Var(within=Binary,bounds=(0,1),initialize=0) m.b24 = Var(within=Binary,bounds=(0,1),initialize=0) m.b25 = Var(within=Binary,bounds=(0,1),initialize=0) m.b26 = Var(within=Binary,bounds=(0,1),initialize=0) m.b27 = Var(within=Binary,bounds=(0,1),initialize=0) m.b28 = Var(within=Binary,bounds=(0,1),initialize=0) m.b29 = Var(within=Binary,bounds=(0,1),initialize=0) m.b30 = Var(within=Binary,bounds=(0,1),initialize=0) m.b31 = Var(within=Binary,bounds=(0,1),initialize=0) m.b32 = Var(within=Binary,bounds=(0,1),initialize=0) m.b33 = Var(within=Binary,bounds=(0,1),initialize=0) m.b34 = Var(within=Binary,bounds=(0,1),initialize=0) m.b35 = Var(within=Binary,bounds=(0,1),initialize=0) m.b36 = Var(within=Binary,bounds=(0,1),initialize=0) m.b37 = Var(within=Binary,bounds=(0,1),initialize=0) m.b38 = Var(within=Binary,bounds=(0,1),initialize=0) m.b39 = Var(within=Binary,bounds=(0,1),initialize=0) m.b40 = Var(within=Binary,bounds=(0,1),initialize=0) m.b41 = Var(within=Binary,bounds=(0,1),initialize=0) m.b42 = Var(within=Binary,bounds=(0,1),initialize=0) m.b43 = Var(within=Binary,bounds=(0,1),initialize=0) m.b44 = Var(within=Binary,bounds=(0,1),initialize=0) m.b45 = Var(within=Binary,bounds=(0,1),initialize=0) m.b46 = Var(within=Binary,bounds=(0,1),initialize=0) m.b47 = Var(within=Binary,bounds=(0,1),initialize=0) m.b48 = Var(within=Binary,bounds=(0,1),initialize=0) m.b49 = Var(within=Binary,bounds=(0,1),initialize=0) m.b50 = Var(within=Binary,bounds=(0,1),initialize=0) m.b51 = Var(within=Binary,bounds=(0,1),initialize=0) m.b52 = Var(within=Binary,bounds=(0,1),initialize=0) m.b53 = Var(within=Binary,bounds=(0,1),initialize=0) m.b54 = Var(within=Binary,bounds=(0,1),initialize=0) m.b55 = Var(within=Binary,bounds=(0,1),initialize=0) m.b56 = Var(within=Binary,bounds=(0,1),initialize=0) m.x58 = Var(within=Reals,bounds=(None,None),initialize=0) m.x59 = Var(within=Reals,bounds=(None,None),initialize=0) m.x60 = Var(within=Reals,bounds=(None,None),initialize=0) m.x61 = Var(within=Reals,bounds=(None,None),initialize=0) m.x62 = Var(within=Reals,bounds=(None,None),initialize=0) m.x63 = Var(within=Reals,bounds=(None,None),initialize=0) m.x64 = Var(within=Reals,bounds=(None,None),initialize=0) m.x65 = Var(within=Reals,bounds=(None,None),initialize=0) m.x66 = Var(within=Reals,bounds=(None,None),initialize=0) m.x67 = Var(within=Reals,bounds=(None,None),initialize=0) m.x68 = Var(within=Reals,bounds=(None,None),initialize=0) m.x69 = Var(within=Reals,bounds=(None,None),initialize=0) m.x70 = Var(within=Reals,bounds=(None,None),initialize=0) m.x71 = Var(within=Reals,bounds=(None,None),initialize=0) m.x72 = Var(within=Reals,bounds=(None,None),initialize=0) m.x73 = Var(within=Reals,bounds=(None,None),initialize=0) m.x74 = Var(within=Reals,bounds=(None,None),initialize=0) m.x75 = Var(within=Reals,bounds=(None,None),initialize=0) m.x76 = Var(within=Reals,bounds=(None,None),initialize=0) m.x77 = Var(within=Reals,bounds=(None,None),initialize=0) m.x78 = Var(within=Reals,bounds=(None,None),initialize=0) m.x79 = Var(within=Reals,bounds=(None,None),initialize=0) m.x80 = Var(within=Reals,bounds=(None,None),initialize=0) m.x81 = Var(within=Reals,bounds=(None,None),initialize=0) m.x82 = Var(within=Reals,bounds=(None,None),initialize=0) m.x83 = Var(within=Reals,bounds=(None,None),initialize=0) m.x84 = Var(within=Reals,bounds=(None,None),initialize=0) m.x85 = Var(within=Reals,bounds=(None,None),initialize=0) m.x86 = Var(within=Reals,bounds=(None,None),initialize=0) m.x87 = Var(within=Reals,bounds=(None,None),initialize=0) m.x88 = Var(within=Reals,bounds=(None,None),initialize=0) m.x89 = Var(within=Reals,bounds=(None,None),initialize=0) m.x90 = Var(within=Reals,bounds=(None,None),initialize=0) m.x91 = Var(within=Reals,bounds=(None,None),initialize=0) m.x92 = Var(within=Reals,bounds=(None,None),initialize=0) m.x93 = Var(within=Reals,bounds=(None,None),initialize=0) m.x94 = Var(within=Reals,bounds=(None,None),initialize=0) m.x95 = Var(within=Reals,bounds=(None,None),initialize=0) m.x96 = Var(within=Reals,bounds=(None,None),initialize=0) m.x97 = Var(within=Reals,bounds=(None,None),initialize=0) m.x98 = Var(within=Reals,bounds=(None,None),initialize=0) m.x99 = Var(within=Reals,bounds=(None,None),initialize=0) m.x100 = Var(within=Reals,bounds=(None,None),initialize=0) m.x101 = Var(within=Reals,bounds=(None,None),initialize=0) m.x102 = Var(within=Reals,bounds=(None,None),initialize=0) m.x103 = Var(within=Reals,bounds=(None,None),initialize=0) m.x104 = Var(within=Reals,bounds=(None,None),initialize=0) m.x105 = Var(within=Reals,bounds=(None,None),initialize=0) m.x106 = Var(within=Reals,bounds=(None,None),initialize=0) m.x107 = Var(within=Reals,bounds=(None,None),initialize=0) m.x108 = Var(within=Reals,bounds=(None,None),initialize=0) m.x109 = Var(within=Reals,bounds=(None,None),initialize=0) m.x110 = Var(within=Reals,bounds=(None,None),initialize=0) m.x111 = Var(within=Reals,bounds=(None,None),initialize=0) m.x112 = Var(within=Reals,bounds=(None,None),initialize=0) m.x113 = Var(within=Reals,bounds=(None,None),initialize=0) m.x114 = Var(within=Reals,bounds=(2,8),initialize=2) m.x115 = Var(within=Reals,bounds=(2,8),initialize=2) m.x116 = Var(within=Reals,bounds=(2,8),initialize=2) m.x117 = Var(within=Reals,bounds=(3,11.31),initialize=3) m.x118 = Var(within=Reals,bounds=(3,11.31),initialize=3) m.x119 = Var(within=Reals,bounds=(1.5,6),initialize=1.5) m.x120 = Var(within=Reals,bounds=(1.5,6),initialize=1.5) m.x121 = Var(within=Reals,bounds=(1.5,6),initialize=1.5) m.x122 = Var(within=Reals,bounds=(11.31,11.31),initialize=11.31) m.x123 = Var(within=Reals,bounds=(2,8),initialize=2) m.x124 = Var(within=Reals,bounds=(2,8),initialize=2) m.x125 = Var(within=Reals,bounds=(2,8),initialize=2) m.x126 = Var(within=Reals,bounds=(3.183,12),initialize=3.183) m.x127 = Var(within=Reals,bounds=(3.183,12),initialize=3.183) m.x128 = Var(within=Reals,bounds=(1.5,6),initialize=1.5) m.x129 = Var(within=Reals,bounds=(1.5,6),initialize=1.5) m.x130 = Var(within=Reals,bounds=(1.5,6),initialize=1.5) m.x131 = Var(within=Reals,bounds=(13,13),initialize=13) m.x132 = Var(within=Reals,bounds=(None,None),initialize=0) m.x133 = Var(within=Reals,bounds=(None,None),initialize=0) m.x134 = Var(within=Reals,bounds=(None,None),initialize=0) m.x135 = Var(within=Reals,bounds=(None,None),initialize=0) m.x136 = Var(within=Reals,bounds=(None,None),initialize=0) m.x137 = Var(within=Reals,bounds=(None,None),initialize=0) m.x138 = Var(within=Reals,bounds=(None,None),initialize=0) m.x139 = Var(within=Reals,bounds=(None,None),initialize=0) m.x140 = Var(within=Reals,bounds=(None,None),initialize=0) m.x141 = Var(within=Reals,bounds=(None,None),initialize=0) m.x142 = Var(within=Reals,bounds=(None,None),initialize=0) m.x143 = Var(within=Reals,bounds=(None,None),initialize=0) m.x144 = Var(within=Reals,bounds=(None,None),initialize=0) m.x145 = Var(within=Reals,bounds=(None,None),initialize=0) m.x146 = Var(within=Reals,bounds=(None,None),initialize=0) m.x147 = Var(within=Reals,bounds=(None,None),initialize=0) m.obj = Objective(expr= m.x58 + m.x59 + m.x72 + m.x73 + m.x84 + m.x85 + m.x94 + m.x95 + m.x102 + m.x103 + m.x108 + m.x109 + m.x112 + m.x113, sense=minimize) m.c2 = Constraint(expr= m.x132 - m.x133 <= 0) m.c3 = Constraint(expr= 0.5*m.x114 - m.x122 + m.x132 <= 0) m.c4 = Constraint(expr= 0.5*m.x114 - m.x132 <= 0) m.c5 = Constraint(expr= 0.5*m.x123 - m.x131 + m.x140 <= 0) m.c6 = Constraint(expr= 0.5*m.x123 - m.x140 <= 0) m.c7 = Constraint(expr= 0.5*m.x115 - m.x122 + m.x133 <= 0) m.c8 = Constraint(expr= 0.5*m.x115 - m.x133 <= 0) m.c9 = Constraint(expr= 0.5*m.x124 - m.x131 + m.x141 <= 0) m.c10 = Constraint(expr= 0.5*m.x124 - m.x141 <= 0) m.c11 = Constraint(expr= 0.5*m.x116 - m.x122 + m.x134 <= 0) m.c12 = Constraint(expr= 0.5*m.x116 - m.x134 <= 0) m.c13 = Constraint(expr= 0.5*m.x125 - m.x131 + m.x142 <= 0) m.c14 = Constraint(expr= 0.5*m.x125 - m.x142 <= 0) m.c15 = Constraint(expr= 0.5*m.x117 - m.x122 + m.x135 <= 0) m.c16 = Constraint(expr= 0.5*m.x117 - m.x135 <= 0) m.c17 = Constraint(expr= 0.5*m.x126 - m.x131 + m.x143 <= 0) m.c18 = Constraint(expr= 0.5*m.x126 - m.x143 <= 0) m.c19 = Constraint(expr= 0.5*m.x118 - m.x122 + m.x136 <= 0) m.c20 = Constraint(expr= 0.5*m.x118 - m.x136 <= 0) m.c21 = Constraint(expr= 0.5*m.x127 - m.x131 + m.x144 <= 0) m.c22 = Constraint(expr= 0.5*m.x127 - m.x144 <= 0) m.c23 = Constraint(expr= 0.5*m.x119 - m.x122 + m.x137 <= 0) m.c24 = Constraint(expr= 0.5*m.x119 - m.x137 <= 0) m.c25 = Constraint(expr= 0.5*m.x128 - m.x131 + m.x145 <= 0) m.c26 = Constraint(expr= 0.5*m.x128 - m.x145 <= 0) m.c27 = Constraint(expr= 0.5*m.x120 - m.x122 + m.x138 <= 0) m.c28 = Constraint(expr= 0.5*m.x120 - m.x138 <= 0) m.c29 = Constraint(expr= 0.5*m.x129 - m.x131 + m.x146 <= 0) m.c30 = Constraint(expr= 0.5*m.x129 - m.x146 <= 0) m.c31 = Constraint(expr= 0.5*m.x121 - m.x122 + m.x139 <= 0) m.c32 = Constraint(expr= 0.5*m.x121 - m.x139 <= 0) m.c33 = Constraint(expr= 0.5*m.x130 - m.x131 + m.x147 <= 0) m.c34 = Constraint(expr= 0.5*m.x130 - m.x147 <= 0) m.c35 = Constraint(expr= - m.x58 + m.x132 - m.x133 <= 0) m.c36 = Constraint(expr= - m.x58 - m.x132 + m.x133 <= 0) m.c37 = Constraint(expr= - m.x59 + m.x140 - m.x141 <= 0) m.c38 = Constraint(expr= - m.x59 - m.x140 + m.x141 <= 0) m.c39 = Constraint(expr= - 11.31*m.b1 - 11.31*m.b2 + 0.5*m.x114 + 0.5*m.x115 - m.x132 + m.x133 <= 0) m.c40 = Constraint(expr= - 11.31*m.b1 + 11.31*m.b2 + 0.5*m.x114 + 0.5*m.x115 + m.x132 - m.x133 <= 11.31) m.c41 = Constraint(expr= 13*m.b1 - 13*m.b2 + 0.5*m.x123 + 0.5*m.x124 - m.x140 + m.x141 <= 13) m.c42 = Constraint(expr= 13*m.b1 + 13*m.b2 + 0.5*m.x123 + 0.5*m.x124 + m.x140 - m.x141 <= 26) m.c43 = Constraint(expr= - m.x60 + m.x132 - m.x134 <= 0) m.c44 = Constraint(expr= - m.x60 - m.x132 + m.x134 <= 0) m.c45 = Constraint(expr= - m.x61 + m.x140 - m.x142 <= 0) m.c46 = Constraint(expr= - m.x61 - m.x140 + m.x142 <= 0) m.c47 = Constraint(expr= - 11.31*m.b3 - 11.31*m.b4 + 0.5*m.x114 + 0.5*m.x116 - m.x132 + m.x134 <= 0) m.c48 = Constraint(expr= - 11.31*m.b3 + 11.31*m.b4 + 0.5*m.x114 + 0.5*m.x116 + m.x132 - m.x134 <= 11.31) m.c49 = Constraint(expr= 13*m.b3 - 13*m.b4 + 0.5*m.x123 + 0.5*m.x125 - m.x140 + m.x142 <= 13) m.c50 = Constraint(expr= 13*m.b3 + 13*m.b4 + 0.5*m.x123 + 0.5*m.x125 + m.x140 - m.x142 <= 26) m.c51 = Constraint(expr= - m.x62 + m.x132 - m.x135 <= 0) m.c52 = Constraint(expr= - m.x62 - m.x132 + m.x135 <= 0) m.c53 = Constraint(expr= - m.x63 + m.x140 - m.x143 <= 0) m.c54 = Constraint(expr= - m.x63 - m.x140 + m.x143 <= 0) m.c55 = Constraint(expr= - 11.31*m.b5 - 11.31*m.b6 + 0.5*m.x114 + 0.5*m.x117 - m.x132 + m.x135 <= 0) m.c56 = Constraint(expr= - 11.31*m.b5 + 11.31*m.b6 + 0.5*m.x114 + 0.5*m.x117 + m.x132 - m.x135 <= 11.31) m.c57 = Constraint(expr= 13*m.b5 - 13*m.b6 + 0.5*m.x123 + 0.5*m.x126 - m.x140 + m.x143 <= 13) m.c58 = Constraint(expr= 13*m.b5 + 13*m.b6 + 0.5*m.x123 + 0.5*m.x126 + m.x140 - m.x143 <= 26) m.c59 = Constraint(expr= - m.x64 + m.x132 - m.x136 <= 0) m.c60 = Constraint(expr= - m.x64 - m.x132 + m.x136 <= 0) m.c61 = Constraint(expr= - m.x65 + m.x140 - m.x144 <= 0) m.c62 = Constraint(expr= - m.x65 - m.x140 + m.x144 <= 0) m.c63 = Constraint(expr= - 11.31*m.b7 - 11.31*m.b8 + 0.5*m.x114 + 0.5*m.x118 - m.x132 + m.x136 <= 0) m.c64 = Constraint(expr= - 11.31*m.b7 + 11.31*m.b8 + 0.5*m.x114 + 0.5*m.x118 + m.x132 - m.x136 <= 11.31) m.c65 = Constraint(expr= 13*m.b7 - 13*m.b8 + 0.5*m.x123 + 0.5*m.x127 - m.x140 + m.x144 <= 13) m.c66 = Constraint(expr= 13*m.b7 + 13*m.b8 + 0.5*m.x123 + 0.5*m.x127 + m.x140 - m.x144 <= 26) m.c67 = Constraint(expr= - m.x66 + m.x132 - m.x137 <= 0) m.c68 = Constraint(expr= - m.x66 - m.x132 + m.x137 <= 0) m.c69 = Constraint(expr= - m.x67 + m.x140 - m.x145 <= 0) m.c70 = Constraint(expr= - m.x67 - m.x140 + m.x145 <= 0) m.c71 = Constraint(expr= - 11.31*m.b9 - 11.31*m.b10 + 0.5*m.x114 + 0.5*m.x119 - m.x132 + m.x137 <= 0) m.c72 = Constraint(expr= - 11.31*m.b9 + 11.31*m.b10 + 0.5*m.x114 + 0.5*m.x119 + m.x132 - m.x137 <= 11.31) m.c73 = Constraint(expr= 13*m.b9 - 13*m.b10 + 0.5*m.x123 + 0.5*m.x128 - m.x140 + m.x145 <= 13) m.c74 = Constraint(expr= 13*m.b9 + 13*m.b10 + 0.5*m.x123 + 0.5*m.x128 + m.x140 - m.x145 <= 26) m.c75 = Constraint(expr= - m.x68 + m.x132 - m.x138 <= 0) m.c76 = Constraint(expr= - m.x68 - m.x132 + m.x138 <= 0) m.c77 = Constraint(expr= - m.x69 + m.x140 - m.x146 <= 0) m.c78 = Constraint(expr= - m.x69 - m.x140 + m.x146 <= 0) m.c79 = Constraint(expr= - 11.31*m.b11 - 11.31*m.b12 + 0.5*m.x114 + 0.5*m.x120 - m.x132 + m.x138 <= 0) m.c80 = Constraint(expr= - 11.31*m.b11 + 11.31*m.b12 + 0.5*m.x114 + 0.5*m.x120 + m.x132 - m.x138 <= 11.31) m.c81 = Constraint(expr= 13*m.b11 - 13*m.b12 + 0.5*m.x123 + 0.5*m.x129 - m.x140 + m.x146 <= 13) m.c82 = Constraint(expr= 13*m.b11 + 13*m.b12 + 0.5*m.x123 + 0.5*m.x129 + m.x140 - m.x146 <= 26) m.c83 = Constraint(expr= - m.x70 + m.x132 - m.x139 <= 0) m.c84 = Constraint(expr= - m.x70 - m.x132 + m.x139 <= 0) m.c85 = Constraint(expr= - m.x71 + m.x140 - m.x147 <= 0) m.c86 = Constraint(expr= - m.x71 - m.x140 + m.x147 <= 0) m.c87 = Constraint(expr= - 11.31*m.b13 - 11.31*m.b14 + 0.5*m.x114 + 0.5*m.x121 - m.x132 + m.x139 <= 0) m.c88 = Constraint(expr= - 11.31*m.b13 + 11.31*m.b14 + 0.5*m.x114 + 0.5*m.x121 + m.x132 - m.x139 <= 11.31) m.c89 = Constraint(expr= 13*m.b13 - 13*m.b14 + 0.5*m.x123 + 0.5*m.x130 - m.x140 + m.x147 <= 13) m.c90 = Constraint(expr= 13*m.b13 + 13*m.b14 + 0.5*m.x123 + 0.5*m.x130 + m.x140 - m.x147 <= 26) m.c91 = Constraint(expr= - m.x72 + m.x133 - m.x134 <= 0) m.c92 = Constraint(expr= - m.x72 - m.x133 + m.x134 <= 0) m.c93 = Constraint(expr= - m.x73 + m.x141 - m.x142 <= 0) m.c94 = Constraint(expr= - m.x73 - m.x141 + m.x142 <= 0) m.c95 = Constraint(expr= - 11.31*m.b15 - 11.31*m.b16 + 0.5*m.x115 + 0.5*m.x116 - m.x133 + m.x134 <= 0) m.c96 = Constraint(expr= - 11.31*m.b15 + 11.31*m.b16 + 0.5*m.x115 + 0.5*m.x116 + m.x133 - m.x134 <= 11.31) m.c97 = Constraint(expr= 13*m.b15 - 13*m.b16 + 0.5*m.x124 + 0.5*m.x125 - m.x141 + m.x142 <= 13) m.c98 = Constraint(expr= 13*m.b15 + 13*m.b16 + 0.5*m.x124 + 0.5*m.x125 + m.x141 - m.x142 <= 26) m.c99 = Constraint(expr= - m.x74 + m.x133 - m.x135 <= 0) m.c100 = Constraint(expr= - m.x74 - m.x133 + m.x135 <= 0) m.c101 = Constraint(expr= - m.x75 + m.x141 - m.x143 <= 0) m.c102 = Constraint(expr= - m.x75 - m.x141 + m.x143 <= 0) m.c103 = Constraint(expr= - 11.31*m.b17 - 11.31*m.b18 + 0.5*m.x115 + 0.5*m.x117 - m.x133 + m.x135 <= 0) m.c104 = Constraint(expr= - 11.31*m.b17 + 11.31*m.b18 + 0.5*m.x115 + 0.5*m.x117 + m.x133 - m.x135 <= 11.31) m.c105 = Constraint(expr= 13*m.b17 - 13*m.b18 + 0.5*m.x124 + 0.5*m.x126 - m.x141 + m.x143 <= 13) m.c106 = Constraint(expr= 13*m.b17 + 13*m.b18 + 0.5*m.x124 + 0.5*m.x126 + m.x141 - m.x143 <= 26) m.c107 = Constraint(expr= - m.x76 + m.x133 - m.x136 <= 0) m.c108 = Constraint(expr= - m.x76 - m.x133 + m.x136 <= 0) m.c109 = Constraint(expr= - m.x77 + m.x141 - m.x144 <= 0) m.c110 = Constraint(expr= - m.x77 - m.x141 + m.x144 <= 0) m.c111 = Constraint(expr= - 11.31*m.b19 - 11.31*m.b20 + 0.5*m.x115 + 0.5*m.x118 - m.x133 + m.x136 <= 0) m.c112 = Constraint(expr= - 11.31*m.b19 + 11.31*m.b20 + 0.5*m.x115 + 0.5*m.x118 + m.x133 - m.x136 <= 11.31) m.c113 = Constraint(expr= 13*m.b19 - 13*m.b20 + 0.5*m.x124 + 0.5*m.x127 - m.x141 + m.x144 <= 13) m.c114 = Constraint(expr= 13*m.b19 + 13*m.b20 + 0.5*m.x124 + 0.5*m.x127 + m.x141 - m.x144 <= 26) m.c115 = Constraint(expr= - m.x78 + m.x133 - m.x137 <= 0) m.c116 = Constraint(expr= - m.x78 - m.x133 + m.x137 <= 0) m.c117 = Constraint(expr= - m.x79 + m.x141 - m.x145 <= 0) m.c118 = Constraint(expr= - m.x79 - m.x141 + m.x145 <= 0) m.c119 = Constraint(expr= - 11.31*m.b21 - 11.31*m.b22 + 0.5*m.x115 + 0.5*m.x119 - m.x133 + m.x137 <= 0) m.c120 = Constraint(expr= - 11.31*m.b21 + 11.31*m.b22 + 0.5*m.x115 + 0.5*m.x119 + m.x133 - m.x137 <= 11.31) m.c121 = Constraint(expr= 13*m.b21 - 13*m.b22 + 0.5*m.x124 + 0.5*m.x128 - m.x141 + m.x145 <= 13) m.c122 = Constraint(expr= 13*m.b21 + 13*m.b22 + 0.5*m.x124 + 0.5*m.x128 + m.x141 - m.x145 <= 26) m.c123 = Constraint(expr= - m.x80 + m.x133 - m.x138 <= 0) m.c124 = Constraint(expr= - m.x80 - m.x133 + m.x138 <= 0) m.c125 = Constraint(expr= - m.x81 + m.x141 - m.x146 <= 0) m.c126 = Constraint(expr= - m.x81 - m.x141 + m.x146 <= 0) m.c127 = Constraint(expr= - 11.31*m.b23 - 11.31*m.b24 + 0.5*m.x115 + 0.5*m.x120 - m.x133 + m.x138 <= 0) m.c128 = Constraint(expr= - 11.31*m.b23 + 11.31*m.b24 + 0.5*m.x115 + 0.5*m.x120 + m.x133 - m.x138 <= 11.31) m.c129 = Constraint(expr= 13*m.b23 - 13*m.b24 + 0.5*m.x124 + 0.5*m.x129 - m.x141 + m.x146 <= 13) m.c130 = Constraint(expr= 13*m.b23 + 13*m.b24 + 0.5*m.x124 + 0.5*m.x129 + m.x141 - m.x146 <= 26) m.c131 = Constraint(expr= - m.x82 + m.x133 - m.x139 <= 0) m.c132 = Constraint(expr= - m.x82 - m.x133 + m.x139 <= 0) m.c133 = Constraint(expr= - m.x83 + m.x141 - m.x147 <= 0) m.c134 = Constraint(expr= - m.x83 - m.x141 + m.x147 <= 0) m.c135 = Constraint(expr= - 11.31*m.b25 - 11.31*m.b26 + 0.5*m.x115 + 0.5*m.x121 - m.x133 + m.x139 <= 0) m.c136 = Constraint(expr= - 11.31*m.b25 + 11.31*m.b26 + 0.5*m.x115 + 0.5*m.x121 + m.x133 - m.x139 <= 11.31) m.c137 = Constraint(expr= 13*m.b25 - 13*m.b26 + 0.5*m.x124 + 0.5*m.x130 - m.x141 + m.x147 <= 13) m.c138 = Constraint(expr= 13*m.b25 + 13*m.b26 + 0.5*m.x124 + 0.5*m.x130 + m.x141 - m.x147 <= 26) m.c139 = Constraint(expr= - m.x84 + m.x134 - m.x135 <= 0) m.c140 = Constraint(expr= - m.x84 - m.x134 + m.x135 <= 0) m.c141 = Constraint(expr= - m.x85 + m.x142 - m.x143 <= 0) m.c142 = Constraint(expr= - m.x85 - m.x142 + m.x143 <= 0) m.c143 = Constraint(expr= - 11.31*m.b27 - 11.31*m.b28 + 0.5*m.x116 + 0.5*m.x117 - m.x134 + m.x135 <= 0) m.c144 = Constraint(expr= - 11.31*m.b27 + 11.31*m.b28 + 0.5*m.x116 + 0.5*m.x117 + m.x134 - m.x135 <= 11.31) m.c145 = Constraint(expr= 13*m.b27 - 13*m.b28 + 0.5*m.x125 + 0.5*m.x126 - m.x142 + m.x143 <= 13) m.c146 = Constraint(expr= 13*m.b27 + 13*m.b28 + 0.5*m.x125 + 0.5*m.x126 + m.x142 - m.x143 <= 26) m.c147 = Constraint(expr= - m.x86 + m.x134 - m.x136 <= 0) m.c148 = Constraint(expr= - m.x86 - m.x134 + m.x136 <= 0) m.c149 = Constraint(expr= - m.x87 + m.x142 - m.x144 <= 0) m.c150 = Constraint(expr= - m.x87 - m.x142 + m.x144 <= 0) m.c151 = Constraint(expr= - 11.31*m.b29 - 11.31*m.b30 + 0.5*m.x116 + 0.5*m.x118 - m.x134 + m.x136 <= 0) m.c152 = Constraint(expr= - 11.31*m.b29 + 11.31*m.b30 + 0.5*m.x116 + 0.5*m.x118 + m.x134 - m.x136 <= 11.31) m.c153 = Constraint(expr= 13*m.b29 - 13*m.b30 + 0.5*m.x125 + 0.5*m.x127 - m.x142 + m.x144 <= 13) m.c154 = Constraint(expr= 13*m.b29 + 13*m.b30 + 0.5*m.x125 + 0.5*m.x127 + m.x142 - m.x144 <= 26) m.c155 = Constraint(expr= - m.x88 + m.x134 - m.x137 <= 0) m.c156 = Constraint(expr= - m.x88 - m.x134 + m.x137 <= 0) m.c157 = Constraint(expr= - m.x89 + m.x142 - m.x145 <= 0) m.c158 = Constraint(expr= - m.x89 - m.x142 + m.x145 <= 0) m.c159 = Constraint(expr= - 11.31*m.b31 - 11.31*m.b32 + 0.5*m.x116 + 0.5*m.x119 - m.x134 + m.x137 <= 0) m.c160 = Constraint(expr= - 11.31*m.b31 + 11.31*m.b32 + 0.5*m.x116 + 0.5*m.x119 + m.x134 - m.x137 <= 11.31) m.c161 = Constraint(expr= 13*m.b31 - 13*m.b32 + 0.5*m.x125 + 0.5*m.x128 - m.x142 + m.x145 <= 13) m.c162 = Constraint(expr= 13*m.b31 + 13*m.b32 + 0.5*m.x125 + 0.5*m.x128 + m.x142 - m.x145 <= 26) m.c163 = Constraint(expr= - m.x90 + m.x134 - m.x138 <= 0) m.c164 = Constraint(expr= - m.x90 - m.x134 + m.x138 <= 0) m.c165 = Constraint(expr= - m.x91 + m.x142 - m.x146 <= 0) m.c166 = Constraint(expr= - m.x91 - m.x142 + m.x146 <= 0) m.c167 = Constraint(expr= - 11.31*m.b33 - 11.31*m.b34 + 0.5*m.x116 + 0.5*m.x120 - m.x134 + m.x138 <= 0) m.c168 = Constraint(expr= - 11.31*m.b33 + 11.31*m.b34 + 0.5*m.x116 + 0.5*m.x120 + m.x134 - m.x138 <= 11.31) m.c169 = Constraint(expr= 13*m.b33 - 13*m.b34 + 0.5*m.x125 + 0.5*m.x129 - m.x142 + m.x146 <= 13) m.c170 = Constraint(expr= 13*m.b33 + 13*m.b34 + 0.5*m.x125 + 0.5*m.x129 + m.x142 - m.x146 <= 26) m.c171 = Constraint(expr= - m.x92 + m.x134 - m.x139 <= 0) m.c172 = Constraint(expr= - m.x92 - m.x134 + m.x139 <= 0) m.c173 = Constraint(expr= - m.x93 + m.x142 - m.x147 <= 0) m.c174 = Constraint(expr= - m.x93 - m.x142 + m.x147 <= 0) m.c175 = Constraint(expr= - 11.31*m.b35 - 11.31*m.b36 + 0.5*m.x116 + 0.5*m.x121 - m.x134 + m.x139 <= 0) m.c176 = Constraint(expr= - 11.31*m.b35 + 11.31*m.b36 + 0.5*m.x116 + 0.5*m.x121 + m.x134 - m.x139 <= 11.31) m.c177 = Constraint(expr= 13*m.b35 - 13*m.b36 + 0.5*m.x125 + 0.5*m.x130 - m.x142 + m.x147 <= 13) m.c178 = Constraint(expr= 13*m.b35 + 13*m.b36 + 0.5*m.x125 + 0.5*m.x130 + m.x142 - m.x147 <= 26) m.c179 = Constraint(expr= - m.x94 + m.x135 - m.x136 <= 0) m.c180 = Constraint(expr= - m.x94 - m.x135 + m.x136 <= 0) m.c181 = Constraint(expr= - m.x95 + m.x143 - m.x144 <= 0) m.c182 = Constraint(expr= - m.x95 - m.x143 + m.x144 <= 0) m.c183 = Constraint(expr= - 11.31*m.b37 - 11.31*m.b38 + 0.5*m.x117 + 0.5*m.x118 - m.x135 + m.x136 <= 0) m.c184 = Constraint(expr= - 11.31*m.b37 + 11.31*m.b38 + 0.5*m.x117 + 0.5*m.x118 + m.x135 - m.x136 <= 11.31) m.c185 = Constraint(expr= 13*m.b37 - 13*m.b38 + 0.5*m.x126 + 0.5*m.x127 - m.x143 + m.x144 <= 13) m.c186 = Constraint(expr= 13*m.b37 + 13*m.b38 + 0.5*m.x126 + 0.5*m.x127 + m.x143 - m.x144 <= 26) m.c187 = Constraint(expr= - m.x96 + m.x135 - m.x137 <= 0) m.c188 = Constraint(expr= - m.x96 - m.x135 + m.x137 <= 0) m.c189 = Constraint(expr= - m.x97 + m.x143 - m.x145 <= 0) m.c190 = Constraint(expr= - m.x97 - m.x143 + m.x145 <= 0) m.c191 = Constraint(expr= - 11.31*m.b39 - 11.31*m.b40 + 0.5*m.x117 + 0.5*m.x119 - m.x135 + m.x137 <= 0) m.c192 = Constraint(expr= - 11.31*m.b39 + 11.31*m.b40 + 0.5*m.x117 + 0.5*m.x119 + m.x135 - m.x137 <= 11.31) m.c193 = Constraint(expr= 13*m.b39 - 13*m.b40 + 0.5*m.x126 + 0.5*m.x128 - m.x143 + m.x145 <= 13) m.c194 = Constraint(expr= 13*m.b39 + 13*m.b40 + 0.5*m.x126 + 0.5*m.x128 + m.x143 - m.x145 <= 26) m.c195 = Constraint(expr= - m.x98 + m.x135 - m.x138 <= 0) m.c196 = Constraint(expr= - m.x98 - m.x135 + m.x138 <= 0) m.c197 = Constraint(expr= - m.x99 + m.x143 - m.x146 <= 0) m.c198 = Constraint(expr= - m.x99 - m.x143 + m.x146 <= 0) m.c199 = Constraint(expr= - 11.31*m.b41 - 11.31*m.b42 + 0.5*m.x117 + 0.5*m.x120 - m.x135 + m.x138 <= 0) m.c200 = Constraint(expr= - 11.31*m.b41 + 11.31*m.b42 + 0.5*m.x117 + 0.5*m.x120 + m.x135 - m.x138 <= 11.31) m.c201 = Constraint(expr= 13*m.b41 - 13*m.b42 + 0.5*m.x126 + 0.5*m.x129 - m.x143 + m.x146 <= 13) m.c202 = Constraint(expr= 13*m.b41 + 13*m.b42 + 0.5*m.x126 + 0.5*m.x129 + m.x143 - m.x146 <= 26) m.c203 = Constraint(expr= - m.x100 + m.x135 - m.x139 <= 0) m.c204 = Constraint(expr= - m.x100 - m.x135 + m.x139 <= 0) m.c205 = Constraint(expr= - m.x101 + m.x143 - m.x147 <= 0) m.c206 = Constraint(expr= - m.x101 - m.x143 + m.x147 <= 0) m.c207 = Constraint(expr= - 11.31*m.b43 - 11.31*m.b44 + 0.5*m.x117 + 0.5*m.x121 - m.x135 + m.x139 <= 0) m.c208 = Constraint(expr= - 11.31*m.b43 + 11.31*m.b44 + 0.5*m.x117 + 0.5*m.x121 + m.x135 - m.x139 <= 11.31) m.c209 = Constraint(expr= 13*m.b43 - 13*m.b44 + 0.5*m.x126 + 0.5*m.x130 - m.x143 + m.x147 <= 13) m.c210 = Constraint(expr= 13*m.b43 + 13*m.b44 + 0.5*m.x126 + 0.5*m.x130 + m.x143 - m.x147 <= 26) m.c211 = Constraint(expr= - m.x102 + m.x136 - m.x137 <= 0) m.c212 = Constraint(expr= - m.x102 - m.x136 + m.x137 <= 0) m.c213 = Constraint(expr= - m.x103 + m.x144 - m.x145 <= 0) m.c214 = Constraint(expr= - m.x103 - m.x144 + m.x145 <= 0) m.c215 = Constraint(expr= - 11.31*m.b45 - 11.31*m.b46 + 0.5*m.x118 + 0.5*m.x119 - m.x136 + m.x137 <= 0) m.c216 = Constraint(expr= - 11.31*m.b45 + 11.31*m.b46 + 0.5*m.x118 + 0.5*m.x119 + m.x136 - m.x137 <= 11.31) m.c217 = Constraint(expr= 13*m.b45 - 13*m.b46 + 0.5*m.x127 + 0.5*m.x128 - m.x144 + m.x145 <= 13) m.c218 = Constraint(expr= 13*m.b45 + 13*m.b46 + 0.5*m.x127 + 0.5*m.x128 + m.x144 - m.x145 <= 26) m.c219 = Constraint(expr= - m.x104 + m.x136 - m.x138 <= 0) m.c220 = Constraint(expr= - m.x104 - m.x136 + m.x138 <= 0) m.c221 = Constraint(expr= - m.x105 + m.x144 - m.x146 <= 0) m.c222 = Constraint(expr= - m.x105 - m.x144 + m.x146 <= 0) m.c223 = Constraint(expr= - 11.31*m.b47 - 11.31*m.b48 + 0.5*m.x118 + 0.5*m.x120 - m.x136 + m.x138 <= 0) m.c224 = Constraint(expr= - 11.31*m.b47 + 11.31*m.b48 + 0.5*m.x118 + 0.5*m.x120 + m.x136 - m.x138 <= 11.31) m.c225 = Constraint(expr= 13*m.b47 - 13*m.b48 + 0.5*m.x127 + 0.5*m.x129 - m.x144 + m.x146 <= 13) m.c226 = Constraint(expr= 13*m.b47 + 13*m.b48 + 0.5*m.x127 + 0.5*m.x129 + m.x144 - m.x146 <= 26) m.c227 = Constraint(expr= - m.x106 + m.x136 - m.x139 <= 0) m.c228 = Constraint(expr= - m.x106 - m.x136 + m.x139 <= 0) m.c229 = Constraint(expr= - m.x107 + m.x144 - m.x147 <= 0) m.c230 = Constraint(expr= - m.x107 - m.x144 + m.x147 <= 0) m.c231 = Constraint(expr= - 11.31*m.b49 - 11.31*m.b50 + 0.5*m.x118 + 0.5*m.x121 - m.x136 + m.x139 <= 0) m.c232 = Constraint(expr= - 11.31*m.b49 + 11.31*m.b50 + 0.5*m.x118 + 0.5*m.x121 + m.x136 - m.x139 <= 11.31) m.c233 = Constraint(expr= 13*m.b49 - 13*m.b50 + 0.5*m.x127 + 0.5*m.x130 - m.x144 + m.x147 <= 13) m.c234 = Constraint(expr= 13*m.b49 + 13*m.b50 + 0.5*m.x127 + 0.5*m.x130 + m.x144 - m.x147 <= 26) m.c235 = Constraint(expr= - m.x108 + m.x137 - m.x138 <= 0) m.c236 = Constraint(expr= - m.x108 - m.x137 + m.x138 <= 0) m.c237 = Constraint(expr= - m.x109 + m.x145 - m.x146 <= 0) m.c238 = Constraint(expr= - m.x109 - m.x145 + m.x146 <= 0) m.c239 = Constraint(expr= - 11.31*m.b51 - 11.31*m.b52 + 0.5*m.x119 + 0.5*m.x120 - m.x137 + m.x138 <= 0) m.c240 = Constraint(expr= - 11.31*m.b51 + 11.31*m.b52 + 0.5*m.x119 + 0.5*m.x120 + m.x137 - m.x138 <= 11.31) m.c241 = Constraint(expr= 13*m.b51 - 13*m.b52 + 0.5*m.x128 + 0.5*m.x129 - m.x145 + m.x146 <= 13) m.c242 = Constraint(expr= 13*m.b51 + 13*m.b52 + 0.5*m.x128 + 0.5*m.x129 + m.x145 - m.x146 <= 26) m.c243 = Constraint(expr= - m.x110 + m.x137 - m.x139 <= 0) m.c244 = Constraint(expr= - m.x110 - m.x137 + m.x139 <= 0) m.c245 = Constraint(expr= - m.x111 + m.x145 - m.x147 <= 0) m.c246 = Constraint(expr= - m.x111 - m.x145 + m.x147 <= 0) m.c247 = Constraint(expr= - 11.31*m.b53 - 11.31*m.b54 + 0.5*m.x119 + 0.5*m.x121 - m.x137 + m.x139 <= 0) m.c248 = Constraint(expr= - 11.31*m.b53 + 11.31*m.b54 + 0.5*m.x119 + 0.5*m.x121 + m.x137 - m.x139 <= 11.31) m.c249 = Constraint(expr= 13*m.b53 - 13*m.b54 + 0.5*m.x128 + 0.5*m.x130 - m.x145 + m.x147 <= 13) m.c250 = Constraint(expr= 13*m.b53 + 13*m.b54 + 0.5*m.x128 + 0.5*m.x130 + m.x145 - m.x147 <= 26) m.c251 = Constraint(expr= - m.x112 + m.x138 - m.x139 <= 0) m.c252 = Constraint(expr= - m.x112 - m.x138 + m.x139 <= 0) m.c253 = Constraint(expr= - m.x113 + m.x146 - m.x147 <= 0) m.c254 = Constraint(expr= - m.x113 - m.x146 + m.x147 <= 0) m.c255 = Constraint(expr= - 11.31*m.b55 - 11.31*m.b56 + 0.5*m.x120 + 0.5*m.x121 - m.x138 + m.x139 <= 0) m.c256 = Constraint(expr= - 11.31*m.b55 + 11.31*m.b56 + 0.5*m.x120 + 0.5*m.x121 + m.x138 - m.x139 <= 11.31) m.c257 = Constraint(expr= 13*m.b55 - 13*m.b56 + 0.5*m.x129 + 0.5*m.x130 - m.x146 + m.x147 <= 13) m.c258 = Constraint(expr= 13*m.b55 + 13*m.b56 + 0.5*m.x129 + 0.5*m.x130 + m.x146 - m.x147 <= 26) m.c259 = Constraint(expr=16/m.x114 - m.x123 <= 0) m.c260 = Constraint(expr=16/m.x123 - m.x114 <= 0) m.c261 = Constraint(expr=16/m.x115 - m.x124 <= 0) m.c262 = Constraint(expr=16/m.x124 - m.x115 <= 0) m.c263 = Constraint(expr=16/m.x116 - m.x125 <= 0) m.c264 = Constraint(expr=16/m.x125 - m.x116 <= 0) m.c265 = Constraint(expr=36/m.x117 - m.x126 <= 0) m.c266 = Constraint(expr=36/m.x126 - m.x117 <= 0) m.c267 = Constraint(expr=36/m.x118 - m.x127 <= 0) m.c268 = Constraint(expr=36/m.x127 - m.x118 <= 0) m.c269 = Constraint(expr=9/m.x119 - m.x128 <= 0) m.c270 = Constraint(expr=9/m.x128 - m.x119 <= 0) m.c271 = Constraint(expr=9/m.x120 - m.x129 <= 0) m.c272 = Constraint(expr=9/m.x129 - m.x120 <= 0) m.c273 = Constraint(expr=9/m.x121 - m.x130 <= 0) m.c274 = Constraint(expr=9/m.x130 - m.x121 <= 0)
41.661111
114
0.610881
acf657e631e1d984826daddaf6d2ecf37694e994
2,494
py
Python
example/3_swarming_trigger_collect.py
pombredanne/swarming.client
45f9d61c66e18bf3bddc2022cba615abbeb826ce
[ "Apache-2.0" ]
null
null
null
example/3_swarming_trigger_collect.py
pombredanne/swarming.client
45f9d61c66e18bf3bddc2022cba615abbeb826ce
[ "Apache-2.0" ]
null
null
null
example/3_swarming_trigger_collect.py
pombredanne/swarming.client
45f9d61c66e18bf3bddc2022cba615abbeb826ce
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # Copyright 2012 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """Runs hello_world.py, through hello_world.isolate, remotely on a Swarming slave. It compiles and archives via 'isolate.py archive', then discard the local files. After, it triggers and finally collects the results. Creates 2 shards and instructs the script to produce a file in the output directory. """ import os import shutil import subprocess import sys import tempfile # Pylint can't find common.py that's in the same directory as this file. # pylint: disable=F0401 import common def main(): options = common.parse_args(use_isolate_server=True, use_swarming=True) try: tempdir = tempfile.mkdtemp(prefix=u'hello_world') try: _, hashval = common.isolate( tempdir, options.isolate_server, options.swarming_os, options.verbose) json_file = os.path.join(tempdir, 'task.json') common.note('Running on %s' % options.swarming) cmd = [ 'swarming.py', 'trigger', '--swarming', options.swarming, '--isolate-server', options.isolate_server, '--dimension', 'os', options.swarming_os, '--dimension', 'pool', 'default', '--task-name', options.task_name, '--dump-json', json_file, '--isolated', hashval, '--shards', '2', ] if options.idempotent: cmd.append('--idempotent') if options.priority is not None: cmd.extend(('--priority', str(options.priority))) if options.service_account: cmd.extend(('--service-account', options.service_account)) cmd.extend(('--', '${ISOLATED_OUTDIR}')) common.run(cmd, options.verbose) common.note('Getting results from %s' % options.swarming) common.run( [ 'swarming.py', 'collect', '--swarming', options.swarming, '--json', json_file, '--task-output-dir', 'example_result', ], options.verbose) for root, _, files in os.walk('example_result'): for name in files: p = os.path.join(root, name) with open(p, 'rb') as f: print('%s content:' % p) print(f.read()) return 0 finally: shutil.rmtree(tempdir) except subprocess.CalledProcessError as e: return e.returncode if __name__ == '__main__': sys.exit(main())
30.414634
80
0.631115
acf6588270b78e0b3cc2ea4ab84475ba95dd51d3
9,018
py
Python
RelationExtraction/utils/utils_re.py
nsu-ai/few-shot-nlu
163b1fa7275cd1a0640c111bfc4bcfead6e0cab4
[ "Apache-2.0" ]
4
2020-09-10T19:50:24.000Z
2021-09-22T13:50:12.000Z
RelationExtraction/utils/utils_re.py
nsu-ai/few-shot-nlu
163b1fa7275cd1a0640c111bfc4bcfead6e0cab4
[ "Apache-2.0" ]
null
null
null
RelationExtraction/utils/utils_re.py
nsu-ai/few-shot-nlu
163b1fa7275cd1a0640c111bfc4bcfead6e0cab4
[ "Apache-2.0" ]
3
2020-08-19T15:47:37.000Z
2022-01-21T02:49:12.000Z
""" From https://github.com/monologg/R-BERT/blob/master/data_loader.py """ import os import csv import copy import json import logging import torch from torch.utils.data import TensorDataset ADDITIONAL_SPECIAL_TOKENS = ["<e1>", "</e1>", "<e2>", "</e2>"] logger = logging.getLogger(__name__) class InputExample(object): """ A single training/test example for simple sequence classification. Args: guid: Unique id for the example. text_a: string. The untokenized text of the first sequence. For single sequence tasks, only this sequence must be specified. label: (Optional) string. The label of the example. This should be specified for train and dev examples, but not for test examples. """ def __init__(self, guid, text_a, label): self.guid = guid self.text_a = text_a self.label = label def __repr__(self): return str(self.to_json_string()) def to_dict(self): """Serializes this instance to a Python dictionary.""" output = copy.deepcopy(self.__dict__) return output def to_json_string(self): """Serializes this instance to a JSON string.""" return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" class InputFeatures(object): """ A single set of features of data. Args: input_ids: Indices of input sequence tokens in the vocabulary. attention_mask: Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: Usually ``1`` for tokens that are NOT MASKED, ``0`` for MASKED (padded) tokens. token_type_ids: Segment token indices to indicate first and second portions of the inputs. """ def __init__(self, input_ids, attention_mask, token_type_ids, label_id, e1_mask, e2_mask): self.input_ids = input_ids self.attention_mask = attention_mask self.token_type_ids = token_type_ids self.label_id = label_id self.e1_mask = e1_mask self.e2_mask = e2_mask def __repr__(self): return str(self.to_json_string()) def to_dict(self): """Serializes this instance to a Python dictionary.""" output = copy.deepcopy(self.__dict__) return output def to_json_string(self): """Serializes this instance to a JSON string.""" return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" class DataProcessor(object): """Processor for the Semeval like dataset """ def __init__(self, args): self.args = args self.relation_labels = get_labels(args) @classmethod def _read_tsv(cls, input_file, quotechar=None): """Reads a tab separated value file.""" with open(input_file, "r", encoding="utf-8") as f: reader = csv.reader(f, delimiter="\t", quotechar=quotechar) lines = [] for line in reader: lines.append(line) return lines def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): guid = "%s-%s" % (set_type, i) text_a = line[0] label = self.relation_labels.index(line[1]) if i % 1000 == 0: logger.info(line) examples.append(InputExample(guid=guid, text_a=text_a, label=label)) return examples def get_examples(self, mode): """ Args: mode: train, dev, test """ file_to_read = None if mode == 'train': file_to_read = self.args.train_file elif mode == 'dev': file_to_read = self.args.dev_file elif mode == 'test': file_to_read = self.args.test_file logger.info("LOOKING AT {}".format(os.path.join(self.args.data_dir, file_to_read))) return self._create_examples(self._read_tsv(os.path.join(self.args.data_dir, file_to_read)), mode) processors = { "semeval": DataProcessor } def read_examples_from_file(data_dir, mode): file_path = os.path.join(data_dir, "{}.txt".format(mode)) guid_index = 1 examples = [] with open(file_path, "r", encoding="utf-8") as f: for line in f.readlines(): line = line.strip().split("\t") if len(line) == 2: text_a = line[0] label = line[1] else: text_a = line[0] label = "NONE" examples.append(InputExample(guid=guid_index, text_a=text_a, label=label)) guid_index += 1 return examples def convert_examples_to_features(examples, max_seq_len, tokenizer, labels, cls_token='[CLS]', cls_token_segment_id=0, sep_token='[SEP]', pad_token=0, pad_token_segment_id=0, sequence_a_segment_id=0, add_sep_token=False, mask_padding_with_zero=True): features = [] for (ex_index, example) in enumerate(examples): if ex_index % 5000 == 0: logger.info("Writing example %d of %d" % (ex_index, len(examples))) tokens_a = tokenizer.tokenize(example.text_a) e11_p = tokens_a.index("<e1>") # the start position of entity1 e12_p = tokens_a.index("</e1>") # the end position of entity1 e21_p = tokens_a.index("<e2>") # the start position of entity2 e22_p = tokens_a.index("</e2>") # the end position of entity2 # Replace the token tokens_a[e11_p] = "$" tokens_a[e12_p] = "$" tokens_a[e21_p] = "#" tokens_a[e22_p] = "#" # Add 1 because of the [CLS] token e11_p += 1 e12_p += 1 e21_p += 1 e22_p += 1 # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. if add_sep_token: special_tokens_count = 2 else: special_tokens_count = 1 if len(tokens_a) > max_seq_len - special_tokens_count: tokens_a = tokens_a[:(max_seq_len - special_tokens_count)] tokens = tokens_a if add_sep_token: tokens += [sep_token] token_type_ids = [sequence_a_segment_id] * len(tokens) tokens = [cls_token] + tokens token_type_ids = [cls_token_segment_id] + token_type_ids input_ids = tokenizer.convert_tokens_to_ids(tokens) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. attention_mask = [1 if mask_padding_with_zero else 0] * len(input_ids) # Zero-pad up to the sequence length. padding_length = max_seq_len - len(input_ids) input_ids = input_ids + ([pad_token] * padding_length) attention_mask = attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length) token_type_ids = token_type_ids + ([pad_token_segment_id] * padding_length) # e1 mask, e2 mask e1_mask = [0] * len(attention_mask) e2_mask = [0] * len(attention_mask) for i in range(e11_p, e12_p + 1): e1_mask[i] = 1 for i in range(e21_p, e22_p + 1): e2_mask[i] = 1 assert len(input_ids) == max_seq_len, "Error with input length {} vs {}".format(len(input_ids), max_seq_len) assert len(attention_mask) == max_seq_len, "Error with attention mask length {} vs {}".format(len(attention_mask), max_seq_len) assert len(token_type_ids) == max_seq_len, "Error with token type length {} vs {}".format(len(token_type_ids), max_seq_len) label_id = labels.index(example.label) if ex_index < 5: logger.info("*** Example ***") logger.info("guid: %s" % example.guid) logger.info("tokens: %s" % " ".join([str(x) for x in tokens])) logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids])) logger.info("attention_mask: %s" % " ".join([str(x) for x in attention_mask])) logger.info("token_type_ids: %s" % " ".join([str(x) for x in token_type_ids])) logger.info("label: %s (id = %d)" % (example.label, label_id)) logger.info("e1_mask: %s" % " ".join([str(x) for x in e1_mask])) logger.info("e2_mask: %s" % " ".join([str(x) for x in e2_mask])) features.append( InputFeatures(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, label_id=label_id, e1_mask=e1_mask, e2_mask=e2_mask)) return features def get_labels(labels): return [label.strip() for label in open(labels, 'r', encoding='utf-8')]
35.785714
135
0.58605
acf6591bb1665cf0bc3962ce43b41023d5b99557
5,214
py
Python
tests/restart-scenarios-test.py
APFDev/actc
be5c1c0539d30a3745a725b0027767448ef8e1f6
[ "MIT" ]
5
2021-01-13T03:34:00.000Z
2021-09-09T05:42:18.000Z
tests/restart-scenarios-test.py
APFDev/actc
be5c1c0539d30a3745a725b0027767448ef8e1f6
[ "MIT" ]
1
2020-05-16T06:30:28.000Z
2020-05-16T06:37:55.000Z
tests/restart-scenarios-test.py
APFDev/actc
be5c1c0539d30a3745a725b0027767448ef8e1f6
[ "MIT" ]
6
2020-01-06T11:18:54.000Z
2020-01-07T09:32:18.000Z
#!/usr/bin/env python3 from testUtils import Utils from Cluster import Cluster from WalletMgr import WalletMgr from TestHelper import TestHelper import random ############################################################### # Test for different nodes restart scenarios. # Nodes can be producing or non-producing. # -p <producing nodes count> # -c <chain strategy[replay|resync|none]> # -s <topology> # -d <delay between nodes startup> # -v <verbose logging> # --kill-sig <kill signal [term|kill]> # --kill-count <nodroxe instances to kill> # --dont-kill <Leave cluster running after test finishes> # --dump-error-details <Upon error print etc/roxe/node_*/config.ini and var/lib/node_*/stderr.log to stdout> # --keep-logs <Don't delete var/lib/node_* folders upon test completion> ############################################################### Print=Utils.Print errorExit=Utils.errorExit args=TestHelper.parse_args({"-p","-d","-s","-c","--kill-sig","--kill-count","--keep-logs" ,"--dump-error-details","-v","--leave-running","--clean-run"}) pnodes=args.p topo=args.s delay=args.d chainSyncStrategyStr=args.c debug=args.v total_nodes = pnodes killCount=args.kill_count if args.kill_count > 0 else 1 killSignal=args.kill_sig killRoxeInstances= not args.leave_running dumpErrorDetails=args.dump_error_details keepLogs=args.keep_logs killAll=args.clean_run seed=1 Utils.Debug=debug testSuccessful=False random.seed(seed) # Use a fixed seed for repeatability. cluster=Cluster(walletd=True) walletMgr=WalletMgr(True) try: TestHelper.printSystemInfo("BEGIN") cluster.setWalletMgr(walletMgr) cluster.setChainStrategy(chainSyncStrategyStr) cluster.setWalletMgr(walletMgr) cluster.killall(allInstances=killAll) cluster.cleanup() walletMgr.killall(allInstances=killAll) walletMgr.cleanup() Print ("producing nodes: %d, topology: %s, delay between nodes launch(seconds): %d, chain sync strategy: %s" % ( pnodes, topo, delay, chainSyncStrategyStr)) Print("Stand up cluster") if cluster.launch(pnodes=pnodes, totalNodes=total_nodes, topo=topo, delay=delay) is False: errorExit("Failed to stand up roxe cluster.") Print ("Wait for Cluster stabilization") # wait for cluster to start producing blocks if not cluster.waitOnClusterBlockNumSync(3): errorExit("Cluster never stabilized") Print("Stand up ROXE wallet kroxed") accountsCount=total_nodes walletName="MyWallet" Print("Creating wallet %s if one doesn't already exist." % walletName) wallet=walletMgr.create(walletName, [cluster.roxeAccount,cluster.defproduceraAccount,cluster.defproducerbAccount]) Print ("Populate wallet with %d accounts." % (accountsCount)) if not cluster.populateWallet(accountsCount, wallet): errorExit("Wallet initialization failed.") defproduceraAccount=cluster.defproduceraAccount roxeAccount=cluster.roxeAccount Print("Importing keys for account %s into wallet %s." % (defproduceraAccount.name, wallet.name)) if not walletMgr.importKey(defproduceraAccount, wallet): errorExit("Failed to import key for account %s" % (defproduceraAccount.name)) Print("Create accounts.") if not cluster.createAccounts(roxeAccount): errorExit("Accounts creation failed.") Print("Wait on cluster sync.") if not cluster.waitOnClusterSync(): errorExit("Cluster sync wait failed.") Print("Kill %d cluster node instances." % (killCount)) if cluster.killSomeRoxeInstances(killCount, killSignal) is False: errorExit("Failed to kill Roxe instances") Print("nodroxe instances killed.") Print("Spread funds and validate") if not cluster.spreadFundsAndValidate(10): errorExit("Failed to spread and validate funds.") Print("Wait on cluster sync.") if not cluster.waitOnClusterSync(): errorExit("Cluster sync wait failed.") Print ("Relaunch dead cluster nodes instances.") if cluster.relaunchRoxeInstances(cachePopen=True) is False: errorExit("Failed to relaunch Roxe instances") Print("nodroxe instances relaunched.") Print ("Resyncing cluster nodes.") if not cluster.waitOnClusterSync(): errorExit("Cluster never synchronized") Print ("Cluster synched") Print("Spread funds and validate") if not cluster.spreadFundsAndValidate(10): errorExit("Failed to spread and validate funds.") Print("Wait on cluster sync.") if not cluster.waitOnClusterSync(): errorExit("Cluster sync wait failed.") if killRoxeInstances: atLeastOne=False for node in cluster.getNodes(): if node.popenProc is not None: atLeastOne=True node.interruptAndVerifyExitStatus() assert atLeastOne, "Test is setup to verify that a cleanly interrupted nodroxe exits with an exit status of 0, but this test may no longer be setup to do that" testSuccessful=True finally: TestHelper.shutdown(cluster, walletMgr, testSuccessful=testSuccessful, killRoxeInstances=killRoxeInstances, killWallet=killRoxeInstances, keepLogs=keepLogs, cleanRun=killAll, dumpErrorDetails=dumpErrorDetails) exit(0)
35.958621
213
0.708861
acf65a464a45fbb17d2bf59159321b7d5c6041e6
126,186
py
Python
pandas/core/groupby/groupby.py
kuantan/pandas
e18921eb0cc86f71c84a4aa0bd6d0c1b7de89def
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause" ]
3
2018-04-24T13:31:51.000Z
2019-07-09T07:31:43.000Z
pandas/core/groupby/groupby.py
fanoway/pandas
71312683b41b5177faf7ecd63555059504853cbd
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause" ]
4
2019-12-14T16:32:46.000Z
2022-02-12T00:32:28.000Z
pandas/core/groupby/groupby.py
lithomas1/pandas
e18921eb0cc86f71c84a4aa0bd6d0c1b7de89def
[ "PSF-2.0", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "ECL-2.0", "BSD-3-Clause" ]
5
2018-04-24T13:31:56.000Z
2021-10-21T05:06:23.000Z
""" Provide the groupby split-apply-combine paradigm. Define the GroupBy class providing the base-class of operations. The SeriesGroupBy and DataFrameGroupBy sub-class (defined in pandas.core.groupby.generic) expose these user-facing objects to provide specific functionality. """ from __future__ import annotations from contextlib import contextmanager import datetime from functools import ( partial, wraps, ) import inspect from textwrap import dedent import types from typing import ( Callable, Hashable, Iterable, Iterator, List, Literal, Mapping, Sequence, TypeVar, Union, cast, final, ) import warnings import numpy as np from pandas._config.config import option_context from pandas._libs import ( Timestamp, lib, ) import pandas._libs.groupby as libgroupby from pandas._typing import ( ArrayLike, IndexLabel, NDFrameT, PositionalIndexer, RandomState, Scalar, T, npt, ) from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import ( Appender, Substitution, cache_readonly, doc, ) from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_bool_dtype, is_datetime64_dtype, is_float_dtype, is_integer, is_integer_dtype, is_numeric_dtype, is_object_dtype, is_scalar, is_timedelta64_dtype, ) from pandas.core.dtypes.missing import ( isna, notna, ) from pandas.core import nanops from pandas.core._numba import executor import pandas.core.algorithms as algorithms from pandas.core.arrays import ( BaseMaskedArray, BooleanArray, Categorical, ExtensionArray, ) from pandas.core.base import ( DataError, PandasObject, SelectionMixin, ) import pandas.core.common as com from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame from pandas.core.groupby import ( base, numba_, ops, ) from pandas.core.groupby.indexing import ( GroupByIndexingMixin, GroupByNthSelector, ) from pandas.core.indexes.api import ( CategoricalIndex, Index, MultiIndex, ) from pandas.core.internals.blocks import ensure_block_shape import pandas.core.sample as sample from pandas.core.series import Series from pandas.core.sorting import get_group_index_sorter from pandas.core.util.numba_ import ( NUMBA_FUNC_CACHE, maybe_use_numba, ) _common_see_also = """ See Also -------- Series.%(name)s : Apply a function %(name)s to a Series. DataFrame.%(name)s : Apply a function %(name)s to each row or column of a DataFrame. """ _apply_docs = { "template": """ Apply function ``func`` group-wise and combine the results together. The function passed to ``apply`` must take a {input} as its first argument and return a DataFrame, Series or scalar. ``apply`` will then take care of combining the results back together into a single dataframe or series. ``apply`` is therefore a highly flexible grouping method. While ``apply`` is a very flexible method, its downside is that using it can be quite a bit slower than using more specific methods like ``agg`` or ``transform``. Pandas offers a wide range of method that will be much faster than using ``apply`` for their specific purposes, so try to use them before reaching for ``apply``. Parameters ---------- func : callable A callable that takes a {input} as its first argument, and returns a dataframe, a series or a scalar. In addition the callable may take positional and keyword arguments. args, kwargs : tuple and dict Optional positional and keyword arguments to pass to ``func``. Returns ------- applied : Series or DataFrame See Also -------- pipe : Apply function to the full GroupBy object instead of to each group. aggregate : Apply aggregate function to the GroupBy object. transform : Apply function column-by-column to the GroupBy object. Series.apply : Apply a function to a Series. DataFrame.apply : Apply a function to each row or column of a DataFrame. Notes ----- .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the passed ``func``, see the examples below. Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` for more details. Examples -------- {examples} """, "dataframe_examples": """ >>> df = pd.DataFrame({'A': 'a a b'.split(), ... 'B': [1,2,3], ... 'C': [4,6,5]}) >>> g = df.groupby('A') Notice that ``g`` has two groups, ``a`` and ``b``. Calling `apply` in various ways, we can get different grouping results: Example 1: below the function passed to `apply` takes a DataFrame as its argument and returns a DataFrame. `apply` combines the result for each group together into a new DataFrame: >>> g[['B', 'C']].apply(lambda x: x / x.sum()) B C 0 0.333333 0.4 1 0.666667 0.6 2 1.000000 1.0 Example 2: The function passed to `apply` takes a DataFrame as its argument and returns a Series. `apply` combines the result for each group together into a new DataFrame. .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the passed ``func``. >>> g[['B', 'C']].apply(lambda x: x.astype(float).max() - x.min()) B C A a 1.0 2.0 b 0.0 0.0 Example 3: The function passed to `apply` takes a DataFrame as its argument and returns a scalar. `apply` combines the result for each group together into a Series, including setting the index as appropriate: >>> g.apply(lambda x: x.C.max() - x.B.min()) A a 5 b 2 dtype: int64""", "series_examples": """ >>> s = pd.Series([0, 1, 2], index='a a b'.split()) >>> g = s.groupby(s.index) From ``s`` above we can see that ``g`` has two groups, ``a`` and ``b``. Calling `apply` in various ways, we can get different grouping results: Example 1: The function passed to `apply` takes a Series as its argument and returns a Series. `apply` combines the result for each group together into a new Series. .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the passed ``func``. >>> g.apply(lambda x: x*2 if x.name == 'a' else x/2) a 0.0 a 2.0 b 1.0 dtype: float64 Example 2: The function passed to `apply` takes a Series as its argument and returns a scalar. `apply` combines the result for each group together into a Series, including setting the index as appropriate: >>> g.apply(lambda x: x.max() - x.min()) a 1 b 0 dtype: int64""", } _groupby_agg_method_template = """ Compute {fname} of group values. Parameters ---------- numeric_only : bool, default {no} Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. min_count : int, default {mc} The required number of valid values to perform the operation. If fewer than ``min_count`` non-NA values are present the result will be NA. Returns ------- Series or DataFrame Computed {fname} of values within each group. """ _pipe_template = """ Apply a function `func` with arguments to this %(klass)s object and return the function's result. Use `.pipe` when you want to improve readability by chaining together functions that expect Series, DataFrames, GroupBy or Resampler objects. Instead of writing >>> h(g(f(df.groupby('group')), arg1=a), arg2=b, arg3=c) # doctest: +SKIP You can write >>> (df.groupby('group') ... .pipe(f) ... .pipe(g, arg1=a) ... .pipe(h, arg2=b, arg3=c)) # doctest: +SKIP which is much more readable. Parameters ---------- func : callable or tuple of (callable, str) Function to apply to this %(klass)s object or, alternatively, a `(callable, data_keyword)` tuple where `data_keyword` is a string indicating the keyword of `callable` that expects the %(klass)s object. args : iterable, optional Positional arguments passed into `func`. kwargs : dict, optional A dictionary of keyword arguments passed into `func`. Returns ------- object : the return type of `func`. See Also -------- Series.pipe : Apply a function with arguments to a series. DataFrame.pipe: Apply a function with arguments to a dataframe. apply : Apply function to each group instead of to the full %(klass)s object. Notes ----- See more `here <https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#piping-function-calls>`_ Examples -------- %(examples)s """ _transform_template = """ Call function producing a like-indexed %(klass)s on each group and return a %(klass)s having the same indexes as the original object filled with the transformed values. Parameters ---------- f : function Function to apply to each group. Can also accept a Numba JIT function with ``engine='numba'`` specified. If the ``'numba'`` engine is chosen, the function must be a user defined function with ``values`` and ``index`` as the first and second arguments respectively in the function signature. Each group's index will be passed to the user defined function and optionally available for use. .. versionchanged:: 1.1.0 *args Positional arguments to pass to func. engine : str, default None * ``'cython'`` : Runs the function through C-extensions from cython. * ``'numba'`` : Runs the function through JIT compiled code from numba. * ``None`` : Defaults to ``'cython'`` or the global setting ``compute.use_numba`` .. versionadded:: 1.1.0 engine_kwargs : dict, default None * For ``'cython'`` engine, there are no accepted ``engine_kwargs`` * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil`` and ``parallel`` dictionary keys. The values must either be ``True`` or ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is ``{'nopython': True, 'nogil': False, 'parallel': False}`` and will be applied to the function .. versionadded:: 1.1.0 **kwargs Keyword arguments to be passed into func. Returns ------- %(klass)s See Also -------- %(klass)s.groupby.apply : Apply function ``func`` group-wise and combine the results together. %(klass)s.groupby.aggregate : Aggregate using one or more operations over the specified axis. %(klass)s.transform : Call ``func`` on self producing a %(klass)s with transformed values. Notes ----- Each group is endowed the attribute 'name' in case you need to know which group you are working on. The current implementation imposes three requirements on f: * f must return a value that either has the same shape as the input subframe or can be broadcast to the shape of the input subframe. For example, if `f` returns a scalar it will be broadcast to have the same shape as the input subframe. * if this is a DataFrame, f must support application column-by-column in the subframe. If f also supports application to the entire subframe, then a fast path is used starting from the second chunk. * f must not mutate groups. Mutation is not supported and may produce unexpected results. See :ref:`gotchas.udf-mutation` for more details. When using ``engine='numba'``, there will be no "fall back" behavior internally. The group data and group index will be passed as numpy arrays to the JITed user defined function, and no alternative execution attempts will be tried. .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the passed ``func``, see the examples below. Examples -------- >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', ... 'foo', 'bar'], ... 'B' : ['one', 'one', 'two', 'three', ... 'two', 'two'], ... 'C' : [1, 5, 5, 2, 5, 5], ... 'D' : [2.0, 5., 8., 1., 2., 9.]}) >>> grouped = df.groupby('A') >>> grouped.transform(lambda x: (x - x.mean()) / x.std()) C D 0 -1.154701 -0.577350 1 0.577350 0.000000 2 0.577350 1.154701 3 -1.154701 -1.000000 4 0.577350 -0.577350 5 0.577350 1.000000 Broadcast result of the transformation >>> grouped.transform(lambda x: x.max() - x.min()) C D 0 4 6.0 1 3 8.0 2 4 6.0 3 3 8.0 4 4 6.0 5 3 8.0 .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the passed ``func``, for example: >>> grouped[['C', 'D']].transform(lambda x: x.astype(int).max()) C D 0 5 8 1 5 9 2 5 8 3 5 9 4 5 8 5 5 9 """ _agg_template = """ Aggregate using one or more operations over the specified axis. Parameters ---------- func : function, str, list or dict Function to use for aggregating the data. If a function, must either work when passed a {klass} or when passed to {klass}.apply. Accepted combinations are: - function - string function name - list of functions and/or function names, e.g. ``[np.sum, 'mean']`` - dict of axis labels -> functions, function names or list of such. Can also accept a Numba JIT function with ``engine='numba'`` specified. Only passing a single function is supported with this engine. If the ``'numba'`` engine is chosen, the function must be a user defined function with ``values`` and ``index`` as the first and second arguments respectively in the function signature. Each group's index will be passed to the user defined function and optionally available for use. .. versionchanged:: 1.1.0 *args Positional arguments to pass to func. engine : str, default None * ``'cython'`` : Runs the function through C-extensions from cython. * ``'numba'`` : Runs the function through JIT compiled code from numba. * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba`` .. versionadded:: 1.1.0 engine_kwargs : dict, default None * For ``'cython'`` engine, there are no accepted ``engine_kwargs`` * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil`` and ``parallel`` dictionary keys. The values must either be ``True`` or ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is ``{{'nopython': True, 'nogil': False, 'parallel': False}}`` and will be applied to the function .. versionadded:: 1.1.0 **kwargs Keyword arguments to be passed into func. Returns ------- {klass} See Also -------- {klass}.groupby.apply : Apply function func group-wise and combine the results together. {klass}.groupby.transform : Aggregate using one or more operations over the specified axis. {klass}.aggregate : Transforms the Series on each group based on the given function. Notes ----- When using ``engine='numba'``, there will be no "fall back" behavior internally. The group data and group index will be passed as numpy arrays to the JITed user defined function, and no alternative execution attempts will be tried. Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` for more details. .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the passed ``func``, see the examples below. {examples}""" @final class GroupByPlot(PandasObject): """ Class implementing the .plot attribute for groupby objects. """ def __init__(self, groupby: GroupBy): self._groupby = groupby def __call__(self, *args, **kwargs): def f(self): return self.plot(*args, **kwargs) f.__name__ = "plot" return self._groupby.apply(f) def __getattr__(self, name: str): def attr(*args, **kwargs): def f(self): return getattr(self.plot, name)(*args, **kwargs) return self._groupby.apply(f) return attr _KeysArgType = Union[ Hashable, List[Hashable], Callable[[Hashable], Hashable], List[Callable[[Hashable], Hashable]], Mapping[Hashable, Hashable], ] class BaseGroupBy(PandasObject, SelectionMixin[NDFrameT], GroupByIndexingMixin): _group_selection: IndexLabel | None = None _apply_allowlist: frozenset[str] = frozenset() _hidden_attrs = PandasObject._hidden_attrs | { "as_index", "axis", "dropna", "exclusions", "grouper", "group_keys", "keys", "level", "mutated", "obj", "observed", "sort", "squeeze", } axis: int grouper: ops.BaseGrouper group_keys: bool @final def __len__(self) -> int: return len(self.groups) @final def __repr__(self) -> str: # TODO: Better repr for GroupBy object return object.__repr__(self) @final @property def groups(self) -> dict[Hashable, np.ndarray]: """ Dict {group name -> group labels}. """ return self.grouper.groups @final @property def ngroups(self) -> int: return self.grouper.ngroups @final @property def indices(self): """ Dict {group name -> group indices}. """ return self.grouper.indices @final def _get_indices(self, names): """ Safe get multiple indices, translate keys for datelike to underlying repr. """ def get_converter(s): # possibly convert to the actual key types # in the indices, could be a Timestamp or a np.datetime64 if isinstance(s, datetime.datetime): return lambda key: Timestamp(key) elif isinstance(s, np.datetime64): return lambda key: Timestamp(key).asm8 else: return lambda key: key if len(names) == 0: return [] if len(self.indices) > 0: index_sample = next(iter(self.indices)) else: index_sample = None # Dummy sample name_sample = names[0] if isinstance(index_sample, tuple): if not isinstance(name_sample, tuple): msg = "must supply a tuple to get_group with multiple grouping keys" raise ValueError(msg) if not len(name_sample) == len(index_sample): try: # If the original grouper was a tuple return [self.indices[name] for name in names] except KeyError as err: # turns out it wasn't a tuple msg = ( "must supply a same-length tuple to get_group " "with multiple grouping keys" ) raise ValueError(msg) from err converters = [get_converter(s) for s in index_sample] names = (tuple(f(n) for f, n in zip(converters, name)) for name in names) else: converter = get_converter(index_sample) names = (converter(name) for name in names) return [self.indices.get(name, []) for name in names] @final def _get_index(self, name): """ Safe get index, translate keys for datelike to underlying repr. """ return self._get_indices([name])[0] @final @cache_readonly def _selected_obj(self): # Note: _selected_obj is always just `self.obj` for SeriesGroupBy if self._selection is None or isinstance(self.obj, Series): if self._group_selection is not None: return self.obj[self._group_selection] return self.obj else: return self.obj[self._selection] @final def _dir_additions(self) -> set[str]: return self.obj._dir_additions() | self._apply_allowlist @Substitution( klass="GroupBy", examples=dedent( """\ >>> df = pd.DataFrame({'A': 'a b a b'.split(), 'B': [1, 2, 3, 4]}) >>> df A B 0 a 1 1 b 2 2 a 3 3 b 4 To get the difference between each groups maximum and minimum value in one pass, you can do >>> df.groupby('A').pipe(lambda x: x.max() - x.min()) B A a 2 b 2""" ), ) @Appender(_pipe_template) def pipe( self, func: Callable[..., T] | tuple[Callable[..., T], str], *args, **kwargs, ) -> T: return com.pipe(self, func, *args, **kwargs) plot = property(GroupByPlot) @final def get_group(self, name, obj=None) -> DataFrame | Series: """ Construct DataFrame from group with provided name. Parameters ---------- name : object The name of the group to get as a DataFrame. obj : DataFrame, default None The DataFrame to take the DataFrame out of. If it is None, the object groupby was called on will be used. Returns ------- group : same type as obj """ if obj is None: obj = self._selected_obj inds = self._get_index(name) if not len(inds): raise KeyError(name) return obj._take_with_is_copy(inds, axis=self.axis) @final def __iter__(self) -> Iterator[tuple[Hashable, NDFrameT]]: """ Groupby iterator. Returns ------- Generator yielding sequence of (name, subsetted object) for each group """ return self.grouper.get_iterator(self._selected_obj, axis=self.axis) # To track operations that expand dimensions, like ohlc OutputFrameOrSeries = TypeVar("OutputFrameOrSeries", bound=NDFrame) class GroupBy(BaseGroupBy[NDFrameT]): """ Class for grouping and aggregating relational data. See aggregate, transform, and apply functions on this object. It's easiest to use obj.groupby(...) to use GroupBy, but you can also do: :: grouped = groupby(obj, ...) Parameters ---------- obj : pandas object axis : int, default 0 level : int, default None Level of MultiIndex groupings : list of Grouping objects Most users should ignore this exclusions : array-like, optional List of columns to exclude name : str Most users should ignore this Returns ------- **Attributes** groups : dict {group name -> group labels} len(grouped) : int Number of groups Notes ----- After grouping, see aggregate, apply, and transform functions. Here are some other brief notes about usage. When grouping by multiple groups, the result index will be a MultiIndex (hierarchical) by default. Iteration produces (key, group) tuples, i.e. chunking the data by group. So you can write code like: :: grouped = obj.groupby(keys, axis=axis) for key, group in grouped: # do something with the data Function calls on GroupBy, if not specially implemented, "dispatch" to the grouped data. So if you group a DataFrame and wish to invoke the std() method on each group, you can simply do: :: df.groupby(mapper).std() rather than :: df.groupby(mapper).aggregate(np.std) You can pass arguments to these "wrapped" functions, too. See the online documentation for full exposition on these topics and much more """ grouper: ops.BaseGrouper as_index: bool @final def __init__( self, obj: NDFrameT, keys: _KeysArgType | None = None, axis: int = 0, level: IndexLabel | None = None, grouper: ops.BaseGrouper | None = None, exclusions: frozenset[Hashable] | None = None, selection: IndexLabel | None = None, as_index: bool = True, sort: bool = True, group_keys: bool = True, squeeze: bool = False, observed: bool = False, mutated: bool = False, dropna: bool = True, ): self._selection = selection assert isinstance(obj, NDFrame), type(obj) self.level = level if not as_index: if not isinstance(obj, DataFrame): raise TypeError("as_index=False only valid with DataFrame") if axis != 0: raise ValueError("as_index=False only valid for axis=0") self.as_index = as_index self.keys = keys self.sort = sort self.group_keys = group_keys self.squeeze = squeeze self.observed = observed self.mutated = mutated self.dropna = dropna if grouper is None: from pandas.core.groupby.grouper import get_grouper grouper, exclusions, obj = get_grouper( obj, keys, axis=axis, level=level, sort=sort, observed=observed, mutated=self.mutated, dropna=self.dropna, ) self.obj = obj self.axis = obj._get_axis_number(axis) self.grouper = grouper self.exclusions = frozenset(exclusions) if exclusions else frozenset() def __getattr__(self, attr: str): if attr in self._internal_names_set: return object.__getattribute__(self, attr) if attr in self.obj: return self[attr] raise AttributeError( f"'{type(self).__name__}' object has no attribute '{attr}'" ) def __getattribute__(self, attr: str): # Intercept nth to allow both call and index if attr == "nth": return GroupByNthSelector(self) elif attr == "nth_actual": return super().__getattribute__("nth") else: return super().__getattribute__(attr) @final def _make_wrapper(self, name: str) -> Callable: assert name in self._apply_allowlist with self._group_selection_context(): # need to setup the selection # as are not passed directly but in the grouper f = getattr(self._obj_with_exclusions, name) if not isinstance(f, types.MethodType): return self.apply(lambda self: getattr(self, name)) f = getattr(type(self._obj_with_exclusions), name) sig = inspect.signature(f) def wrapper(*args, **kwargs): # a little trickery for aggregation functions that need an axis # argument if "axis" in sig.parameters: if kwargs.get("axis", None) is None: kwargs["axis"] = self.axis def curried(x): return f(x, *args, **kwargs) # preserve the name so we can detect it when calling plot methods, # to avoid duplicates curried.__name__ = name # special case otherwise extra plots are created when catching the # exception below if name in base.plotting_methods: return self.apply(curried) return self._python_apply_general(curried, self._obj_with_exclusions) wrapper.__name__ = name return wrapper # ----------------------------------------------------------------- # Selection @final def _set_group_selection(self) -> None: """ Create group based selection. Used when selection is not passed directly but instead via a grouper. NOTE: this should be paired with a call to _reset_group_selection """ # This is a no-op for SeriesGroupBy grp = self.grouper if not ( self.as_index and grp.groupings is not None and self.obj.ndim > 1 and self._group_selection is None ): return groupers = [g.name for g in grp.groupings if g.level is None and g.in_axis] if len(groupers): # GH12839 clear selected obj cache when group selection changes ax = self.obj._info_axis self._group_selection = ax.difference(Index(groupers), sort=False).tolist() self._reset_cache("_selected_obj") @final def _reset_group_selection(self) -> None: """ Clear group based selection. Used for methods needing to return info on each group regardless of whether a group selection was previously set. """ if self._group_selection is not None: # GH12839 clear cached selection too when changing group selection self._group_selection = None self._reset_cache("_selected_obj") @contextmanager def _group_selection_context(self) -> Iterator[GroupBy]: """ Set / reset the _group_selection_context. """ self._set_group_selection() try: yield self finally: self._reset_group_selection() def _iterate_slices(self) -> Iterable[Series]: raise AbstractMethodError(self) # ----------------------------------------------------------------- # Dispatch/Wrapping @final def _concat_objects(self, values, not_indexed_same: bool = False): from pandas.core.reshape.concat import concat def reset_identity(values): # reset the identities of the components # of the values to prevent aliasing for v in com.not_none(*values): ax = v._get_axis(self.axis) ax._reset_identity() return values if not not_indexed_same: result = concat(values, axis=self.axis) ax = self._selected_obj._get_axis(self.axis) if self.dropna: labels = self.grouper.group_info[0] mask = labels != -1 ax = ax[mask] # this is a very unfortunate situation # we can't use reindex to restore the original order # when the ax has duplicates # so we resort to this # GH 14776, 30667 if ax.has_duplicates and not result.axes[self.axis].equals(ax): indexer, _ = result.index.get_indexer_non_unique(ax._values) indexer = algorithms.unique1d(indexer) result = result.take(indexer, axis=self.axis) else: result = result.reindex(ax, axis=self.axis, copy=False) elif self.group_keys: values = reset_identity(values) if self.as_index: # possible MI return case group_keys = self.grouper.result_index group_levels = self.grouper.levels group_names = self.grouper.names result = concat( values, axis=self.axis, keys=group_keys, levels=group_levels, names=group_names, sort=False, ) else: # GH5610, returns a MI, with the first level being a # range index keys = list(range(len(values))) result = concat(values, axis=self.axis, keys=keys) else: values = reset_identity(values) result = concat(values, axis=self.axis) name = self.obj.name if self.obj.ndim == 1 else self._selection if isinstance(result, Series) and name is not None: result.name = name return result @final def _set_result_index_ordered( self, result: OutputFrameOrSeries ) -> OutputFrameOrSeries: # set the result index on the passed values object and # return the new object, xref 8046 if self.grouper.is_monotonic: # shortcut if we have an already ordered grouper result.set_axis(self.obj._get_axis(self.axis), axis=self.axis, inplace=True) return result # row order is scrambled => sort the rows by position in original index original_positions = Index( np.concatenate(self._get_indices(self.grouper.result_index)) ) result.set_axis(original_positions, axis=self.axis, inplace=True) result = result.sort_index(axis=self.axis) dropped_rows = len(result.index) < len(self.obj.index) if dropped_rows: # get index by slicing original index according to original positions # slice drops attrs => use set_axis when no rows were dropped sorted_indexer = result.index result.index = self._selected_obj.index[sorted_indexer] else: result.set_axis(self.obj._get_axis(self.axis), axis=self.axis, inplace=True) return result def _indexed_output_to_ndframe( self, result: Mapping[base.OutputKey, ArrayLike] ) -> Series | DataFrame: raise AbstractMethodError(self) @final def _wrap_aggregated_output( self, output: Series | DataFrame | Mapping[base.OutputKey, ArrayLike], qs: npt.NDArray[np.float64] | None = None, ): """ Wraps the output of GroupBy aggregations into the expected result. Parameters ---------- output : Series, DataFrame, or Mapping[base.OutputKey, ArrayLike] Data to wrap. Returns ------- Series or DataFrame """ if isinstance(output, (Series, DataFrame)): # We get here (for DataFrameGroupBy) if we used Manager.grouped_reduce, # in which case our columns are already set correctly. # ATM we do not get here for SeriesGroupBy; when we do, we will # need to require that result.name already match self.obj.name result = output else: result = self._indexed_output_to_ndframe(output) if not self.as_index: # `not self.as_index` is only relevant for DataFrameGroupBy, # enforced in __init__ self._insert_inaxis_grouper_inplace(result) result = result._consolidate() index = Index(range(self.grouper.ngroups)) else: index = self.grouper.result_index if qs is not None: # We get here with len(qs) != 1 and not self.as_index # in test_pass_args_kwargs index = _insert_quantile_level(index, qs) result.index = index if self.axis == 1: # Only relevant for DataFrameGroupBy, no-op for SeriesGroupBy result = result.T if result.index.equals(self.obj.index): # Retain e.g. DatetimeIndex/TimedeltaIndex freq result.index = self.obj.index.copy() # TODO: Do this more systematically return self._reindex_output(result, qs=qs) @final def _wrap_transformed_output( self, output: Mapping[base.OutputKey, ArrayLike] ) -> Series | DataFrame: """ Wraps the output of GroupBy transformations into the expected result. Parameters ---------- output : Mapping[base.OutputKey, ArrayLike] Data to wrap. Returns ------- Series or DataFrame Series for SeriesGroupBy, DataFrame for DataFrameGroupBy """ if isinstance(output, (Series, DataFrame)): result = output else: result = self._indexed_output_to_ndframe(output) if self.axis == 1: # Only relevant for DataFrameGroupBy result = result.T result.columns = self.obj.columns result.index = self.obj.index return result def _wrap_applied_output(self, data, values: list, not_indexed_same: bool = False): raise AbstractMethodError(self) def _resolve_numeric_only(self, numeric_only: bool | lib.NoDefault) -> bool: """ Determine subclass-specific default value for 'numeric_only'. For SeriesGroupBy we want the default to be False (to match Series behavior). For DataFrameGroupBy we want it to be True (for backwards-compat). Parameters ---------- numeric_only : bool or lib.no_default Returns ------- bool """ # GH#41291 if numeric_only is lib.no_default: # i.e. not explicitly passed by user if self.obj.ndim == 2: # i.e. DataFrameGroupBy numeric_only = True # GH#42395 GH#43108 GH#43154 # Regression from 1.2.5 to 1.3 caused object columns to be dropped if self.axis: obj = self._obj_with_exclusions.T else: obj = self._obj_with_exclusions check = obj._get_numeric_data() if len(obj.columns) and not len(check.columns) and not obj.empty: numeric_only = False # TODO: v1.4+ Add FutureWarning else: numeric_only = False # error: Incompatible return value type (got "Union[bool, NoDefault]", # expected "bool") return numeric_only # type: ignore[return-value] # ----------------------------------------------------------------- # numba @final def _numba_prep(self, func, data): if not callable(func): raise NotImplementedError( "Numba engine can only be used with a single function." ) ids, _, ngroups = self.grouper.group_info sorted_index = get_group_index_sorter(ids, ngroups) sorted_ids = algorithms.take_nd(ids, sorted_index, allow_fill=False) sorted_data = data.take(sorted_index, axis=self.axis).to_numpy() sorted_index_data = data.index.take(sorted_index).to_numpy() starts, ends = lib.generate_slices(sorted_ids, ngroups) return ( starts, ends, sorted_index_data, sorted_data, ) def _numba_agg_general( self, func: Callable, engine_kwargs: dict[str, bool] | None, numba_cache_key_str: str, *aggregator_args, ): """ Perform groupby with a standard numerical aggregation function (e.g. mean) with Numba. """ if not self.as_index: raise NotImplementedError( "as_index=False is not supported. Use .reset_index() instead." ) if self.axis == 1: raise NotImplementedError("axis=1 is not supported.") with self._group_selection_context(): data = self._selected_obj df = data if data.ndim == 2 else data.to_frame() starts, ends, sorted_index, sorted_data = self._numba_prep(func, df) aggregator = executor.generate_shared_aggregator( func, engine_kwargs, numba_cache_key_str ) result = aggregator(sorted_data, starts, ends, 0, *aggregator_args) cache_key = (func, numba_cache_key_str) if cache_key not in NUMBA_FUNC_CACHE: NUMBA_FUNC_CACHE[cache_key] = aggregator index = self.grouper.result_index if data.ndim == 1: result_kwargs = {"name": data.name} result = result.ravel() else: result_kwargs = {"columns": data.columns} return data._constructor(result, index=index, **result_kwargs) @final def _transform_with_numba(self, data, func, *args, engine_kwargs=None, **kwargs): """ Perform groupby transform routine with the numba engine. This routine mimics the data splitting routine of the DataSplitter class to generate the indices of each group in the sorted data and then passes the data and indices into a Numba jitted function. """ starts, ends, sorted_index, sorted_data = self._numba_prep(func, data) numba_transform_func = numba_.generate_numba_transform_func( kwargs, func, engine_kwargs ) result = numba_transform_func( sorted_data, sorted_index, starts, ends, len(data.columns), *args, ) cache_key = (func, "groupby_transform") if cache_key not in NUMBA_FUNC_CACHE: NUMBA_FUNC_CACHE[cache_key] = numba_transform_func # result values needs to be resorted to their original positions since we # evaluated the data sorted by group return result.take(np.argsort(sorted_index), axis=0) @final def _aggregate_with_numba(self, data, func, *args, engine_kwargs=None, **kwargs): """ Perform groupby aggregation routine with the numba engine. This routine mimics the data splitting routine of the DataSplitter class to generate the indices of each group in the sorted data and then passes the data and indices into a Numba jitted function. """ starts, ends, sorted_index, sorted_data = self._numba_prep(func, data) numba_agg_func = numba_.generate_numba_agg_func(kwargs, func, engine_kwargs) result = numba_agg_func( sorted_data, sorted_index, starts, ends, len(data.columns), *args, ) cache_key = (func, "groupby_agg") if cache_key not in NUMBA_FUNC_CACHE: NUMBA_FUNC_CACHE[cache_key] = numba_agg_func return result # ----------------------------------------------------------------- # apply/agg/transform @Appender( _apply_docs["template"].format( input="dataframe", examples=_apply_docs["dataframe_examples"] ) ) def apply(self, func, *args, **kwargs): func = com.is_builtin_func(func) # this is needed so we don't try and wrap strings. If we could # resolve functions to their callable functions prior, this # wouldn't be needed if args or kwargs: if callable(func): @wraps(func) def f(g): with np.errstate(all="ignore"): return func(g, *args, **kwargs) elif hasattr(nanops, "nan" + func): # TODO: should we wrap this in to e.g. _is_builtin_func? f = getattr(nanops, "nan" + func) else: raise ValueError( "func must be a callable if args or kwargs are supplied" ) elif isinstance(func, str): if hasattr(self, func): res = getattr(self, func) if callable(res): return res() return res else: raise TypeError(f"apply func should be callable, not '{func}'") else: f = func # ignore SettingWithCopy here in case the user mutates with option_context("mode.chained_assignment", None): try: result = self._python_apply_general(f, self._selected_obj) except TypeError: # gh-20949 # try again, with .apply acting as a filtering # operation, by excluding the grouping column # This would normally not be triggered # except if the udf is trying an operation that # fails on *some* columns, e.g. a numeric operation # on a string grouper column with self._group_selection_context(): return self._python_apply_general(f, self._selected_obj) return result @final def _python_apply_general( self, f: Callable, data: DataFrame | Series, not_indexed_same: bool | None = None, ) -> DataFrame | Series: """ Apply function f in python space Parameters ---------- f : callable Function to apply data : Series or DataFrame Data to apply f to not_indexed_same: bool, optional When specified, overrides the value of not_indexed_same. Apply behaves differently when the result index is equal to the input index, but this can be coincidental leading to value-dependent behavior. Returns ------- Series or DataFrame data after applying f """ values, mutated = self.grouper.apply(f, data, self.axis) if not_indexed_same is None: not_indexed_same = mutated or self.mutated return self._wrap_applied_output( data, values, not_indexed_same=not_indexed_same ) @final def _python_agg_general(self, func, *args, **kwargs): func = com.is_builtin_func(func) f = lambda x: func(x, *args, **kwargs) # iterate through "columns" ex exclusions to populate output dict output: dict[base.OutputKey, ArrayLike] = {} if self.ngroups == 0: # agg_series below assumes ngroups > 0 return self._python_apply_general(f, self._selected_obj) for idx, obj in enumerate(self._iterate_slices()): name = obj.name try: # if this function is invalid for this dtype, we will ignore it. result = self.grouper.agg_series(obj, f) except TypeError: warn_dropping_nuisance_columns_deprecated(type(self), "agg") continue key = base.OutputKey(label=name, position=idx) output[key] = result if not output: return self._python_apply_general(f, self._selected_obj) return self._wrap_aggregated_output(output) @final def _agg_general( self, numeric_only: bool = True, min_count: int = -1, *, alias: str, npfunc: Callable, ): with self._group_selection_context(): # try a cython aggregation if we can result = self._cython_agg_general( how=alias, alt=npfunc, numeric_only=numeric_only, min_count=min_count, ) return result.__finalize__(self.obj, method="groupby") def _agg_py_fallback( self, values: ArrayLike, ndim: int, alt: Callable ) -> ArrayLike: """ Fallback to pure-python aggregation if _cython_operation raises NotImplementedError. """ # We get here with a) EADtypes and b) object dtype if values.ndim == 1: # For DataFrameGroupBy we only get here with ExtensionArray ser = Series(values) else: # We only get here with values.dtype == object # TODO: special case not needed with ArrayManager df = DataFrame(values.T) # bc we split object blocks in grouped_reduce, we have only 1 col # otherwise we'd have to worry about block-splitting GH#39329 assert df.shape[1] == 1 # Avoid call to self.values that can occur in DataFrame # reductions; see GH#28949 ser = df.iloc[:, 0] # We do not get here with UDFs, so we know that our dtype # should always be preserved by the implemented aggregations # TODO: Is this exactly right; see WrappedCythonOp get_result_dtype? res_values = self.grouper.agg_series(ser, alt, preserve_dtype=True) if isinstance(values, Categorical): # Because we only get here with known dtype-preserving # reductions, we cast back to Categorical. # TODO: if we ever get "rank" working, exclude it here. res_values = type(values)._from_sequence(res_values, dtype=values.dtype) # If we are DataFrameGroupBy and went through a SeriesGroupByPath # then we need to reshape # GH#32223 includes case with IntegerArray values, ndarray res_values # test_groupby_duplicate_columns with object dtype values return ensure_block_shape(res_values, ndim=ndim) @final def _cython_agg_general( self, how: str, alt: Callable, numeric_only: bool, min_count: int = -1 ): # Note: we never get here with how="ohlc" for DataFrameGroupBy; # that goes through SeriesGroupBy data = self._get_data_to_aggregate() is_ser = data.ndim == 1 if numeric_only: if is_ser and not is_numeric_dtype(self._selected_obj.dtype): # GH#41291 match Series behavior kwd_name = "numeric_only" if how in ["any", "all"]: kwd_name = "bool_only" raise NotImplementedError( f"{type(self).__name__}.{how} does not implement {kwd_name}." ) elif not is_ser: data = data.get_numeric_data(copy=False) def array_func(values: ArrayLike) -> ArrayLike: try: result = self.grouper._cython_operation( "aggregate", values, how, axis=data.ndim - 1, min_count=min_count ) except NotImplementedError: # generally if we have numeric_only=False # and non-applicable functions # try to python agg # TODO: shouldn't min_count matter? result = self._agg_py_fallback(values, ndim=data.ndim, alt=alt) return result # TypeError -> we may have an exception in trying to aggregate # continue and exclude the block new_mgr = data.grouped_reduce(array_func, ignore_failures=True) if not is_ser and len(new_mgr) < len(data): warn_dropping_nuisance_columns_deprecated(type(self), how) res = self._wrap_agged_manager(new_mgr) if is_ser: res.index = self.grouper.result_index return self._reindex_output(res) else: return res def _cython_transform( self, how: str, numeric_only: bool = True, axis: int = 0, **kwargs ): raise AbstractMethodError(self) @final def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): if maybe_use_numba(engine): # TODO: tests with self._selected_obj.ndim == 1 on DataFrameGroupBy with self._group_selection_context(): data = self._selected_obj df = data if data.ndim == 2 else data.to_frame() result = self._transform_with_numba( df, func, *args, engine_kwargs=engine_kwargs, **kwargs ) if self.obj.ndim == 2: return cast(DataFrame, self.obj)._constructor( result, index=data.index, columns=data.columns ) else: return cast(Series, self.obj)._constructor( result.ravel(), index=data.index, name=data.name ) # optimized transforms func = com.get_cython_func(func) or func if not isinstance(func, str): return self._transform_general(func, *args, **kwargs) elif func not in base.transform_kernel_allowlist: msg = f"'{func}' is not a valid function name for transform(name)" raise ValueError(msg) elif func in base.cythonized_kernels or func in base.transformation_kernels: # cythonized transform or canned "agg+broadcast" return getattr(self, func)(*args, **kwargs) else: # i.e. func in base.reduction_kernels # GH#30918 Use _transform_fast only when we know func is an aggregation # If func is a reduction, we need to broadcast the # result to the whole group. Compute func result # and deal with possible broadcasting below. # Temporarily set observed for dealing with categoricals. with com.temp_setattr(self, "observed", True): result = getattr(self, func)(*args, **kwargs) if self._can_use_transform_fast(result): return self._wrap_transform_fast_result(result) # only reached for DataFrameGroupBy return self._transform_general(func, *args, **kwargs) @final def _wrap_transform_fast_result(self, result: NDFrameT) -> NDFrameT: """ Fast transform path for aggregations. """ obj = self._obj_with_exclusions # for each col, reshape to size of original frame by take operation ids, _, _ = self.grouper.group_info result = result.reindex(self.grouper.result_index, copy=False) if self.obj.ndim == 1: # i.e. SeriesGroupBy out = algorithms.take_nd(result._values, ids) output = obj._constructor(out, index=obj.index, name=obj.name) else: output = result.take(ids, axis=0) output.index = obj.index return output # ----------------------------------------------------------------- # Utilities @final def _apply_filter(self, indices, dropna): if len(indices) == 0: indices = np.array([], dtype="int64") else: indices = np.sort(np.concatenate(indices)) if dropna: filtered = self._selected_obj.take(indices, axis=self.axis) else: mask = np.empty(len(self._selected_obj.index), dtype=bool) mask.fill(False) mask[indices.astype(int)] = True # mask fails to broadcast when passed to where; broadcast manually. mask = np.tile(mask, list(self._selected_obj.shape[1:]) + [1]).T filtered = self._selected_obj.where(mask) # Fill with NaNs. return filtered @final def _cumcount_array(self, ascending: bool = True) -> np.ndarray: """ Parameters ---------- ascending : bool, default True If False, number in reverse, from length of group - 1 to 0. Notes ----- this is currently implementing sort=False (though the default is sort=True) for groupby in general """ ids, _, ngroups = self.grouper.group_info sorter = get_group_index_sorter(ids, ngroups) ids, count = ids[sorter], len(ids) if count == 0: return np.empty(0, dtype=np.int64) run = np.r_[True, ids[:-1] != ids[1:]] rep = np.diff(np.r_[np.nonzero(run)[0], count]) out = (~run).cumsum() if ascending: out -= np.repeat(out[run], rep) else: out = np.repeat(out[np.r_[run[1:], True]], rep) - out rev = np.empty(count, dtype=np.intp) rev[sorter] = np.arange(count, dtype=np.intp) return out[rev].astype(np.int64, copy=False) # ----------------------------------------------------------------- @final @property def _obj_1d_constructor(self) -> type[Series]: # GH28330 preserve subclassed Series/DataFrames if isinstance(self.obj, DataFrame): return self.obj._constructor_sliced assert isinstance(self.obj, Series) return self.obj._constructor @final def _bool_agg(self, val_test: Literal["any", "all"], skipna: bool): """ Shared func to call any / all Cython GroupBy implementations. """ def objs_to_bool(vals: ArrayLike) -> tuple[np.ndarray, type]: if is_object_dtype(vals.dtype): # GH#37501: don't raise on pd.NA when skipna=True if skipna: func = np.vectorize(lambda x: bool(x) if not isna(x) else True) vals = func(vals) else: vals = vals.astype(bool, copy=False) vals = cast(np.ndarray, vals) elif isinstance(vals, BaseMaskedArray): vals = vals._data.astype(bool, copy=False) else: vals = vals.astype(bool, copy=False) return vals.view(np.int8), bool def result_to_bool( result: np.ndarray, inference: type, nullable: bool = False, ) -> ArrayLike: if nullable: return BooleanArray(result.astype(bool, copy=False), result == -1) else: return result.astype(inference, copy=False) return self._get_cythonized_result( libgroupby.group_any_all, numeric_only=False, cython_dtype=np.dtype(np.int8), needs_mask=True, needs_nullable=True, pre_processing=objs_to_bool, post_processing=result_to_bool, val_test=val_test, skipna=skipna, ) @final @Substitution(name="groupby") @Appender(_common_see_also) def any(self, skipna: bool = True): """ Return True if any value in the group is truthful, else False. Parameters ---------- skipna : bool, default True Flag to ignore nan values during truth testing. Returns ------- Series or DataFrame DataFrame or Series of boolean values, where a value is True if any element is True within its respective group, False otherwise. """ return self._bool_agg("any", skipna) @final @Substitution(name="groupby") @Appender(_common_see_also) def all(self, skipna: bool = True): """ Return True if all values in the group are truthful, else False. Parameters ---------- skipna : bool, default True Flag to ignore nan values during truth testing. Returns ------- Series or DataFrame DataFrame or Series of boolean values, where a value is True if all elements are True within its respective group, False otherwise. """ return self._bool_agg("all", skipna) @final @Substitution(name="groupby") @Appender(_common_see_also) def count(self) -> Series | DataFrame: """ Compute count of group, excluding missing values. Returns ------- Series or DataFrame Count of values within each group. """ data = self._get_data_to_aggregate() ids, _, ngroups = self.grouper.group_info mask = ids != -1 is_series = data.ndim == 1 def hfunc(bvalues: ArrayLike) -> ArrayLike: # TODO(EA2D): reshape would not be necessary with 2D EAs if bvalues.ndim == 1: # EA masked = mask & ~isna(bvalues).reshape(1, -1) else: masked = mask & ~isna(bvalues) counted = lib.count_level_2d(masked, labels=ids, max_bin=ngroups, axis=1) if is_series: assert counted.ndim == 2 assert counted.shape[0] == 1 return counted[0] return counted new_mgr = data.grouped_reduce(hfunc) # If we are grouping on categoricals we want unobserved categories to # return zero, rather than the default of NaN which the reindexing in # _wrap_agged_manager() returns. GH 35028 with com.temp_setattr(self, "observed", True): result = self._wrap_agged_manager(new_mgr) if result.ndim == 1: result.index = self.grouper.result_index return self._reindex_output(result, fill_value=0) @final @Substitution(name="groupby") @Substitution(see_also=_common_see_also) def mean( self, numeric_only: bool | lib.NoDefault = lib.no_default, engine: str = "cython", engine_kwargs: dict[str, bool] | None = None, ): """ Compute mean of groups, excluding missing values. Parameters ---------- numeric_only : bool, default True Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. engine : str, default None * ``'cython'`` : Runs the operation through C-extensions from cython. * ``'numba'`` : Runs the operation through JIT compiled code from numba. * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba`` .. versionadded:: 1.4.0 engine_kwargs : dict, default None * For ``'cython'`` engine, there are no accepted ``engine_kwargs`` * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil`` and ``parallel`` dictionary keys. The values must either be ``True`` or ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is ``{{'nopython': True, 'nogil': False, 'parallel': False}}`` .. versionadded:: 1.4.0 Returns ------- pandas.Series or pandas.DataFrame %(see_also)s Examples -------- >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2], ... 'B': [np.nan, 2, 3, 4, 5], ... 'C': [1, 2, 1, 1, 2]}, columns=['A', 'B', 'C']) Groupby one column and return the mean of the remaining columns in each group. >>> df.groupby('A').mean() B C A 1 3.0 1.333333 2 4.0 1.500000 Groupby two columns and return the mean of the remaining column. >>> df.groupby(['A', 'B']).mean() C A B 1 2.0 2.0 4.0 1.0 2 3.0 1.0 5.0 2.0 Groupby one column and return the mean of only particular column in the group. >>> df.groupby('A')['B'].mean() A 1 3.0 2 4.0 Name: B, dtype: float64 """ numeric_only_bool = self._resolve_numeric_only(numeric_only) if maybe_use_numba(engine): from pandas.core._numba.kernels import sliding_mean return self._numba_agg_general(sliding_mean, engine_kwargs, "groupby_mean") else: result = self._cython_agg_general( "mean", alt=lambda x: Series(x).mean(numeric_only=numeric_only_bool), numeric_only=numeric_only_bool, ) return result.__finalize__(self.obj, method="groupby") @final @Substitution(name="groupby") @Appender(_common_see_also) def median(self, numeric_only: bool | lib.NoDefault = lib.no_default): """ Compute median of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex Parameters ---------- numeric_only : bool, default True Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Returns ------- Series or DataFrame Median of values within each group. """ numeric_only_bool = self._resolve_numeric_only(numeric_only) result = self._cython_agg_general( "median", alt=lambda x: Series(x).median(numeric_only=numeric_only_bool), numeric_only=numeric_only_bool, ) return result.__finalize__(self.obj, method="groupby") @final @Substitution(name="groupby") @Appender(_common_see_also) def std( self, ddof: int = 1, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, ): """ Compute standard deviation of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex. Parameters ---------- ddof : int, default 1 Degrees of freedom. engine : str, default None * ``'cython'`` : Runs the operation through C-extensions from cython. * ``'numba'`` : Runs the operation through JIT compiled code from numba. * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba`` .. versionadded:: 1.4.0 engine_kwargs : dict, default None * For ``'cython'`` engine, there are no accepted ``engine_kwargs`` * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil`` and ``parallel`` dictionary keys. The values must either be ``True`` or ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is ``{{'nopython': True, 'nogil': False, 'parallel': False}}`` .. versionadded:: 1.4.0 Returns ------- Series or DataFrame Standard deviation of values within each group. """ if maybe_use_numba(engine): from pandas.core._numba.kernels import sliding_var return np.sqrt( self._numba_agg_general(sliding_var, engine_kwargs, "groupby_std", ddof) ) else: return self._get_cythonized_result( libgroupby.group_var, needs_counts=True, cython_dtype=np.dtype(np.float64), post_processing=lambda vals, inference: np.sqrt(vals), ddof=ddof, ) @final @Substitution(name="groupby") @Appender(_common_see_also) def var( self, ddof: int = 1, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, ): """ Compute variance of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex. Parameters ---------- ddof : int, default 1 Degrees of freedom. engine : str, default None * ``'cython'`` : Runs the operation through C-extensions from cython. * ``'numba'`` : Runs the operation through JIT compiled code from numba. * ``None`` : Defaults to ``'cython'`` or globally setting ``compute.use_numba`` .. versionadded:: 1.4.0 engine_kwargs : dict, default None * For ``'cython'`` engine, there are no accepted ``engine_kwargs`` * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil`` and ``parallel`` dictionary keys. The values must either be ``True`` or ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is ``{{'nopython': True, 'nogil': False, 'parallel': False}}`` .. versionadded:: 1.4.0 Returns ------- Series or DataFrame Variance of values within each group. """ if maybe_use_numba(engine): from pandas.core._numba.kernels import sliding_var return self._numba_agg_general( sliding_var, engine_kwargs, "groupby_var", ddof ) else: if ddof == 1: numeric_only = self._resolve_numeric_only(lib.no_default) return self._cython_agg_general( "var", alt=lambda x: Series(x).var(ddof=ddof), numeric_only=numeric_only, ) else: func = lambda x: x.var(ddof=ddof) with self._group_selection_context(): return self._python_agg_general(func) @final @Substitution(name="groupby") @Appender(_common_see_also) def sem(self, ddof: int = 1): """ Compute standard error of the mean of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex. Parameters ---------- ddof : int, default 1 Degrees of freedom. Returns ------- Series or DataFrame Standard error of the mean of values within each group. """ result = self.std(ddof=ddof) if result.ndim == 1: result /= np.sqrt(self.count()) else: cols = result.columns.difference(self.exclusions).unique() counts = self.count() result_ilocs = result.columns.get_indexer_for(cols) count_ilocs = counts.columns.get_indexer_for(cols) result.iloc[:, result_ilocs] /= np.sqrt(counts.iloc[:, count_ilocs]) return result @final @Substitution(name="groupby") @Appender(_common_see_also) def size(self) -> DataFrame | Series: """ Compute group sizes. Returns ------- DataFrame or Series Number of rows in each group as a Series if as_index is True or a DataFrame if as_index is False. """ result = self.grouper.size() # GH28330 preserve subclassed Series/DataFrames through calls if issubclass(self.obj._constructor, Series): result = self._obj_1d_constructor(result, name=self.obj.name) else: result = self._obj_1d_constructor(result) if not self.as_index: # Item "None" of "Optional[Series]" has no attribute "reset_index" result = result.rename("size").reset_index() # type: ignore[union-attr] return self._reindex_output(result, fill_value=0) @final @doc(_groupby_agg_method_template, fname="sum", no=True, mc=0) def sum( self, numeric_only: bool | lib.NoDefault = lib.no_default, min_count: int = 0, engine: str | None = None, engine_kwargs: dict[str, bool] | None = None, ): if maybe_use_numba(engine): from pandas.core._numba.kernels import sliding_sum return self._numba_agg_general( sliding_sum, engine_kwargs, "groupby_sum", ) else: numeric_only = self._resolve_numeric_only(numeric_only) # If we are grouping on categoricals we want unobserved categories to # return zero, rather than the default of NaN which the reindexing in # _agg_general() returns. GH #31422 with com.temp_setattr(self, "observed", True): result = self._agg_general( numeric_only=numeric_only, min_count=min_count, alias="add", npfunc=np.sum, ) return self._reindex_output(result, fill_value=0) @final @doc(_groupby_agg_method_template, fname="prod", no=True, mc=0) def prod( self, numeric_only: bool | lib.NoDefault = lib.no_default, min_count: int = 0 ): numeric_only = self._resolve_numeric_only(numeric_only) return self._agg_general( numeric_only=numeric_only, min_count=min_count, alias="prod", npfunc=np.prod ) @final @doc(_groupby_agg_method_template, fname="min", no=False, mc=-1) def min(self, numeric_only: bool = False, min_count: int = -1): return self._agg_general( numeric_only=numeric_only, min_count=min_count, alias="min", npfunc=np.min ) @final @doc(_groupby_agg_method_template, fname="max", no=False, mc=-1) def max(self, numeric_only: bool = False, min_count: int = -1): return self._agg_general( numeric_only=numeric_only, min_count=min_count, alias="max", npfunc=np.max ) @final @doc(_groupby_agg_method_template, fname="first", no=False, mc=-1) def first(self, numeric_only: bool = False, min_count: int = -1): def first_compat(obj: NDFrameT, axis: int = 0): def first(x: Series): """Helper function for first item that isn't NA.""" arr = x.array[notna(x.array)] if not len(arr): return np.nan return arr[0] if isinstance(obj, DataFrame): return obj.apply(first, axis=axis) elif isinstance(obj, Series): return first(obj) else: # pragma: no cover raise TypeError(type(obj)) return self._agg_general( numeric_only=numeric_only, min_count=min_count, alias="first", npfunc=first_compat, ) @final @doc(_groupby_agg_method_template, fname="last", no=False, mc=-1) def last(self, numeric_only: bool = False, min_count: int = -1): def last_compat(obj: NDFrameT, axis: int = 0): def last(x: Series): """Helper function for last item that isn't NA.""" arr = x.array[notna(x.array)] if not len(arr): return np.nan return arr[-1] if isinstance(obj, DataFrame): return obj.apply(last, axis=axis) elif isinstance(obj, Series): return last(obj) else: # pragma: no cover raise TypeError(type(obj)) return self._agg_general( numeric_only=numeric_only, min_count=min_count, alias="last", npfunc=last_compat, ) @final @Substitution(name="groupby") @Appender(_common_see_also) def ohlc(self) -> DataFrame: """ Compute open, high, low and close values of a group, excluding missing values. For multiple groupings, the result index will be a MultiIndex Returns ------- DataFrame Open, high, low and close values within each group. """ if self.obj.ndim == 1: # self._iterate_slices() yields only self._selected_obj obj = self._selected_obj is_numeric = is_numeric_dtype(obj.dtype) if not is_numeric: raise DataError("No numeric types to aggregate") res_values = self.grouper._cython_operation( "aggregate", obj._values, "ohlc", axis=0, min_count=-1 ) agg_names = ["open", "high", "low", "close"] result = self.obj._constructor_expanddim( res_values, index=self.grouper.result_index, columns=agg_names ) return self._reindex_output(result) return self._apply_to_column_groupbys( lambda x: x.ohlc(), self._obj_with_exclusions ) @doc(DataFrame.describe) def describe(self, **kwargs): with self._group_selection_context(): result = self.apply(lambda x: x.describe(**kwargs)) if self.axis == 1: return result.T return result.unstack() @final def resample(self, rule, *args, **kwargs): """ Provide resampling when using a TimeGrouper. Given a grouper, the function resamples it according to a string "string" -> "frequency". See the :ref:`frequency aliases <timeseries.offset_aliases>` documentation for more details. Parameters ---------- rule : str or DateOffset The offset string or object representing target grouper conversion. *args, **kwargs Possible arguments are `how`, `fill_method`, `limit`, `kind` and `on`, and other arguments of `TimeGrouper`. Returns ------- Grouper Return a new grouper with our resampler appended. See Also -------- Grouper : Specify a frequency to resample with when grouping by a key. DatetimeIndex.resample : Frequency conversion and resampling of time series. Examples -------- >>> idx = pd.date_range('1/1/2000', periods=4, freq='T') >>> df = pd.DataFrame(data=4 * [range(2)], ... index=idx, ... columns=['a', 'b']) >>> df.iloc[2, 0] = 5 >>> df a b 2000-01-01 00:00:00 0 1 2000-01-01 00:01:00 0 1 2000-01-01 00:02:00 5 1 2000-01-01 00:03:00 0 1 Downsample the DataFrame into 3 minute bins and sum the values of the timestamps falling into a bin. >>> df.groupby('a').resample('3T').sum() a b a 0 2000-01-01 00:00:00 0 2 2000-01-01 00:03:00 0 1 5 2000-01-01 00:00:00 5 1 Upsample the series into 30 second bins. >>> df.groupby('a').resample('30S').sum() a b a 0 2000-01-01 00:00:00 0 1 2000-01-01 00:00:30 0 0 2000-01-01 00:01:00 0 1 2000-01-01 00:01:30 0 0 2000-01-01 00:02:00 0 0 2000-01-01 00:02:30 0 0 2000-01-01 00:03:00 0 1 5 2000-01-01 00:02:00 5 1 Resample by month. Values are assigned to the month of the period. >>> df.groupby('a').resample('M').sum() a b a 0 2000-01-31 0 3 5 2000-01-31 5 1 Downsample the series into 3 minute bins as above, but close the right side of the bin interval. >>> df.groupby('a').resample('3T', closed='right').sum() a b a 0 1999-12-31 23:57:00 0 1 2000-01-01 00:00:00 0 2 5 2000-01-01 00:00:00 5 1 Downsample the series into 3 minute bins and close the right side of the bin interval, but label each bin using the right edge instead of the left. >>> df.groupby('a').resample('3T', closed='right', label='right').sum() a b a 0 2000-01-01 00:00:00 0 1 2000-01-01 00:03:00 0 2 5 2000-01-01 00:03:00 5 1 """ from pandas.core.resample import get_resampler_for_grouping return get_resampler_for_grouping(self, rule, *args, **kwargs) @final @Substitution(name="groupby") @Appender(_common_see_also) def rolling(self, *args, **kwargs): """ Return a rolling grouper, providing rolling functionality per group. """ from pandas.core.window import RollingGroupby return RollingGroupby( self._selected_obj, *args, _grouper=self.grouper, _as_index=self.as_index, **kwargs, ) @final @Substitution(name="groupby") @Appender(_common_see_also) def expanding(self, *args, **kwargs): """ Return an expanding grouper, providing expanding functionality per group. """ from pandas.core.window import ExpandingGroupby return ExpandingGroupby( self._selected_obj, *args, _grouper=self.grouper, **kwargs, ) @final @Substitution(name="groupby") @Appender(_common_see_also) def ewm(self, *args, **kwargs): """ Return an ewm grouper, providing ewm functionality per group. """ from pandas.core.window import ExponentialMovingWindowGroupby return ExponentialMovingWindowGroupby( self._selected_obj, *args, _grouper=self.grouper, **kwargs, ) @final def _fill(self, direction: Literal["ffill", "bfill"], limit=None): """ Shared function for `pad` and `backfill` to call Cython method. Parameters ---------- direction : {'ffill', 'bfill'} Direction passed to underlying Cython function. `bfill` will cause values to be filled backwards. `ffill` and any other values will default to a forward fill limit : int, default None Maximum number of consecutive values to fill. If `None`, this method will convert to -1 prior to passing to Cython Returns ------- `Series` or `DataFrame` with filled values See Also -------- pad : Returns Series with minimum number of char in object. backfill : Backward fill the missing values in the dataset. """ # Need int value for Cython if limit is None: limit = -1 ids, _, _ = self.grouper.group_info sorted_labels = np.argsort(ids, kind="mergesort").astype(np.intp, copy=False) if direction == "bfill": sorted_labels = sorted_labels[::-1] col_func = partial( libgroupby.group_fillna_indexer, labels=ids, sorted_labels=sorted_labels, direction=direction, limit=limit, dropna=self.dropna, ) def blk_func(values: ArrayLike) -> ArrayLike: mask = isna(values) if values.ndim == 1: indexer = np.empty(values.shape, dtype=np.intp) col_func(out=indexer, mask=mask) return algorithms.take_nd(values, indexer) else: # We broadcast algorithms.take_nd analogous to # np.take_along_axis # Note: we only get here with backfill/pad, # so if we have a dtype that cannot hold NAs, # then there will be no -1s in indexer, so we can use # the original dtype (no need to ensure_dtype_can_hold_na) if isinstance(values, np.ndarray): out = np.empty(values.shape, dtype=values.dtype) else: out = type(values)._empty(values.shape, dtype=values.dtype) for i in range(len(values)): # call group_fillna_indexer column-wise indexer = np.empty(values.shape[1], dtype=np.intp) col_func(out=indexer, mask=mask[i]) out[i, :] = algorithms.take_nd(values[i], indexer) return out obj = self._obj_with_exclusions if self.axis == 1: obj = obj.T mgr = obj._mgr res_mgr = mgr.apply(blk_func) new_obj = obj._constructor(res_mgr) if isinstance(new_obj, Series): new_obj.name = obj.name return self._wrap_transformed_output(new_obj) @final @Substitution(name="groupby") def pad(self, limit=None): """ Forward fill the values. Parameters ---------- limit : int, optional Limit of how many values to fill. Returns ------- Series or DataFrame Object with missing values filled. See Also -------- Series.pad: Returns Series with minimum number of char in object. DataFrame.pad: Object with missing values filled or None if inplace=True. Series.fillna: Fill NaN values of a Series. DataFrame.fillna: Fill NaN values of a DataFrame. """ return self._fill("ffill", limit=limit) ffill = pad @final @Substitution(name="groupby") def backfill(self, limit=None): """ Backward fill the values. Parameters ---------- limit : int, optional Limit of how many values to fill. Returns ------- Series or DataFrame Object with missing values filled. See Also -------- Series.backfill : Backward fill the missing values in the dataset. DataFrame.backfill: Backward fill the missing values in the dataset. Series.fillna: Fill NaN values of a Series. DataFrame.fillna: Fill NaN values of a DataFrame. """ return self._fill("bfill", limit=limit) bfill = backfill @final @Substitution(name="groupby") @Substitution(see_also=_common_see_also) def nth( self, n: PositionalIndexer | tuple, dropna: Literal["any", "all", None] = None, ) -> NDFrameT: """ Take the nth row from each group if n is an int, otherwise a subset of rows. Can be either a call or an index. dropna is not available with index notation. Index notation accepts a comma separated list of integers and slices. If dropna, will take the nth non-null row, dropna is either 'all' or 'any'; this is equivalent to calling dropna(how=dropna) before the groupby. Parameters ---------- n : int, slice or list of ints and slices A single nth value for the row or a list of nth values or slices. .. versionchanged:: 1.4.0 Added slice and lists containiing slices. Added index notation. dropna : {'any', 'all', None}, default None Apply the specified dropna operation before counting which row is the nth row. Only supported if n is an int. Returns ------- Series or DataFrame N-th value within each group. %(see_also)s Examples -------- >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2], ... 'B': [np.nan, 2, 3, 4, 5]}, columns=['A', 'B']) >>> g = df.groupby('A') >>> g.nth(0) B A 1 NaN 2 3.0 >>> g.nth(1) B A 1 2.0 2 5.0 >>> g.nth(-1) B A 1 4.0 2 5.0 >>> g.nth([0, 1]) B A 1 NaN 1 2.0 2 3.0 2 5.0 >>> g.nth(slice(None, -1)) B A 1 NaN 1 2.0 2 3.0 Index notation may also be used >>> g.nth[0, 1] B A 1 NaN 1 2.0 2 3.0 2 5.0 >>> g.nth[:-1] B A 1 NaN 1 2.0 2 3.0 Specifying `dropna` allows count ignoring ``NaN`` >>> g.nth(0, dropna='any') B A 1 2.0 2 3.0 NaNs denote group exhausted when using dropna >>> g.nth(3, dropna='any') B A 1 NaN 2 NaN Specifying `as_index=False` in `groupby` keeps the original index. >>> df.groupby('A', as_index=False).nth(1) A B 1 1 2.0 4 2 5.0 """ if not dropna: with self._group_selection_context(): mask = self._make_mask_from_positional_indexer(n) ids, _, _ = self.grouper.group_info # Drop NA values in grouping mask = mask & (ids != -1) out = self._mask_selected_obj(mask) if not self.as_index: return out result_index = self.grouper.result_index if self.axis == 0: out.index = result_index[ids[mask]] if not self.observed and isinstance(result_index, CategoricalIndex): out = out.reindex(result_index) out = self._reindex_output(out) else: out.columns = result_index[ids[mask]] return out.sort_index(axis=self.axis) if self.sort else out # dropna is truthy if not is_integer(n): raise ValueError("dropna option only supported for an integer argument") if dropna not in ["any", "all"]: # Note: when agg-ing picker doesn't raise this, just returns NaN raise ValueError( "For a DataFrame or Series groupby.nth, dropna must be " "either None, 'any' or 'all', " f"(was passed {dropna})." ) # old behaviour, but with all and any support for DataFrames. # modified in GH 7559 to have better perf n = cast(int, n) max_len = n if n >= 0 else -1 - n dropped = self.obj.dropna(how=dropna, axis=self.axis) # get a new grouper for our dropped obj if self.keys is None and self.level is None: # we don't have the grouper info available # (e.g. we have selected out # a column that is not in the current object) axis = self.grouper.axis grouper = axis[axis.isin(dropped.index)] else: # create a grouper with the original parameters, but on dropped # object from pandas.core.groupby.grouper import get_grouper grouper, _, _ = get_grouper( dropped, key=self.keys, axis=self.axis, level=self.level, sort=self.sort, mutated=self.mutated, ) grb = dropped.groupby( grouper, as_index=self.as_index, sort=self.sort, axis=self.axis ) sizes, result = grb.size(), grb.nth(n) mask = (sizes < max_len)._values # set the results which don't meet the criteria if len(result) and mask.any(): result.loc[mask] = np.nan # reset/reindex to the original groups if len(self.obj) == len(dropped) or len(result) == len( self.grouper.result_index ): result.index = self.grouper.result_index else: result = result.reindex(self.grouper.result_index) return result @final def quantile(self, q=0.5, interpolation: str = "linear"): """ Return group values at the given quantile, a la numpy.percentile. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) Value(s) between 0 and 1 providing the quantile(s) to compute. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} Method to use when the desired quantile falls between two points. Returns ------- Series or DataFrame Return type determined by caller of GroupBy object. See Also -------- Series.quantile : Similar method for Series. DataFrame.quantile : Similar method for DataFrame. numpy.percentile : NumPy method to compute qth percentile. Examples -------- >>> df = pd.DataFrame([ ... ['a', 1], ['a', 2], ['a', 3], ... ['b', 1], ['b', 3], ['b', 5] ... ], columns=['key', 'val']) >>> df.groupby('key').quantile() val key a 2.0 b 3.0 """ def pre_processor(vals: ArrayLike) -> tuple[np.ndarray, np.dtype | None]: if is_object_dtype(vals): raise TypeError( "'quantile' cannot be performed against 'object' dtypes!" ) inference: np.dtype | None = None if is_integer_dtype(vals.dtype): if isinstance(vals, ExtensionArray): out = vals.to_numpy(dtype=float, na_value=np.nan) else: out = vals inference = np.dtype(np.int64) elif is_bool_dtype(vals.dtype) and isinstance(vals, ExtensionArray): out = vals.to_numpy(dtype=float, na_value=np.nan) elif is_datetime64_dtype(vals.dtype): inference = np.dtype("datetime64[ns]") out = np.asarray(vals).astype(float) elif is_timedelta64_dtype(vals.dtype): inference = np.dtype("timedelta64[ns]") out = np.asarray(vals).astype(float) elif isinstance(vals, ExtensionArray) and is_float_dtype(vals): inference = np.dtype(np.float64) out = vals.to_numpy(dtype=float, na_value=np.nan) else: out = np.asarray(vals) return out, inference def post_processor(vals: np.ndarray, inference: np.dtype | None) -> np.ndarray: if inference: # Check for edge case if not ( is_integer_dtype(inference) and interpolation in {"linear", "midpoint"} ): vals = vals.astype(inference) return vals orig_scalar = is_scalar(q) if orig_scalar: q = [q] qs = np.array(q, dtype=np.float64) ids, _, ngroups = self.grouper.group_info nqs = len(qs) func = partial( libgroupby.group_quantile, labels=ids, qs=qs, interpolation=interpolation ) # Put '-1' (NaN) labels as the last group so it does not interfere # with the calculations. Note: length check avoids failure on empty # labels. In that case, the value doesn't matter na_label_for_sorting = ids.max() + 1 if len(ids) > 0 else 0 labels_for_lexsort = np.where(ids == -1, na_label_for_sorting, ids) def blk_func(values: ArrayLike) -> ArrayLike: mask = isna(values) vals, inference = pre_processor(values) ncols = 1 if vals.ndim == 2: ncols = vals.shape[0] shaped_labels = np.broadcast_to( labels_for_lexsort, (ncols, len(labels_for_lexsort)) ) else: shaped_labels = labels_for_lexsort out = np.empty((ncols, ngroups, nqs), dtype=np.float64) # Get an index of values sorted by values and then labels order = (vals, shaped_labels) sort_arr = np.lexsort(order).astype(np.intp, copy=False) if vals.ndim == 1: func(out[0], values=vals, mask=mask, sort_indexer=sort_arr) else: for i in range(ncols): func(out[i], values=vals[i], mask=mask[i], sort_indexer=sort_arr[i]) if vals.ndim == 1: out = out.ravel("K") else: out = out.reshape(ncols, ngroups * nqs) return post_processor(out, inference) obj = self._obj_with_exclusions is_ser = obj.ndim == 1 mgr = self._get_data_to_aggregate() res_mgr = mgr.grouped_reduce(blk_func, ignore_failures=True) if not is_ser and len(res_mgr.items) != len(mgr.items): warn_dropping_nuisance_columns_deprecated(type(self), "quantile") if len(res_mgr.items) == 0: # re-call grouped_reduce to get the desired exception message mgr.grouped_reduce(blk_func, ignore_failures=False) # grouped_reduce _should_ raise, so this should not be reached raise TypeError( # pragma: no cover "All columns were dropped in grouped_reduce" ) if is_ser: res = self._wrap_agged_manager(res_mgr) else: res = obj._constructor(res_mgr) if orig_scalar: # Avoid expensive MultiIndex construction return self._wrap_aggregated_output(res) return self._wrap_aggregated_output(res, qs=qs) @final @Substitution(name="groupby") def ngroup(self, ascending: bool = True): """ Number each group from 0 to the number of groups - 1. This is the enumerative complement of cumcount. Note that the numbers given to the groups match the order in which the groups would be seen when iterating over the groupby object, not the order they are first observed. Parameters ---------- ascending : bool, default True If False, number in reverse, from number of group - 1 to 0. Returns ------- Series Unique numbers for each group. See Also -------- .cumcount : Number the rows in each group. Examples -------- >>> df = pd.DataFrame({"A": list("aaabba")}) >>> df A 0 a 1 a 2 a 3 b 4 b 5 a >>> df.groupby('A').ngroup() 0 0 1 0 2 0 3 1 4 1 5 0 dtype: int64 >>> df.groupby('A').ngroup(ascending=False) 0 1 1 1 2 1 3 0 4 0 5 1 dtype: int64 >>> df.groupby(["A", [1,1,2,3,2,1]]).ngroup() 0 0 1 0 2 1 3 3 4 2 5 0 dtype: int64 """ with self._group_selection_context(): index = self._selected_obj.index result = self._obj_1d_constructor( self.grouper.group_info[0], index, dtype=np.int64 ) if not ascending: result = self.ngroups - 1 - result return result @final @Substitution(name="groupby") def cumcount(self, ascending: bool = True): """ Number each item in each group from 0 to the length of that group - 1. Essentially this is equivalent to .. code-block:: python self.apply(lambda x: pd.Series(np.arange(len(x)), x.index)) Parameters ---------- ascending : bool, default True If False, number in reverse, from length of group - 1 to 0. Returns ------- Series Sequence number of each element within each group. See Also -------- .ngroup : Number the groups themselves. Examples -------- >>> df = pd.DataFrame([['a'], ['a'], ['a'], ['b'], ['b'], ['a']], ... columns=['A']) >>> df A 0 a 1 a 2 a 3 b 4 b 5 a >>> df.groupby('A').cumcount() 0 0 1 1 2 2 3 0 4 1 5 3 dtype: int64 >>> df.groupby('A').cumcount(ascending=False) 0 3 1 2 2 1 3 1 4 0 5 0 dtype: int64 """ with self._group_selection_context(): index = self._selected_obj._get_axis(self.axis) cumcounts = self._cumcount_array(ascending=ascending) return self._obj_1d_constructor(cumcounts, index) @final @Substitution(name="groupby") @Substitution(see_also=_common_see_also) def rank( self, method: str = "average", ascending: bool = True, na_option: str = "keep", pct: bool = False, axis: int = 0, ): """ Provide the rank of values within each group. Parameters ---------- method : {'average', 'min', 'max', 'first', 'dense'}, default 'average' * average: average rank of group. * min: lowest rank in group. * max: highest rank in group. * first: ranks assigned in order they appear in the array. * dense: like 'min', but rank always increases by 1 between groups. ascending : bool, default True False for ranks by high (1) to low (N). na_option : {'keep', 'top', 'bottom'}, default 'keep' * keep: leave NA values where they are. * top: smallest rank if ascending. * bottom: smallest rank if descending. pct : bool, default False Compute percentage rank of data within each group. axis : int, default 0 The axis of the object over which to compute the rank. Returns ------- DataFrame with ranking of values within each group %(see_also)s Examples -------- >>> df = pd.DataFrame( ... { ... "group": ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b"], ... "value": [2, 4, 2, 3, 5, 1, 2, 4, 1, 5], ... } ... ) >>> df group value 0 a 2 1 a 4 2 a 2 3 a 3 4 a 5 5 b 1 6 b 2 7 b 4 8 b 1 9 b 5 >>> for method in ['average', 'min', 'max', 'dense', 'first']: ... df[f'{method}_rank'] = df.groupby('group')['value'].rank(method) >>> df group value average_rank min_rank max_rank dense_rank first_rank 0 a 2 1.5 1.0 2.0 1.0 1.0 1 a 4 4.0 4.0 4.0 3.0 4.0 2 a 2 1.5 1.0 2.0 1.0 2.0 3 a 3 3.0 3.0 3.0 2.0 3.0 4 a 5 5.0 5.0 5.0 4.0 5.0 5 b 1 1.5 1.0 2.0 1.0 1.0 6 b 2 3.0 3.0 3.0 2.0 3.0 7 b 4 4.0 4.0 4.0 3.0 4.0 8 b 1 1.5 1.0 2.0 1.0 2.0 9 b 5 5.0 5.0 5.0 4.0 5.0 """ if na_option not in {"keep", "top", "bottom"}: msg = "na_option must be one of 'keep', 'top', or 'bottom'" raise ValueError(msg) kwargs = { "ties_method": method, "ascending": ascending, "na_option": na_option, "pct": pct, } if axis != 0: # DataFrame uses different keyword name kwargs["method"] = kwargs.pop("ties_method") return self.apply(lambda x: x.rank(axis=axis, numeric_only=False, **kwargs)) return self._cython_transform( "rank", numeric_only=False, axis=axis, **kwargs, ) @final @Substitution(name="groupby") @Appender(_common_see_also) def cumprod(self, axis=0, *args, **kwargs): """ Cumulative product for each group. Returns ------- Series or DataFrame """ nv.validate_groupby_func("cumprod", args, kwargs, ["numeric_only", "skipna"]) if axis != 0: return self.apply(lambda x: x.cumprod(axis=axis, **kwargs)) return self._cython_transform("cumprod", **kwargs) @final @Substitution(name="groupby") @Appender(_common_see_also) def cumsum(self, axis=0, *args, **kwargs): """ Cumulative sum for each group. Returns ------- Series or DataFrame """ nv.validate_groupby_func("cumsum", args, kwargs, ["numeric_only", "skipna"]) if axis != 0: return self.apply(lambda x: x.cumsum(axis=axis, **kwargs)) return self._cython_transform("cumsum", **kwargs) @final @Substitution(name="groupby") @Appender(_common_see_also) def cummin(self, axis=0, **kwargs): """ Cumulative min for each group. Returns ------- Series or DataFrame """ skipna = kwargs.get("skipna", True) if axis != 0: return self.apply(lambda x: np.minimum.accumulate(x, axis)) return self._cython_transform("cummin", numeric_only=False, skipna=skipna) @final @Substitution(name="groupby") @Appender(_common_see_also) def cummax(self, axis=0, **kwargs): """ Cumulative max for each group. Returns ------- Series or DataFrame """ skipna = kwargs.get("skipna", True) if axis != 0: return self.apply(lambda x: np.maximum.accumulate(x, axis)) return self._cython_transform("cummax", numeric_only=False, skipna=skipna) @final def _get_cythonized_result( self, base_func: Callable, cython_dtype: np.dtype, numeric_only: bool | lib.NoDefault = lib.no_default, needs_counts: bool = False, needs_nullable: bool = False, needs_mask: bool = False, pre_processing=None, post_processing=None, **kwargs, ): """ Get result for Cythonized functions. Parameters ---------- base_func : callable, Cythonized function to be called cython_dtype : np.dtype Type of the array that will be modified by the Cython call. numeric_only : bool, default True Whether only numeric datatypes should be computed needs_counts : bool, default False Whether the counts should be a part of the Cython call needs_mask : bool, default False Whether boolean mask needs to be part of the Cython call signature needs_nullable : bool, default False Whether a bool specifying if the input is nullable is part of the Cython call signature pre_processing : function, default None Function to be applied to `values` prior to passing to Cython. Function should return a tuple where the first element is the values to be passed to Cython and the second element is an optional type which the values should be converted to after being returned by the Cython operation. This function is also responsible for raising a TypeError if the values have an invalid type. Raises if `needs_values` is False. post_processing : function, default None Function to be applied to result of Cython function. Should accept an array of values as the first argument and type inferences as its second argument, i.e. the signature should be (ndarray, Type). If `needs_nullable=True`, a third argument should be `nullable`, to allow for processing specific to nullable values. **kwargs : dict Extra arguments to be passed back to Cython funcs Returns ------- `Series` or `DataFrame` with filled values """ numeric_only = self._resolve_numeric_only(numeric_only) if post_processing and not callable(post_processing): raise ValueError("'post_processing' must be a callable!") if pre_processing and not callable(pre_processing): raise ValueError("'pre_processing' must be a callable!") grouper = self.grouper ids, _, ngroups = grouper.group_info how = base_func.__name__ base_func = partial(base_func, labels=ids) def blk_func(values: ArrayLike) -> ArrayLike: values = values.T ncols = 1 if values.ndim == 1 else values.shape[1] result: ArrayLike result = np.zeros(ngroups * ncols, dtype=cython_dtype) result = result.reshape((ngroups, ncols)) func = partial(base_func, out=result) inferences = None if needs_counts: counts = np.zeros(self.ngroups, dtype=np.int64) func = partial(func, counts=counts) vals = values if pre_processing: vals, inferences = pre_processing(vals) vals = vals.astype(cython_dtype, copy=False) if vals.ndim == 1: vals = vals.reshape((-1, 1)) func = partial(func, values=vals) if needs_mask: mask = isna(values).view(np.uint8) if mask.ndim == 1: mask = mask.reshape(-1, 1) func = partial(func, mask=mask) if needs_nullable: is_nullable = isinstance(values, BaseMaskedArray) func = partial(func, nullable=is_nullable) func(**kwargs) # Call func to modify indexer values in place if values.ndim == 1: assert result.shape[1] == 1, result.shape result = result[:, 0] if post_processing: pp_kwargs = {} if needs_nullable: pp_kwargs["nullable"] = isinstance(values, BaseMaskedArray) result = post_processing(result, inferences, **pp_kwargs) return result.T obj = self._obj_with_exclusions # Operate block-wise instead of column-by-column is_ser = obj.ndim == 1 mgr = self._get_data_to_aggregate() if numeric_only: mgr = mgr.get_numeric_data() res_mgr = mgr.grouped_reduce(blk_func, ignore_failures=True) if not is_ser and len(res_mgr.items) != len(mgr.items): howstr = how.replace("group_", "") warn_dropping_nuisance_columns_deprecated(type(self), howstr) if len(res_mgr.items) == 0: # We re-call grouped_reduce to get the right exception message mgr.grouped_reduce(blk_func, ignore_failures=False) # grouped_reduce _should_ raise, so this should not be reached raise TypeError( # pragma: no cover "All columns were dropped in grouped_reduce" ) if is_ser: out = self._wrap_agged_manager(res_mgr) else: out = obj._constructor(res_mgr) return self._wrap_aggregated_output(out) @final @Substitution(name="groupby") def shift(self, periods=1, freq=None, axis=0, fill_value=None): """ Shift each group by periods observations. If freq is passed, the index will be increased using the periods and the freq. Parameters ---------- periods : int, default 1 Number of periods to shift. freq : str, optional Frequency string. axis : axis to shift, default 0 Shift direction. fill_value : optional The scalar value to use for newly introduced missing values. Returns ------- Series or DataFrame Object shifted within each group. See Also -------- Index.shift : Shift values of Index. tshift : Shift the time index, using the index’s frequency if available. """ if freq is not None or axis != 0: return self.apply(lambda x: x.shift(periods, freq, axis, fill_value)) ids, _, ngroups = self.grouper.group_info res_indexer = np.zeros(len(ids), dtype=np.int64) libgroupby.group_shift_indexer(res_indexer, ids, ngroups, periods) obj = self._obj_with_exclusions res = obj._reindex_with_indexers( {self.axis: (obj.axes[self.axis], res_indexer)}, fill_value=fill_value, allow_dups=True, ) return res @final @Substitution(name="groupby") @Appender(_common_see_also) def pct_change(self, periods=1, fill_method="pad", limit=None, freq=None, axis=0): """ Calculate pct_change of each value to previous entry in group. Returns ------- Series or DataFrame Percentage changes within each group. """ # TODO(GH#23918): Remove this conditional for SeriesGroupBy when # GH#23918 is fixed if freq is not None or axis != 0: return self.apply( lambda x: x.pct_change( periods=periods, fill_method=fill_method, limit=limit, freq=freq, axis=axis, ) ) if fill_method is None: # GH30463 fill_method = "pad" limit = 0 filled = getattr(self, fill_method)(limit=limit) fill_grp = filled.groupby(self.grouper.codes, axis=self.axis) shifted = fill_grp.shift(periods=periods, freq=freq, axis=self.axis) return (filled / shifted) - 1 @final @Substitution(name="groupby") @Substitution(see_also=_common_see_also) def head(self, n=5): """ Return first n rows of each group. Similar to ``.apply(lambda x: x.head(n))``, but it returns a subset of rows from the original DataFrame with original index and order preserved (``as_index`` flag is ignored). Parameters ---------- n : int If positive: number of entries to include from start of each group. If negative: number of entries to exclude from end of each group. Returns ------- Series or DataFrame Subset of original Series or DataFrame as determined by n. %(see_also)s Examples -------- >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], ... columns=['A', 'B']) >>> df.groupby('A').head(1) A B 0 1 2 2 5 6 >>> df.groupby('A').head(-1) A B 0 1 2 """ self._reset_group_selection() mask = self._make_mask_from_positional_indexer(slice(None, n)) return self._mask_selected_obj(mask) @final @Substitution(name="groupby") @Substitution(see_also=_common_see_also) def tail(self, n=5): """ Return last n rows of each group. Similar to ``.apply(lambda x: x.tail(n))``, but it returns a subset of rows from the original DataFrame with original index and order preserved (``as_index`` flag is ignored). Parameters ---------- n : int If positive: number of entries to include from end of each group. If negative: number of entries to exclude from start of each group. Returns ------- Series or DataFrame Subset of original Series or DataFrame as determined by n. %(see_also)s Examples -------- >>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]], ... columns=['A', 'B']) >>> df.groupby('A').tail(1) A B 1 a 2 3 b 2 >>> df.groupby('A').tail(-1) A B 1 a 2 3 b 2 """ self._reset_group_selection() if n: mask = self._make_mask_from_positional_indexer(slice(-n, None)) else: mask = self._make_mask_from_positional_indexer([]) return self._mask_selected_obj(mask) @final def _mask_selected_obj(self, mask: np.ndarray) -> NDFrameT: """ Return _selected_obj with mask applied to the correct axis. Parameters ---------- mask : np.ndarray Boolean mask to apply. Returns ------- Series or DataFrame Filtered _selected_obj. """ if self.axis == 0: return self._selected_obj[mask] else: return self._selected_obj.iloc[:, mask] @final def _reindex_output( self, output: OutputFrameOrSeries, fill_value: Scalar = np.NaN, qs: npt.NDArray[np.float64] | None = None, ) -> OutputFrameOrSeries: """ If we have categorical groupers, then we might want to make sure that we have a fully re-indexed output to the levels. This means expanding the output space to accommodate all values in the cartesian product of our groups, regardless of whether they were observed in the data or not. This will expand the output space if there are missing groups. The method returns early without modifying the input if the number of groupings is less than 2, self.observed == True or none of the groupers are categorical. Parameters ---------- output : Series or DataFrame Object resulting from grouping and applying an operation. fill_value : scalar, default np.NaN Value to use for unobserved categories if self.observed is False. qs : np.ndarray[float64] or None, default None quantile values, only relevant for quantile. Returns ------- Series or DataFrame Object (potentially) re-indexed to include all possible groups. """ groupings = self.grouper.groupings if len(groupings) == 1: return output # if we only care about the observed values # we are done elif self.observed: return output # reindexing only applies to a Categorical grouper elif not any( isinstance(ping.grouping_vector, (Categorical, CategoricalIndex)) for ping in groupings ): return output levels_list = [ping.group_index for ping in groupings] names = self.grouper.names if qs is not None: # error: Argument 1 to "append" of "list" has incompatible type # "ndarray[Any, dtype[floating[_64Bit]]]"; expected "Index" levels_list.append(qs) # type: ignore[arg-type] names = names + [None] index, _ = MultiIndex.from_product(levels_list, names=names).sortlevel() if self.as_index: d = { self.obj._get_axis_name(self.axis): index, "copy": False, "fill_value": fill_value, } return output.reindex(**d) # GH 13204 # Here, the categorical in-axis groupers, which need to be fully # expanded, are columns in `output`. An idea is to do: # output = output.set_index(self.grouper.names) # .reindex(index).reset_index() # but special care has to be taken because of possible not-in-axis # groupers. # So, we manually select and drop the in-axis grouper columns, # reindex `output`, and then reset the in-axis grouper columns. # Select in-axis groupers in_axis_grps = ( (i, ping.name) for (i, ping) in enumerate(groupings) if ping.in_axis ) g_nums, g_names = zip(*in_axis_grps) output = output.drop(labels=list(g_names), axis=1) # Set a temp index and reindex (possibly expanding) output = output.set_index(self.grouper.result_index).reindex( index, copy=False, fill_value=fill_value ) # Reset in-axis grouper columns # (using level numbers `g_nums` because level names may not be unique) output = output.reset_index(level=g_nums) return output.reset_index(drop=True) @final def sample( self, n: int | None = None, frac: float | None = None, replace: bool = False, weights: Sequence | Series | None = None, random_state: RandomState | None = None, ): """ Return a random sample of items from each group. You can use `random_state` for reproducibility. .. versionadded:: 1.1.0 Parameters ---------- n : int, optional Number of items to return for each group. Cannot be used with `frac` and must be no larger than the smallest group unless `replace` is True. Default is one if `frac` is None. frac : float, optional Fraction of items to return. Cannot be used with `n`. replace : bool, default False Allow or disallow sampling of the same row more than once. weights : list-like, optional Default None results in equal probability weighting. If passed a list-like then values must have the same length as the underlying DataFrame or Series object and will be used as sampling probabilities after normalization within each group. Values must be non-negative with at least one positive element within each group. random_state : int, array-like, BitGenerator, np.random.RandomState, np.random.Generator, optional If int, array-like, or BitGenerator, seed for random number generator. If np.random.RandomState or np.random.Generator, use as given. .. versionchanged:: 1.4.0 np.random.Generator objects now accepted Returns ------- Series or DataFrame A new object of same type as caller containing items randomly sampled within each group from the caller object. See Also -------- DataFrame.sample: Generate random samples from a DataFrame object. numpy.random.choice: Generate a random sample from a given 1-D numpy array. Examples -------- >>> df = pd.DataFrame( ... {"a": ["red"] * 2 + ["blue"] * 2 + ["black"] * 2, "b": range(6)} ... ) >>> df a b 0 red 0 1 red 1 2 blue 2 3 blue 3 4 black 4 5 black 5 Select one row at random for each distinct value in column a. The `random_state` argument can be used to guarantee reproducibility: >>> df.groupby("a").sample(n=1, random_state=1) a b 4 black 4 2 blue 2 1 red 1 Set `frac` to sample fixed proportions rather than counts: >>> df.groupby("a")["b"].sample(frac=0.5, random_state=2) 5 5 2 2 0 0 Name: b, dtype: int64 Control sample probabilities within groups by setting weights: >>> df.groupby("a").sample( ... n=1, ... weights=[1, 1, 1, 0, 0, 1], ... random_state=1, ... ) a b 5 black 5 2 blue 2 0 red 0 """ # noqa:E501 size = sample.process_sampling_size(n, frac, replace) if weights is not None: weights_arr = sample.preprocess_weights( self._selected_obj, weights, axis=self.axis ) random_state = com.random_state(random_state) group_iterator = self.grouper.get_iterator(self._selected_obj, self.axis) sampled_indices = [] for labels, obj in group_iterator: grp_indices = self.indices[labels] group_size = len(grp_indices) if size is not None: sample_size = size else: assert frac is not None sample_size = round(frac * group_size) grp_sample = sample.sample( group_size, size=sample_size, replace=replace, weights=None if weights is None else weights_arr[grp_indices], random_state=random_state, ) sampled_indices.append(grp_indices[grp_sample]) sampled_indices = np.concatenate(sampled_indices) return self._selected_obj.take(sampled_indices, axis=self.axis) @doc(GroupBy) def get_groupby( obj: NDFrame, by: _KeysArgType | None = None, axis: int = 0, level=None, grouper: ops.BaseGrouper | None = None, exclusions=None, selection=None, as_index: bool = True, sort: bool = True, group_keys: bool = True, squeeze: bool = False, observed: bool = False, mutated: bool = False, dropna: bool = True, ) -> GroupBy: klass: type[GroupBy] if isinstance(obj, Series): from pandas.core.groupby.generic import SeriesGroupBy klass = SeriesGroupBy elif isinstance(obj, DataFrame): from pandas.core.groupby.generic import DataFrameGroupBy klass = DataFrameGroupBy else: # pragma: no cover raise TypeError(f"invalid type: {obj}") return klass( obj=obj, keys=by, axis=axis, level=level, grouper=grouper, exclusions=exclusions, selection=selection, as_index=as_index, sort=sort, group_keys=group_keys, squeeze=squeeze, observed=observed, mutated=mutated, dropna=dropna, ) def _insert_quantile_level(idx: Index, qs: npt.NDArray[np.float64]) -> MultiIndex: """ Insert the sequence 'qs' of quantiles as the inner-most level of a MultiIndex. The quantile level in the MultiIndex is a repeated copy of 'qs'. Parameters ---------- idx : Index qs : np.ndarray[float64] Returns ------- MultiIndex """ nqs = len(qs) if idx._is_multi: idx = cast(MultiIndex, idx) lev_codes, lev = Index(qs).factorize() levels = list(idx.levels) + [lev] codes = [np.repeat(x, nqs) for x in idx.codes] + [np.tile(lev_codes, len(idx))] mi = MultiIndex(levels=levels, codes=codes, names=idx.names + [None]) else: mi = MultiIndex.from_product([idx, qs]) return mi def warn_dropping_nuisance_columns_deprecated(cls, how: str) -> None: warnings.warn( "Dropping invalid columns in " f"{cls.__name__}.{how} is deprecated. " "In a future version, a TypeError will be raised. " f"Before calling .{how}, select only columns which " "should be valid for the function.", FutureWarning, stacklevel=find_stack_level(), )
32.530549
106
0.566521
acf65a8202522afc6cdc52b52e5667b758b7903d
7,479
py
Python
metaskills.py
roscroft/delve
a629eca4e23e3fd525cad9c811b050e4f0ca886a
[ "MIT" ]
null
null
null
metaskills.py
roscroft/delve
a629eca4e23e3fd525cad9c811b050e4f0ca886a
[ "MIT" ]
null
null
null
metaskills.py
roscroft/delve
a629eca4e23e3fd525cad9c811b050e4f0ca886a
[ "MIT" ]
null
null
null
import json def json_parser(skills_file): with open(skills_file) as skills_json: skill_data = json.load(skills_json) return skill_data class Skill(): def __init__(self, **kwargs): self.full_name = kwargs["full_name"] self.description = kwargs["description"] self.rank = kwargs["rank"] class MetaSkill(Skill): def __init__(self, **kwargs): super().__init__(**kwargs) self.multipliers = dict() self.adders = dict() self.effects = kwargs.get("effects") if self.effects: self.set_effects() self.arg_effects = kwargs.get("arg_effects") if self.arg_effects: self.set_arg_effects() def set_effects(self): for effect in self.effects: change = effect["change"] base = effect["base"] per_rank = effect["per_rank"] total_change = base + self.rank * per_rank if base == 0: self.adders[change] = total_change elif base == 1: self.multipliers[change] = total_change def set_arg_effects(self): for effect in self.arg_effects: change = effect["change"] base = effect["base"] if base == 0: self.adders[change] = base elif base == 1: self.multipliers[change] = base class AuraSynergy(MetaSkill): def __init__(self, synergy, **kwargs): super().__init__(**kwargs) # Synergy is the sum of all aura ranks self.synergy = synergy self.adders["intensity"] *= self.synergy self.adders["range"] *= self.synergy class AuraCompression(MetaSkill): def __init__(self, compress, **kwargs): super().__init__(**kwargs) # Compress is a number of meters self.compress = compress self.adders["intensity"] *= self.compress # This is a direct range addition, not a percentage added self.adders["range"] -= self.compress class ChannelMastery(MetaSkill): def __init__(self, channel, **kwargs): super().__init__(**kwargs) # Channel is a multiplier, 0 to 2 self.channel = channel self.multipliers["intensity"] *= self.channel self.multipliers["cost"] *= self.channel class Aura(Skill): def __init__(self, **kwargs): super().__init__(**kwargs) base_cost = kwargs["base_cost"] self.cost = self.rank * base_cost self.cost_unit = kwargs["cost_unit"] base_range = kwargs["base_range"] self.range = self.rank * base_range class OffensiveAura(Aura): def __init__(self, focus, **kwargs): super().__init__(**kwargs) base_intensity = kwargs["base_intensity"] self.intensity = self.rank * base_intensity per_focus_intensity = kwargs["per_focus_intensity"] self.intensity += focus * per_focus_intensity class DefensiveAura(Aura): def __init__(self, **kwargs): super().__init__(**kwargs) base_intensity = kwargs["base_intensity"] self.intensity = self.rank * base_intensity class Purify(Aura): def __init__(self, **kwargs): super().__init__(**kwargs) class Detection(Aura): def __init__(self, **kwargs): super().__init__(**kwargs) base_resolution = kwargs["base_resolution"] self.resolution = self.rank * base_resolution self.resolution_unit = kwargs["resolution_unit"] class EssenceWell(Aura): def __init__(self, **kwargs): super().__init__(**kwargs) # The transfer rate here is represented by cost. # Actual mana transferred is modulated by efficiency. base_efficiency = kwargs["base_efficiency"] self.efficiency = self.rank * base_efficiency class Velocity(Aura): def __init__(self, **kwargs): super().__init__(**kwargs) base_speed_boost = kwargs["base_speed_boost"] self.speed_boost = self.rank * base_speed_boost class ManaManipulation(Skill): def __init__(self, focus, **kwargs): super().__init__(**kwargs) base_transfer_rate = kwargs["base_transfer_rate"] per_focus_transfer_rate = kwargs["per_focus_transfer_rate"] self.transfer_rate = self.rank * base_transfer_rate + focus * per_focus_transfer_rate self.transfer_rate_unit = kwargs["transfer_rate_unit"] class Winter(Aura): def __init__(self, **kwargs): super().__init__(**kwargs) base_regen_boost = kwargs["base_regen_boost"] self.regen_boost = self.rank * base_regen_boost def test(): skills = json_parser("skills.json") focus = 10 meta_skills = skills["meta_skills"] amplify_info = meta_skills["amplify"] amplify = MetaSkill(**amplify_info) print(f"Amplify adders: {amplify.adders}") print(f"Amplify multipliers: {amplify.multipliers}") aura_synergy_info = meta_skills["aura_synergy"] synergy = 80 aura_synergy = AuraSynergy(synergy, **aura_synergy_info) print(f"Aura Synergy adders: {aura_synergy.adders}") compression_info = meta_skills["aura_compression"] compress = 5 compression = AuraCompression(compress, **compression_info) print(f"Compression adders: {compression.adders}") channel_info = meta_skills["channel_mastery"] channel = 1.5 channel_mastery = ChannelMastery(channel, **channel_info) print(f"Channel multipliers: {channel_mastery.multipliers}") offensive_auras = skills["offensive_auras"] immolate_info = offensive_auras["immolate"] immolate = OffensiveAura(focus, **immolate_info) print(f"Immolate intensity: {immolate.intensity}") print(f"Immolate cost: {immolate.cost}/{immolate.cost_unit}") print(f"Immolate range: {immolate.range}") defensive_auras = skills["defensive_auras"] force_ward_info = defensive_auras["force_ward"] force_ward = DefensiveAura(**force_ward_info) print(f"Force Ward intensity: {100*force_ward.intensity}%") print(f"Force Ward cost: {force_ward.cost}/{force_ward.cost_unit}") print(f"Force Ward range: {force_ward.range}") utility_auras = skills["utility_auras"] purify_info = utility_auras["purify"] purify = Purify(**purify_info) print(f"Purify cost: {purify.cost}/{purify.cost_unit}") print(f"Purify range: {purify.range}") detection_info = utility_auras["detection"] detection = Detection(**detection_info) print(f"Detection cost: {detection.cost}") print(f"Detection range: {detection.range}") print(f"Detection resolution: {detection.resolution}/{detection.resolution_unit}") essence_well_info = utility_auras["essence_well"] essence_well = EssenceWell(**essence_well_info) print(f"Essence Well transfer rate: {essence_well.cost}mp/{essence_well.cost_unit}") print(f"Essence Well efficiency: {essence_well.efficiency}") print(f"Essence Well range: {essence_well.range}") winter_info = utility_auras["winter"] winter = Winter(**winter_info) print(f"Winter boost: {winter.regen_boost}") print(f"Winter range: {winter.range}") print(f"Winter cost: {winter.cost}/{winter.cost_unit}") utilities = skills["utilities"] mana_manipulation_info = utilities["mana_manipulation"] mana_manipulation = ManaManipulation(focus, **mana_manipulation_info) print(f"Mana Manipulation transfer rate: {mana_manipulation.transfer_rate}/{mana_manipulation.transfer_rate_unit}") test()
37.024752
119
0.664928
acf65ac0c38b075b719e2bbe170ab546698db9b9
4,271
py
Python
datasource/card.py
Artemis-ii/LDA
496e43f875ef35084cfb8539ee8bfe4e4fe68fb7
[ "Apache-2.0" ]
null
null
null
datasource/card.py
Artemis-ii/LDA
496e43f875ef35084cfb8539ee8bfe4e4fe68fb7
[ "Apache-2.0" ]
null
null
null
datasource/card.py
Artemis-ii/LDA
496e43f875ef35084cfb8539ee8bfe4e4fe68fb7
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Mon Oct 8 15:09:40 2018 @author: Administrator """ import requests from lxml import etree import re import xlwt f = xlwt.Workbook() #创建工作簿 sheet1 = f.add_sheet(u'sheet1') #创建sheet dlist = ['title', 'pic','text','content', 'from', 'date'] for i in range(len(dlist)): sheet1.write(0,i,dlist[i]) counts=1 def jx(url): global counts #url="http://tieba.baidu.com/p/5722219880" r = requests.get(url) r.encoding='utf-8' s = r.text selector = etree.HTML(s) who ="" count=1 title = selector.xpath('//*[@class="core_title core_title_theme_bright"]/h1/text()') title = ''.join(title) pic = "kong" text="" context ="" froms = "来源百度贴吧" date="2018-10-17 14:35" content = selector.xpath('//*[@class="l_post j_l_post l_post_bright "]') #print("title:"+title) for i in content: kk = i.xpath('.//a[@class="p_author_name j_user_card"]/text()') kkk = ''.join(kk) if count==1: who=kkk count = 2 if who==kkk: ii = i.xpath('.//div[@class="d_post_content j_d_post_content clearfix"]') kkkk =ii[0].xpath('string(.)') text = text+kkkk context = context+kkkk it = ''.join(ii[0].xpath('img/@src')) if "imgsrc" in it: pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') # 匹配模式 url = re.findall(pattern,it) for i in url: if i is not None: ii = i.split("http") for k in ii: if "static" not in k and len(k)>10: context = context+"sssshttp"+k+"ssss" if pic =='kong': pic = "http"+k sheet1.write(counts,0,title) sheet1.write(counts,1,pic) sheet1.write(counts,2,text) sheet1.write(counts,3,context) sheet1.write(counts,4,froms) sheet1.write(counts,5,date) counts = counts+1 for imun in range(4000,4500,50): url="http://tieba.baidu.com/f?kw=%E7%BE%8E%E9%A3%9F&ie=utf-8&pn="+str(imun) #url="http://tieba.baidu.com/f?kw=meishi" r = requests.get(url) r.encoding='utf-8' s = r.text selector = etree.HTML(s) title = selector.xpath('//*[@class="threadlist_title pull_left j_th_tit "]') for i in title: href = i.xpath('a/@href') #name = i.xpath('a/text()') href = 'http://tieba.baidu.com'+''.join(href) print(href) #print(''.join(name)) #print("*"*30) jx(href) f.save('cartdata14.xls') #获取帖子列表 ''' title = selector.xpath('//*[@class="threadlist_title pull_left j_th_tit "]') for i in title: href = i.xpath('a/@href') name = i.xpath('a/text()') print('http://tieba.baidu.com'+''.join(href)) print(''.join(name)) print("*"*30) ''' #content = selector.xpath('//*[@class="d_post_content j_d_post_content clearfix"]') #content = content[0].xpath('string(.)') #content = ''.join(content) #print(content) #获取某一个帖子 ''' title = selector.xpath('//*[@class="core_title core_title_theme_bright"]/h1/text()') title = ''.join(title) content = selector.xpath('//*[@class="d_post_content j_d_post_content clearfix"]') print("title:"+title) for i in content: #kk = i.xpath('//*[@id="post_content_95091918657"]') #kkk = ''.join(kk) kkk =i.xpath('string(.)') print(kkk) it = ''.join(i.xpath('img/@src')) if "imgsrc" in it: """ slist = it.split('.jpg') for i in slist: if "imgsrc" in i: print(i) """ pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') # 匹配模式 url = re.findall(pattern,it) for i in url: if i is not None: ii = i.split("http") for k in ii: if "static" not in k and len(k)>10: print("|") print("http"+k) print("*"*30) '''
24.976608
129
0.503629
acf65ae672da068b8cc3f88c588053ea74bc72ea
7,066
py
Python
app.py
zmwangx/YODO
2b2a09ebd6d701c53892bfde2514c33badba5d3c
[ "WTFPL" ]
4
2019-08-06T23:23:46.000Z
2022-01-07T13:02:10.000Z
app.py
zmwangx/YODO
2b2a09ebd6d701c53892bfde2514c33badba5d3c
[ "WTFPL" ]
null
null
null
app.py
zmwangx/YODO
2b2a09ebd6d701c53892bfde2514c33badba5d3c
[ "WTFPL" ]
1
2019-09-25T10:07:56.000Z
2019-09-25T10:07:56.000Z
#!/usr/bin/env python3 import json import mimetypes import os import pathlib import shutil import string import tempfile import urllib.parse import uuid import flask from werkzeug.middleware.proxy_fix import ProxyFix app = flask.Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) MAX_CONTENT_LENGTH = int(os.getenv("MAX_CONTENT_LENGTH", default=0)) or 10 * 1024 * 1024 app.config["MAX_CONTENT_LENGTH"] = MAX_CONTENT_LENGTH if not os.getenv("STATE_DIRECTORY"): raise RuntimeError("STATE_DIRECTORY not set or empty") STATE_DIR = pathlib.Path(os.getenv("STATE_DIRECTORY")) if not STATE_DIR.is_dir(): raise RuntimeError( f"STATE_DIRECTORY {str(STATE_DIR)!r} does not exist or is not a directory" ) if not STATE_DIR.is_absolute(): raise RuntimeError(f"STATE_DIRECTORY {str(STATE_DIR)!r} is not an absolute path") def url_for(endpoint, *args, **kwargs): return flask.url_for(endpoint, *args, **kwargs, _external=True) def usage_instructions(): return f"""\ YODO - You Only Download Once ============================= YODO is an ephemeral file hosting service. There are two ways to upload a file (say, image.png): $ curl --header 'Content-Type: image/png' --data-binary @image.png {url_for('index')} $ curl --form 'file=@image.png;type=image/png' {url_for('index')} Apparently these are just different flavors of POST requests. The former simply uses the content of the file as request body, and identifies itself via the Content-Type header, but there is no way to provide a filename. The latter is a multipart/form-data request where the content is uploaded through the 'file' part; both Content-Type and filename may be specified this way. Note that application/x-www-form-urlencoded requests are not allowed. There is an upload size limit of {MAX_CONTENT_LENGTH} bytes. The response should be HTTP 201 with the URL of the newly uploaded file, e.g., $ curl --dump-header - --form 'file=@image.png;type=image/png' {url_for('index')} HTTP/1.1 100 Continue HTTP/1.0 201 CREATED Content-Type: text/html; charset=utf-8 Content-Length: 60 {url_for('retrieval', identifier='2c8000bc-7c10-4700-9cc3-eb0dce0a9d1a')} The URL is available for download exactly once; the file is destroyed after the first GET request (but not HEAD). Content-Type, if not specified at upload time, is guessed. The Content-Disposition header is available if filename was specified at upload time. $ curl --head {url_for('retrieval', identifier='2c8000bc-7c10-4700-9cc3-eb0dce0a9d1a')} HTTP/1.0 200 OK Content-Type: image/png Content-Disposition: attachment; filename="image.png" Content-Length: 25715 """ def bad_request(msg, code=400): return msg, code, {"Content-Type": "text/plain"} def server_error(msg, code=500): return msg, code, {"Content-Type": "text/plain"} def content_disposition_header(filename): # Is this filename safe for legacy quoted-string filename parameter? if all(ch in string.printable and ch not in '\\"' for ch in filename): return f'attachment; filename="{filename}"' else: # RFC 5987/8187 filename* parameter. Not universally supported. # Typical browsers and wget with --content-disposition supports # it, but curl (at least up to 7.64.1) with --remote-header-name # does not. return f"attachment; filename*=UTF-8''{urllib.parse.quote(filename)}" def exclusive_create(path): os.close(os.open(path, os.O_CREAT | os.O_EXCL)) def try_unlink(path): try: os.unlink(path) except OSError: pass @app.route("/", methods=["GET", "POST"]) def index(): if flask.request.method in ["GET", "HEAD"]: return usage_instructions(), {"Content-Type": "text/plain"} elif flask.request.method == "POST": if flask.request.content_type == "application/x-www-form-urlencoded": return bad_request("application/x-www-form-urlencoded not allowed.\n") stream = None content_type = None filename = None if not flask.request.files: stream = flask.request.stream content_type = flask.request.content_type else: if "file" not in flask.request.files: return bad_request("No file part.\n") file = flask.request.files["file"] stream = file.stream content_type = file.content_type filename = file.filename if not content_type and filename: content_type, _ = mimetypes.guess_type(filename, strict=False) with tempfile.NamedTemporaryFile(dir=STATE_DIR, delete=False) as tmp: try: shutil.copyfileobj(stream, tmp) stream.close() tmp.close() for _ in range(3): identifier = str(uuid.uuid4()) dest = STATE_DIR / identifier try: exclusive_create(dest) os.rename(tmp.name, dest) except OSError: continue metafile = STATE_DIR / f"{identifier}.json" with metafile.open("w") as fp: json.dump( dict(content_type=content_type, filename=filename), fp ) return f"{url_for('retrieval', identifier=identifier)}\n", 201 # Either the filesystem is broken and open(2) or # rename(2) stops working, or you hit the jackpot with # 3 UUID collisions in a row. return server_error("Failed to allocate URL.") finally: try_unlink(tmp.name) else: raise NotImplementedError @app.route("/<uuid:identifier>") def retrieval(identifier): identifier = str(identifier) file = STATE_DIR / identifier metafile = STATE_DIR / f"{identifier}.json" lockfile = STATE_DIR / f"{identifier}.lock" def generate_response(): with metafile.open() as fp: metadata = json.load(fp) content_type = metadata["content_type"] or "application/octet-stream" filename = metadata["filename"] headers = {"Content-Type": content_type} if filename: headers["Content-Disposition"] = content_disposition_header(filename) with file.open("rb") as fp: body = fp.read() return body, headers if flask.request.method == "HEAD": try: return generate_response() except OSError: flask.abort(404) try: exclusive_create(lockfile) except: # Beaten to it by another request. flask.abort(404) try: return generate_response() except OSError: flask.abort(404) finally: try_unlink(file) try_unlink(metafile) try_unlink(lockfile) def main(): app.run(host="127.0.0.1", port=14641, debug=True, threaded=True) if __name__ == "__main__": main()
32.26484
91
0.638409
acf65c027d129f3eee2222e70a70038b2b4948fe
387
py
Python
app/grandchallenge/github/migrations/0005_githubusertoken_github_user_id.py
kaczmarj/grand-challenge.org
8dc8a2170e51072354f7e94f2a22578805a67b94
[ "Apache-2.0" ]
7
2016-11-05T07:16:30.000Z
2017-11-23T03:38:03.000Z
app/grandchallenge/github/migrations/0005_githubusertoken_github_user_id.py
kaczmarj/grand-challenge.org
8dc8a2170e51072354f7e94f2a22578805a67b94
[ "Apache-2.0" ]
113
2015-05-26T09:27:59.000Z
2018-03-21T10:45:56.000Z
app/grandchallenge/github/migrations/0005_githubusertoken_github_user_id.py
kaczmarj/grand-challenge.org
8dc8a2170e51072354f7e94f2a22578805a67b94
[ "Apache-2.0" ]
7
2015-07-16T20:11:22.000Z
2017-06-06T02:41:24.000Z
# Generated by Django 3.1.13 on 2021-09-20 08:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("github", "0004_auto_20210916_0746")] operations = [ migrations.AddField( model_name="githubusertoken", name="github_user_id", field=models.BigIntegerField(null=True), ) ]
22.764706
58
0.640827
acf65ccf1c341ccd4dc47812f277ffad3534f0c1
13,062
py
Python
Alignment/MillePedeAlignmentAlgorithm/templates/universalConfigTemplate.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Alignment/MillePedeAlignmentAlgorithm/templates/universalConfigTemplate.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Alignment/MillePedeAlignmentAlgorithm/templates/universalConfigTemplate.py
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
###### Universal configuration template for tracker alignment # # Usage: # # Make a copy of this file and insert Startgeometry, Alignables and # Pedesettings directly into it. # # Specify the path to this config-Template in the alignment_setup.ini # # The scripts mps_alisetup.py and mps_setup.py set the Variables at the top (setup*). # # Collection specifies the type of Tracks. Currently these are supported: # - ALCARECOTkAlMinBias -> Minimum Bias # - ALCARECOTkAlCosmicsCTF0T -> Cosmics, either at 0T or 3.8T # - ALCARECOTkAlMuonIsolated -> Isolated Muon # - ALCARECOTkAlZMuMu -> Z decay to two Muons # - ALCARECOTkAlUpsilonMuMu -> Upsilon decay to two Muons # - generalTracks -> general tracks treated like Minimum Bias # - ALCARECOTkAlCosmicsInCollisions -> Cosmics taken during collisions # # Globaltag specifies the detector conditions. # Parts of the Globaltag are overwritten in Startgeometry. # # monitorFile and binaryFile are automatically set by mps_setup. # e.g. millePedeMonitor004.root and milleBinary004.dat # # AlgoMode specifies mode of AlignmentProducer.algoConfig -> mille or pede # mille is default. Pede mode is automatically set when merge config is created by MPS # # CosmicsDecoMode and CosmicsZeroTesla are only relevant if collection # is ALCARECOTkAlCosmicsCTF0T # # If primaryWidth is bigger than 0.0 it overwrites # process.AlignmentProducer.algoConfig.TrajectoryFactory.ParticleProperties.PrimaryWidth = ... # if primaryWidth<=0.0 it has no effect at all. import FWCore.ParameterSet.Config as cms process = cms.Process("Alignment") ################################################################################ # Variables edited by mps_alisetup.py. Used in functions below. # You can change them manually as well. # ------------------------------------------------------------------------------ setupGlobaltag = "placeholder_globaltag" setupCollection = "placeholder_collection" setupCosmicsDecoMode = False setupCosmicsZeroTesla = False setupPrimaryWidth = -1.0 setupJson = "placeholder_json" setupRunStartGeometry = -1 ################################################################################ # Variables edited by MPS (mps_setup and mps_merge). Be careful. # ------------------------------------------------------------------------------ # Default is "mille". Gets changed to "pede" by mps_merge. setupAlgoMode = "mille" # MPS looks specifically for the string "ISN" so don't change this. setupMonitorFile = "millePedeMonitorISN.root" setupBinaryFile = "milleBinaryISN.dat" # Input files. Edited by mps_splice.py readFiles = cms.untracked.vstring() ################################################################################ ################################################################################ # General setup # ------------------------------------------------------------------------------ import Alignment.MillePedeAlignmentAlgorithm.alignmentsetup.GeneralSetup as generalSetup generalSetup.setup(process, setupGlobaltag, setupCosmicsZeroTesla) ################################################################################ # setup alignment producer # ------------------------------------------------------------------------------ import Alignment.MillePedeAlignmentAlgorithm.alignmentsetup.ConfigureAlignmentProducer as confAliProducer confAliProducer.setConfiguration(process, collection = setupCollection, mode = setupAlgoMode, monitorFile = setupMonitorFile, binaryFile = setupBinaryFile, primaryWidth = setupPrimaryWidth, cosmicsZeroTesla = setupCosmicsZeroTesla) ################################################################################ # Overwrite some conditions in global tag # ------------------------------------------------------------------------------ import Alignment.MillePedeAlignmentAlgorithm.alignmentsetup.SetCondition as tagwriter ########################## ## insert Startgeometry ## ########################## # # You can use tagwriter.setCondition() to overwrite conditions in globaltag # # # # Examples (ideal phase-1 tracker-alignment conditions): # tagwriter.setCondition(process, # connect = "frontier://FrontierProd/CMS_CONDITIONS", # record = "TrackerAlignmentRcd", # tag = "TrackerAlignment_Upgrade2017_design_v4") # tagwriter.setCondition(process, # connect = "frontier://FrontierProd/CMS_CONDITIONS", # record = "TrackerSurfaceDeformationRcd", # tag = "TrackerSurfaceDeformations_zero") # tagwriter.setCondition(process, # connect = "frontier://FrontierProd/CMS_CONDITIONS", # record = "TrackerAlignmentErrorExtendedRcd", # tag = "TrackerAlignmentErrorsExtended_Upgrade2017_design_v0") # tagwriter.setCondition(process, # connect = "frontier://FrontierProd/CMS_CONDITIONS", # record = "SiPixelLorentzAngleRcd", # label = "fromAlignment", # tag = "SiPixelLorentzAngle_fromAlignment_phase1_mc_v1") ####################### ## insert Alignables ## ####################### # # to run a high-level alignment on real data (including TOB centering; use # # pixel-barrel centering for MC) of the whole tracker you can use the # # following configuration: # # process.AlignmentProducer.ParameterBuilder.parameterTypes = [ # "SelectorRigid,RigidBody", # ] # # # Define the high-level structure alignables # process.AlignmentProducer.ParameterBuilder.SelectorRigid = cms.PSet( # alignParams = cms.vstring( # "TrackerP1PXBHalfBarrel,111111", # "TrackerP1PXECHalfCylinder,111111", # "TrackerTIBHalfBarrel,111111", # "TrackerTOBHalfBarrel,rrrrrr", # "TrackerTIDEndcap,111111", # "TrackerTECEndcap,111111", # ) # ) # # to run a module-level alignment on real data (including TOB centering; use # # pixel-barrel centering for MC) of the whole tracker (including surface # # deformations) you can use the following configuration (read comments on # # multi-IOV alignment below): # # process.AlignmentProducer.ParameterBuilder.parameterTypes = [ # "SelectorRigid,RigidBody", # "SelectorBowed,BowedSurface", # "SelectorTwoBowed,TwoBowedSurfaces", # ] # # # Define the high-level structure alignables # process.AlignmentProducer.ParameterBuilder.SelectorRigid = cms.PSet( # alignParams = cms.vstring( # "TrackerP1PXBHalfBarrel,111111", # "TrackerP1PXECHalfCylinder,111111", # "TrackerTIBHalfBarrel,111111", # "TrackerTOBHalfBarrel,rrrrrr", # "TrackerTIDEndcap,111111", # "TrackerTECEndcap,111111", # ) # ) # # # Define the module-level alignables (for single modules) # process.AlignmentProducer.ParameterBuilder.SelectorBowed = cms.PSet( # alignParams = cms.vstring( # "TrackerP1PXBModule,111111 111", # "TrackerP1PXECModule,111111 111", # "TrackerTIBModuleUnit,101111 111", # "TrackerTIDModuleUnit,111111 111", # "TrackerTECModuleUnit,111111 111,tecSingleSens", # ), # tecSingleSens = cms.PSet(tecDetId = cms.PSet(ringRanges = cms.vint32(1,4))), # ) # # process.AlignmentProducer.ParameterBuilder.SelectorTwoBowed = cms.PSet( # alignParams = cms.vstring( # "TrackerTOBModuleUnit,101111 111 101111 111", # "TrackerTECModuleUnit,111111 111 111111 111,tecDoubleSens", # ), # tecDoubleSens = cms.PSet(tecDetId = cms.PSet(ringRanges = cms.vint32(5,7))), # ) # # # IOV definition # # - defaults to single-IOV starting at "1", if omitted # # - alignables have to match high-level structures above # # -> except for 'rrrrrr' alignables # process.AlignmentProducer.RunRangeSelection = [ # cms.PSet( # RunRanges = cms.vstring( # "290550", # "300000", # ), # selector = cms.vstring( # "TrackerP1PXBHalfBarrel,111111", # "TrackerP1PXECHalfCylinder,111111", # "TrackerTIBHalfBarrel,111111", # "TrackerTIDEndcap,111111", # "TrackerTECEndcap,111111", # ) # ) # ] # end of process.AlignmentProducer.RunRangeSelection # # To run simultaneous calibrations of the pixel Lorentz angle you need to # # include the corresponding config fragment and configure the granularity and # # IOVs (must be consistent with input LA/template/alignment IOVs) for it. # # Note: There are different version of the LA record available in the global # # tag. Depending on the TTRHBuilder, one has to set a label to configure # # which of them is to be used. The default TTRHBuilder uses pixel # # templates which ignores the unlabelled LA record and uses only the one # # labelled "fromAlignment". This is also the default value in the # # integrated LA calibration. If you are using the generic CPE instead of # # the template CPE you have to use the following setting: # # # # siPixelLA.lorentzAngleLabel = "" # # from Alignment.CommonAlignmentAlgorithm.SiPixelLorentzAngleCalibration_cff \ # import SiPixelLorentzAngleCalibration as siPixelLA # siPixelLA.LorentzAngleModuleGroups.Granularity = cms.VPSet() # siPixelLA.LorentzAngleModuleGroups.RunRange = cms.vuint32(290550, # 295000, # 298100) # # siPixelLA.LorentzAngleModuleGroups.Granularity.extend([ # cms.PSet( # levels = cms.PSet( # alignParams = cms.vstring( # 'TrackerP1PXBModule,,RINGLAYER' # ), # RINGLAYER = cms.PSet( # pxbDetId = cms.PSet( # moduleRanges = cms.vint32(ring, ring), # layerRanges = cms.vint32(layer, layer) # ) # ) # ) # ) # for ring in xrange(1,9) # [1,8] # for layer in xrange(1,5) # [1,4] # ]) # siPixelLA.LorentzAngleModuleGroups.Granularity.append( # cms.PSet( # levels = cms.PSet( # alignParams = cms.vstring('TrackerP1PXECModule,,posz'), # posz = cms.PSet(zRanges = cms.vdouble(-9999.0, 9999.0)) # ) # ) # ) # # process.AlignmentProducer.calibrations.append(siPixelLA) ######################### ## insert Pedesettings ## ######################### # # reasonable pede settings are already defined in # # 'confAliProducer.setConfiguration' above # # # # if you want to obtain alignment errors, use the following setting: # # process.AlignmentProducer.algoConfig.pedeSteerer.method = "inversion 3 0.8" # # # # a list of possible options is documented here: # # http://www.desy.de/~kleinwrt/MP2/doc/html/option_page.html#sec-cmd # # # # if you need to request a larger stack size for individual threads when # # running pede, you can do this with this setting: # # process.AlignmentProducer.algoConfig.pedeSteerer.pedeCommand = "export OMP_STACKSIZE=20M; pede" # # # # you can change or drop pede options as follows: # # import Alignment.MillePedeAlignmentAlgorithm.alignmentsetup.helper as helper # helper.set_pede_option(process, "entries 50 10 2") # helper.set_pede_option(process, "compress", drop = True) ################# ## add filters ## ################# # # please add any EDFilter here that should run before processing the event, # # e.g. add the following lines to ensure that only 3.8T events are selected # # import Alignment.MillePedeAlignmentAlgorithm.alignmentsetup.helper as helper # process.load("Alignment.CommonAlignment.magneticFieldFilter_cfi") # process.magneticFieldFilter.magneticField = 38 # in units of kGauss (=0.1T) # helper.add_filter(process, process.magneticFieldFilter) ################################################################################ # Mille-procedure # ------------------------------------------------------------------------------ if setupAlgoMode == "mille": import Alignment.MillePedeAlignmentAlgorithm.alignmentsetup.MilleSetup as mille mille.setup(process, input_files = readFiles, collection = setupCollection, json_file = setupJson, cosmics_zero_tesla = setupCosmicsZeroTesla, cosmics_deco_mode = setupCosmicsDecoMode) ################################################################################ # Pede-procedure # ------------------------------------------------------------------------------ else: # placeholers get replaced by mps_merge.py, which is called in mps_setup.pl merge_binary_files = ['placeholder_binaryList'] merge_tree_files = ['placeholder_treeList'] import Alignment.MillePedeAlignmentAlgorithm.alignmentsetup.PedeSetup as pede pede.setup(process, binary_files = merge_binary_files, tree_files = merge_tree_files, run_start_geometry = setupRunStartGeometry)
40.81875
105
0.618818
acf65d24552ce0b6f98c2aa00fb020470be9accf
1,817
py
Python
scripts/benchmark_mock_kinect.py
rjw57/streamkinect2
967fc9855cff1f980e75f5330530d9eb6dc37e5a
[ "BSD-2-Clause" ]
3
2015-09-19T06:55:22.000Z
2018-03-31T06:51:31.000Z
scripts/benchmark_mock_kinect.py
rjw57/streamkinect2
967fc9855cff1f980e75f5330530d9eb6dc37e5a
[ "BSD-2-Clause" ]
null
null
null
scripts/benchmark_mock_kinect.py
rjw57/streamkinect2
967fc9855cff1f980e75f5330530d9eb6dc37e5a
[ "BSD-2-Clause" ]
null
null
null
from logging import getLogger import time import tornado.ioloop from zmq.eventloop import ioloop # Install the zmq tornado IOLoop version ioloop.install() from streamkinect2.mock import MockKinect from streamkinect2.compress import DepthFrameCompressor def benchmark_compressed(wait_time): io_loop = tornado.ioloop.IOLoop.instance() print('Running compressed pipeline for {0} seconds...'.format(wait_time)) packets = [] with MockKinect() as kinect: fc = DepthFrameCompressor(kinect) @fc.on_compressed_frame.connect_via(fc) def new_compressed_frame(_, compressed_frame): packets.append(compressed_frame) then = time.time() io_loop.call_later(5, io_loop.stop) io_loop.start() now = time.time() delta = now - then data_size = sum(len(p) for p in packets) data_rate = float(data_size) / delta # bytes/sec pps = len(packets) / delta print('Mock kinect runs at {0:.2f} packets/second w/ compression'.format(pps)) print('Data rate is {0:2f} Mbytes/second'.format(data_rate / (1024*1024))) def benchmark_mock(wait_time): io_loop = tornado.ioloop.IOLoop.instance() print('Running mock kinect for {0} seconds...'.format(wait_time)) state = { 'n_frames': 0 } with MockKinect() as kinect: @kinect.on_depth_frame.connect_via(kinect) def f(kinect, depth_frame): state['n_frames'] += 1 then = time.time() io_loop.call_later(5, io_loop.stop) io_loop.start() now = time.time() delta = now - then fps = state['n_frames'] / delta print('Mock kinect runs at {0:.2f} frames/second'.format(fps)) def main(): wait_time = 5 benchmark_compressed(wait_time) benchmark_mock(wait_time) if __name__ == '__main__': main()
29.306452
82
0.670336
acf65d7865888efb43c281f7253e8b3eb1788485
13,873
py
Python
original_tests/train_ice.py
zhanghuiying2319/Master
1f4d11dd8277517b7e63d34651a9629f58dd7070
[ "MIT" ]
null
null
null
original_tests/train_ice.py
zhanghuiying2319/Master
1f4d11dd8277517b7e63d34651a9629f58dd7070
[ "MIT" ]
null
null
null
original_tests/train_ice.py
zhanghuiying2319/Master
1f4d11dd8277517b7e63d34651a9629f58dd7070
[ "MIT" ]
null
null
null
import os,sys,math,numpy as np, matplotlib.pyplot as plt import torch import torch.utils.data import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import torchvision from torchvision import datasets, models, transforms, utils from torch.utils.data import Dataset, DataLoader import cv2 import random seedv=9 random.seed(seedv) np.random.seed(seedv) torch.manual_seed(seedv) def loadindexlist(outpath,numcv): indexlist=[ [] for i in range(numcv) ] for cv in range(numcv): fname= os.path.join(outpath,'split_cv'+str(cv)+'.txt') with open(fname,'r') as f: line = f.readline().rstrip().split() for k in line: indexlist[cv].append(int(k)) return indexlist def getrandomsampler_innersplit5to2simple(outpath,numcv, outercvind, trainvalortest): indexlist = loadindexlist(outpath,numcv) trainvalcvinds= [ cvi for cvi in range(numcv) if cvi !=outercvind] if trainvalortest == 'train': indices=[] for cvinds in trainvalcvinds[:numcv-3]: indices.extend( indexlist[cvinds] ) elif trainvalortest == 'val': indices=[] for cvinds in trainvalcvinds[numcv-3:]: indices.extend( indexlist[cvinds] ) elif trainvalortest == 'test': indices = indexlist[outercvind] else: print('unknown trainvalortest', trainvalortest) exit() sampler = torch.utils.data.SubsetRandomSampler(indices) return sampler def getrandomsampler_innercv(outpath,numcv, outercvind, innercvind, trainvalortest): indexlist = loadindexlist(outpath,numcv) trainvalcvinds= [ cvi for cvi in range(numcv) if cvi !=outercvind] if trainvalortest == 'train': indices=[] for cvi in range(numcv-1): if cvi !=innercvind: indices.extend( indexlist[ trainvalcvinds[cvi] ] ) elif trainvalortest == 'val': indices = indexlist[trainvalcvinds[innercvind]] elif trainvalortest == 'test': indices = indexlist[outercvind] else: print('unknown trainvalortest', trainvalortest) exit() #https://www.youtube.com/watch?v=CFpGXUxXk2g sampler = torch.utils.data.SubsetRandomSampler(indices) return sampler #for better perf #https://github.com/hcarlens/pytorch-tabular/blob/master/fast_tensor_data_loader.py #train: random flip h/v , random rotation # also grayscale mod? #eval: return 2 flips times n rotations for avg classif # eval simple: return img class icedataset_train_uresize(torch.utils.data.Dataset): def __init__(self, thenumpyfile, transforms ): self.transforms=transforms self.uniformresize = 128 # a bit above 80% quant # alternative: embed into 224x224 with padding, and corner / random position crop if test image is too large over 224 numcl =9 with open(thenumpyfile,'rb') as f: a = np.load(f,allow_pickle=True) b = np.load(f,allow_pickle=True) c = np.load(f,allow_pickle=True) #self.rawimgslist=[] #for l in range(a.shape[0]): # self.rawimgslist.append( torch.tensor(a[l]) ) self.processedimgslist=[] for l in range(a.shape[0]): d1=a[l].shape[0] d2=a[l].shape[1] if d1>d2: dsize=(self.uniformresize, int( round( self.uniformresize*d2/d1 ) ) ) else: dsize= ( int( round( self.uniformresize*d1/d2 ) ) , self.uniformresize ) resizedimg = cv2.resize( a[l], dsize= dsize ) self.processedimgslist.append( torch.tensor(resizedimg) ) labels = np.zeros((c.shape[0],numcl), dtype = np.int32) for l in range(c.shape[0]): labels[l,:]=c[l] self.labels=torch.IntTensor(labels) def __getitem__(self,idx): #pad t = torch.zeros((1, self.uniformresize, self.uniformresize) ) d1=self.processedimgslist[idx].shape[0] d2=self.processedimgslist[idx].shape[1] if d1 > d2: offset = (self.uniformresize- d2)//2 t[0,:,offset:offset+self.processedimgslist[idx].shape[1]] = self.processedimgslist[idx].clone() else: offset = (self.uniformresize- d1)//2 t[0,offset:offset+self.processedimgslist[idx].shape[0],:] = self.processedimgslist[idx].clone() img = torch.cat ( ( t,t,t ),dim=0 ) if self.transforms: img = self.transforms(img) ''' clslabel = torch.nonzero(self.labels[idx,:], as_tuple=True)[0] if clslabel.shape[0]>1: print('err') exit() sample = [ img , clslabel[0] ,idx] ''' sample = [ img , self.labels[idx,:] ,idx] return sample def __len__(self): return self.labels.shape[0] def train_epoch(model, trainloader, criterion, device, optimizer ): model.train() lf = torch.nn.CrossEntropyLoss() losses = [] for batch_idx, data in enumerate(trainloader): inputs=data[0].to(device) labels=data[1].to(device) optimizer.zero_grad() outputs = model(inputs) if batch_idx ==0: print(outputs.shape,labels.shape) slab = torch.nonzero(labels,as_tuple=True)[1] loss = lf(outputs, slab) #loss = torch.mean( torch.nn.functional.log_softmax(outputs, dim=1)*labels) #loss = criterion(output, labels) loss.backward() optimizer.step() losses.append(loss.item()) if (batch_idx%100==0) and (batch_idx>=100): print('at batchindex: ',batch_idx,' mean of losses: ',np.mean(losses)) return np.mean(losses) def evaluate2(model, dataloader, criterion, device, numcl): model.eval() lf = torch.nn.CrossEntropyLoss() classcounts = torch.zeros(numcl) confusion_matrix = torch.zeros(numcl, numcl) with torch.no_grad(): losses = [] for batch_idx, data in enumerate(dataloader): if (batch_idx%100==0) and (batch_idx>=100): print('at val batchindex: ',batch_idx) inputs = data[0].to(device) outputs = model(inputs) labels = data[1] #loss = criterion(outputs, labels.to(device) ) #loss = torch.mean( torch.nn.functional.log_softmax(outputs, dim=1)*labels.to(device)) slab = torch.nonzero(labels,as_tuple=True)[1].to(device) loss = lf(outputs, slab) losses.append(loss.item()) cpuout= outputs.to('cpu') _, preds = torch.max(cpuout, 1) for si in range(labels.shape[0]): inds = torch.nonzero(labels[si,:],as_tuple=True) confusion_matrix[inds[0],preds[si].long()]+=1 classcounts+=torch.sum(labels,dim=0) globalacc=0 for c in range(numcl): globalacc+= confusion_matrix[c,c] globalacc/=torch.sum(classcounts) cwacc = confusion_matrix.diag() / classcounts return globalacc, cwacc, confusion_matrix, classcounts, np.mean(losses) def traineval2_nocv_notest(dataloader_train, dataloader_val , model , criterion, optimizer, scheduler, num_epochs, device, numcl): best_measure = 0 best_epoch =-1 trainlosses=[] testperfs1=[] testperfs2=[] for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs - 1)) print('-' * 10) model.train(True) avgloss=train_epoch(model, dataloader_train, criterion, device , optimizer ) trainlosses.append(avgloss) if scheduler is not None: scheduler.step() model.train(False) globalacc, cwacc, confusion_matrix, classcounts , avgvalloss = evaluate2(model, dataloader_val, criterion, device, numcl) print(avgloss,avgvalloss) testperfs1.append(globalacc) testperfs2.append(cwacc) print('at epoch: ', epoch,' classwise perfmeasure ', torch.mean(cwacc).item()) print('at epoch: ', epoch,' acc ', globalacc.item()) avgperfmeasure = globalacc #torch.mean(cwacc) print('at epoch: ', epoch,' avgperfmeasure ', avgperfmeasure.item()) if avgperfmeasure > best_measure: #higher is better or lower is better? bestweights= model.state_dict() best_measure = avgperfmeasure best_epoch = epoch bestcwacc = cwacc bestacc = globalacc ''' savept= './scores' if not os.path.isdir(savept): os.makedirs(savept) np.save(os.path.join(savept,'predsv1.npy'), cwacc.cpu().numpy() ) ''' print('current best', best_measure.item(), ' at epoch ', best_epoch) return best_epoch,bestcwacc, bestacc , bestweights def runstuff(): ''' if len(sys.argv)!=2: print('len(sys.argv)!=2', len(sys.argv)) exit() ''' config = dict() # kind of a dataset property config['numcl']=9 config['numcv']=10 config['splitpath']='icesplits_v2_09052021' config['use_gpu'] = True #change lr here!!!!!!!!!!!!!!!!! config['lr']=0.0001 config['batchsize_train'] = 32 config['batchsize_val'] = 64 config['maxnumepochs'] = 35 config['scheduler_stepsize']=15 config['scheduler_factor']=0.3 #data augmentations data_transforms = { 'train': transforms.Compose([ #transforms.Resize(128), #transforms.RandomCrop(128), transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip(), transforms.RandomRotation(degrees=180 ),#, interpolation= "bilinear"), transforms.Normalize([0.111, 0.111, 0.111], [0.14565, 0.14565, 0.14565]) ]), 'test': transforms.Compose([ #transforms.Resize(128), #transforms.CenterCrop(128), transforms.Normalize([0.111, 0.111, 0.111], [0.14565, 0.14565, 0.14565]) ]), } if True == config['use_gpu']: device= torch.device('cuda:0') else: device= torch.device('cpu') dataset_trainval = icedataset_train_uresize('./test_withBoundaries_new_Julie.npy', transforms = data_transforms['train'] ) dataset_test = icedataset_train_uresize('./test_withBoundaries_new_Julie.npy', transforms = data_transforms['test']) #cvind = int(sys.argv[1]) for cvind in range(config['numcv']): sampler_train = getrandomsampler_innersplit5to2simple(outpath = config['splitpath'] ,numcv = config['numcv'], outercvind = cvind, trainvalortest ='train') dataloader_train = torch.utils.data.DataLoader(dataset = dataset_trainval, batch_size= config['batchsize_train'], shuffle=False, sampler=sampler_train, batch_sampler=None, num_workers=0, collate_fn=None) sampler_val = getrandomsampler_innersplit5to2simple(outpath = config['splitpath'] ,numcv = config['numcv'], outercvind = cvind, trainvalortest ='val') dataloader_val = torch.utils.data.DataLoader(dataset = dataset_trainval, batch_size= config['batchsize_val'], shuffle=False, sampler=sampler_val, batch_sampler=None, num_workers=0, collate_fn=None) sampler_test = getrandomsampler_innersplit5to2simple(outpath = config['splitpath'] ,numcv = config['numcv'], outercvind = cvind, trainvalortest ='test') dataloader_test = torch.utils.data.DataLoader(dataset = dataset_test, batch_size= config['batchsize_val'], shuffle=False, sampler=sampler_test, batch_sampler=None, num_workers=0, collate_fn=None) #change different pre-tranined model here!!!!!!!!!!!!!!! model = models.densenet121(pretrained=True) #resnet # num_ft = model.fc.in_features # model.fc = nn.Linear(num_ft, config['numcl']) #densenet num_ft = model.classifier.in_features model.classifier = nn.Linear(num_ft, config['numcl']) model = model.to(device) #change SGD here! !!!!!!!!!!!!!!!!!!!!! #Adam #optimizer = optim.Adam(model.parameters(), lr=config['lr']) #AdamW optimizer = optim.AdamW(model.parameters(), lr=config['lr']) #SGD #optimizer = optim.SGD(model.parameters(), lr=config['lr'], momentum=0.9) #freezing some layers #trainable_params=[] #for nam,lay in model.named_parameters(): # print(nam) # if 'classifier' in nam: # trainable_params.append(lay) # elif 'denseblock3' in nam: # trainable_params.append(lay) # elif 'denseblock3' in nam: # trainable_params.append(lay) # elif 'features.norm5' in nam: # trainable_params.append(lay) #optimizer = optim.SGD(trainable_params, lr=config['lr'], momentum=0.9) #optimizer = optim.Adam(trainable_params, lr=config['lr']) #optimizer = optim.AdamW(trainable_params, lr=config['lr']) somelr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=config['scheduler_stepsize'], gamma= config['scheduler_factor']) best_epoch,bestcwacc, bestacc , bestweights = traineval2_nocv_notest(dataloader_train, dataloader_val , model , criterion = None, optimizer = optimizer , scheduler = somelr_scheduler, num_epochs = config['maxnumepochs'] , device = device , numcl = config['numcl'] ) #test evaluation model.load_state_dict(bestweights) globalacc, cwacc, confusion_matrix, classcounts, testlossavg = evaluate2(model, dataloader_test, criterion = None, device = device, numcl = config['numcl'] ) print('test eval class-wise acc', torch.mean(cwacc.cpu()).item() ) print('test eval global acc', globalacc.cpu().item() ) # save results savept= './scores_v2_10052021_densenet121_AdamW_lr10-5_lay34clfn5' if not os.path.isdir(savept): os.makedirs(savept) np.save(os.path.join(savept,'cwacc_outercv{:d}.npy'.format(cvind)), cwacc.cpu().numpy() ) np.save(os.path.join(savept,'globalacc_outercv{:d}.npy'.format(cvind)), globalacc.cpu().numpy() ) np.save(os.path.join(savept,'confusion_matrix_outercv{:d}.npy'.format(cvind)), confusion_matrix.cpu().numpy() ) torch.save(bestweights, os.path.join(savept,'bestweights_outercv{:d}.pt'.format(cvind)) ) if __name__=='__main__': runstuff()
31.105381
271
0.653211
acf65de48b324c28c96eb2c45b906dca60a7d32e
17,646
py
Python
statsmodels/stats/_lilliefors.py
chartrix/statsmodels
14fb572ce70202f970786986179dbc91efdd0aa3
[ "BSD-3-Clause" ]
null
null
null
statsmodels/stats/_lilliefors.py
chartrix/statsmodels
14fb572ce70202f970786986179dbc91efdd0aa3
[ "BSD-3-Clause" ]
null
null
null
statsmodels/stats/_lilliefors.py
chartrix/statsmodels
14fb572ce70202f970786986179dbc91efdd0aa3
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """ Implements Lilliefors corrected Kolmogorov-Smirnov tests for normal and exponential distributions. `kstest_fit` is provided as a top-level function to access both tests. `kstest_normal` and `kstest_exponential` are provided as convenience functions with the appropriate test as the default. `lilliefors` is provided as an alias for `kstest_fit`. Created on Sat Oct 01 13:16:49 2011 Author: Josef Perktold License: BSD-3 pvalues for Lilliefors test are based on formula and table in An Analytic Approximation to the Distribution of Lilliefors's Test Statistic for Normality Author(s): Gerard E. Dallal and Leland WilkinsonSource: The American Statistician, Vol. 40, No. 4 (Nov., 1986), pp. 294-296Published by: American Statistical AssociationStable URL: http://www.jstor.org/stable/2684607 . On the Kolmogorov-Smirnov Test for Normality with Mean and Variance Unknown Hubert W. Lilliefors Journal of the American Statistical Association, Vol. 62, No. 318. (Jun., 1967), pp. 399-402. --- Updated 2017-07-23 Jacob C. Kimmel Ref: Lilliefors, H.W. On the Kolmogorov-Smirnov test for the exponential distribution with mean unknown. Journal of the American Statistical Association, Vol 64, No. 325. (1969), pp. 387–389. """ from statsmodels.compat.python import string_types import numpy as np from scipy.interpolate import interp1d from scipy import stats from .tabledist import TableDist def ksstat(x, cdf, alternative='two_sided', args=()): """ Calculate statistic for the Kolmogorov-Smirnov test for goodness of fit This calculates the test statistic for a test of the distribution G(x) of an observed variable against a given distribution F(x). Under the null hypothesis the two distributions are identical, G(x)=F(x). The alternative hypothesis can be either 'two_sided' (default), 'less' or 'greater'. The KS test is only valid for continuous distributions. Parameters ---------- x : array_like, 1d array of observations cdf : string or callable string: name of a distribution in scipy.stats callable: function to evaluate cdf alternative : 'two_sided' (default), 'less' or 'greater' defines the alternative hypothesis (see explanation) args : tuple, sequence distribution parameters for call to cdf Returns ------- D : float KS test statistic, either D, D+ or D- See Also -------- scipy.stats.kstest Notes ----- In the one-sided test, the alternative is that the empirical cumulative distribution function of the random variable is "less" or "greater" than the cumulative distribution function F(x) of the hypothesis, G(x)<=F(x), resp. G(x)>=F(x). In contrast to scipy.stats.kstest, this function only calculates the statistic which can be used either as distance measure or to implement case specific p-values. """ nobs = float(len(x)) if isinstance(cdf, string_types): cdf = getattr(stats.distributions, cdf).cdf elif hasattr(cdf, 'cdf'): cdf = getattr(cdf, 'cdf') x = np.sort(x) cdfvals = cdf(x, *args) if alternative in ['two_sided', 'greater']: Dplus = (np.arange(1.0, nobs+1)/nobs - cdfvals).max() if alternative == 'greater': return Dplus if alternative in ['two_sided', 'less']: Dmin = (cdfvals - np.arange(0.0, nobs)/nobs).max() if alternative == 'less': return Dmin D = np.max([Dplus,Dmin]) return D # new version with tabledist # -------------------------- def get_lilliefors_table(dist='norm'): ''' Generates tables for significance levels of Lilliefors test statistics Tables for available normal and exponential distribution testing, as specified in Lilliefors references above Parameters ---------- dist : string. distribution being tested in set {'norm', 'exp'}. Returns ------- lf : TableDist object. table of critical values ''' # function just to keep things together # for this test alpha is sf probability, i.e. right tail probability if dist == 'norm': alpha = np.array([ 0.2 , 0.15 , 0.1 , 0.05 , 0.01 , 0.001])[::-1] size = np.array([ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30, 40, 100, 400, 900], float) # critical values, rows are by sample size, columns are by alpha crit_lf = np.array( [[303, 321, 346, 376, 413, 433], [289, 303, 319, 343, 397, 439], [269, 281, 297, 323, 371, 424], [252, 264, 280, 304, 351, 402], [239, 250, 265, 288, 333, 384], [227, 238, 252, 274, 317, 365], [217, 228, 241, 262, 304, 352], [208, 218, 231, 251, 291, 338], [200, 210, 222, 242, 281, 325], [193, 202, 215, 234, 271, 314], [187, 196, 208, 226, 262, 305], [181, 190, 201, 219, 254, 296], [176, 184, 195, 213, 247, 287], [171, 179, 190, 207, 240, 279], [167, 175, 185, 202, 234, 273], [163, 170, 181, 197, 228, 266], [159, 166, 176, 192, 223, 260], [143, 150, 159, 173, 201, 236], [131, 138, 146, 159, 185, 217], [115, 120, 128, 139, 162, 189], [ 74, 77, 82, 89, 104, 122], [ 37, 39, 41, 45, 52, 61], [ 25, 26, 28, 30, 35, 42]])[:,::-1] / 1000. # also build a table for larger sample sizes def f(n): return np.array([0.736, 0.768, 0.805, 0.886, 1.031]) / np.sqrt(n) higher_sizes = np.array([35, 40, 45, 50, 60, 70, 80, 100, 200, 500, 1000, 2000, 3000, 5000, 10000, 100000], float) higher_crit_lf = np.zeros([higher_sizes.shape[0], crit_lf.shape[1]-1]) for i in range(len(higher_sizes)): higher_crit_lf[i, :] = f(higher_sizes[i]) alpha_large = alpha[:-1] size_large = np.concatenate([size, higher_sizes]) crit_lf_large = np.vstack([crit_lf[:-4,:-1], higher_crit_lf]) lf = TableDist(alpha, size, crit_lf) elif dist == 'exp': alpha = np.array([0.2, 0.15, 0.1, 0.05, 0.01])[::-1] size = np.array([3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,30], float) crit_lf = np.array([ [451, 479, 511, 551, 600], [396, 422, 499, 487, 548], [359, 382, 406, 442, 504], [331, 351, 375, 408, 470], [309, 327, 350, 382, 442], [291, 308, 329, 360, 419], [277, 291, 311, 341, 399], [263, 277, 295, 325, 380], [251, 264, 283, 311, 365], [241, 254, 271, 298, 351], [232, 245, 261, 287, 338], [224, 237, 252, 277, 326], [217, 229, 244, 269, 315], [211, 222, 236, 261, 306], [204, 215, 229, 253, 297], [199, 210, 223, 246, 289], [193, 204, 218, 239, 283], [188, 199, 212, 234, 278], [170, 180, 191, 210, 247], [155, 164, 174, 192, 226]])[:,::-1] / 1000. def f(n): return np.array([.86, .91, .96, 1.06, 1.25]) / np.sqrt(n) higher_sizes = np.array([35, 40, 45, 50, 60, 70, 80, 100, 200, 500, 1000, 2000, 3000, 5000, 10000, 100000], float) higher_crit_lf = np.zeros([higher_sizes.shape[0], crit_lf.shape[1]]) for i in range(len(higher_sizes)): higher_crit_lf[i,:] = f(higher_sizes[i]) size = np.concatenate([size, higher_sizes]) crit_lf = np.vstack([crit_lf, higher_crit_lf]) lf = TableDist(alpha, size, crit_lf) else: raise ValueError("Invalid dist parameter. dist must be 'norm' or 'exp'") return lf lilliefors_table_norm = get_lilliefors_table(dist='norm') lilliefors_table_expon = get_lilliefors_table(dist='exp') def pval_lf(Dmax, n): '''approximate pvalues for Lilliefors test This is only valid for pvalues smaller than 0.1 which is not checked in this function. Parameters ---------- Dmax : array_like two-sided Kolmogorov-Smirnov test statistic n : int or float sample size Returns ------- p-value : float or ndarray pvalue according to approximation formula of Dallal and Wilkinson. Notes ----- This is mainly a helper function where the calling code should dispatch on bound violations. Therefore it doesn't check whether the pvalue is in the valid range. Precision for the pvalues is around 2 to 3 decimals. This approximation is also used by other statistical packages (e.g. R:fBasics) but might not be the most precise available. References ---------- DallalWilkinson1986 ''' #todo: check boundaries, valid range for n and Dmax if n > 100: Dmax *= (n / 100.)**0.49 n = 100 pval = np.exp(-7.01256 * Dmax**2 * (n + 2.78019) + 2.99587 * Dmax * np.sqrt(n + 2.78019) - 0.122119 + 0.974598/np.sqrt(n) + 1.67997/n) return pval def kstest_fit(x, dist='norm', pvalmethod='approx'): """ Lilliefors test for normality or an exponential distribution. Kolmogorov Smirnov test with estimated mean and variance Parameters ---------- x : array_like, 1d data series, sample dist : {'norm', 'exp'}, optional Distribution to test in set. pvalmethod : {'approx', 'table'}, optional 'approx' is only valid for normality. if `dist = 'exp'`, `table` is returned. 'approx' uses the approximation formula of Dalal and Wilkinson, valid for pvalues < 0.1. If the pvalue is larger than 0.1, then the result of `table` is returned For normality: 'table' uses the table from Dalal and Wilkinson, which is available for pvalues between 0.001 and 0.2, and the formula of Lilliefors for large n (n>900). Values in the table are linearly interpolated. Values outside the range will be returned as bounds, 0.2 for large and 0.001 for small pvalues. For exponential: 'table' uses the table from Lilliefors 1967, available for pvalues between 0.01 and 0.2. Values outside the range will be returned as bounds, 0.2 for large and 0.01 for small pvalues. Returns ------- ksstat : float Kolmogorov-Smirnov test statistic with estimated mean and variance. pvalue : float If the pvalue is lower than some threshold, e.g. 0.05, then we can reject the Null hypothesis that the sample comes from a normal distribution Notes ----- Reported power to distinguish normal from some other distributions is lower than with the Anderson-Darling test. could be vectorized """ x = np.asarray(x) nobs = len(x) if dist == 'norm': z = (x - x.mean()) / x.std(ddof=1) test_d = stats.norm.cdf lilliefors_table = lilliefors_table_norm elif dist == 'exp': z = x / x.mean() test_d = stats.expon.cdf lilliefors_table = lilliefors_table_expon pvalmethod = 'table' else: raise ValueError("Invalid dist parameter. dist must be 'norm' or 'exp'") d_ks = ksstat(z, test_d, alternative='two_sided') if pvalmethod == 'approx': pval = pval_lf(d_ks, nobs) # check pval is in desired range if pval > 0.1: pval = lilliefors_table.prob(d_ks, nobs) elif pvalmethod == 'table': pval = lilliefors_table.prob(d_ks, nobs) return d_ks, pval lilliefors = kstest_fit lillifors = np.deprecate(lilliefors, 'lillifors', 'lilliefors', "Use lilliefors, lillifors will be " "removed in 0.9 \n(Note: misspelling missing 'e')") # namespace aliases from functools import partial kstest_normal = kstest_fit kstest_exponential = partial(kstest_fit, dist='exp') # old version: # ------------ ''' tble = \ 00 20 15 10 05 01 .1 4 .303 .321 .346 .376 .413 .433 5 .289 .303 .319 .343 .397 .439 6 .269 .281 .297 .323 .371 .424 7 .252 .264 .280 .304 .351 .402 8 .239 .250 .265 .288 .333 .384 9 .227 .238 .252 .274 .317 .365 10 .217 .228 .241 .262 .304 .352 11 .208 .218 .231 .251 .291 .338 12 .200 .210 .222 .242 .281 .325 13 .193 .202 .215 .234 .271 .314 14 .187 .196 .208 .226 .262 .305 15 .181 .190 .201 .219 .254 .296 16 .176 .184 .195 .213 .247 .287 17 .171 .179 .190 .207 .240 .279 18 .167 .175 .185 .202 .234 .273 19 .163 .170 .181 .197 .228 .266 20 .159 .166 .176 .192 .223 .260 25 .143 .150 .159 .173 .201 .236 30 .131 .138 .146 .159 .185 .217 40 .115 .120 .128 .139 .162 .189 100 .074 .077 .082 .089 .104 .122 400 .037 .039 .041 .045 .052 .061 900 .025 .026 .028 .030 .035 .042''' ''' parr = np.array([line.split() for line in tble.split('\n')],float) size = parr[1:,0] alpha = parr[0,1:] / 100. crit = parr[1:, 1:] alpha = np.array([ 0.2 , 0.15 , 0.1 , 0.05 , 0.01 , 0.001]) size = np.array([ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30, 40, 100, 400, 900], float) #critical values, rows are by sample size, columns are by alpha crit_lf = np.array( [[303, 321, 346, 376, 413, 433], [289, 303, 319, 343, 397, 439], [269, 281, 297, 323, 371, 424], [252, 264, 280, 304, 351, 402], [239, 250, 265, 288, 333, 384], [227, 238, 252, 274, 317, 365], [217, 228, 241, 262, 304, 352], [208, 218, 231, 251, 291, 338], [200, 210, 222, 242, 281, 325], [193, 202, 215, 234, 271, 314], [187, 196, 208, 226, 262, 305], [181, 190, 201, 219, 254, 296], [176, 184, 195, 213, 247, 287], [171, 179, 190, 207, 240, 279], [167, 175, 185, 202, 234, 273], [163, 170, 181, 197, 228, 266], [159, 166, 176, 192, 223, 260], [143, 150, 159, 173, 201, 236], [131, 138, 146, 159, 185, 217], [115, 120, 128, 139, 162, 189], [ 74, 77, 82, 89, 104, 122], [ 37, 39, 41, 45, 52, 61], [ 25, 26, 28, 30, 35, 42]]) / 1000. #original Lilliefors paper crit_greater30 = lambda n: np.array([0.736, 0.768, 0.805, 0.886, 1.031])/np.sqrt(n) alpha_greater30 = np.array([ 0.2 , 0.15 , 0.1 , 0.05 , 0.01 , 0.001]) n_alpha = 6 polyn = [interp1d(size, crit[:,i]) for i in range(n_alpha)] def critpolys(n): return np.array([p(n) for p in polyn]) def pval_lftable(x, n): #returns extrem probabilities, 0.001 and 0.2, for out of range critvals = critpolys(n) if x < critvals[0]: return alpha[0] elif x > critvals[-1]: return alpha[-1] else: return interp1d(critvals, alpha)(x) for n in [19, 19.5, 20, 21, 25]: print critpolys(n) print pval_lftable(0.166, 20) print pval_lftable(0.166, 21) print 'n=25:', '.103 .052 .010' print [pval_lf(x, 25) for x in [.159, .173, .201, .236]] print 'n=10', '.103 .050 .009' print [pval_lf(x, 10) for x in [.241, .262, .304, .352]] print 'n=400', '.104 .050 .011' print [pval_lf(x, 400) for x in crit[-2,2:-1]] print 'n=900', '.093 .054 .011' print [pval_lf(x, 900) for x in crit[-1,2:-1]] print [pval_lftable(x, 400) for x in crit[-2,:]] print [pval_lftable(x, 300) for x in crit[-3,:]] xx = np.random.randn(40) print kstest_normal(xx) xx2 = np.array([ 1.138, -0.325, -1.461, -0.441, -0.005, -0.957, -1.52 , 0.481, 0.713, 0.175, -1.764, -0.209, -0.681, 0.671, 0.204, 0.403, -0.165, 1.765, 0.127, -1.261, -0.101, 0.527, 1.114, -0.57 , -1.172, 0.697, 0.146, 0.704, 0.422, 0.63 , 0.661, 0.025, 0.177, 0.578, 0.945, 0.211, 0.153, 0.279, 0.35 , 0.396]) ( 1.138, -0.325, -1.461, -0.441, -0.005, -0.957, -1.52 , 0.481, 0.713, 0.175, -1.764, -0.209, -0.681, 0.671, 0.204, 0.403, -0.165, 1.765, 0.127, -1.261, -0.101, 0.527, 1.114, -0.57 , -1.172, 0.697, 0.146, 0.704, 0.422, 0.63 , 0.661, 0.025, 0.177, 0.578, 0.945, 0.211, 0.153, 0.279, 0.35 , 0.396) r_lillieTest = [0.15096827429598147, 0.02225473302348436] print kstest_normal(xx2), np.array(kstest_normal(xx2)) - r_lillieTest print kstest_normal(xx2, 'table') '''
36.308642
218
0.543239
acf65e2a4ee5c04fbd00a21248f5bbd49d17e71d
1,788
py
Python
factuurinput/productSuggestion.py
mrngm/madmin
19067ac41f68380f3191c9182538af74f417f174
[ "MIT" ]
null
null
null
factuurinput/productSuggestion.py
mrngm/madmin
19067ac41f68380f3191c9182538af74f417f174
[ "MIT" ]
null
null
null
factuurinput/productSuggestion.py
mrngm/madmin
19067ac41f68380f3191c9182538af74f417f174
[ "MIT" ]
null
null
null
from client_lib.servercall import remote_call _isInitialized = False _productList = None _productNameList = [] _productNumberList = [] _productBtwList = {} def _prodSugInit(): global _isInitialized global _productList global _productNameList global _productNumberList global _productBtwList _productList = remote_call('/product/all') # Build product name and number lists for product in _productList: _productNameList.append((product['naam'].encode('utf-8'), product['id'])) _productNumberList.append((product['leverancier_id'].encode('utf-8'), product['id'])) _productBtwList[str(product["id"])] = product["btw"] _productNameList.sort() _productNumberList.sort() _isInitialized = True def getBtw(pid): global _productBtwList return _productBtwList[str(pid)] def findSuggestion(curInput): global _isInitialized global _productNameList global _productNumberList if not _isInitialized: _prodSugInit() low = -1 high = len(_productNameList)-1 if len(_productNameList[high]) == 0: return (None,'') while high - low > 1: mid = (high+low)/2 if _productNameList[mid][0] >= curInput: high = mid else: low = mid if _productNameList[high][0].startswith(curInput): return (_productNameList[high][1], _productNameList[high][0]) low = -1 high = len(_productNumberList)-1 while high - low > 1: mid = (high + low)/2 if _productNumberList[mid][0] >= curInput: high = mid else: low = mid if _productNumberList[high][0].startswith(curInput): return (_productNumberList[high][1], _productNumberList[high][0]) return (None, '')
26.686567
93
0.64821
acf65f1b1cc5cead26aad6495b471c4f5fdcd9c3
3,808
py
Python
notebooks_for_development/compare_ndl_my_phases.py
mwanakijiji/rrlfe
4a822bb499bd0af4543f8b34d9322e812a5a3d2c
[ "MIT" ]
null
null
null
notebooks_for_development/compare_ndl_my_phases.py
mwanakijiji/rrlfe
4a822bb499bd0af4543f8b34d9322e812a5a3d2c
[ "MIT" ]
18
2022-01-13T14:43:57.000Z
2022-03-24T12:52:41.000Z
notebooks_for_development/compare_ndl_my_phases.py
mwanakijiji/rrlfe
4a822bb499bd0af4543f8b34d9322e812a5a3d2c
[ "MIT" ]
null
null
null
#!/usr/bin/env python # coding: utf-8 # This reads in my and NDL's phase analysis outputs and compares them # Create 2022 May 28 by E.S. import pandas as pd import numpy as np import matplotlib.pyplot as plt # read in NDL df_ndl_epochs = pd.read_csv("./data/spectra_epochs_lc.csv") df_ndl_phases = pd.read_csv("./data/phases_ndl.csv") # read in mine df_mine = pd.read_csv("./data/spectra_my_bjds.csv") # make specific df_mine["my_spec_bjd"] = np.subtract(df_mine["bjd"],2400000) # subtract to compare with NDL df_mine["my_phase"] = df_mine["phasemod"] df_mine["spec_file"] = df_mine["file"] # the original spectrum file name df_ndl_epochs["spec_file"] = df_ndl_epochs["filenames"] # the original spectrum file name (no change by NDL) df_ndl_epochs["ndl_spec_bjd"] = df_ndl_epochs["bjd"] df_ndl_phases["ndl_phase"] = df_ndl_phases["Phases"] # remove redundant rows with "c.fits" in filenames col df_ndl_epochs = df_ndl_epochs.loc[df_ndl_epochs["filenames"].str.contains(".c.fits")==False] # convert to ints df_ndl_epochs["number_cur"] = df_ndl_epochs["#"].astype(int) # extract the "cur" number from NDL's other table df_ndl_phases["number_cur"] = df_ndl_phases["#Name"].str.split("_").str[-1] #df_ndl_phases["number_cur"] = df_ndl_phases["#Name"].str.extract('(\d+)') df_ndl_phases["number_cur"] = df_ndl_phases["number_cur"].astype(int) # extract the star name df_ndl_epochs["star_name"] = df_ndl_epochs["filenames"].str[:6] df_ndl_phases["star_name"] = df_ndl_phases["#Name"].str[:6] # merge NDL's tables with each other based on star name and cur number df_ndl_merged = df_ndl_epochs.merge(df_ndl_phases, on=["star_name","number_cur"], suffixes=(None,"_y")) # match NDL net table to my results by spectrum number (#) df_all_merged = df_mine.merge(df_ndl_merged, how='outer', on=["spec_file"]) # find NDL time baselines, for checking only df_all_merged["ndl_time_baselines"] = np.subtract(np.subtract(df_all_merged["Epoch_Max"],2400000),df_all_merged["ndl_spec_bjd"]) df_all_merged["ndl_baseline_div_period"] = np.divide(df_all_merged["ndl_time_baselines"],df_all_merged["period"]) # erro in phase we would expect from NDL df_all_merged["error_ndl_phase"] = np.multiply(np.abs(df_all_merged["ndl_baseline_div_period"]),df_all_merged["err_tot"]) # for fyi, find error in phases: multiply error in period by number of cycles in the time baseline df_all_merged["error_my_phase"] = np.multiply(np.abs(df_all_merged["baseline_div_period"]),df_all_merged["err_tot"]) # one last thing: insert star names in rows where no KELT data (i.e., name was left NaN) #idx_name_nan = df_all_merged["star_name"].isinf() #df_all_merged[df_all_merged["star_name"].isna()] import ipdb; ipdb.set_trace() ''' # for checking plt.clf() plt.hist(df_all_merged["error_my_phase"], bins=100) plt.show() ''' ''' # for checking plt.scatter(df_all_merged["my_spec_bjd"],df_all_merged["ndl_spec_bjd"]) plt.plot([56200,56500],[56200,56500], linestyle=":", color="gray") plt.show() ''' ''' # for checking plt.scatter(df_all_merged["Period"],df_all_merged["T_final"]) plt.plot([0,1],[0,1], linestyle=":", color="gray") plt.show() ''' # for comparing NDL and my phases, and troubleshooting disagreement ''' plt.clf() plt.scatter(df_all_merged["my_phase"],df_all_merged["ndl_phase"]) for i in range(0,len(df_all_merged)): plt.annotate(df_all_merged["spec_file"].loc[i], xy=(df_all_merged["my_phase"].loc[i],df_all_merged["ndl_phase"].loc[i])) plt.annotate(np.round(df_all_merged["ndl_baseline_div_period"].loc[i],2), xy=(df_all_merged["my_phase"].loc[i],df_all_merged["ndl_phase"].loc[i])) #plt.scatter(np.subtract(1.,df_all_merged["my_phase"]),df_all_merged["ndl_phase"]) plt.plot([0,1],[0,1], linestyle=":", color="gray") plt.show() ''' df_all_merged.to_csv("./data/junk.csv")
37.333333
128
0.735819
acf660408f8202ce1a592dd629aa3493335346a9
223
py
Python
notebooks/_solutions/case4_air_quality_analysis4.py
jonasvdd/DS-python-data-analysis
835226f562ee0b0631d70e48a17c4526ff58a538
[ "BSD-3-Clause" ]
65
2017-03-21T09:15:40.000Z
2022-02-01T23:43:08.000Z
notebooks/_solutions/case4_air_quality_analysis4.py
jonasvdd/DS-python-data-analysis
835226f562ee0b0631d70e48a17c4526ff58a538
[ "BSD-3-Clause" ]
100
2016-12-15T03:44:06.000Z
2022-03-07T08:14:07.000Z
notebooks/_solutions/case4_air_quality_analysis4.py
jorisvandenbossche/ICES-python-data
63864947657f37cb26cb4e2dcd67ff106dffe9cd
[ "BSD-3-Clause" ]
52
2016-12-19T07:48:52.000Z
2022-02-19T17:53:48.000Z
fig, ax = plt.subplots() data.loc['2009':, 'FR04037'].resample('M').mean().plot(ax=ax, label='mean') data.loc['2009':, 'FR04037'].resample('M').median().plot(ax=ax, label='median') ax.legend(ncol=2) ax.set_title("FR04037");
44.6
79
0.659193
acf66073ce52cd504ca0af0522f948c4ea0a70ae
19,331
py
Python
mceutils.py
gpmidi/MCEdit-Unified
60e1408899fa04113412b89616fd3486db5c8545
[ "0BSD" ]
null
null
null
mceutils.py
gpmidi/MCEdit-Unified
60e1408899fa04113412b89616fd3486db5c8545
[ "0BSD" ]
null
null
null
mceutils.py
gpmidi/MCEdit-Unified
60e1408899fa04113412b89616fd3486db5c8545
[ "0BSD" ]
null
null
null
"""Copyright (c) 2010-2012 David Rio Vierra Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.""" # import resource_packs # not the right place, moving it a bit furtehr """ mceutils.py Exception catching, some basic box drawing, texture pack loading, oddball UI elements """ # Modified by D.C.-G. for translation purpose #.# Marks the layout modifications. -- D.C.-G. #!# #!# The stuff in there related to albow should be in albow module. #!# This stuff will then be available for components base classes in this GUI module. #!# And make albow/widgets more coherent to use. #!# import resource_packs from albow.controls import ValueDisplay from albow import alert, ask, Button, Column, Label, root, Row, ValueButton, Widget from albow.translate import _ from datetime import datetime import directories import numpy from OpenGL import GL import os import png from pygame import display import pymclevel import json import hashlib import shutil import logging #!# Used to track the ALBOW stuff imported from here def warn(obj): name = getattr(obj, '__name__', getattr(getattr(obj, '__class__', obj), '__name__', obj)) logging.getLogger().warn('%s.%s is deprecated and will be removed. Use albow.%s instead.'%(obj.__module__, name, name)) #!# def alertException(func): def _alertException(*args, **kw): try: return func(*args, **kw) except root.Cancel: alert("Canceled.") except pymclevel.infiniteworld.SessionLockLost as e: alert(_(e.message) + _("\n\nYour changes cannot be saved.")) except Exception, e: logging.exception("Exception:") ask(_("Error during {0}: {1!r}").format(func, e)[:1000], ["OK"], cancel=0) return _alertException def drawFace(box, face, type=GL.GL_QUADS): x, y, z, = box.origin x2, y2, z2 = box.maximum if face == pymclevel.faces.FaceXDecreasing: faceVertices = numpy.array( (x, y2, z2, x, y2, z, x, y, z, x, y, z2, ), dtype='f4') elif face == pymclevel.faces.FaceXIncreasing: faceVertices = numpy.array( (x2, y, z2, x2, y, z, x2, y2, z, x2, y2, z2, ), dtype='f4') elif face == pymclevel.faces.FaceYDecreasing: faceVertices = numpy.array( (x2, y, z2, x, y, z2, x, y, z, x2, y, z, ), dtype='f4') elif face == pymclevel.faces.FaceYIncreasing: faceVertices = numpy.array( (x2, y2, z, x, y2, z, x, y2, z2, x2, y2, z2, ), dtype='f4') elif face == pymclevel.faces.FaceZDecreasing: faceVertices = numpy.array( (x, y, z, x, y2, z, x2, y2, z, x2, y, z, ), dtype='f4') elif face == pymclevel.faces.FaceZIncreasing: faceVertices = numpy.array( (x2, y, z2, x2, y2, z2, x, y2, z2, x, y, z2, ), dtype='f4') faceVertices.shape = (4, 3) dim = face >> 1 dims = [0, 1, 2] dims.remove(dim) texVertices = numpy.array( faceVertices[:, dims], dtype='f4' ).flatten() faceVertices.shape = (12,) texVertices *= 16 GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glVertexPointer(3, GL.GL_FLOAT, 0, faceVertices) GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, texVertices) GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) GL.glEnable(GL.GL_POLYGON_OFFSET_LINE) if type is GL.GL_LINE_STRIP: indexes = numpy.array((0, 1, 2, 3, 0), dtype='uint32') GL.glDrawElements(type, 5, GL.GL_UNSIGNED_INT, indexes) else: GL.glDrawArrays(type, 0, 4) GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) GL.glDisable(GL.GL_POLYGON_OFFSET_LINE) GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) def drawCube(box, cubeType=GL.GL_QUADS, blockType=0, texture=None, textureVertices=None, selectionBox=False): """ pass a different cubeType e.g. GL_LINE_STRIP for wireframes """ x, y, z, = box.origin x2, y2, z2 = box.maximum dx, dy, dz = x2 - x, y2 - y, z2 - z cubeVertices = numpy.array( ( x, y, z, x, y2, z, x2, y2, z, x2, y, z, x2, y, z2, x2, y2, z2, x, y2, z2, x, y, z2, x2, y, z2, x, y, z2, x, y, z, x2, y, z, x2, y2, z, x, y2, z, x, y2, z2, x2, y2, z2, x, y2, z2, x, y2, z, x, y, z, x, y, z2, x2, y, z2, x2, y, z, x2, y2, z, x2, y2, z2, ), dtype='f4') if textureVertices is None: textureVertices = numpy.array( ( 0, -dy * 16, 0, 0, dx * 16, 0, dx * 16, -dy * 16, dx * 16, -dy * 16, dx * 16, 0, 0, 0, 0, -dy * 16, dx * 16, -dz * 16, 0, -dz * 16, 0, 0, dx * 16, 0, dx * 16, 0, 0, 0, 0, -dz * 16, dx * 16, -dz * 16, dz * 16, 0, 0, 0, 0, -dy * 16, dz * 16, -dy * 16, dz * 16, -dy * 16, 0, -dy * 16, 0, 0, dz * 16, 0, ), dtype='f4') textureVertices.shape = (6, 4, 2) if selectionBox: textureVertices[0:2] += (16 * (x & 15), 16 * (y2 & 15)) textureVertices[2:4] += (16 * (x & 15), -16 * (z & 15)) textureVertices[4:6] += (16 * (z & 15), 16 * (y2 & 15)) textureVertices[:] += 0.5 GL.glVertexPointer(3, GL.GL_FLOAT, 0, cubeVertices) if texture is not None: GL.glEnable(GL.GL_TEXTURE_2D) GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) texture.bind() GL.glTexCoordPointer(2, GL.GL_FLOAT, 0, textureVertices), GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) GL.glEnable(GL.GL_POLYGON_OFFSET_LINE) GL.glDrawArrays(cubeType, 0, 24) GL.glDisable(GL.GL_POLYGON_OFFSET_FILL) GL.glDisable(GL.GL_POLYGON_OFFSET_LINE) if texture is not None: GL.glDisableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glDisable(GL.GL_TEXTURE_2D) def drawTerrainCuttingWire(box, c0=(0.75, 0.75, 0.75, 0.4), c1=(1.0, 1.0, 1.0, 1.0)): # glDepthMask(False) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDepthFunc(GL.GL_LEQUAL) GL.glColor(*c1) GL.glLineWidth(2.0) drawCube(box, cubeType=GL.GL_LINE_STRIP) GL.glDepthFunc(GL.GL_GREATER) GL.glColor(*c0) GL.glLineWidth(1.0) drawCube(box, cubeType=GL.GL_LINE_STRIP) GL.glDepthFunc(GL.GL_LEQUAL) GL.glDisable(GL.GL_DEPTH_TEST) # glDepthMask(True) def loadAlphaTerrainTexture(): pngFile = None texW, texH, terraindata = loadPNGFile(os.path.join(directories.getDataDir(), resource_packs.packs.get_selected_resource_pack().terrain_path())) def _loadFunc(): loadTextureFunc(texW, texH, terraindata) tex = glutils.Texture(_loadFunc) tex.data = terraindata return tex def loadPNGData(filename_or_data): reader = png.Reader(filename_or_data) (w, h, data, metadata) = reader.read_flat() data = numpy.array(data, dtype='uint8') data.shape = (h, w, metadata['planes']) if data.shape[2] == 1: # indexed color. remarkably straightforward. data.shape = data.shape[:2] data = numpy.array(reader.palette(), dtype='uint8')[data] if data.shape[2] < 4: data = numpy.insert(data, 3, 255, 2) return w, h, data def loadPNGFile(filename): (w, h, data) = loadPNGData(filename) powers = (16, 32, 64, 128, 256, 512, 1024, 2048, 4096) assert (w in powers) and (h in powers) # how crude return w, h, data def loadTextureFunc(w, h, ndata): GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, w, h, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, ndata) return w, h def loadPNGTexture(filename, *a, **kw): filename = os.path.join(directories.getDataDir(), filename) try: w, h, ndata = loadPNGFile(filename) tex = glutils.Texture(functools.partial(loadTextureFunc, w, h, ndata), *a, **kw) tex.data = ndata return tex except Exception, e: print "Exception loading ", filename, ": ", repr(e) return glutils.Texture() import glutils def normalize(x): l = x[0] * x[0] + x[1] * x[1] + x[2] * x[2] if l <= 0.0: return [0, 0, 0] size = numpy.sqrt(l) if size <= 0.0: return [0, 0, 0] return map(lambda a: a / size, x) def normalize_size(x): l = x[0] * x[0] + x[1] * x[1] + x[2] * x[2] if l <= 0.0: return [0., 0., 0.], 0. size = numpy.sqrt(l) if size <= 0.0: return [0, 0, 0], 0 return (x / size), size # Label = GLLabel class HotkeyColumn(Widget): is_gl_container = True def __init__(self, items, keysColumn=None, buttonsColumn=None, item_spacing=None): warn(self) if keysColumn is None: keysColumn = [] if buttonsColumn is None: buttonsColumn = [] labels = [] Widget.__init__(self) for t in items: if len(t) == 3: (hotkey, title, action) = t tooltipText = None else: (hotkey, title, action, tooltipText) = t if isinstance(title, (str, unicode)): button = Button(title, action=action) else: button = ValueButton(ref=title, action=action, width=200) button.anchor = self.anchor label = Label(hotkey, width=100, margin=button.margin) label.anchor = "wh" label.height = button.height labels.append(label) if tooltipText: button.tooltipText = tooltipText keysColumn.append(label) buttonsColumn.append(button) self.buttons = list(buttonsColumn) #.# if item_spacing == None: buttonsColumn = Column(buttonsColumn) else: buttonsColumn = Column(buttonsColumn, spacing=item_spacing) #.# buttonsColumn.anchor = self.anchor #.# if item_spacing == None: keysColumn = Column(keysColumn) else: keysColumn = Column(keysColumn, spacing=item_spacing) commandRow = Row((keysColumn, buttonsColumn)) self.labels = labels self.add(commandRow) self.shrink_wrap() from albow import CheckBox, AttrRef, Menu class MenuButton(Button): def __init__(self, title, choices, **kw): warn(self) Button.__init__(self, title, **kw) self.choices = choices self.menu = Menu(title, ((c, c) for c in choices)) def action(self): index = self.menu.present(self, (0, 0)) if index == -1: return self.menu_picked(index) def menu_picked(self, index): pass class ChoiceButton(ValueButton): align = "c" choose = None def __init__(self, choices, scrolling=True, scroll_items=30, **kw): # passing an empty list of choices is ill-advised warn(self) if 'choose' in kw: self.choose = kw.pop('choose') ValueButton.__init__(self, action=self.showMenu, **kw) self.scrolling = scrolling self.scroll_items = scroll_items self.choices = choices or ["[UNDEFINED]"] widths = [self.font.size(_(c))[0] for c in choices] + [self.width] if len(widths): self.width = max(widths) + self.margin * 2 self.choiceIndex = 0 def showMenu(self): choiceIndex = self.menu.present(self, (0, 0)) if choiceIndex != -1: self.choiceIndex = choiceIndex if self.choose: self.choose() def get_value(self): return self.selectedChoice @property def selectedChoice(self): if self.choiceIndex >= len(self.choices) or self.choiceIndex < 0: return "" return self.choices[self.choiceIndex] @selectedChoice.setter def selectedChoice(self, val): idx = self.choices.index(val) if idx != -1: self.choiceIndex = idx @property def choices(self): return self._choices @choices.setter def choices(self, ch): self._choices = ch self.menu = Menu("", ((name, "pickMenu") for name in self._choices), self.scrolling, self.scroll_items) def CheckBoxLabel(title, *args, **kw): warn(CheckBoxLabel) tooltipText = kw.pop('tooltipText', None) cb = CheckBox(*args, **kw) lab = Label(title, fg_color=cb.fg_color) lab.mouse_down = cb.mouse_down if tooltipText: cb.tooltipText = tooltipText lab.tooltipText = tooltipText class CBRow(Row): margin = 0 @property def value(self): return self.checkbox.value @value.setter def value(self, val): self.checkbox.value = val row = CBRow((lab, cb)) row.checkbox = cb return row from albow import FloatField, IntField, TextFieldWrapped def FloatInputRow(title, *args, **kw): warn(FloatInputRow) return Row((Label(title, tooltipText=kw.get('tooltipText')), FloatField(*args, **kw))) def IntInputRow(title, *args, **kw): warn(IntInputRow) return Row((Label(title, tooltipText=kw.get('tooltipText')), IntField(*args, **kw))) from albow.dialogs import Dialog from datetime import timedelta def TextInputRow(title, *args, **kw): warn(TextInputRow) return Row((Label(title, tooltipText=kw.get('tooltipText')), TextFieldWrapped(*args, **kw))) def setWindowCaption(prefix): caption = display.get_caption()[0] prefix = _(prefix) if type(prefix) == unicode: prefix = prefix.encode("utf8") class ctx: def __enter__(self): display.set_caption(prefix + caption) def __exit__(self, *args): display.set_caption(caption) return ctx() def showProgress(progressText, progressIterator, cancel=False): """Show the progress for a long-running synchronous operation. progressIterator should be a generator-like object that can return either None, for an indeterminate indicator, A float value between 0.0 and 1.0 for a determinate indicator, A string, to update the progress info label or a tuple of (float value, string) to set the progress and update the label""" warn(ShowProgress) class ProgressWidget(Dialog): progressFraction = 0.0 firstDraw = False root = None def draw(self, surface): if self.root is None: self.root = self.get_root() Widget.draw(self, surface) frameStart = datetime.now() frameInterval = timedelta(0, 1, 0) / 2 amount = None try: while datetime.now() < frameStart + frameInterval: amount = progressIterator.next() if self.firstDraw is False: self.firstDraw = True break except StopIteration: self.dismiss() infoText = "" if amount is not None: if isinstance(amount, tuple): if len(amount) > 2: infoText = ": " + amount[2] amount, max = amount[:2] else: max = amount maxwidth = (self.width - self.margin * 2) if amount is None: self.progressBar.width = maxwidth self.progressBar.bg_color = (255, 255, 25, 255) elif isinstance(amount, basestring): self.statusText = amount else: self.progressAmount = amount if isinstance(amount, (int, float)): self.progressFraction = float(amount) / (float(max) or 1) self.progressBar.width = maxwidth * self.progressFraction self.statusText = str("{0} / {1}".format(amount, max)) else: self.statusText = str(amount) if infoText: self.statusText += infoText @property def estimateText(self): delta = (datetime.now() - self.startTime) progressPercent = (int(self.progressFraction * 10000)) if progressPercent > 10000: progressPercent = 10000 left = delta * (10000 - progressPercent) / (progressPercent or 1) return _("Time left: {0}").format(left) def cancel(self): if cancel: self.dismiss(False) def idleevent(self, evt): self.invalidate() def key_down(self, event): pass def key_up(self, event): pass def mouse_up(self, event): try: if "SelectionTool" in str(self.root.editor.currentTool): if self.root.get_nudge_block().count > 0: self.root.get_nudge_block().mouse_up(event) except: pass widget = ProgressWidget() widget.progressText = _(progressText) widget.statusText = "" widget.progressAmount = 0.0 progressLabel = ValueDisplay(ref=AttrRef(widget, 'progressText'), width=550) statusLabel = ValueDisplay(ref=AttrRef(widget, 'statusText'), width=550) estimateLabel = ValueDisplay(ref=AttrRef(widget, 'estimateText'), width=550) progressBar = Widget(size=(550, 20), bg_color=(150, 150, 150, 255)) widget.progressBar = progressBar col = (progressLabel, statusLabel, estimateLabel, progressBar) if cancel: cancelButton = Button("Cancel", action=widget.cancel, fg_color=(255, 0, 0, 255)) col += (Column((cancelButton,), align="r"),) widget.add(Column(col)) widget.shrink_wrap() widget.startTime = datetime.now() if widget.present(): return widget.progressAmount else: return "Canceled" from glutils import DisplayList import functools
28.723626
147
0.566189
acf660d85c18d2fafabc1e4ec67fc079f8088010
31,871
py
Python
electrum_trc/gui/kivy/uix/dialogs/installwizard.py
TheSin-/electrum-trc
d2f5b15fd4399a9248cce0d63e20128f3f54e69c
[ "MIT" ]
1
2019-08-20T18:05:32.000Z
2019-08-20T18:05:32.000Z
electrum_trc/gui/kivy/uix/dialogs/installwizard.py
TheSin-/electrum-trc
d2f5b15fd4399a9248cce0d63e20128f3f54e69c
[ "MIT" ]
1
2022-03-14T19:45:31.000Z
2022-03-14T19:45:31.000Z
electrum_trc/gui/kivy/uix/dialogs/installwizard.py
TheSin-/electrum-trc
d2f5b15fd4399a9248cce0d63e20128f3f54e69c
[ "MIT" ]
null
null
null
from functools import partial import threading import os from kivy.app import App from kivy.clock import Clock from kivy.lang import Builder from kivy.properties import ObjectProperty, StringProperty, OptionProperty from kivy.core.window import Window from kivy.uix.button import Button from kivy.utils import platform from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.clock import Clock from kivy.utils import platform from electrum_trc.base_wizard import BaseWizard from electrum_trc.util import is_valid_email from . import EventsDialog from ...i18n import _ from .password_dialog import PasswordDialog # global Variables is_test = (platform == "linux") test_seed = "grape impose jazz bind spatial mind jelly tourist tank today holiday stomach" test_seed = "time taxi field recycle tiny license olive virus report rare steel portion achieve" test_xpub = "xpub661MyMwAqRbcEbvVtRRSjqxVnaWVUMewVzMiURAKyYratih4TtBpMypzzefmv8zUNebmNVzB3PojdC5sV2P9bDgMoo9B3SARw1MXUUfU1GL" Builder.load_string(''' #:import Window kivy.core.window.Window #:import _ electrum_trc.gui.kivy.i18n._ <WizardTextInput@TextInput> border: 4, 4, 4, 4 font_size: '15sp' padding: '15dp', '15dp' background_color: (1, 1, 1, 1) if self.focus else (0.454, 0.909, 0.721, 1) foreground_color: (0.31, 0.31, 0.31, 1) if self.focus else (0.835, 0.972, 0.909, 1) hint_text_color: self.foreground_color background_active: 'atlas://electrum_trc/gui/kivy/theming/light/create_act_text_active' background_normal: 'atlas://electrum_trc/gui/kivy/theming/light/create_act_text_active' size_hint_y: None height: '48sp' <WizardButton@Button>: root: None size_hint: 1, None height: '48sp' on_press: if self.root: self.root.dispatch('on_press', self) on_release: if self.root: self.root.dispatch('on_release', self) <BigLabel@Label> color: .854, .984, .929, 1 size_hint: 1, None text_size: self.width, None height: self.texture_size[1] bold: True <-WizardDialog> text_color: .854, .984, .929, 1 value: '' #auto_dismiss: False size_hint: None, None canvas.before: Color: rgba: (.45, .2, 0, 1) if app.testnet else (.239, .882, .623, 1) Rectangle: size: Window.size crcontent: crcontent # add electrum icon BoxLayout: orientation: 'vertical' if self.width < self.height else 'horizontal' padding: min(dp(27), self.width/32), min(dp(27), self.height/32),\ min(dp(27), self.width/32), min(dp(27), self.height/32) spacing: '10dp' GridLayout: id: grid_logo cols: 1 pos_hint: {'center_y': .5} size_hint: 1, None height: self.minimum_height Label: color: root.text_color text: 'TERRACOIN ELECTRUM' size_hint: 1, None height: self.texture_size[1] if self.opacity else 0 font_size: '33sp' font_name: 'electrum_trc/gui/kivy/data/fonts/tron/Tr2n.ttf' Label: color: root.text_color text: 'TESTNET' if app.testnet else '' size_hint: 1, None height: self.texture_size[1] if self.opacity else 0 font_size: '33sp' font_name: 'electrum_trc/gui/kivy/data/fonts/tron/Tr2n.ttf' GridLayout: cols: 1 id: crcontent spacing: '1dp' Widget: size_hint: 1, 0.3 GridLayout: rows: 1 spacing: '12dp' size_hint: 1, None height: self.minimum_height WizardButton: id: back text: _('Back') root: root WizardButton: id: next text: _('Next') root: root disabled: root.value == '' <WizardMultisigDialog> value: 'next' Widget size_hint: 1, 1 Label: color: root.text_color size_hint: 1, None text_size: self.width, None height: self.texture_size[1] text: _("Choose the number of signatures needed to unlock funds in your wallet") Widget size_hint: 1, 1 GridLayout: orientation: 'vertical' cols: 2 spacing: '14dp' size_hint: 1, 1 height: self.minimum_height Label: color: root.text_color text: _('From {} cosigners').format(n.value) Slider: id: n range: 2, 5 step: 1 value: 2 Label: color: root.text_color text: _('Require {} signatures').format(m.value) Slider: id: m range: 1, n.value step: 1 value: 2 <WizardChoiceDialog> message : '' Widget: size_hint: 1, 1 Label: color: root.text_color size_hint: 1, None text_size: self.width, None height: self.texture_size[1] text: root.message Widget size_hint: 1, 1 GridLayout: row_default_height: '48dp' orientation: 'vertical' id: choices cols: 1 spacing: '14dp' size_hint: 1, None <WizardConfirmDialog> message : '' Widget: size_hint: 1, 1 Label: color: root.text_color size_hint: 1, None text_size: self.width, None height: self.texture_size[1] text: root.message Widget size_hint: 1, 1 <WizardTOSDialog> message : '' size_hint: 1, 1 ScrollView: size_hint: 1, 1 TextInput: color: root.text_color size_hint: 1, None text_size: self.width, None height: self.minimum_height text: root.message disabled: True <WizardEmailDialog> Label: color: root.text_color size_hint: 1, None text_size: self.width, None height: self.texture_size[1] text: 'Please enter your email address' WizardTextInput: id: email on_text: Clock.schedule_once(root.on_text) multiline: False on_text_validate: Clock.schedule_once(root.on_enter) <WizardKnownOTPDialog> message : '' message2: '' Widget: size_hint: 1, 1 Label: color: root.text_color size_hint: 1, None text_size: self.width, None height: self.texture_size[1] text: root.message Widget size_hint: 1, 1 WizardTextInput: id: otp on_text: Clock.schedule_once(root.on_text) multiline: False on_text_validate: Clock.schedule_once(root.on_enter) Widget size_hint: 1, 1 Label: color: root.text_color size_hint: 1, None text_size: self.width, None height: self.texture_size[1] text: root.message2 Widget size_hint: 1, 1 height: '48sp' BoxLayout: orientation: 'horizontal' WizardButton: id: cb text: _('Request new secret') on_release: root.request_new_secret() size_hint: 1, None WizardButton: id: abort text: _('Abort creation') on_release: root.abort_wallet_creation() size_hint: 1, None <WizardNewOTPDialog> message : '' message2 : '' Label: color: root.text_color size_hint: 1, None text_size: self.width, None height: self.texture_size[1] text: root.message QRCodeWidget: id: qr size_hint: 1, 1 Label: color: root.text_color size_hint: 1, None text_size: self.width, None height: self.texture_size[1] text: root.message2 WizardTextInput: id: otp on_text: Clock.schedule_once(root.on_text) multiline: False on_text_validate: Clock.schedule_once(root.on_enter) <MButton@Button>: size_hint: 1, None height: '33dp' on_release: self.parent.update_amount(self.text) <WordButton@Button>: size_hint: None, None padding: '5dp', '5dp' text_size: None, self.height width: self.texture_size[0] height: '30dp' on_release: self.parent.new_word(self.text) <SeedButton@Button>: height: dp(100) border: 4, 4, 4, 4 halign: 'justify' valign: 'top' font_size: '18dp' text_size: self.width - dp(24), self.height - dp(12) color: .1, .1, .1, 1 background_normal: 'atlas://electrum_trc/gui/kivy/theming/light/white_bg_round_top' background_down: self.background_normal size_hint_y: None <SeedLabel@Label>: font_size: '12sp' text_size: self.width, None size_hint: 1, None height: self.texture_size[1] halign: 'justify' valign: 'middle' border: 4, 4, 4, 4 <RestoreSeedDialog> message: '' word: '' BigLabel: text: "ENTER YOUR SEED PHRASE" GridLayout cols: 1 padding: 0, '12dp' orientation: 'vertical' spacing: '12dp' size_hint: 1, None height: self.minimum_height SeedButton: id: text_input_seed text: '' on_text: Clock.schedule_once(root.on_text) on_release: root.options_dialog() SeedLabel: text: root.message BoxLayout: id: suggestions height: '35dp' size_hint: 1, None new_word: root.on_word BoxLayout: id: line1 update_amount: root.update_text size_hint: 1, None height: '30dp' MButton: text: 'Q' MButton: text: 'W' MButton: text: 'E' MButton: text: 'R' MButton: text: 'T' MButton: text: 'Y' MButton: text: 'U' MButton: text: 'I' MButton: text: 'O' MButton: text: 'P' BoxLayout: id: line2 update_amount: root.update_text size_hint: 1, None height: '30dp' Widget: size_hint: 0.5, None height: '33dp' MButton: text: 'A' MButton: text: 'S' MButton: text: 'D' MButton: text: 'F' MButton: text: 'G' MButton: text: 'H' MButton: text: 'J' MButton: text: 'K' MButton: text: 'L' Widget: size_hint: 0.5, None height: '33dp' BoxLayout: id: line3 update_amount: root.update_text size_hint: 1, None height: '30dp' Widget: size_hint: 1, None MButton: text: 'Z' MButton: text: 'X' MButton: text: 'C' MButton: text: 'V' MButton: text: 'B' MButton: text: 'N' MButton: text: 'M' MButton: text: ' ' MButton: text: '<' <AddXpubDialog> title: '' message: '' BigLabel: text: root.title GridLayout cols: 1 padding: 0, '12dp' orientation: 'vertical' spacing: '12dp' size_hint: 1, None height: self.minimum_height SeedButton: id: text_input text: '' on_text: Clock.schedule_once(root.check_text) SeedLabel: text: root.message GridLayout rows: 1 spacing: '12dp' size_hint: 1, None height: self.minimum_height IconButton: id: scan height: '48sp' on_release: root.scan_xpub() icon: 'atlas://electrum_trc/gui/kivy/theming/light/camera' size_hint: 1, None WizardButton: text: _('Paste') on_release: root.do_paste() WizardButton: text: _('Clear') on_release: root.do_clear() <ShowXpubDialog> xpub: '' message: _('Here is your master public key. Share it with your cosigners.') BigLabel: text: "MASTER PUBLIC KEY" GridLayout cols: 1 padding: 0, '12dp' orientation: 'vertical' spacing: '12dp' size_hint: 1, None height: self.minimum_height SeedButton: id: text_input text: root.xpub SeedLabel: text: root.message GridLayout rows: 1 spacing: '12dp' size_hint: 1, None height: self.minimum_height WizardButton: text: _('QR code') on_release: root.do_qr() WizardButton: text: _('Copy') on_release: root.do_copy() WizardButton: text: _('Share') on_release: root.do_share() <ShowSeedDialog> spacing: '12dp' value: 'next' BigLabel: text: "PLEASE WRITE DOWN YOUR SEED PHRASE" GridLayout: id: grid cols: 1 pos_hint: {'center_y': .5} size_hint_y: None height: self.minimum_height orientation: 'vertical' spacing: '12dp' SeedButton: text: root.seed_text on_release: root.options_dialog() SeedLabel: text: root.message <LineDialog> BigLabel: text: root.title SeedLabel: text: root.message TextInput: id: passphrase_input multiline: False size_hint: 1, None height: '27dp' SeedLabel: text: root.warning ''') class WizardDialog(EventsDialog): ''' Abstract dialog to be used as the base for all Create Account Dialogs ''' crcontent = ObjectProperty(None) def __init__(self, wizard, **kwargs): self.auto_dismiss = False super(WizardDialog, self).__init__() self.wizard = wizard self.ids.back.disabled = not wizard.can_go_back() self.app = App.get_running_app() self.run_next = kwargs['run_next'] self._trigger_size_dialog = Clock.create_trigger(self._size_dialog) # note: everything bound here needs to be unbound as otherwise the # objects will be kept around and keep receiving the callbacks Window.bind(size=self._trigger_size_dialog, rotation=self._trigger_size_dialog, on_keyboard=self.on_keyboard) self._trigger_size_dialog() self._on_release = False def _size_dialog(self, dt): app = App.get_running_app() if app.ui_mode[0] == 'p': self.size = Window.size else: #tablet if app.orientation[0] == 'p': #portrait self.size = Window.size[0]/1.67, Window.size[1]/1.4 else: self.size = Window.size[0]/2.5, Window.size[1] def add_widget(self, widget, index=0): if not self.crcontent: super(WizardDialog, self).add_widget(widget) else: self.crcontent.add_widget(widget, index=index) def on_keyboard(self, instance, key, keycode, codepoint, modifier): if key == 27: if self.wizard.can_go_back(): self._on_release = True self.dismiss() self.wizard.go_back() else: app = App.get_running_app() if not app.is_exit: app.is_exit = True app.show_info(_('Press again to exit')) else: self._on_release = False self.dismiss() return True def on_dismiss(self): Window.unbind(size=self._trigger_size_dialog, rotation=self._trigger_size_dialog, on_keyboard=self.on_keyboard) app = App.get_running_app() if app.wallet is None and not self._on_release: app.stop() def get_params(self, button): return (None,) def on_release(self, button): self._on_release = True self.dismiss() if not button: self.parent.dispatch('on_wizard_complete', None) return if button is self.ids.back: self.wizard.go_back() return params = self.get_params(button) self.run_next(*params) class WizardMultisigDialog(WizardDialog): def get_params(self, button): m = self.ids.m.value n = self.ids.n.value return m, n class WizardOTPDialogBase(WizardDialog): def get_otp(self): otp = self.ids.otp.text if len(otp) != 6: return try: return int(otp) except: return def on_text(self, dt): self.ids.next.disabled = self.get_otp() is None def on_enter(self, dt): # press next next = self.ids.next if not next.disabled: next.dispatch('on_release') class WizardKnownOTPDialog(WizardOTPDialogBase): def __init__(self, wizard, **kwargs): WizardOTPDialogBase.__init__(self, wizard, **kwargs) self.message = _("This wallet is already registered with TrustedCoin. To finalize wallet creation, please enter your Google Authenticator Code.") self.message2 =_("If you have lost your Google Authenticator account, you can request a new secret. You will need to retype your seed.") self.request_new = False def get_params(self, button): return (self.get_otp(), self.request_new) def request_new_secret(self): self.request_new = True self.on_release(True) def abort_wallet_creation(self): self._on_release = True self.wizard.terminate(aborted=True) self.dismiss() class WizardNewOTPDialog(WizardOTPDialogBase): def __init__(self, wizard, **kwargs): WizardOTPDialogBase.__init__(self, wizard, **kwargs) otp_secret = kwargs['otp_secret'] uri = "otpauth://totp/%s?secret=%s"%('trustedcoin.com', otp_secret) self.message = "Please scan the following QR code in Google Authenticator. You may also use the secret key: %s"%otp_secret self.message2 = _('Then, enter your Google Authenticator code:') self.ids.qr.set_data(uri) def get_params(self, button): return (self.get_otp(), False) class WizardTOSDialog(WizardDialog): def __init__(self, wizard, **kwargs): WizardDialog.__init__(self, wizard, **kwargs) self.ids.next.text = 'Accept' self.ids.next.disabled = False self.message = kwargs['tos'] self.message2 = _('Enter your email address:') class WizardEmailDialog(WizardDialog): def get_params(self, button): return (self.ids.email.text,) def on_text(self, dt): self.ids.next.disabled = not is_valid_email(self.ids.email.text) def on_enter(self, dt): # press next next = self.ids.next if not next.disabled: next.dispatch('on_release') class WizardConfirmDialog(WizardDialog): def __init__(self, wizard, **kwargs): super(WizardConfirmDialog, self).__init__(wizard, **kwargs) self.message = kwargs.get('message', '') self.value = 'ok' def on_parent(self, instance, value): if value: app = App.get_running_app() self._back = _back = partial(app.dispatch, 'on_back') def get_params(self, button): return (True,) class WizardChoiceDialog(WizardDialog): def __init__(self, wizard, **kwargs): super(WizardChoiceDialog, self).__init__(wizard, **kwargs) self.message = kwargs.get('message', '') choices = kwargs.get('choices', []) layout = self.ids.choices layout.bind(minimum_height=layout.setter('height')) for action, text in choices: l = WizardButton(text=text) l.action = action l.height = '48dp' l.root = self layout.add_widget(l) def on_parent(self, instance, value): if value: app = App.get_running_app() self._back = _back = partial(app.dispatch, 'on_back') def get_params(self, button): return (button.action,) class LineDialog(WizardDialog): title = StringProperty('') message = StringProperty('') warning = StringProperty('') def __init__(self, wizard, **kwargs): WizardDialog.__init__(self, wizard, **kwargs) self.ids.next.disabled = False def get_params(self, b): return (self.ids.passphrase_input.text,) class ShowSeedDialog(WizardDialog): seed_text = StringProperty('') message = _("If you forget your PIN or lose your device, your seed phrase will be the only way to recover your funds.") ext = False def __init__(self, wizard, **kwargs): super(ShowSeedDialog, self).__init__(wizard, **kwargs) self.seed_text = kwargs['seed_text'] def on_parent(self, instance, value): if value: app = App.get_running_app() self._back = _back = partial(self.ids.back.dispatch, 'on_release') def options_dialog(self): from .seed_options import SeedOptionsDialog def callback(status): self.ext = status d = SeedOptionsDialog(self.ext, callback) d.open() def get_params(self, b): return (self.ext,) class WordButton(Button): pass class WizardButton(Button): pass class RestoreSeedDialog(WizardDialog): def __init__(self, wizard, **kwargs): super(RestoreSeedDialog, self).__init__(wizard, **kwargs) self._test = kwargs['test'] from electrum_trc.mnemonic import Mnemonic from electrum_trc.old_mnemonic import words as old_wordlist self.words = set(Mnemonic('en').wordlist).union(set(old_wordlist)) self.ids.text_input_seed.text = test_seed if is_test else '' self.message = _('Please type your seed phrase using the virtual keyboard.') self.title = _('Enter Seed') self.ext = False def options_dialog(self): from .seed_options import SeedOptionsDialog def callback(status): self.ext = status d = SeedOptionsDialog(self.ext, callback) d.open() def get_suggestions(self, prefix): for w in self.words: if w.startswith(prefix): yield w def on_text(self, dt): self.ids.next.disabled = not bool(self._test(self.get_text())) text = self.ids.text_input_seed.text if not text: last_word = '' elif text[-1] == ' ': last_word = '' else: last_word = text.split(' ')[-1] enable_space = False self.ids.suggestions.clear_widgets() suggestions = [x for x in self.get_suggestions(last_word)] if last_word in suggestions: b = WordButton(text=last_word) self.ids.suggestions.add_widget(b) enable_space = True for w in suggestions: if w != last_word and len(suggestions) < 10: b = WordButton(text=w) self.ids.suggestions.add_widget(b) i = len(last_word) p = set() for x in suggestions: if len(x)>i: p.add(x[i]) for line in [self.ids.line1, self.ids.line2, self.ids.line3]: for c in line.children: if isinstance(c, Button): if c.text in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': c.disabled = (c.text.lower() not in p) and bool(last_word) elif c.text == ' ': c.disabled = not enable_space def on_word(self, w): text = self.get_text() words = text.split(' ') words[-1] = w text = ' '.join(words) self.ids.text_input_seed.text = text + ' ' self.ids.suggestions.clear_widgets() def get_text(self): ti = self.ids.text_input_seed return ' '.join(ti.text.strip().split()) def update_text(self, c): c = c.lower() text = self.ids.text_input_seed.text if c == '<': text = text[:-1] else: text += c self.ids.text_input_seed.text = text def on_parent(self, instance, value): if value: tis = self.ids.text_input_seed tis.focus = True #tis._keyboard.bind(on_key_down=self.on_key_down) self._back = _back = partial(self.ids.back.dispatch, 'on_release') app = App.get_running_app() def on_key_down(self, keyboard, keycode, key, modifiers): if keycode[0] in (13, 271): self.on_enter() return True def on_enter(self): #self._remove_keyboard() # press next next = self.ids.next if not next.disabled: next.dispatch('on_release') def _remove_keyboard(self): tis = self.ids.text_input_seed if tis._keyboard: tis._keyboard.unbind(on_key_down=self.on_key_down) tis.focus = False def get_params(self, b): return (self.get_text(), False, self.ext) class ConfirmSeedDialog(RestoreSeedDialog): def get_params(self, b): return (self.get_text(),) def options_dialog(self): pass class ShowXpubDialog(WizardDialog): def __init__(self, wizard, **kwargs): WizardDialog.__init__(self, wizard, **kwargs) self.xpub = kwargs['xpub'] self.ids.next.disabled = False def do_copy(self): self.app._clipboard.copy(self.xpub) def do_share(self): self.app.do_share(self.xpub, _("Master Public Key")) def do_qr(self): from .qr_dialog import QRDialog popup = QRDialog(_("Master Public Key"), self.xpub, True) popup.open() class AddXpubDialog(WizardDialog): def __init__(self, wizard, **kwargs): WizardDialog.__init__(self, wizard, **kwargs) def is_valid(x): try: return kwargs['is_valid'](x) except: return False self.is_valid = is_valid self.title = kwargs['title'] self.message = kwargs['message'] self.allow_multi = kwargs.get('allow_multi', False) def check_text(self, dt): self.ids.next.disabled = not bool(self.is_valid(self.get_text())) def get_text(self): ti = self.ids.text_input return ti.text.strip() def get_params(self, button): return (self.get_text(),) def scan_xpub(self): def on_complete(text): if self.allow_multi: self.ids.text_input.text += text + '\n' else: self.ids.text_input.text = text self.app.scan_qr(on_complete) def do_paste(self): self.ids.text_input.text = test_xpub if is_test else self.app._clipboard.paste() def do_clear(self): self.ids.text_input.text = '' class InstallWizard(BaseWizard, Widget): ''' events:: `on_wizard_complete` Fired when the wizard is done creating/ restoring wallet/s. ''' __events__ = ('on_wizard_complete', ) def on_wizard_complete(self, wallet): """overriden by main_window""" pass def waiting_dialog(self, task, msg, on_finished=None): '''Perform a blocking task in the background by running the passed method in a thread. ''' def target(): # run your threaded function try: task() except Exception as err: self.show_error(str(err)) # on completion hide message Clock.schedule_once(lambda dt: app.info_bubble.hide(now=True), -1) if on_finished: def protected_on_finished(): try: on_finished() except Exception as e: self.show_error(str(e)) Clock.schedule_once(lambda dt: protected_on_finished(), -1) app = App.get_running_app() app.show_info_bubble( text=msg, icon='atlas://electrum_trc/gui/kivy/theming/light/important', pos=Window.center, width='200sp', arrow_pos=None, modal=True) t = threading.Thread(target = target) t.start() def terminate(self, *, storage=None, aborted=False): if storage is None and not aborted: storage = self.create_storage(self.path) self.dispatch('on_wizard_complete', storage) def choice_dialog(self, **kwargs): choices = kwargs['choices'] if len(choices) > 1: WizardChoiceDialog(self, **kwargs).open() else: f = kwargs['run_next'] f(choices[0][0]) def multisig_dialog(self, **kwargs): WizardMultisigDialog(self, **kwargs).open() def show_seed_dialog(self, **kwargs): ShowSeedDialog(self, **kwargs).open() def line_dialog(self, **kwargs): LineDialog(self, **kwargs).open() def confirm_seed_dialog(self, **kwargs): kwargs['title'] = _('Confirm Seed') kwargs['message'] = _('Please retype your seed phrase, to confirm that you properly saved it') ConfirmSeedDialog(self, **kwargs).open() def restore_seed_dialog(self, **kwargs): RestoreSeedDialog(self, **kwargs).open() def confirm_dialog(self, **kwargs): WizardConfirmDialog(self, **kwargs).open() def tos_dialog(self, **kwargs): WizardTOSDialog(self, **kwargs).open() def email_dialog(self, **kwargs): WizardEmailDialog(self, **kwargs).open() def otp_dialog(self, **kwargs): if kwargs['otp_secret']: WizardNewOTPDialog(self, **kwargs).open() else: WizardKnownOTPDialog(self, **kwargs).open() def add_xpub_dialog(self, **kwargs): kwargs['message'] += ' ' + _('Use the camera button to scan a QR code.') AddXpubDialog(self, **kwargs).open() def add_cosigner_dialog(self, **kwargs): kwargs['title'] = _("Add Cosigner") + " %d"%kwargs['index'] kwargs['message'] = _('Please paste your cosigners master public key, or scan it using the camera button.') AddXpubDialog(self, **kwargs).open() def show_xpub_dialog(self, **kwargs): ShowXpubDialog(self, **kwargs).open() def show_message(self, msg): self.show_error(msg) def show_error(self, msg): app = App.get_running_app() Clock.schedule_once(lambda dt: app.show_error(msg)) def request_password(self, run_next, force_disable_encrypt_cb=False): if force_disable_encrypt_cb: # do not request PIN for watching-only wallets run_next(None, False) return def on_success(old_pin, pin): assert old_pin is None run_next(pin, False) def on_failure(): self.show_error(_('PIN mismatch')) self.run('request_password', run_next) popup = PasswordDialog() app = App.get_running_app() popup.init(app, None, _('Choose PIN code'), on_success, on_failure, is_change=2) popup.open() def action_dialog(self, action, run_next): f = getattr(self, action) f()
29.374194
153
0.571931
acf66197a9040c02811504784ed70f917399c05e
6,332
py
Python
tests/test_proof.py
onyxfish/proof
0e81e9f9cdcefd4d559c789cba793ac4a17f76a7
[ "MIT" ]
149
2015-09-01T00:30:25.000Z
2016-02-16T02:10:22.000Z
tests/test_proof.py
onyxfish/proof
0e81e9f9cdcefd4d559c789cba793ac4a17f76a7
[ "MIT" ]
14
2015-09-01T00:04:40.000Z
2016-01-22T04:04:31.000Z
tests/test_proof.py
wireservice/proof
0e81e9f9cdcefd4d559c789cba793ac4a17f76a7
[ "MIT" ]
14
2016-02-18T20:32:38.000Z
2020-03-04T19:08:57.000Z
#!/usr/bin/env python # -*- coding: utf8 -*- from copy import deepcopy from glob import glob import os import shutil try: import unittest2 as unittest except ImportError: import unittest import proof TEST_CACHE = '.proof-test' class TestAnalysis(unittest.TestCase): def setUp(self): self.executed_stage1 = 0 self.data_before_stage1 = None self.data_after_stage1 = None self.executed_stage2 = 0 self.data_before_stage2 = None self.data_after_stage2 = None self.executed_stage_unicode = 0 self.executed_stage_never_cache = 0 def tearDown(self): shutil.rmtree(TEST_CACHE) def stage1(self, data): self.executed_stage1 += 1 self.data_before_stage1 = deepcopy(data) data['stage1'] = 5 self.data_after_stage1 = deepcopy(data) def stage2(self, data): self.executed_stage2 += 1 self.data_before_stage2 = deepcopy(data) data['stage2'] = data['stage1'] * 5 self.data_after_stage2 = deepcopy(data) def stage_unicode(self, data): self.executed_stage_unicode += 1 data['state_unicode'] = u'ßäœ' @proof.never_cache def stage_never_cache(self, data): self.executed_stage_never_cache += 1 def stage_noop(self, data): pass def test_data_flow(self): analysis = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) analysis.then(self.stage2) data = {} analysis.run(data) self.assertEqual(data, {}) self.assertEqual(self.data_before_stage1, {}) self.assertEqual(self.data_after_stage1, { 'stage1': 5 }) self.assertEqual(self.data_before_stage2, { 'stage1' : 5 }) self.assertEqual(self.data_after_stage2, { 'stage1': 5, 'stage2': 25 }) def test_caching(self): analysis = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) analysis.then(self.stage2) analysis.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage2, 1) analysis.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage2, 1) def test_cache_unicode(self): analysis = proof.Analysis(self.stage_unicode, cache_dir=TEST_CACHE) analysis.run() self.assertEqual(self.executed_stage_unicode, 1) def test_never_cache(self): analysis = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) analysis.then(self.stage_never_cache) analysis.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage_never_cache, 1) analysis.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage_never_cache, 2) def test_descendent_fingerprint_deleted(self): analysis = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) stage2_analysis = analysis.then(self.stage2) analysis.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage2, 1) os.remove(stage2_analysis._cache_path) analysis.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage2, 2) def test_ancestor_fingerprint_deleted(self): analysis = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) analysis.then(self.stage2) analysis.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage2, 1) os.remove(analysis._cache_path) analysis.run() self.assertEqual(self.executed_stage1, 2) self.assertEqual(self.executed_stage2, 2) def test_cache_reused(self): analysis = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) analysis.then(self.stage2) analysis.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage2, 1) analysis2 = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) analysis2.then(self.stage2) analysis2.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage2, 1) def test_ancestor_changed(self): analysis = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) noop = analysis.then(self.stage_noop) noop.then(self.stage2) analysis.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage2, 1) analysis2 = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) analysis2.then(self.stage2) analysis2.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage2, 2) def test_same_function_twice_parallel(self): analysis = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) noop = analysis.then(self.stage_noop) noop.then(self.stage2) noop.then(self.stage2) analysis.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage2, 2) def test_same_function_twice_sequence(self): analysis = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) analysis.then(self.stage2) analysis.then(self.stage_noop) analysis.then(self.stage2) analysis.run() self.assertEqual(self.executed_stage1, 1) self.assertEqual(self.executed_stage2, 2) def test_cleanup(self): self.assertFalse(os.path.exists(TEST_CACHE)) analysis = proof.Analysis(self.stage1, cache_dir=TEST_CACHE) analysis.then(self.stage2) data = {} # Initial run, creates two cache files analysis.run(data) cache_files = glob(os.path.join(TEST_CACHE, '*.cache')) self.assertEqual(len(cache_files), 2) # Create false third cache file open(os.path.join(TEST_CACHE, 'foo.cache'), 'a').close() cache_files2 = glob(os.path.join(TEST_CACHE, '*.cache')) self.assertEqual(len(cache_files2), 3) # Second run, removes false cache file analysis.run(data) cache_files3 = glob(os.path.join(TEST_CACHE, '*.cache')) self.assertEqual(len(cache_files3), 2) self.assertSequenceEqual(cache_files, cache_files3)
28.017699
79
0.662824
acf6625f125b7d0c8332cc76bef5d3d5fd28172f
4,814
py
Python
tests/gold_tests/redirect/number_of_redirects.test.py
cmcfarlen/trafficserver
2aa1d3106398eb082e5a454212b0273c63d5f69d
[ "Apache-2.0" ]
1,351
2015-01-03T08:25:40.000Z
2022-03-31T09:14:08.000Z
tests/gold_tests/redirect/number_of_redirects.test.py
cmcfarlen/trafficserver
2aa1d3106398eb082e5a454212b0273c63d5f69d
[ "Apache-2.0" ]
7,009
2015-01-14T16:22:45.000Z
2022-03-31T17:18:04.000Z
tests/gold_tests/redirect/number_of_redirects.test.py
cmcfarlen/trafficserver
2aa1d3106398eb082e5a454212b0273c63d5f69d
[ "Apache-2.0" ]
901
2015-01-11T19:21:08.000Z
2022-03-18T18:21:33.000Z
''' Specific test for number_of_redirections config. ''' # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os Test.Summary = ''' Test redirection/location & number of redirects(number_of_redirections config) ''' class NumberOfRedirectionsTest: ''' Handy class to test with number_of_redirections values. Three servers will be created and request will flow between them. Depending on the configured number_of_redirections, some request may be followed by ATS and some directly by the client(curl) ''' def __init__(self, testName, numberOfRedirections): self._numberOfRedirections = numberOfRedirections self._tr = Test.AddTestRun(testName) self.setup_ts(f'ts{self._numberOfRedirections}') self.setup_dns() self.setup_verifier_servers() self.add_config() def setup_ts(self, name="ts"): self._ts = Test.MakeATSProcess(name, enable_cache=False) def setup_verifier_servers(self): self._srv3 = Test.MakeVerifierServerProcess(f"srv3_{self._numberOfRedirections}", "replay/redirect_srv3_replay.yaml") self._srv2 = Test.MakeVerifierServerProcess( f"srv2_{self._numberOfRedirections}", "replay/redirect_srv2_replay.yaml", context={ "vs_http_port": self._srv3.Variables.http_port}) self._srv1 = Test.MakeVerifierServerProcess( f"srv1_{self._numberOfRedirections}", "replay/redirect_srv1_replay.yaml", context={ "vs_http_port": self._srv2.Variables.http_port}) def setup_dns(self): self._dns = Test.MakeDNServer(f"dns_{self._numberOfRedirections}") self._dns.addRecords(records={"a.test": ["127.0.0.1"]}) self._dns.addRecords(records={"b.test": ["127.0.0.1"]}) self._dns.addRecords(records={"c.test": ["127.0.0.1"]}) def add_config(self): self._ts.Disk.records_config.update({ 'proxy.config.diags.debug.enabled': 1, 'proxy.config.diags.debug.tags': 'http|dns|redirect|http_redirect', 'proxy.config.http.number_of_redirections': self._numberOfRedirections, 'proxy.config.dns.nameservers': f'127.0.0.1:{self._dns.Variables.Port}', 'proxy.config.dns.resolv_conf': 'NULL', 'proxy.config.url_remap.remap_required': 0, # need this so the domain gets a chance to be evaluated through DNS 'proxy.config.http.redirect.actions': 'self:follow', # redirects to self are not followed by default }) self._ts.Disk.remap_config.AddLines([ 'map a.test/ping http://a.test:{0}/'.format(self._srv1.Variables.http_port), 'map b.test/pong http://b.test:{0}/'.format(self._srv2.Variables.http_port), 'map c.test/pang http://c.test:{0}/'.format(self._srv3.Variables.http_port), ]) def run(self): self._tr.Processes.Default.StartBefore(self._srv1) self._tr.Processes.Default.StartBefore(self._srv2) self._tr.Processes.Default.StartBefore(self._srv3) self._tr.Processes.Default.StartBefore(self._dns) self._tr.Processes.Default.StartBefore(self._ts) self._tr.Command = "curl -L -vvv a.test/ping --proxy 127.0.0.1:{0} -H 'uuid: redirect_test_1'".format( self._ts.Variables.port) self._tr.Processes.Default.Streams.All = f"gold/number_of_redirections_{self._numberOfRedirections}.gold" self._tr.ReturnCode = 0 self._tr.StillRunningAfter = self._ts # No redirect, curl will get 302 and do the rest of the redirection. NumberOfRedirectionsTest("Test number_of_redirections=0", 0).run() # Single redirect, ATS will follow 1 redirect and the client the last one. NumberOfRedirectionsTest("Test number_of_redirections=1", 1).run() # The client will just get 200OK and no redirect will be done by it, TS will follow the two # 302 Redirect. NumberOfRedirectionsTest("Test number_of_redirections=2", 2).run() # If adding more, need to touch the server side as well. It won't be enough.
48.14
125
0.694641
acf66323a68e46e079b560c5f95187c8c752e827
343
py
Python
{{cookiecutter.project_slug}}/base/validation.py
cuongnb14/cookiecutter-django-drf
52450df3dab6c9913c589e25c5aee6cc883aff97
[ "MIT" ]
null
null
null
{{cookiecutter.project_slug}}/base/validation.py
cuongnb14/cookiecutter-django-drf
52450df3dab6c9913c589e25c5aee6cc883aff97
[ "MIT" ]
2
2021-05-11T03:24:32.000Z
2022-02-10T21:12:38.000Z
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/base/validation.py
cuongnb14/cookiecutter-django
3312cf6ab117d49a110e36390753c6373ca26818
[ "MIT" ]
null
null
null
import re from django import forms REGEX = { "EMAIL": "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", "USERNAME": "^[a-zA-Z0-9_]+$", "PASSWORD": "^.{8,}$", } def validate_email(email): if not re.match(REGEX["EMAIL"], email): raise forms.ValidationError("Email already exists") return email
22.866667
82
0.530612
acf663b099a32012321a824a5b372aa01cd9a8f2
10,279
py
Python
python/ray/serve/tests/test_router.py
AIX2/ray
91a1ac620012e0c779bf1bbf6983af22675cf26a
[ "Apache-2.0" ]
null
null
null
python/ray/serve/tests/test_router.py
AIX2/ray
91a1ac620012e0c779bf1bbf6983af22675cf26a
[ "Apache-2.0" ]
null
null
null
python/ray/serve/tests/test_router.py
AIX2/ray
91a1ac620012e0c779bf1bbf6983af22675cf26a
[ "Apache-2.0" ]
null
null
null
""" Unit tests for the router class. Please don't add any test that will involve controller or the backend worker, use mock if necessary. """ import asyncio from collections import defaultdict import os import pytest from ray.serve.context import TaskContext import ray from ray.serve.config import BackendConfig from ray.serve.controller import TrafficPolicy from ray.serve.router import Query, ReplicaSet, RequestMetadata, Router from ray.serve.utils import get_random_letters from ray.test_utils import SignalActor pytestmark = pytest.mark.asyncio @pytest.fixture def ray_instance(): os.environ["SERVE_LOG_DEBUG"] = "1" # Turns on debug log for tests ray.init(num_cpus=16) yield ray.shutdown() def mock_task_runner(): @ray.remote(num_cpus=0) class TaskRunnerMock: def __init__(self): self.query = None self.queries = [] async def handle_request(self, request): if isinstance(request, bytes): request = Query.ray_deserialize(request) self.query = request self.queries.append(request) return "DONE" def get_recent_call(self): return self.query def get_all_calls(self): return self.queries def clear_calls(self): self.queries = [] def ready(self): pass return TaskRunnerMock.remote() @pytest.fixture def task_runner_mock_actor(): yield mock_task_runner() @pytest.fixture def mock_controller(): @ray.remote(num_cpus=0) class MockControllerActor: def __init__(self): from ray.serve.long_poll import LongPollerHost self.host = LongPollerHost() self.backend_replicas = defaultdict(list) self.backend_configs = dict() self.clear() def clear(self): self.host.notify_changed("worker_handles", {}) self.host.notify_changed("traffic_policies", {}) self.host.notify_changed("backend_configs", {}) async def listen_for_change(self, snapshot_ids): return await self.host.listen_for_change(snapshot_ids) def set_traffic(self, endpoint, traffic_policy): self.host.notify_changed("traffic_policies", {endpoint: traffic_policy}) def add_new_replica(self, backend_tag, runner_actor, backend_config=BackendConfig()): self.backend_replicas[backend_tag].append(runner_actor) self.backend_configs[backend_tag] = backend_config self.host.notify_changed( "worker_handles", self.backend_replicas, ) self.host.notify_changed("backend_configs", self.backend_configs) yield MockControllerActor.remote() async def test_simple_endpoint_backend_pair(ray_instance, mock_controller, task_runner_mock_actor): q = ray.remote(Router).remote(mock_controller) await q.setup_in_async_loop.remote() # Propogate configs await mock_controller.set_traffic.remote( "svc", TrafficPolicy({ "backend-single-prod": 1.0 })) await mock_controller.add_new_replica.remote("backend-single-prod", task_runner_mock_actor) # Make sure we get the request result back ref = await q.assign_request.remote( RequestMetadata(get_random_letters(10), "svc", None), 1) result = await ref assert result == "DONE" # Make sure it's the right request got_work = await task_runner_mock_actor.get_recent_call.remote() assert got_work.args[0] == 1 assert got_work.kwargs == {} async def test_changing_backend(ray_instance, mock_controller, task_runner_mock_actor): q = ray.remote(Router).remote(mock_controller) await q.setup_in_async_loop.remote() await mock_controller.set_traffic.remote( "svc", TrafficPolicy({ "backend-alter": 1 })) await mock_controller.add_new_replica.remote("backend-alter", task_runner_mock_actor) await (await q.assign_request.remote( RequestMetadata(get_random_letters(10), "svc", None), 1)) got_work = await task_runner_mock_actor.get_recent_call.remote() assert got_work.args[0] == 1 await mock_controller.set_traffic.remote( "svc", TrafficPolicy({ "backend-alter-2": 1 })) await mock_controller.add_new_replica.remote("backend-alter-2", task_runner_mock_actor) await (await q.assign_request.remote( RequestMetadata(get_random_letters(10), "svc", None), 2)) got_work = await task_runner_mock_actor.get_recent_call.remote() assert got_work.args[0] == 2 async def test_split_traffic_random(ray_instance, mock_controller, task_runner_mock_actor): q = ray.remote(Router).remote(mock_controller) await q.setup_in_async_loop.remote() await mock_controller.set_traffic.remote( "svc", TrafficPolicy({ "backend-split": 0.5, "backend-split-2": 0.5 })) runner_1, runner_2 = [mock_task_runner() for _ in range(2)] await mock_controller.add_new_replica.remote("backend-split", runner_1) await mock_controller.add_new_replica.remote("backend-split-2", runner_2) # assume 50% split, the probability of all 20 requests goes to a # single queue is 0.5^20 ~ 1-6 object_refs = [] for _ in range(20): ref = await q.assign_request.remote( RequestMetadata(get_random_letters(10), "svc", None), 1) object_refs.append(ref) ray.get(object_refs) got_work = [ await runner.get_recent_call.remote() for runner in (runner_1, runner_2) ] assert [g.args[0] for g in got_work] == [1, 1] async def test_shard_key(ray_instance, mock_controller, task_runner_mock_actor): q = ray.remote(Router).remote(mock_controller) await q.setup_in_async_loop.remote() num_backends = 5 traffic_dict = {} runners = [mock_task_runner() for _ in range(num_backends)] for i, runner in enumerate(runners): backend_name = "backend-split-" + str(i) traffic_dict[backend_name] = 1.0 / num_backends await mock_controller.add_new_replica.remote(backend_name, runner) await mock_controller.set_traffic.remote("svc", TrafficPolicy(traffic_dict)) # Generate random shard keys and send one request for each. shard_keys = [get_random_letters() for _ in range(100)] for shard_key in shard_keys: await (await q.assign_request.remote( RequestMetadata( get_random_letters(10), "svc", None, shard_key=shard_key), shard_key)) # Log the shard keys that were assigned to each backend. runner_shard_keys = defaultdict(set) for i, runner in enumerate(runners): calls = await runner.get_all_calls.remote() for call in calls: runner_shard_keys[i].add(call.args[0]) await runner.clear_calls.remote() # Send queries with the same shard keys a second time. for shard_key in shard_keys: await (await q.assign_request.remote( RequestMetadata( get_random_letters(10), "svc", None, shard_key=shard_key), shard_key)) # Check that the requests were all mapped to the same backends. for i, runner in enumerate(runners): calls = await runner.get_all_calls.remote() for call in calls: assert call.args[0] in runner_shard_keys[i] async def test_replica_set(ray_instance): signal = SignalActor.remote() @ray.remote(num_cpus=0) class MockWorker: _num_queries = 0 async def handle_request(self, request): self._num_queries += 1 await signal.wait.remote() return "DONE" async def num_queries(self): return self._num_queries # We will test a scenario with two replicas in the replica set. rs = ReplicaSet() workers = [MockWorker.remote() for _ in range(2)] rs.set_max_concurrent_queries(1) rs.update_worker_replicas(workers) # Send two queries. They should go through the router but blocked by signal # actors. query = Query([], {}, TaskContext.Python, RequestMetadata("request-id", "endpoint", TaskContext.Python)) first_ref = await rs.assign_replica(query) second_ref = await rs.assign_replica(query) # These should be blocked by signal actor. with pytest.raises(ray.exceptions.GetTimeoutError): ray.get([first_ref, second_ref], timeout=1) # Each replica should have exactly one inflight query. Let make sure the # queries arrived there. for worker in workers: while await worker.num_queries.remote() != 1: await asyncio.sleep(1) # Let's try to send another query. third_ref_pending_task = asyncio.get_event_loop().create_task( rs.assign_replica(query)) # We should fail to assign a replica, so this coroutine should still be # pending after some time. await asyncio.sleep(0.2) assert not third_ref_pending_task.done() # Let's unblock the two workers await signal.send.remote() assert await first_ref == "DONE" assert await second_ref == "DONE" # The third request should be unblocked and sent to first worker. # This meas we should be able to get the object ref. third_ref = await third_ref_pending_task # Now we got the object ref, let's get it result. await signal.send.remote() assert await third_ref == "DONE" # Finally, make sure that one of the replica processed the third query. num_queries_set = {(await worker.num_queries.remote()) for worker in workers} assert num_queries_set == {2, 1} if __name__ == "__main__": import sys sys.exit(pytest.main(["-v", "-s", __file__]))
34.149502
79
0.643253
acf6645d0b9742be5ac915096aa121991b4bca04
1,025
py
Python
backend/core/mixins.py
dominikbullo/SportAgenda
fa130111e08aed38d93b9ab85e14684f362b1930
[ "Apache-2.0" ]
null
null
null
backend/core/mixins.py
dominikbullo/SportAgenda
fa130111e08aed38d93b9ab85e14684f362b1930
[ "Apache-2.0" ]
null
null
null
backend/core/mixins.py
dominikbullo/SportAgenda
fa130111e08aed38d93b9ab85e14684f362b1930
[ "Apache-2.0" ]
null
null
null
class FlattenMixin(object): """Flatens the specified related objects in this representation""" def to_representation(self, obj): assert hasattr(self.Meta, 'flatten'), ( 'Class {serializer_class} missing "Meta.flatten" attribute'.format( serializer_class=self.__class__.__name__ ) ) # Get the current object representation rep = super(FlattenMixin, self).to_representation(obj) try: # Iterate the specified related objects with their serializer for field, serializer_class in self.Meta.flatten: serializer = serializer_class(context=self.context) objrep = serializer.to_representation(getattr(obj, field)) # Include their fields, prefixed, in the current representation for key in objrep: rep[key] = objrep[key] return rep except Exception as e: print(e) pass return rep
41
81
0.599024
acf664968a94dacb3266c91e734cc55cee78b4ae
2,298
py
Python
jkbd-v2/grab-question-ids.py
gaodacheng/crawler
7331b1a3c79d9477d1fb9e8f129cbb27dcc8900d
[ "Apache-2.0" ]
1
2020-02-26T09:41:27.000Z
2020-02-26T09:41:27.000Z
jkbd-v2/grab-question-ids.py
gaodacheng/crawler
7331b1a3c79d9477d1fb9e8f129cbb27dcc8900d
[ "Apache-2.0" ]
null
null
null
jkbd-v2/grab-question-ids.py
gaodacheng/crawler
7331b1a3c79d9477d1fb9e8f129cbb27dcc8900d
[ "Apache-2.0" ]
1
2017-08-29T05:06:00.000Z
2017-08-29T05:06:00.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import requests import json from bs4 import BeautifulSoup '''grab question id and save it to resource-question-ids.txt file''' def save_txt(content, file_name = 'log.txt', new_line = True, over_write = False): ''' save text to file ''' if over_write: fp = open(file_name, 'w') else: fp = open(file_name, 'a') if new_line: content = str(content) + '\n' fp.write(content) fp.close() def get_json(url): ''' make GET request and return ''' headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36'} result = requests.get(url, headers = headers) if result.status_code == 200: return json.loads(result.content) else: return None # http://api2.jiakaobaodian.com/api/open/exercise/sequence.htm?_r=11258564547825243087&course=kemu1&carType=bus def Iturls(): ''' return Iterator ''' base_url = 'http://api2.jiakaobaodian.com/api/open/exercise/sequence.htm?_r=11258564547825243087' settings = [ {'car_type': 'bus', 'course': 'kemu1'}, {'car_type': 'bus', 'course': 'kemu3'}, {'car_type': 'truck', 'course': 'kemu1'}, {'car_type': 'truck', 'course': 'kemu3'}, {'car_type': 'car', 'course': 'kemu1'}, {'car_type': 'car', 'course': 'kemu3'}, {'car_type': 'moto', 'course': 'kemu1'}, {'car_type': 'moto', 'course': 'kemu3'}, {'car_type': 'keyun', 'course': 'zigezheng'}, {'car_type': 'huoyun', 'course': 'zigezheng'}, {'car_type': 'weixian', 'course': 'zigezheng'}, {'car_type': 'jiaolian', 'course': 'zigezheng'}, {'car_type': 'chuzu', 'course': 'zigezheng'} ] return ({'car_type': s['car_type'], 'course': s['course'], 'url': base_url + '&course=' + s['course'] + '&carType=' + s['car_type']} for s in settings) # run here if __name__ == '__main__': for item in Iturls(): print item result = get_json(item['url']) question_ids = result[u'data'] raw_string = '\n'.join(str(item['car_type']) + '|' + str(item['course']) + '|' + str(id) for id in question_ids) save_txt(raw_string, 'resource-question-ids.txt')
35.90625
155
0.594865
acf6649fb5e81ea112406f6117f0accbbebea83c
9,913
py
Python
tests/test_dtw.py
i-aki-y/librosa
a464b336c23a94e00943fc50e936180f503367eb
[ "ISC" ]
4,795
2016-05-12T04:39:33.000Z
2022-03-30T21:34:30.000Z
tests/test_dtw.py
i-aki-y/librosa
a464b336c23a94e00943fc50e936180f503367eb
[ "ISC" ]
1,110
2016-05-12T16:56:48.000Z
2022-03-31T19:26:42.000Z
tests/test_dtw.py
i-aki-y/librosa
a464b336c23a94e00943fc50e936180f503367eb
[ "ISC" ]
919
2016-05-12T09:17:06.000Z
2022-03-27T07:09:19.000Z
#!/usr/bin/env python # -*- encoding: utf-8 -*- import librosa import numpy as np from scipy.spatial.distance import cdist import pytest from test_core import srand @pytest.mark.xfail(raises=librosa.ParameterError) def test_1d_input(): X = np.array([[1], [3], [3], [8], [1]]) Y = np.array([[2], [0], [0], [8], [7], [2]]) librosa.sequence.dtw(X=X, Y=Y) def test_dtw_global(): # Example taken from: # Meinard Mueller, Fundamentals of Music Processing X = np.array([[1, 3, 3, 8, 1]]) Y = np.array([[2, 0, 0, 8, 7, 2]]) gt_D = np.array( [ [1.0, 2.0, 3.0, 10.0, 16.0, 17.0], [2.0, 4.0, 5.0, 8.0, 12.0, 13.0], [3.0, 5.0, 7.0, 10.0, 12.0, 13.0], [9.0, 11.0, 13.0, 7.0, 8.0, 14.0], [10, 10.0, 11.0, 14.0, 13.0, 9.0], ] ) mut_D, _ = librosa.sequence.dtw(X, Y) assert np.array_equal(gt_D, mut_D) # Check that it works without backtracking mut_D2 = librosa.sequence.dtw(X, Y, backtrack=False) assert np.array_equal(mut_D, mut_D2) def test_dtw_global_constrained(): # Example taken from: # Meinard Mueller, Fundamentals of Music Processing X = np.array([[1, 3, 3, 8, 1]]) Y = np.array([[2, 0, 0, 8, 7, 2]]) # With band_rad = 0.5, the GT distance array is gt_D = np.array( [ [1.0, 2.0, 3.0, np.inf, np.inf, np.inf], [2.0, 4.0, 5.0, 8.0, np.inf, np.inf], [np.inf, 5.0, 7.0, 10.0, 12.0, np.inf], [np.inf, np.inf, 13.0, 7.0, 8.0, 14.0], [np.inf, np.inf, np.inf, 14.0, 13.0, 9.0], ] ) mut_D = librosa.sequence.dtw( X, Y, backtrack=False, global_constraints=True, band_rad=0.5 ) assert np.array_equal(gt_D, mut_D) def test_dtw_global_supplied_distance_matrix(): # Example taken from: # Meinard Mueller, Fundamentals of Music Processing X = np.array([[1, 3, 3, 8, 1]]) Y = np.array([[2, 0, 0, 8, 7, 2]]) # Precompute distance matrix. C = cdist(X.T, Y.T, metric="euclidean") gt_D = np.array( [ [1.0, 2.0, 3.0, 10.0, 16.0, 17.0], [2.0, 4.0, 5.0, 8.0, 12.0, 13.0], [3.0, 5.0, 7.0, 10.0, 12.0, 13.0], [9.0, 11.0, 13.0, 7.0, 8.0, 14.0], [10, 10.0, 11.0, 14.0, 13.0, 9.0], ] ) # Supply precomputed distance matrix and specify an invalid distance # metric to verify that it isn't used. mut_D, _ = librosa.sequence.dtw(C=C, metric="invalid") assert np.array_equal(gt_D, mut_D) def test_dtw_gobal_boundary(): # Verify that boundary condition is fulfilled for subseq=False. # See https://github.com/librosa/librosa/pull/920 X = np.array([1, 2, 3, 4, 5]) Y = np.array([1, 1, 1, 2, 4, 5, 6, 5, 5]) gt_wp = np.array( [[0, 0], [0, 1], [0, 2], [1, 3], [2, 3], [3, 4], [4, 5], [4, 6], [4, 7], [4, 8]] ) D, wp = librosa.sequence.dtw(X, Y, subseq=False) wp = wp[::-1] assert np.array_equal(gt_wp, wp) def test_dtw_subseq_boundary(): # Verify that boundary condition doesn't have to be fulfilled for # subseq=True. # See https://github.com/librosa/librosa/pull/920 X = np.array([1, 2, 3, 4, 5]) Y = np.array([1, 1, 1, 2, 4, 5, 6, 5, 5]) gt_wp = np.array([[0, 2], [1, 3], [2, 3], [3, 4], [4, 5]]) D, wp = librosa.sequence.dtw(X, Y, subseq=True) wp = wp[::-1] assert np.array_equal(gt_wp, wp) def test_dtw_subseq_steps(): # Verify that the same warping path is computed for backtracking # within the dtw function and manually outside by the user # See https://github.com/librosa/librosa/pull/1166 X = np.array([1, 2, 3, 4, 5]) Y = np.array([1, 1, 1, 2, 4, 5, 6, 5, 5]) gt_wp = np.array([[0, 2], [1, 3], [2, 3], [3, 4], [4, 5]]) D1, wp1 = librosa.sequence.dtw(X, Y, subseq=True, backtrack=True) wp1 = wp1[::-1] D2, steps = librosa.sequence.dtw( X, Y, subseq=True, backtrack=False, return_steps=True ) start_idx = np.argmin(D2[-1, :]) wp2 = librosa.sequence.dtw_backtracking(steps, subseq=True, start=start_idx) wp2 = wp2[::-1] assert np.array_equal(D1, D2) assert np.array_equal(gt_wp, wp1) assert np.array_equal(wp1, wp2) @pytest.mark.xfail(raises=librosa.ParameterError) def test_dtw_backtracking_incompatible_args_01(): # See https://github.com/librosa/librosa/pull/1166 X = np.array([1, 2, 3, 4, 5]) Y = np.array([1, 1, 1, 2, 4, 5, 6, 5, 5]) D, steps = librosa.sequence.dtw( X, Y, subseq=True, backtrack=False, return_steps=True ) start_idx = np.argmin(D[-1, :]) librosa.sequence.dtw_backtracking(steps, subseq=False, start=start_idx) @pytest.mark.xfail(raises=librosa.ParameterError) def test_dtw_incompatible_args_01(): librosa.sequence.dtw(C=1, X=1, Y=1) @pytest.mark.xfail(raises=librosa.ParameterError) def test_dtw_incompatible_args_02(): librosa.sequence.dtw(C=None, X=None, Y=None) @pytest.mark.xfail(raises=librosa.ParameterError) def test_dtw_incompatible_sigma_add(): X = np.array([[1, 3, 3, 8, 1]]) Y = np.array([[2, 0, 0, 8, 7, 2]]) librosa.sequence.dtw(X=X, Y=Y, weights_add=np.arange(10)) @pytest.mark.xfail(raises=librosa.ParameterError) def test_dtw_incompatible_sigma_mul(): X = np.array([[1, 3, 3, 8, 1]]) Y = np.array([[2, 0, 0, 8, 7, 2]]) librosa.sequence.dtw(X=X, Y=Y, weights_mul=np.arange(10)) @pytest.mark.xfail(raises=librosa.ParameterError) def test_dtw_incompatible_sigma_diag(): X = np.array([[1, 3, 3, 8, 1, 2]]) Y = np.array([[2, 0, 0, 8, 7]]) librosa.sequence.dtw(X=X, Y=Y, step_sizes_sigma=np.ones((1, 2), dtype=int)) @pytest.mark.xfail(raises=librosa.ParameterError) def test_dtw_incompatible_sigma_diag_precomp(): C = np.ones((5, 3)) librosa.sequence.dtw(C=C, step_sizes_sigma=[[1, 1]]) def test_dtw_global_diagonal(): # query is a linear ramp X = np.linspace(0.1, 1, 10) Y = X gt_wp = list(zip(list(range(10)), list(range(10))))[::-1] mut_D, mut_wp = librosa.sequence.dtw( X, Y, subseq=True, metric="cosine", step_sizes_sigma=np.array([[1, 1]]), weights_mul=np.array([1]), ) assert np.array_equal(np.asarray(gt_wp), np.asarray(mut_wp)) def test_dtw_subseq(): srand() # query is a linear ramp X = np.linspace(0, 1, 100) # database is query surrounded by noise noise_len = 200 noise = np.random.rand(noise_len) Y = np.concatenate((noise, noise, X, noise)) _, mut_wp = librosa.sequence.dtw(X, Y, subseq=True) # estimated sequence has to match original sequence # note the +1 due to python indexing mut_X = Y[mut_wp[-1][1] : mut_wp[0][1] + 1] assert np.array_equal(X, mut_X) def test_dtw_subseq_supplied_distance_matrix(): X = np.array([[0], [1], [2]]) Y = np.array([[1], [2], [3], [4]]) C = cdist(X, Y) costs0, path0 = librosa.sequence.dtw(X.T, Y.T, subseq=True) costs1, path1 = librosa.sequence.dtw(C=C, subseq=True) assert np.array_equal(costs0, costs1) assert np.array_equal(path0, path1) def test_dtw_subseq_sym(): Y = np.array([10.0, 10.0, 0.0, 1.0, 2.0, 3.0, 10.0, 10.0]) X = np.arange(4) gt_wp_XY = np.array([[3, 5], [2, 4], [1, 3], [0, 2]]) gt_wp_YX = np.array([[5, 3], [4, 2], [3, 1], [2, 0]]) _, mut_wp_XY = librosa.sequence.dtw(X, Y, subseq=True) _, mut_wp_YX = librosa.sequence.dtw(Y, X, subseq=True) assert np.array_equal(gt_wp_XY, mut_wp_XY) assert np.array_equal(gt_wp_YX, mut_wp_YX) def test_dtw_global_constraint_destructive(): # Issue #1029, dtw with global constraints inserts nans # into the cost matrix. This is fine when the cost is computed # locally, but if passed by reference, it's destructive. # This test checks that the cost matrix is unmodified. C1 = np.ones((20, 20)) C2 = np.copy(C1) librosa.sequence.dtw(C=C1, global_constraints=True) assert np.array_equal(C1, C2) def test_dtw_global_inf(): # What should we do if backtracking fails in full sequence mode? # This will happen if the inner loop of bt aborts prematurely # by walking off the edge of the cost array instead of # path-following to (0, 0) # Construct a cost matrix where full alignment is impossible C = np.zeros((4, 4), dtype=np.float) C[-1, -1] = np.inf with pytest.raises(librosa.ParameterError): librosa.sequence.dtw(C=C, subseq=False) def test_dtw_subseq_inf(): # Construct a cost matrix where partial alignment is impossible C = np.zeros((4, 4), dtype=np.float) C[-1, :] = np.inf with pytest.raises(librosa.ParameterError): librosa.sequence.dtw(C=C, subseq=True) def test_dtw_subseq_pass(): # Construct a cost matrix where partial alignment is possible C = np.zeros((4, 4), dtype=np.float) C[-1, 2:] = np.inf librosa.sequence.dtw(C=C, subseq=True) @pytest.mark.xfail(raises=librosa.ParameterError) def test_dtw_nan_fail(): C = np.ones((10, 10)) C[4, 6] = np.nan librosa.sequence.dtw(C=C) @pytest.mark.xfail(raises=librosa.ParameterError) @pytest.mark.parametrize( "steps", [np.array([[1, -1]]), np.array([[-1, 1]]), np.array([[-1, -1]])] ) def test_dtw_negative_steps(steps): C = np.ones((10, 10)) librosa.sequence.dtw(C=C, step_sizes_sigma=steps) def test_dtw_multi(): srand() X = np.random.randn(2, 5, 10) Y = np.random.randn(2, 5, 20) D, wp, steps = librosa.sequence.dtw(X=X, Y=Y, backtrack=True, return_steps=True) # Should give identical results to calling with concatenated inputs Xf = np.concatenate([X[0], X[1]], axis=0) Yf = np.concatenate([Y[0], Y[1]], axis=0) Df, wpf, stepsf = librosa.sequence.dtw(X=Xf, Y=Yf, backtrack=True, return_steps=True) assert np.allclose(D, Df) assert np.allclose(wp, wpf) assert np.allclose(steps, stepsf)
30.130699
89
0.609604
acf664a5c853153dee5089747f359cdc4e11c072
24,220
py
Python
fairseq/tasks/fairseq_task.py
Feecely/fairseq_bertnmt
86a97432ba27a44b4a5cb66a35569c8517fbc66d
[ "MIT" ]
null
null
null
fairseq/tasks/fairseq_task.py
Feecely/fairseq_bertnmt
86a97432ba27a44b4a5cb66a35569c8517fbc66d
[ "MIT" ]
null
null
null
fairseq/tasks/fairseq_task.py
Feecely/fairseq_bertnmt
86a97432ba27a44b4a5cb66a35569c8517fbc66d
[ "MIT" ]
null
null
null
# 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. import logging import os import warnings from argparse import Namespace from typing import Any, Callable, Dict, List import torch from fairseq import metrics, search, tokenizer, utils from fairseq.data import Dictionary, FairseqDataset, data_utils, encoders, iterators from fairseq.dataclass import FairseqDataclass from fairseq.dataclass.utils import gen_parser_from_dataclass from omegaconf import DictConfig logger = logging.getLogger(__name__) class StatefulContainer(object): _state: Dict[str, Any] = dict() _factories: Dict[str, Callable[[], Any]] = dict() def add_factory(self, name, factory: Callable[[], Any]): self._factories[name] = factory def merge_state_dict(self, state_dict: Dict[str, Any]): self._state.update(state_dict) @property def state_dict(self) -> Dict[str, Any]: return self._state def __getattr__(self, name): if name not in self._state and name in self._factories: self._state[name] = self._factories[name]() if name in self._state: return self._state[name] raise AttributeError(f"Task state has no factory for attribute {name}") class FairseqTask(object): """ Tasks store dictionaries and provide helpers for loading/iterating over Datasets, initializing the Model/Criterion and calculating the loss. Tasks have limited statefulness. In particular, state that needs to be saved to/loaded from checkpoints needs to be stored in the `self.state` :class:`StatefulContainer` object. For example:: self.state.add_factory("dictionary", self.load_dictionary) print(self.state.dictionary) # calls self.load_dictionary() This is necessary so that when loading checkpoints, we can properly recreate the task state after initializing the task instance. """ @classmethod def add_args(cls, parser): """Add task-specific arguments to the parser.""" dc = getattr(cls, "__dataclass", None) if dc is not None: gen_parser_from_dataclass(parser, dc()) @staticmethod def logging_outputs_can_be_summed(criterion) -> bool: """ Whether the logging outputs returned by `train_step` and `valid_step` can be summed across workers prior to calling `aggregate_logging_outputs`. Setting this to True will improves distributed training speed. """ return criterion.logging_outputs_can_be_summed() cfg: FairseqDataclass datasets: Dict[str, FairseqDataset] dataset_to_epoch_iter: Dict[FairseqDataset, Any] state: StatefulContainer = None def __init__(self, cfg: FairseqDataclass, **kwargs): self.cfg = cfg self.datasets = dict() self.dataset_to_epoch_iter = dict() self.state = StatefulContainer() @classmethod def load_dictionary(cls, filename): """Load the dictionary from the filename Args: filename (str): the filename """ return Dictionary.load(filename) @classmethod def build_dictionary( cls, filenames, workers=1, threshold=-1, nwords=-1, padding_factor=8 ): """Build the dictionary Args: filenames (list): list of filenames workers (int): number of concurrent workers threshold (int): defines the minimum word count nwords (int): defines the total number of words in the final dictionary, including special symbols padding_factor (int): can be used to pad the dictionary size to be a multiple of 8, which is important on some hardware (e.g., Nvidia Tensor Cores). """ d = Dictionary() for filename in filenames: Dictionary.add_file_to_dictionary( filename, d, tokenizer.tokenize_line, workers ) d.finalize(threshold=threshold, nwords=nwords, padding_factor=padding_factor) return d @classmethod def setup_task(cls, cfg: DictConfig, **kwargs): """Setup the task (e.g., load dictionaries). Args: cfg (omegaconf.DictConfig): parsed command-line arguments """ return cls(cfg, **kwargs) def has_sharded_data(self, split): return os.pathsep in getattr(self.cfg, "data", "") def load_dataset( self, split: str, combine: bool = False, task_cfg: FairseqDataclass = None, **kwargs ): """Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test) combine (bool): combines a split segmented into pieces into one dataset task_cfg (FairseqDataclass): optional task configuration stored in the checkpoint that can be used to load datasets """ raise NotImplementedError def dataset(self, split): """ Return a loaded dataset split. Args: split (str): name of the split (e.g., train, valid, test) Returns: a :class:`~fairseq.data.FairseqDataset` corresponding to *split* """ from fairseq.data import FairseqDataset if split not in self.datasets: raise KeyError("Dataset not loaded: " + split) if not isinstance(self.datasets[split], FairseqDataset): raise TypeError("Datasets are expected to be of type FairseqDataset") return self.datasets[split] def filter_indices_by_size( self, indices, dataset, max_positions=None, ignore_invalid_inputs=False ): """ Filter examples that are too large Args: indices (np.array): original array of sample indices dataset (~fairseq.data.FairseqDataset): dataset to batch max_positions (optional): max sentence length supported by the model (default: None). ignore_invalid_inputs (bool, optional): don't raise Exception for sentences that are too long (default: False). Returns: np.array: array of filtered sample indices """ indices, ignored = dataset.filter_indices_by_size(indices, max_positions) if len(ignored) > 0: if not ignore_invalid_inputs: raise Exception( ( "Size of sample #{} is invalid (={}) since max_positions={}, " "skip this example with --skip-invalid-size-inputs-valid-test" ).format(ignored[0], dataset.size(ignored[0]), max_positions) ) logger.warning( ( "{:,} samples have invalid sizes and will be skipped, " "max_positions={}, first few sample ids={}" ).format(len(ignored), max_positions, ignored[:10]) ) return indices def can_reuse_epoch_itr(self, dataset): # We can reuse the epoch iterator across epochs as long as the dataset # hasn't disabled it. We default to ``False`` here, although in practice # this will be ``True`` for most datasets that inherit from # ``FairseqDataset`` due to the base implementation there. return getattr(dataset, "can_reuse_epoch_itr_across_epochs", False) def get_batch_iterator( self, dataset, max_tokens=None, max_sentences=None, max_positions=None, ignore_invalid_inputs=False, required_batch_size_multiple=1, seed=1, num_shards=1, shard_id=0, num_workers=0, epoch=1, data_buffer_size=0, disable_iterator_cache=False, ): """ Get an iterator that yields batches of data from the given dataset. Args: dataset (~fairseq.data.FairseqDataset): dataset to batch max_tokens (int, optional): max number of tokens in each batch (default: None). max_sentences (int, optional): max number of sentences in each batch (default: None). max_positions (optional): max sentence length supported by the model (default: None). ignore_invalid_inputs (bool, optional): don't raise Exception for sentences that are too long (default: False). required_batch_size_multiple (int, optional): require batch size to be a multiple of N (default: 1). seed (int, optional): seed for random number generator for reproducibility (default: 1). num_shards (int, optional): shard the data iterator into N shards (default: 1). shard_id (int, optional): which shard of the data iterator to return (default: 0). num_workers (int, optional): how many subprocesses to use for data loading. 0 means the data will be loaded in the main process (default: 0). epoch (int, optional): the epoch to start the iterator from (default: 1). data_buffer_size (int, optional): number of batches to preload (default: 0). disable_iterator_cache (bool, optional): don't cache the EpochBatchIterator (ignores `FairseqTask::can_reuse_epoch_itr`) (default: False). Returns: ~fairseq.iterators.EpochBatchIterator: a batched iterator over the given dataset split """ can_reuse_epoch_itr = not disable_iterator_cache and self.can_reuse_epoch_itr( dataset ) if can_reuse_epoch_itr and dataset in self.dataset_to_epoch_iter: logger.debug("reusing EpochBatchIterator for epoch {}".format(epoch)) return self.dataset_to_epoch_iter[dataset] assert isinstance(dataset, FairseqDataset) # initialize the dataset with the correct starting epoch dataset.set_epoch(epoch) # get indices ordered by example size with data_utils.numpy_seed(seed): indices = dataset.ordered_indices() # filter examples that are too large if max_positions is not None: indices = self.filter_indices_by_size( indices, dataset, max_positions, ignore_invalid_inputs ) # create mini-batches with given size constraints batch_sampler = dataset.batch_by_size( indices, max_tokens=max_tokens, max_sentences=max_sentences, required_batch_size_multiple=required_batch_size_multiple, ) # return a reusable, sharded iterator epoch_iter = iterators.EpochBatchIterator( dataset=dataset, collate_fn=dataset.collater, batch_sampler=batch_sampler, seed=seed, num_shards=num_shards, shard_id=shard_id, num_workers=num_workers, epoch=epoch, buffer_size=data_buffer_size, ) if can_reuse_epoch_itr: self.dataset_to_epoch_iter[dataset] = epoch_iter return epoch_iter def build_model(self, cfg: FairseqDataclass): """ Build the :class:`~fairseq.models.BaseFairseqModel` instance for this task. Args: cfg (FairseqDataclass): configuration object Returns: a :class:`~fairseq.models.BaseFairseqModel` instance """ from fairseq import models, quantization_utils model = models.build_model(cfg, self) model = quantization_utils.quantize_model_scalar(model, cfg) return model def build_criterion(self, cfg: DictConfig): """ Build the :class:`~fairseq.criterions.FairseqCriterion` instance for this task. Args: cfg (omegaconf.DictConfig): configration object Returns: a :class:`~fairseq.criterions.FairseqCriterion` instance """ from fairseq import criterions return criterions.build_criterion(cfg, self) def build_generator( self, models, args, seq_gen_cls=None, extra_gen_cls_kwargs=None ): if getattr(args, "score_reference", False): from fairseq.sequence_scorer import SequenceScorer return SequenceScorer( self.target_dictionary, compute_alignment=getattr(args, "print_alignment", False), ) from fairseq.sequence_generator import ( SequenceGenerator, SequenceGeneratorWithAlignment, ) try: from fairseq.fb_sequence_generator import FBSequenceGenerator except ModuleNotFoundError: pass # Choose search strategy. Defaults to Beam Search. sampling = getattr(args, "sampling", False) sampling_topk = getattr(args, "sampling_topk", -1) sampling_topp = getattr(args, "sampling_topp", -1.0) diverse_beam_groups = getattr(args, "diverse_beam_groups", -1) diverse_beam_strength = getattr(args, "diverse_beam_strength", 0.5) match_source_len = getattr(args, "match_source_len", False) diversity_rate = getattr(args, "diversity_rate", -1) constrained = getattr(args, "constraints", False) prefix_allowed_tokens_fn = getattr(args, "prefix_allowed_tokens_fn", None) if ( sum( int(cond) for cond in [ sampling, diverse_beam_groups > 0, match_source_len, diversity_rate > 0, ] ) > 1 ): raise ValueError("Provided Search parameters are mutually exclusive.") assert sampling_topk < 0 or sampling, "--sampling-topk requires --sampling" assert sampling_topp < 0 or sampling, "--sampling-topp requires --sampling" if sampling: search_strategy = search.Sampling( self.target_dictionary, sampling_topk, sampling_topp ) elif diverse_beam_groups > 0: search_strategy = search.DiverseBeamSearch( self.target_dictionary, diverse_beam_groups, diverse_beam_strength ) elif match_source_len: # this is useful for tagging applications where the output # length should match the input length, so we hardcode the # length constraints for simplicity search_strategy = search.LengthConstrainedBeamSearch( self.target_dictionary, min_len_a=1, min_len_b=0, max_len_a=1, max_len_b=0, ) elif diversity_rate > -1: search_strategy = search.DiverseSiblingsSearch( self.target_dictionary, diversity_rate ) elif constrained: search_strategy = search.LexicallyConstrainedBeamSearch( self.target_dictionary, args.constraints ) elif prefix_allowed_tokens_fn: search_strategy = search.PrefixConstrainedBeamSearch( self.target_dictionary, prefix_allowed_tokens_fn ) else: search_strategy = search.BeamSearch(self.target_dictionary) extra_gen_cls_kwargs = extra_gen_cls_kwargs or {} if seq_gen_cls is None: if getattr(args, "print_alignment", False): seq_gen_cls = SequenceGeneratorWithAlignment extra_gen_cls_kwargs["print_alignment"] = args.print_alignment elif getattr(args, "fb_seq_gen", False): seq_gen_cls = FBSequenceGenerator else: seq_gen_cls = SequenceGenerator return seq_gen_cls( models, self.target_dictionary, beam_size=getattr(args, "beam", 5), max_len_a=getattr(args, "max_len_a", 0), max_len_b=getattr(args, "max_len_b", 200), min_len=getattr(args, "min_len", 1), normalize_scores=(not getattr(args, "unnormalized", False)), len_penalty=getattr(args, "lenpen", 1), unk_penalty=getattr(args, "unkpen", 0), temperature=getattr(args, "temperature", 1.0), match_source_len=getattr(args, "match_source_len", False), no_repeat_ngram_size=getattr(args, "no_repeat_ngram_size", 0), search_strategy=search_strategy, args=args, **extra_gen_cls_kwargs, ) def train_step( self, sample, model, criterion, optimizer, update_num, ignore_grad=False ): """ Do forward and backward, and return the loss as computed by *criterion* for the given *model* and *sample*. Args: sample (dict): the mini-batch. The format is defined by the :class:`~fairseq.data.FairseqDataset`. model (~fairseq.models.BaseFairseqModel): the model criterion (~fairseq.criterions.FairseqCriterion): the criterion optimizer (~fairseq.optim.FairseqOptimizer): the optimizer update_num (int): the current update ignore_grad (bool): multiply loss by 0 if this is set to True Returns: tuple: - the loss - the sample size, which is used as the denominator for the gradient - logging outputs to display while training """ model.train() model.set_num_updates(update_num) with torch.autograd.profiler.record_function("forward"): loss, sample_size, logging_output = criterion(model, sample) if ignore_grad: loss *= 0 with torch.autograd.profiler.record_function("backward"): optimizer.backward(loss) return loss, sample_size, logging_output def valid_step(self, sample, model, criterion): model.eval() with torch.no_grad(): loss, sample_size, logging_output = criterion(model, sample) return loss, sample_size, logging_output def optimizer_step(self, optimizer, model, update_num): optimizer.step() def build_dataset_for_inference( self, src_tokens: List[torch.Tensor], src_lengths: List[int], **kwargs ) -> torch.utils.data.Dataset: raise NotImplementedError def inference_step( self, generator, models, sample, prefix_tokens=None, constraints=None ): with torch.no_grad(): return generator.generate( models, sample, prefix_tokens=prefix_tokens, constraints=constraints ) def begin_epoch(self, epoch, model): """Hook function called before the start of each epoch.""" pass def begin_valid_epoch(self, epoch, model): """Hook function called before the start of each validation epoch.""" pass def aggregate_logging_outputs(self, logging_outputs, criterion): """[deprecated] Aggregate logging outputs from data parallel training.""" utils.deprecation_warning( "The aggregate_logging_outputs API is deprecated. " "Please use the reduce_metrics API instead." ) with metrics.aggregate() as agg: self.reduce_metrics(logging_outputs, criterion) return agg.get_smoothed_values() def reduce_metrics(self, logging_outputs, criterion): """Aggregate logging outputs from data parallel training.""" # backward compatibility for tasks that override aggregate_logging_outputs base_func = FairseqTask.aggregate_logging_outputs self_func = getattr(self, "aggregate_logging_outputs").__func__ if self_func is not base_func: utils.deprecation_warning( "Tasks should implement the reduce_metrics API. " "Falling back to deprecated aggregate_logging_outputs API." ) agg_logging_outputs = self.aggregate_logging_outputs( logging_outputs, criterion ) for k, v in agg_logging_outputs.items(): metrics.log_scalar(k, v) return if not any("ntokens" in log for log in logging_outputs): warnings.warn( "ntokens not found in Criterion logging outputs, cannot log wpb or wps" ) else: ntokens = sum(log.get("ntokens", 0) for log in logging_outputs) metrics.log_scalar("wpb", ntokens, priority=180, round=1) metrics.log_speed("wps", ntokens, priority=90, round=1) if not any("nsentences" in log for log in logging_outputs): warnings.warn( "nsentences not found in Criterion logging outputs, cannot log bsz" ) else: nsentences = sum(log.get("nsentences", 0) for log in logging_outputs) metrics.log_scalar("bsz", nsentences, priority=190, round=1) criterion.__class__.reduce_metrics(logging_outputs) def state_dict(self): if self.state is not None: return self.state.state_dict return {} def load_state_dict(self, state_dict: Dict[str, Any]): if self.state is not None: self.state.merge_state_dict(state_dict) def max_positions(self): """Return the max input length allowed by the task.""" return None @property def source_dictionary(self): """Return the source :class:`~fairseq.data.Dictionary` (if applicable for this task).""" raise NotImplementedError @property def target_dictionary(self): """Return the target :class:`~fairseq.data.Dictionary` (if applicable for this task).""" raise NotImplementedError def build_tokenizer(self, args): """Build the pre-tokenizer for this task.""" return encoders.build_tokenizer(args) def build_bpe(self, args): """Build the tokenizer for this task.""" return encoders.build_bpe(args) def get_interactive_tokens_and_lengths(self, lines, encode_fn): tokens = [ self.source_dictionary.encode_line( encode_fn(src_str), add_if_not_exist=False ).long() for src_str in lines ] lengths = [t.numel() for t in tokens] return tokens, lengths class LegacyFairseqTask(FairseqTask): def __init__(self, args: Namespace): self.args = args self.datasets = {} self.dataset_to_epoch_iter = {} @classmethod def setup_task(cls, args: Namespace, **kwargs): """Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments """ return cls(args, **kwargs) def has_sharded_data(self, split): return os.pathsep in getattr(self.args, "data", "") def build_model(self, args: Namespace): """ Build the :class:`~fairseq.models.BaseFairseqModel` instance for this task. Args: args (argparse.Namespace): parsed command-line arguments Returns: a :class:`~fairseq.models.BaseFairseqModel` instance """ from fairseq import models, quantization_utils model = models.build_model(args, self) model = quantization_utils.quantize_model_scalar(model, args) return model def build_criterion(self, args: Namespace): """ Build the :class:`~fairseq.criterions.FairseqCriterion` instance for this task. Args: args (argparse.Namespace): parsed command-line arguments Returns: a :class:`~fairseq.criterions.FairseqCriterion` instance """ from fairseq import criterions return criterions.build_criterion(args, self)
37.147239
110
0.619405
acf665483ed2a64b86d4c24daeb2e4703551cf04
2,500
py
Python
src/sage/modular/modsym/hecke_operator.py
bopopescu/sage-5
9d85b34956ca2edd55af307f99c5d3859acd30bf
[ "BSL-1.0" ]
5
2015-01-04T07:15:06.000Z
2022-03-04T15:15:18.000Z
src/sage/modular/modsym/hecke_operator.py
bopopescu/sage-5
9d85b34956ca2edd55af307f99c5d3859acd30bf
[ "BSL-1.0" ]
null
null
null
src/sage/modular/modsym/hecke_operator.py
bopopescu/sage-5
9d85b34956ca2edd55af307f99c5d3859acd30bf
[ "BSL-1.0" ]
10
2016-09-28T13:12:40.000Z
2022-02-12T09:28:34.000Z
########################################################################## # # Copyright (C) 2008 William Stein <wstein@gmail.com> # # Distributed under the terms of the GNU General Public License (GPL) # # http://www.gnu.org/licenses/ # ########################################################################## import sage.modular.hecke.hecke_operator from sage.rings.arith import is_prime import heilbronn class HeckeOperator(sage.modular.hecke.hecke_operator.HeckeOperator): def apply_sparse(self, x): """ Return the image of x under self. If x is not in self.domain(), raise a TypeError. EXAMPLES: sage: M = ModularSymbols(17,4,-1) sage: T = M.hecke_operator(4) sage: T.apply_sparse(M.0) 64*[X^2,(1,8)] + 24*[X^2,(1,10)] - 9*[X^2,(1,13)] + 37*[X^2,(1,16)] sage: [ T.apply_sparse(x) == T.hecke_module_morphism()(x) for x in M.basis() ] [True, True, True, True] sage: N = ModularSymbols(17,4,1) sage: T.apply_sparse(N.0) Traceback (most recent call last): ... TypeError: x (=[X^2,(0,1)]) must be in Modular Symbols space of dimension 4 for Gamma_0(17) of weight 4 with sign -1 over Rational Field """ if x not in self.domain(): raise TypeError, "x (=%s) must be in %s"%(x, self.domain()) # old version just to check for correctness #return self.hecke_module_morphism()(x) p = self.index() if is_prime(p): H = heilbronn.HeilbronnCremona(p) else: H = heilbronn.HeilbronnMerel(p) M = self.parent().module() mod2term = M._mod2term syms = M.manin_symbols() K = M.base_ring() R = M.manin_gens_to_basis() W = R.new_matrix(nrows=1, ncols = R.nrows()) B = M.manin_basis() #from sage.all import cputime #t = cputime() v = x.element() for i in v.nonzero_positions(): for h in H: entries = syms.apply(B[i], h) for k, w in entries: f, s = mod2term[k] if s: W[0,f] += s*K(w)*v[i] #print 'sym', cputime(t) #t = cputime() ans = M( v.parent()((W * R).row(0)) ) #print 'mul', cputime(t) #print 'density: ', len(W.nonzero_positions())/(W.nrows()*float(W.ncols())) return ans
32.894737
148
0.4976
acf665b371300ac0be8b718f2dd93470fcf1c351
113
py
Python
Assignments/Assignment 4/Assignment4.py
Mad-Driscoll/CMPT-120L-902-21S
ea61a4bd4751416e12acd9669138445270549937
[ "MIT" ]
null
null
null
Assignments/Assignment 4/Assignment4.py
Mad-Driscoll/CMPT-120L-902-21S
ea61a4bd4751416e12acd9669138445270549937
[ "MIT" ]
null
null
null
Assignments/Assignment 4/Assignment4.py
Mad-Driscoll/CMPT-120L-902-21S
ea61a4bd4751416e12acd9669138445270549937
[ "MIT" ]
null
null
null
def userinput(x: int): return x y = input("Enter a random integer:") print(sum(range(userinput(int(y) + 1))))
18.833333
40
0.663717
acf665e1ac5134ccca7640a69ddc7571ab753263
15,006
py
Python
skimage/restoration/deconvolution.py
serge-sans-paille/scikit-image
a897bb6ad94ea2b760a10f8078e59b21be51cafd
[ "BSD-3-Clause" ]
null
null
null
skimage/restoration/deconvolution.py
serge-sans-paille/scikit-image
a897bb6ad94ea2b760a10f8078e59b21be51cafd
[ "BSD-3-Clause" ]
null
null
null
skimage/restoration/deconvolution.py
serge-sans-paille/scikit-image
a897bb6ad94ea2b760a10f8078e59b21be51cafd
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # deconvolution.py --- Image deconvolution """Implementations restoration functions""" import numpy as np import numpy.random as npr from scipy.signal import fftconvolve, convolve from . import uft __keywords__ = "restoration, image, deconvolution" def wiener(image, psf, balance, reg=None, is_real=True, clip=True): """Wiener-Hunt deconvolution Return the deconvolution with a Wiener-Hunt approach (i.e. with Fourier diagonalisation). Parameters ---------- image : (M, N) ndarray Input degraded image psf : ndarray Point Spread Function. This is assumed to be the impulse response (input image space) if the data-type is real, or the transfer function (Fourier space) if the data-type is complex. There is no constraints on the shape of the impulse response. The transfer function must be of shape `(M, N)` if `is_real is True`, `(M, N // 2 + 1)` otherwise (see `np.fft.rfftn`). balance : float The regularisation parameter value that tunes the balance between the data adequacy that improve frequency restoration and the prior adequacy that reduce frequency restoration (to avoid noise artifacts). reg : ndarray, optional The regularisation operator. The Laplacian by default. It can be an impulse response or a transfer function, as for the psf. Shape constraint is the same as for the `psf` parameter. is_real : boolean, optional True by default. Specify if ``psf`` and ``reg`` are provided with hermitian hypothesis, that is only half of the frequency plane is provided (due to the redundancy of Fourier transform of real signal). It's apply only if ``psf`` and/or ``reg`` are provided as transfer function. For the hermitian property see ``uft`` module or ``np.fft.rfftn``. clip : boolean, optional True by default. If True, pixel values of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. Returns ------- im_deconv : (M, N) ndarray The deconvolved image. Examples -------- >>> from skimage import color, data, restoration >>> img = color.rgb2gray(data.astronaut()) >>> from scipy.signal import convolve2d >>> psf = np.ones((5, 5)) / 25 >>> img = convolve2d(img, psf, 'same') >>> img += 0.1 * img.std() * np.random.standard_normal(img.shape) >>> deconvolved_img = restoration.wiener(img, psf, 1100) Notes ----- This function applies the Wiener filter to a noisy and degraded image by an impulse response (or PSF). If the data model is .. math:: y = Hx + n where :math:`n` is noise, :math:`H` the PSF and :math:`x` the unknown original image, the Wiener filter is .. math:: \hat x = F^\dagger (|\Lambda_H|^2 + \lambda |\Lambda_D|^2) \Lambda_H^\dagger F y where :math:`F` and :math:`F^\dagger` are the Fourier and inverse Fourier transfroms respectively, :math:`\Lambda_H` the transfer function (or the Fourier transfrom of the PSF, see [Hunt] below) and :math:`\Lambda_D` the filter to penalize the restored image frequencies (Laplacian by default, that is penalization of high frequency). The parameter :math:`\lambda` tunes the balance between the data (that tends to increase high frequency, even those coming from noise), and the regularization. These methods are then specific to a prior model. Consequently, the application or the true image nature must corresponds to the prior model. By default, the prior model (Laplacian) introduce image smoothness or pixel correlation. It can also be interpreted as high-frequency penalization to compensate the instability of the solution with respect to the data (sometimes called noise amplification or "explosive" solution). Finally, the use of Fourier space implies a circulant property of :math:`H`, see [Hunt]. References ---------- .. [1] François Orieux, Jean-François Giovannelli, and Thomas Rodet, "Bayesian estimation of regularization and point spread function parameters for Wiener-Hunt deconvolution", J. Opt. Soc. Am. A 27, 1593-1607 (2010) http://www.opticsinfobase.org/josaa/abstract.cfm?URI=josaa-27-7-1593 http://research.orieux.fr/files/papers/OGR-JOSA10.pdf .. [2] B. R. Hunt "A matrix theory proof of the discrete convolution theorem", IEEE Trans. on Audio and Electroacoustics, vol. au-19, no. 4, pp. 285-288, dec. 1971 """ if reg is None: reg, _ = uft.laplacian(image.ndim, image.shape, is_real=is_real) if not np.iscomplexobj(reg): reg = uft.ir2tf(reg, image.shape, is_real=is_real) if psf.shape != reg.shape: trans_func = uft.ir2tf(psf, image.shape, is_real=is_real) else: trans_func = psf wiener_filter = np.conj(trans_func) / (np.abs(trans_func) ** 2 + balance * np.abs(reg) ** 2) if is_real: deconv = uft.uirfft2(wiener_filter * uft.urfft2(image), shape=image.shape) else: deconv = uft.uifft2(wiener_filter * uft.ufft2(image)) if clip: deconv[deconv > 1] = 1 deconv[deconv < -1] = -1 return deconv def unsupervised_wiener(image, psf, reg=None, user_params=None, is_real=True, clip=True): """Unsupervised Wiener-Hunt deconvolution. Return the deconvolution with a Wiener-Hunt approach, where the hyperparameters are automatically estimated. The algorithm is a stochastic iterative process (Gibbs sampler) described in the reference below. See also ``wiener`` function. Parameters ---------- image : (M, N) ndarray The input degraded image. psf : ndarray The impulse response (input image's space) or the transfer function (Fourier space). Both are accepted. The transfer function is automatically recognized as being complex (``np.iscomplexobj(psf)``). reg : ndarray, optional The regularisation operator. The Laplacian by default. It can be an impulse response or a transfer function, as for the psf. user_params : dict Dictionary of parameters for the Gibbs sampler. See below. clip : boolean, optional True by default. If true, pixel values of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. Returns ------- x_postmean : (M, N) ndarray The deconvolved image (the posterior mean). chains : dict The keys ``noise`` and ``prior`` contain the chain list of noise and prior precision respectively. Other parameters ---------------- The keys of ``user_params`` are: threshold : float The stopping criterion: the norm of the difference between to successive approximated solution (empirical mean of object samples, see Notes section). 1e-4 by default. burnin : int The number of sample to ignore to start computation of the mean. 15 by default. min_iter : int The minimum number of iterations. 30 by default. max_iter : int The maximum number of iterations if ``threshold`` is not satisfied. 200 by default. callback : callable (None by default) A user provided callable to which is passed, if the function exists, the current image sample for whatever purpose. The user can store the sample, or compute other moments than the mean. It has no influence on the algorithm execution and is only for inspection. Examples -------- >>> from skimage import color, data, restoration >>> img = color.rgb2gray(data.astronaut()) >>> from scipy.signal import convolve2d >>> psf = np.ones((5, 5)) / 25 >>> img = convolve2d(img, psf, 'same') >>> img += 0.1 * img.std() * np.random.standard_normal(img.shape) >>> deconvolved_img = restoration.unsupervised_wiener(img, psf) Notes ----- The estimated image is design as the posterior mean of a probability law (from a Bayesian analysis). The mean is defined as a sum over all the possible images weighted by their respective probability. Given the size of the problem, the exact sum is not tractable. This algorithm use of MCMC to draw image under the posterior law. The practical idea is to only draw highly probable images since they have the biggest contribution to the mean. At the opposite, the less probable images are drawn less often since their contribution is low. Finally the empirical mean of these samples give us an estimation of the mean, and an exact computation with an infinite sample set. References ---------- .. [1] François Orieux, Jean-François Giovannelli, and Thomas Rodet, "Bayesian estimation of regularization and point spread function parameters for Wiener-Hunt deconvolution", J. Opt. Soc. Am. A 27, 1593-1607 (2010) http://www.opticsinfobase.org/josaa/abstract.cfm?URI=josaa-27-7-1593 http://research.orieux.fr/files/papers/OGR-JOSA10.pdf """ params = {'threshold': 1e-4, 'max_iter': 200, 'min_iter': 30, 'burnin': 15, 'callback': None} params.update(user_params or {}) if reg is None: reg, _ = uft.laplacian(image.ndim, image.shape, is_real=is_real) if not np.iscomplexobj(reg): reg = uft.ir2tf(reg, image.shape, is_real=is_real) if psf.shape != reg.shape: trans_fct = uft.ir2tf(psf, image.shape, is_real=is_real) else: trans_fct = psf # The mean of the object x_postmean = np.zeros(trans_fct.shape) # The previous computed mean in the iterative loop prev_x_postmean = np.zeros(trans_fct.shape) # Difference between two successive mean delta = np.NAN # Initial state of the chain gn_chain, gx_chain = [1], [1] # The correlation of the object in Fourier space (if size is big, # this can reduce computation time in the loop) areg2 = np.abs(reg) ** 2 atf2 = np.abs(trans_fct) ** 2 # The Fourier transfrom may change the image.size attribut, so we # store it. if is_real: data_spectrum = uft.urfft2(image.astype(np.float)) else: data_spectrum = uft.ufft2(image.astype(np.float)) # Gibbs sampling for iteration in range(params['max_iter']): # Sample of Eq. 27 p(circX^k | gn^k-1, gx^k-1, y). # weighting (correlation in direct space) precision = gn_chain[-1] * atf2 + gx_chain[-1] * areg2 # Eq. 29 excursion = np.sqrt(0.5) / np.sqrt(precision) * ( np.random.standard_normal(data_spectrum.shape) + 1j * np.random.standard_normal(data_spectrum.shape)) # mean Eq. 30 (RLS for fixed gn, gamma0 and gamma1 ...) wiener_filter = gn_chain[-1] * np.conj(trans_fct) / precision # sample of X in Fourier space x_sample = wiener_filter * data_spectrum + excursion if params['callback']: params['callback'](x_sample) # sample of Eq. 31 p(gn | x^k, gx^k, y) gn_chain.append(npr.gamma(image.size / 2, 2 / uft.image_quad_norm(data_spectrum - x_sample * trans_fct))) # sample of Eq. 31 p(gx | x^k, gn^k-1, y) gx_chain.append(npr.gamma((image.size - 1) / 2, 2 / uft.image_quad_norm(x_sample * reg))) # current empirical average if iteration > params['burnin']: x_postmean = prev_x_postmean + x_sample if iteration > (params['burnin'] + 1): current = x_postmean / (iteration - params['burnin']) previous = prev_x_postmean / (iteration - params['burnin'] - 1) delta = np.sum(np.abs(current - previous)) / \ np.sum(np.abs(x_postmean)) / (iteration - params['burnin']) prev_x_postmean = x_postmean # stop of the algorithm if (iteration > params['min_iter']) and (delta < params['threshold']): break # Empirical average \approx POSTMEAN Eq. 44 x_postmean = x_postmean / (iteration - params['burnin']) if is_real: x_postmean = uft.uirfft2(x_postmean, shape=image.shape) else: x_postmean = uft.uifft2(x_postmean) if clip: x_postmean[x_postmean > 1] = 1 x_postmean[x_postmean < -1] = -1 return (x_postmean, {'noise': gn_chain, 'prior': gx_chain}) def richardson_lucy(image, psf, iterations=50, clip=True): """Richardson-Lucy deconvolution. Parameters ---------- image : ndarray Input degraded image (can be N dimensional). psf : ndarray The point spread function. iterations : int Number of iterations. This parameter plays the role of regularisation. clip : boolean, optional True by default. If true, pixel value of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. Returns ------- im_deconv : ndarray The deconvolved image. Examples -------- >>> from skimage import color, data, restoration >>> camera = color.rgb2gray(data.camera()) >>> from scipy.signal import convolve2d >>> psf = np.ones((5, 5)) / 25 >>> camera = convolve2d(camera, psf, 'same') >>> camera += 0.1 * camera.std() * np.random.standard_normal(camera.shape) >>> deconvolved = restoration.richardson_lucy(camera, psf, 5) References ---------- .. [1] http://en.wikipedia.org/wiki/Richardson%E2%80%93Lucy_deconvolution """ # compute the times for direct convolution and the fft method. The fft is of # complexity O(N log(N)) for each dimension and the direct method does # straight arithmetic (and is O(n*k) to add n elements k times) direct_time = np.prod(image.shape + psf.shape) fft_time = np.sum([n*np.log(n) for n in image.shape + psf.shape]) # see whether the fourier transform convolution method or the direct # convolution method is faster (discussed in scikit-image PR #1792) time_ratio = 40.032 * fft_time / direct_time if time_ratio <= 1 or len(image.shape) > 2: convolve_method = fftconvolve else: convolve_method = convolve image = image.astype(np.float) psf = psf.astype(np.float) im_deconv = 0.5 * np.ones(image.shape) psf_mirror = psf[::-1, ::-1] for _ in range(iterations): relative_blur = image / convolve_method(im_deconv, psf, 'same') im_deconv *= convolve_method(relative_blur, psf_mirror, 'same') if clip: im_deconv[im_deconv > 1] = 1 im_deconv[im_deconv < -1] = -1 return im_deconv
37.893939
80
0.641743
acf6668900f7942713424118a2995e1b8c00403f
5,082
py
Python
python/neptune/source/nutil/stats/lognormal.py
b-io/io.barras
87b103baeb2c14c8d91360bc27b9c0468a2d4e71
[ "MIT" ]
5
2018-08-12T19:48:54.000Z
2021-03-16T12:46:10.000Z
python/neptune/source/nutil/stats/lognormal.py
b-io/io.barras
87b103baeb2c14c8d91360bc27b9c0468a2d4e71
[ "MIT" ]
2
2021-06-12T08:09:24.000Z
2021-12-21T23:08:41.000Z
python/neptune/source/nutil/stats/lognormal.py
b-io/io.barras
87b103baeb2c14c8d91360bc27b9c0468a2d4e71
[ "MIT" ]
null
null
null
#!/usr/bin/env python #################################################################################################### # NAME # <NAME> - contain statistical utility functions # # SYNOPSIS # <NAME> # # AUTHOR # Written by Florian Barras (florian@barras.io). # # COPYRIGHT # Copyright © 2013-2021 Florian Barras <https://barras.io>. # The MIT License (MIT) <https://opensource.org/licenses/MIT>. #################################################################################################### from nutil.stats import normal from nutil.stats.common import * #################################################################################################### # LOG-NORMAL CONSTANTS #################################################################################################### __LOG_NORMAL_CONSTANTS____________________________ = '' LOG_NORMAL_NAME = 'Log-Normal' #################################################################################################### # LOG-NORMAL CLASSES #################################################################################################### __LOG_NORMAL_CLASSES______________________________ = '' class LogNormal(Distribution): def __init__(self, mu=0, sigma=1, series=None, dof=1): super().__init__(LOG_NORMAL_NAME, series=series, dof=dof) if is_null(series): self.mu = mu self.sigma = sigma else: # Estimate the parameters μ and σ of the distribution self.mu = normal.mean(log(series)) self.sigma = normal.std(log(series), dof=dof) ############################################## # OPERATORS ############################################## def __str__(self): return self.name + par(collist(self.mu, self.sigma)) ############################################## # PROCESSORS ############################################## def mean(self): sigma2 = self.sigma ** 2 return exp(self.mu + sigma2 / 2) def median(self): return exp(self.mu) def mode(self): sigma2 = self.sigma ** 2 return exp(self.mu - sigma2) def std(self): return sqrt(self.var()) def var(self): sigma2 = self.sigma ** 2 return exp(2 * self.mu + sigma2) * (exp(sigma2) - 1) def skew(self): sigma2 = self.sigma ** 2 return (exp(sigma2) + 2) * sqrt(exp(sigma2) - 1) def kurtosis(self): sigma2 = self.sigma ** 2 return exp(4 * sigma2) + 2 * exp(3 * sigma2) + 3 * exp(2 * sigma2) - 6 def entropy(self): sigma2 = self.sigma ** 2 return self.mu + log(2 * PI * E * sigma2) / 2 def pdf(self, x): return pdf(x, mu=self.mu, sigma=self.sigma) def cdf(self, x): return cdf(x, mu=self.mu, sigma=self.sigma) def inv_cdf(self, p): return inv_cdf(p, mu=self.mu, sigma=self.sigma) def margin(self, p=DEFAULT_CONFIDENCE_LEVEL, tail=2, mean=False, std=False): if mean or std: # Confidence interval q = normal.quantile(p=p, tail=tail, dof=self.size - 1, std=std) if mean: if self.dof == 0: # Cox's method sigma2 = self.sigma ** 2 s = sqrt(sigma2 / self.size + sigma2 ** 2 / (2 * (self.size - 1))) else: # Angus's conservative method if tail == -1: q = t(p=p, tail=-1, dof=self.size - 1) elif tail == 1: q = sqrt(self.size / 2 * ((self.size - 1) / chi2(self.size - 1, p=p, tail=-1) - 1)) elif tail == 2: p = 0.5 + p / 2 q = to_array(t(p=p, tail=-1, dof=self.size - 1), sqrt(self.size / 2 * ((self.size - 1) / chi2(self.size - 1, p=p, tail=-1) - 1))) sigma2 = self.sigma ** 2 s = sqrt((sigma2 + sigma2 ** 2 / 2) / self.size) return exp(multiply(q, s)) elif std: return exp(multiply(sqrt((self.size - 1) / q), self.sigma)) # Prediction interval return divide(interval(p=p, tail=tail, mu=self.mu, sigma=self.sigma), self.mean()) def interval(self, p=DEFAULT_CONFIDENCE_LEVEL, tail=2, mean=False, std=False): margin = self.margin(p=p, tail=tail, mean=mean, std=std) if std: return multiply(self.std(), margin) return multiply(self.mean(), margin) #################################################################################################### # LOG-NORMAL FUNCTIONS #################################################################################################### __LOG_NORMAL______________________________________ = '' def generate(size=1, mu=0, sigma=1): return np.random.lognormal(mean=mu, sigma=sigma, size=size) ################################################## def pdf(x, mu=0, sigma=1): return stats.lognorm.pdf(x, s=sigma, scale=exp(mu)) def cdf(x, mu=0, sigma=1): return stats.lognorm.cdf(x, s=sigma, scale=exp(mu)) def inv_cdf(p, mu=0, sigma=1): return stats.lognorm.ppf(p, s=sigma, scale=exp(mu)) ######################### def quantile(p=DEFAULT_CONFIDENCE_LEVEL, tail=2, dof=None, mu=0, sigma=1, std=False): if std: return normal.chi2(dof, p=p, tail=tail, sigma=sigma) return apply(inv_cdf, interval_probability(p=p, tail=tail), mu=mu, sigma=sigma) def interval(p=DEFAULT_CONFIDENCE_LEVEL, tail=2, mu=0, sigma=1): return apply(inv_cdf, interval_probability(p=p, tail=tail), mu=mu, sigma=sigma)
30.431138
100
0.514758
acf666e5bcae88f4cd565588eee643d9e06f46e3
237
py
Python
openpipe/about.py
OpenPipe/openpipe
bf00bafc1d9240459dd26873141074b89b53d36f
[ "Apache-2.0" ]
2
2021-01-28T15:33:15.000Z
2022-03-09T10:20:27.000Z
openpipe/about.py
Openpipe/openpipe
bf00bafc1d9240459dd26873141074b89b53d36f
[ "Apache-2.0" ]
35
2019-03-22T10:49:21.000Z
2019-11-29T09:23:47.000Z
openpipe/about.py
OpenPipe/openpipe
bf00bafc1d9240459dd26873141074b89b53d36f
[ "Apache-2.0" ]
1
2022-01-26T22:08:40.000Z
2022-01-26T22:08:40.000Z
__title__ = "Openpipe" __version__ = "1.3.0" __summary__ = "A human friendly data-oriented integration toolkit" __uri__ = "https://www.openpipe.org" __author__ = "João Pinto" __email__ = "lamego.pinto@gmail.com" __license__ = "APACHE-2"
29.625
66
0.746835
acf666faca2fcf544b856b88ccfb72f970c9f066
1,720
py
Python
sbp/__main__.py
ErrorsAndGlitches/collection-day-lambda
6bbdfb37340f7dc20755c628e5293c10f0027f44
[ "MIT" ]
null
null
null
sbp/__main__.py
ErrorsAndGlitches/collection-day-lambda
6bbdfb37340f7dc20755c628e5293c10f0027f44
[ "MIT" ]
3
2019-05-04T00:41:56.000Z
2019-05-10T02:47:50.000Z
sbp/__main__.py
ErrorsAndGlitches/collection-day-lambda
6bbdfb37340f7dc20755c628e5293c10f0027f44
[ "MIT" ]
null
null
null
from argparse import ArgumentParser import boto3 from sbp.sbp_reserve_fitness_notifications import check_fitness_reservations_for_openings DEFAULT_AWS_REGION = 'us-west-2' def args(): parser = ArgumentParser(description='Run sbp reserve fitness notifications locally') # required parser.add_argument('--date', required=True, help='Date of reservation in YYYY-MM-DD format.') parser.add_argument('--start-time', required=True, help='Start time in HH:MM format to search for. Inclusive.') parser.add_argument('--end-time', required=True, help='End time in HH:MM format to search for. Inclusive.') # optional parser.add_argument('--from-email', required=False, help='Address of email sender.') parser.add_argument('--to-email', required=False, help='Address of email recipient.') parser.add_argument('--reservation-type', required=False, default='fitness', help='Reservation type. "climbing" or "fitness". Default: "fitness"') parser.add_argument('--aws-profile', required=False, help='AWS profile to use for credentials') parser.add_argument( '--aws-region', required=False, default=DEFAULT_AWS_REGION, help='AWS region to use; Default: {}'.format(DEFAULT_AWS_REGION) ) return parser.parse_args() def main(): cli_args = args() boto3.setup_default_session(profile_name=cli_args.aws_profile, region_name=cli_args.aws_region) check_fitness_reservations_for_openings( cli_args.date, cli_args.start_time, cli_args.end_time, cli_args.from_email, cli_args.to_email, cli_args.reservation_type, boto3.client('ses') ) if __name__ == '__main__': main()
35.833333
115
0.706395
acf66747f4cf9be1b6f6a745e95387f58cc0304a
43
py
Python
custom_components/consul/const.py
cerebrate/consul
e3e105ac6f38a4caf24c7f5567b66df6c2d1f62a
[ "MIT" ]
1
2021-06-13T20:38:33.000Z
2021-06-13T20:38:33.000Z
custom_components/consul/const.py
cerebrate/consul
e3e105ac6f38a4caf24c7f5567b66df6c2d1f62a
[ "MIT" ]
null
null
null
custom_components/consul/const.py
cerebrate/consul
e3e105ac6f38a4caf24c7f5567b66df6c2d1f62a
[ "MIT" ]
1
2021-09-12T14:33:30.000Z
2021-09-12T14:33:30.000Z
"""Consul constants.""" DOMAIN = "consul"
10.75
23
0.627907
acf667e5972bea98c7da1bcb71c6fb233a5cbaa9
8,737
py
Python
pdf_generator.py
MoritzGuck/CheatSheet_Creator
13fbaf09deae17355a5b9cbed1b6d568a5656110
[ "MIT" ]
1
2020-05-26T08:09:39.000Z
2020-05-26T08:09:39.000Z
pdf_generator.py
MoritzGuck/CheatSheet_Creator
13fbaf09deae17355a5b9cbed1b6d568a5656110
[ "MIT" ]
null
null
null
pdf_generator.py
MoritzGuck/CheatSheet_Creator
13fbaf09deae17355a5b9cbed1b6d568a5656110
[ "MIT" ]
1
2021-09-19T22:03:20.000Z
2021-09-19T22:03:20.000Z
from reportlab.pdfgen import canvas from reportlab.lib import colors from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import SimpleDocTemplate,BaseDocTemplate, TableStyle, PageTemplate, Paragraph, Table, Spacer, Frame from reportlab.lib.units import inch import json import argparse import re import yaml def open_file(file_name): """open files Args: file_name (str): name of input file Raises: TypeError: [description] Returns: [type]: [description] """ if re.match(r'\w+.yml$|\w+.yaml$|\w+.json$', file_name): with open(file_name) as file: dictionary = yaml.load(file, Loader=yaml.FullLoader) else: raise TypeError("wrong file type. please use .json, .yml or .yaml files.") # TODO this could also just be a missing file return dictionary def gen_file_name(output_path, title): """Generates the name of the PDF-file from the "doc title" in the json file. Args: output_path (string): relative output path title (string): title of the file according to content.json Returns: string: file_name of the pdf-file """ file_name = output_path + title + ".pdf" return file_name class Document: """The document class for storing variables for the entire cheatsheet """ def __init__(self, document, design): """ Args: document (Dict): content_file dictionary containting the setup and paragraphs design (Dict): Design_file dictionary containing the stylings """ self.doc_metdata = document["document setup"] self.content = document["paragraphs"] self.design = design self.styles = getSampleStyleSheet() # color converter self.color_dict = { "grey": colors.grey, "black": colors.black, "darkblue": colors.darkblue } def place_doc_title(self, canvas, doc): """places the title at the location defined in design.json Args: canvas (Canvas): canvas object from reportlab doc (string): Title of the document """ x = self.design["doc title"]["x"] y = self.design["doc title"]["y"] size = self.design["doc title"]["size"] doc_title = self.doc_metdata["doc title"] # Place title: canvas.saveState() canvas.setFont("Helvetica-Bold", 16) canvas.drawString(x, y, doc_title) canvas.restoreState() def merge_paragraphs_from_content(self): """Concatenate the paragraphs defined in the content file Returns: story (List): list of paragraph objects that are than used to fill the object """ story = [] for paragraph_obj in self.content: if "table" in paragraph_obj.keys(): table_obj = self.format_table_content(paragraph_obj["table"], self.design["table style"]) paragraph = self.define_table_paragraph(paragraph_obj["title"], table_obj) elif "text" in paragraph_obj.keys(): paragraph = self.define_text_paragraph(paragraph_obj["title"], paragraph_obj["text"]) story.append(paragraph[0]) story.append(paragraph[1]) return story def define_text_paragraph(self, title, text): """Put together title and text of a paragraph Args: title (string): Title of the paragraph text (string): Text of the paragraph Returns: list: paragraph-object for title, paragraph-object for text """ title_style = self.styles["Heading2"] title_style.fontSize = self.design["par style"]["font-size title"] paragraph_title = Paragraph(title, title_style) text_style = self.styles["Normal"] text_style.fontSize = self.design["par style"]["font-size text"] paragraph_text = Paragraph(text, text_style) return [paragraph_title, paragraph_text] def format_table_content(self, table_content, table_style_specs): # TODO: might be better to fetch the table_style_specs (via design) directly from the document object """Format the content of the separate table cells via paragraph styles Args: table_content (Dict): Unformatted table content table_style_spec (Dict): table style specifications from design.json Returns: table (Table-obj): The same content, but now within Paragraphs """ # Define grid table_style = TableStyle() if table_style_specs["grid lines"] == True: table_style.add("GRID", (0, 0), (-1, -1), 0.5, self.color_dict[table_style_specs["grid color"]]) # add the content and format text n_rows = len(table_content) n_cols = len(table_content[0]) content_style = self.styles["Normal"] # every cell is a paragraph with its style content_style.fontSize = table_style_specs["font-size"] for row_idx in range(0, n_rows): for col_idx in range(0, n_cols): if "font left column" in table_style_specs.keys() and col_idx == 0: content_style.fontName = table_style_specs["font left column"] if "font right column" in table_style_specs.keys() and col_idx == n_cols-1: content_style.fontName = table_style_specs["font right column"] table_content[row_idx][col_idx] = Paragraph(table_content[row_idx][col_idx], content_style) table = Table(table_content, style=table_style) return Table(table_content, style=table_style) # table_content, style_list def define_table_paragraph(self, title, table): """Put together title and text of a paragraph Args: title (string): Title of the paragraph table (Reportlab table_obj): contains the formatted table Returns: list: paragraph-object for title, paragraph-object for text """ paragraph_title = Paragraph(title, self.styles["Heading2"]) paragraph_title.fontSize = self.design["par style"]["font-size title"] table.hAlign = "LEFT" return [paragraph_title, table] def page_template(self, page_width, page_height, n_cols, first_page = False): """defines the page template for the cheat sheet Args: page_width (int): width of the shee in img points page_height (int): height of the sheet in img points n_cols (int): number of columns in the file first_page (bool, optional): defines, if it is the first page - if yes, than there is additional space for header. Defaults to False. Returns: page_template (Reportlab PageTemplate): page template object """ left_margin = 20 right_margin = 20 top_margin = 20 bottom_margin = 20 spacer_betw_cols = 20 first_page_top_spacer = 40 col_width = (page_width-left_margin-right_margin-spacer_betw_cols*2)/n_cols col_height = page_height - top_margin - bottom_margin if first_page: col_height = col_height - first_page_top_spacer page_frame_left = Frame(x1 = left_margin, y1 = bottom_margin, width = col_width, height = col_height, id=None, showBoundary=0) page_frame_middle = Frame(left_margin+col_width+spacer_betw_cols, bottom_margin, col_width, col_height, id=None, showBoundary=0) page_frame_right = Frame(left_margin+2*col_width+2*spacer_betw_cols, bottom_margin, col_width, col_height, id=None, showBoundary=0) page_template = PageTemplate(frames=[page_frame_left, page_frame_middle, page_frame_right], onPage=self.place_doc_title) return page_template if __name__ == "__main__": # parse arguments: parser = argparse.ArgumentParser(description="create combinations of shapelets") parser.add_argument("--c", required=False, help="relative path and name of contentfile.json", default="content.json") parser.add_argument("--o", required=False, help="relative path to output folder", default="./pdfs/") args = parser.parse_args() # open files: document = open_file(args.c) # open content file design = open_file(document["document setup"]["design file"]) # set up cheat sheet doc_obj = Document(document, design) first_page_template = doc_obj.page_template(841.89,595.27, 3, True) output_doc = BaseDocTemplate(filename=gen_file_name(args.o, document["document setup"]["doc title"]), pagesize=(841.89,595.27), pageTemplates=[first_page_template]) story = doc_obj.merge_paragraphs_from_content() output_doc.build(story)
44.805128
171
0.657091
acf668708cbc18ba06c8089ec35ff1d7fa72bec0
2,206
py
Python
tests/intergration/test_lock_io.py
phillmac/dagr_revamped
61e3f0485896eb85f099629fa2de82f574372477
[ "MIT" ]
null
null
null
tests/intergration/test_lock_io.py
phillmac/dagr_revamped
61e3f0485896eb85f099629fa2de82f574372477
[ "MIT" ]
5
2021-01-08T09:38:35.000Z
2021-12-16T22:48:06.000Z
tests/intergration/test_lock_io.py
phillmac/dagr_revamped
61e3f0485896eb85f099629fa2de82f574372477
[ "MIT" ]
null
null
null
import logging import unittest from os import urandom from pathlib import Path from dagr_revamped.exceptions import DagrCacheLockException from io_tests_setup import (create_io, select_io_class, setUpTestCase, tearDownTestCase) class TestIO(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.container = None self.results_dir = None def containerLogs(self): for log_item in self.container.logs(stdout=True, stderr=True, stream=True, follow=False): logging.info(log_item.decode('utf-8')) def setUp(self): setUpTestCase(self) def test_lock(self): result = None lockdir = self.results_dir.joinpath('lockdir') lockdir.mkdir() with create_io(self, select_io_class(), base_dir=lockdir, rel_dir=lockdir.name) as io: try: io.lock() try: with create_io(self, select_io_class(), base_dir=lockdir, rel_dir=lockdir.name) as io2: io2.lock() except DagrCacheLockException: result = True except: logging.exception('Failed to lock dir') self.containerLogs() self.assertTrue(result is True) def test_rentrant_lock(self): result = None r_lockdir = self.results_dir.joinpath('rlockdir') r_lockdir.mkdir() with create_io(self, select_io_class(), base_dir=r_lockdir, rel_dir=r_lockdir.name) as io: try: io.lock() with io: io.lock() try: with create_io(self, select_io_class(), base_dir=r_lockdir, rel_dir=r_lockdir.name) as io2: io2.lock() except DagrCacheLockException: result = True result = True except: logging.exception('Failed to lock dir') self.containerLogs() self.assertTrue(result is True) def tearDown(self): tearDownTestCase(self) if __name__ == '__main__': unittest.main()
30.638889
111
0.575703
acf6687ea265ba9064631164b9adabbad52391d5
5,398
py
Python
desktop/core/ext-py/Django-1.11/tests/flatpages_tests/test_forms.py
kokosing/hue
2307f5379a35aae9be871e836432e6f45138b3d9
[ "Apache-2.0" ]
5,079
2015-01-01T03:39:46.000Z
2022-03-31T07:38:22.000Z
tests/flatpages_tests/test_forms.py
287977288/test
142e3626ab3c676574631383ae6b5a4eced5a10e
[ "PSF-2.0", "BSD-3-Clause" ]
1,623
2015-01-01T08:06:24.000Z
2022-03-30T19:48:52.000Z
tests/flatpages_tests/test_forms.py
287977288/test
142e3626ab3c676574631383ae6b5a4eced5a10e
[ "PSF-2.0", "BSD-3-Clause" ]
2,033
2015-01-04T07:18:02.000Z
2022-03-28T19:55:47.000Z
from __future__ import unicode_literals from django.conf import settings from django.contrib.flatpages.forms import FlatpageForm from django.contrib.flatpages.models import FlatPage from django.contrib.sites.models import Site from django.test import TestCase, modify_settings, override_settings from django.utils import translation @modify_settings(INSTALLED_APPS={'append': ['django.contrib.flatpages', ]}) @override_settings(SITE_ID=1) class FlatpageAdminFormTests(TestCase): @classmethod def setUpTestData(cls): # don't use the manager because we want to ensure the site exists # with pk=1, regardless of whether or not it already exists. cls.site1 = Site(pk=1, domain='example.com', name='example.com') cls.site1.save() def setUp(self): # Site fields cache needs to be cleared after flatpages is added to # INSTALLED_APPS Site._meta._expire_cache() self.form_data = { 'title': "A test page", 'content': "This is a test", 'sites': [settings.SITE_ID], } def test_flatpage_admin_form_url_validation(self): "The flatpage admin form correctly validates urls" self.assertTrue(FlatpageForm(data=dict(url='/new_flatpage/', **self.form_data)).is_valid()) self.assertTrue(FlatpageForm(data=dict(url='/some.special~chars/', **self.form_data)).is_valid()) self.assertTrue(FlatpageForm(data=dict(url='/some.very_special~chars-here/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a space/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a % char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a ! char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a & char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a ? char/', **self.form_data)).is_valid()) def test_flatpage_requires_leading_slash(self): form = FlatpageForm(data=dict(url='no_leading_slash/', **self.form_data)) with translation.override('en'): self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a leading slash."]) @override_settings(APPEND_SLASH=True, MIDDLEWARE=['django.middleware.common.CommonMiddleware']) def test_flatpage_requires_trailing_slash_with_append_slash(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) with translation.override('en'): self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."]) @override_settings(APPEND_SLASH=False, MIDDLEWARE=['django.middleware.common.CommonMiddleware']) def test_flatpage_doesnt_requires_trailing_slash_without_append_slash(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) self.assertTrue(form.is_valid()) @override_settings( APPEND_SLASH=True, MIDDLEWARE=None, MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware'], ) def test_flatpage_requires_trailing_slash_with_append_slash_middleware_classes(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) with translation.override('en'): self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."]) @override_settings( APPEND_SLASH=False, MIDDLEWARE=None, MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware'], ) def test_flatpage_doesnt_requires_trailing_slash_without_append_slash_middleware_classes(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) self.assertTrue(form.is_valid()) def test_flatpage_admin_form_url_uniqueness_validation(self): "The flatpage admin form correctly enforces url uniqueness among flatpages of the same site" data = dict(url='/myflatpage1/', **self.form_data) FlatpageForm(data=data).save() f = FlatpageForm(data=data) with translation.override('en'): self.assertFalse(f.is_valid()) self.assertEqual( f.errors, {'__all__': ['Flatpage with url /myflatpage1/ already exists for site example.com']}) def test_flatpage_admin_form_edit(self): """ Existing flatpages can be edited in the admin form without triggering the url-uniqueness validation. """ existing = FlatPage.objects.create( url="/myflatpage1/", title="Some page", content="The content") existing.sites.add(settings.SITE_ID) data = dict(url='/myflatpage1/', **self.form_data) f = FlatpageForm(data=data, instance=existing) self.assertTrue(f.is_valid(), f.errors) updated = f.save() self.assertEqual(updated.title, "A test page") def test_flatpage_nosites(self): data = dict(url='/myflatpage1/', **self.form_data) data.update({'sites': ''}) f = FlatpageForm(data=data) self.assertFalse(f.is_valid()) self.assertEqual( f.errors, {'sites': [translation.ugettext('This field is required.')]})
43.184
115
0.680993
acf6689e4292ebe7b25cc92a34f302f4d29d7e39
25,872
py
Python
modules/dashboard/filer.py
dannielarriola/uai-coursebuilder
fbd440a8bfe1a928ac52985aea2949d5e91ad203
[ "Apache-2.0" ]
null
null
null
modules/dashboard/filer.py
dannielarriola/uai-coursebuilder
fbd440a8bfe1a928ac52985aea2949d5e91ad203
[ "Apache-2.0" ]
27
2016-08-31T19:04:46.000Z
2016-09-29T00:22:32.000Z
modules/dashboard/filer.py
dannielarriola/uai-coursebuilder
fbd440a8bfe1a928ac52985aea2949d5e91ad203
[ "Apache-2.0" ]
null
null
null
# Copyright 2012 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. """Classes supporting online file editing.""" __author__ = 'Pavel Simakov (psimakov@google.com)' import base64 import cgi import collections import os import urllib import yaml import appengine_config from common import schema_fields from common import users from controllers.utils import ApplicationHandler from controllers.utils import BaseRESTHandler from controllers.utils import XsrfTokenManager from models import courses from models import roles from models import transforms from models import vfs from modules.dashboard import asset_paths from modules.dashboard import messages from modules.dashboard import utils as dashboard_utils from modules.oeditor import oeditor MAX_ASSET_UPLOAD_SIZE_K = 500 def is_text_payload(payload): try: transforms.dumps(payload) return True except: # All errors are equivalently bad. pylint: disable=bare-except return False def is_readonly_asset(asset): return not getattr(asset, 'metadata', None) class FilesRights(object): """Manages view/edit rights for files.""" @classmethod def can_view(cls, handler): return roles.Roles.is_course_admin(handler.app_context) @classmethod def can_edit(cls, handler): return roles.Roles.is_course_admin(handler.app_context) @classmethod def can_delete(cls, handler): return cls.can_edit(handler) @classmethod def can_add(cls, handler): return cls.can_edit(handler) class FileManagerAndEditor(ApplicationHandler): """An editor for editing and managing files.""" _ASSET_TYPE_TO_CODEMIRROR_MODE = { 'js':'javascript', 'css':'css', 'templates':'htmlmixed', 'html':'htmlmixed', } local_fs = vfs.LocalReadOnlyFileSystem(logical_home_folder='/') def _get_delete_url(self, base_url, key, xsrf_token_name): return '%s?%s' % ( self.canonicalize_url(base_url), urllib.urlencode({ 'key': key, 'xsrf_token': cgi.escape( self.create_xsrf_token(xsrf_token_name)), })) def post_create_or_edit_settings(self): """Handles creation or/and editing of course.yaml.""" create_course_file_if_not_exists(self) extra_args = {} from_action = self.request.get('from_action') if from_action: extra_args['from_action'] = from_action self.redirect(self.get_action_url('edit_settings', key='/course.yaml', extra_args=extra_args)) def get_edit_settings(self): """Shows editor for course.yaml.""" key = self.request.get('key') from_action = self.request.get('from_action') exit_url = self.canonicalize_url( '/dashboard?action={}'.format(from_action)) rest_url = self.canonicalize_url('/rest/files/item') form_html = oeditor.ObjectEditor.get_html_for( self, FilesItemRESTHandler.SCHEMA_JSON, FilesItemRESTHandler.SCHEMA_ANNOTATIONS_DICT, key, rest_url, exit_url, required_modules=FilesItemRESTHandler.REQUIRED_MODULES) template_values = {} template_values['page_title'] = self.format_title('Edit Settings') template_values['main_content'] = form_html self.render_page(template_values, in_action=from_action) def get_manage_asset(self): """Show an upload/delete dialog for assets.""" path = self.request.get('key') key = asset_paths.as_key(path) if not asset_paths.AllowedBases.is_path_allowed(path): raise ValueError('Cannot add/edit asset with key "%s" ' % key + 'which is not under a valid asset path') fs = self.app_context.fs.impl delete_url = None delete_method = None delete_message = None auto_return = False if fs.isfile(fs.physical_to_logical(key)): delete_url = self._get_delete_url( FilesItemRESTHandler.URI, key, 'delete-asset') delete_method = 'delete' else: # Sadly, since we don't know the name of the asset when we build # the form, the form can't update itself to show the uploaded # asset when the upload completes. Rather than continue to # show a blank form, bring the user back to the assets list. auto_return = True details = AssetItemRESTHandler.get_schema_details(path) json, ann = details.json, details.annotations from_action = self.request.get('from_action') exit_url = self.canonicalize_url( dashboard_utils.build_assets_url(from_action)) rest_url = self.canonicalize_url(AssetItemRESTHandler.URI) form_html = oeditor.ObjectEditor.get_html_for( self, json, ann, key, rest_url, exit_url, save_method='upload', save_button_caption='Upload', auto_return=auto_return, delete_url=delete_url, delete_method=delete_method, delete_message=delete_message, required_modules=AssetItemRESTHandler.REQUIRED_MODULES, additional_dirs=[os.path.join(dashboard_utils.RESOURCES_DIR, 'js')]) template_values = {} template_values['page_title'] = self.format_title('Manage Asset') template_values['main_content'] = form_html self.render_page(template_values, in_action=from_action) def get_manage_text_asset(self): """Show an edit/save/delete/revert form for a text asset.""" assert self.app_context.is_editable_fs() uri = self.request.get('uri') assert uri asset_type = self.request.get('type') from_action = self.request.get('from_action') mode = self._ASSET_TYPE_TO_CODEMIRROR_MODE.get(asset_type, '') asset = self.app_context.fs.impl.get( os.path.join(appengine_config.BUNDLE_ROOT, uri)) assert asset asset_in_datastore_fs = not is_readonly_asset(asset) try: asset_in_local_fs = bool(self.local_fs.get(uri)) except IOError: asset_in_local_fs = False exit_url = self.get_action_url(from_action) rest_url = self.canonicalize_url(TextAssetRESTHandler.URI) delete_button_caption = 'Delete' delete_message = None delete_url = None if asset_in_datastore_fs: delete_message = 'Are you sure you want to delete %s?' % uri delete_url = self._get_delete_url( TextAssetRESTHandler.URI, uri, TextAssetRESTHandler.XSRF_TOKEN_NAME) if asset_in_local_fs: delete_message = ( 'Are you sure you want to restore %s to the original version? ' 'All your customizations will be lost.' % uri) delete_button_caption = 'Restore original' # Disable the save button if the payload is not text by setting method # to ''. save_method = 'put' if is_text_payload(asset.read()) else '' schema = TextAssetRESTHandler.get_asset_schema(mode) form_html = oeditor.ObjectEditor.get_html_for( self, schema.get_json_schema(), schema.get_schema_dict(), uri, rest_url, exit_url, delete_button_caption=delete_button_caption, delete_method='delete', delete_message=delete_message, delete_url=delete_url, required_modules=TextAssetRESTHandler.REQUIRED_MODULES, save_method=save_method, ) self.render_page({ 'page_title': self.format_title('Edit ' + uri), 'main_content': form_html, }, in_action=from_action) def create_course_file_if_not_exists(handler): assert handler.app_context.is_editable_fs() # Check if course.yaml exists; create if not. fs = handler.app_context.fs.impl course_yaml = fs.physical_to_logical('/course.yaml') if not fs.isfile(course_yaml): fs.put(course_yaml, vfs.string_to_stream( courses.Course.EMPTY_COURSE_YAML % users.get_current_user().email())) class TextAssetRESTHandler(BaseRESTHandler): """REST endpoints for text assets.""" ERROR_MESSAGE_UNEDITABLE = ( 'Error: contents are not text and cannot be edited.') REQUIRED_MODULES = [ 'inputex-hidden', 'inputex-textarea', 'gcb-code', ] URI = '/rest/assets/text' XSRF_TOKEN_NAME = 'manage-text-asset' @classmethod def get_asset_schema(cls, mode): schema = schema_fields.FieldRegistry('Edit asset', description='Text Asset', extra_schema_dict_values={ 'className':'inputEx-Group new-form-layout hidden-header' }) schema.add_property(schema_fields.SchemaField( 'contents', 'Contents', 'text', extra_schema_dict_values={ 'mode': mode, '_type': 'code', 'large': True, }, )) schema.add_property(schema_fields.SchemaField( 'is_text', 'Is Text', 'boolean', hidden=True, )) schema.add_property(schema_fields.SchemaField( 'readonly', 'ReadOnly', 'boolean', hidden=True, )) return schema def delete(self): """Handles the delete verb.""" assert self.app_context.is_editable_fs() filename = self.request.get('key') if not (filename and self.assert_xsrf_token_or_fail( self.request, self.XSRF_TOKEN_NAME, {'key': filename})): return if not FilesRights.can_delete(self): transforms.send_json_response( self, 401, 'Access denied.', {'key': filename}) return if not asset_paths.AllowedBases.is_path_allowed(filename): transforms.send_json_response( self, 400, 'Malformed request.', {'key': filename}) return self.app_context.fs.impl.delete( os.path.join(appengine_config.BUNDLE_ROOT, filename)) transforms.send_json_response(self, 200, 'Done.') def get(self): """Handles the get verb.""" assert FilesRights.can_edit(self) filename = self.request.get('key') assert filename asset = self.app_context.fs.impl.get( os.path.join(appengine_config.BUNDLE_ROOT, filename)) assert asset contents = asset.read() is_text = is_text_payload(contents) if not is_text: contents = self.ERROR_MESSAGE_UNEDITABLE json_message = 'Success.' if is_text else self.ERROR_MESSAGE_UNEDITABLE json_payload = { 'contents': contents, 'is_text': is_text, 'readonly': is_readonly_asset(asset), } transforms.send_json_response( self, 200, json_message, payload_dict=json_payload, xsrf_token=XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN_NAME)) def put(self): """Handles the put verb.""" assert self.app_context.is_editable_fs() request = self.request.get('request') assert request request = transforms.loads(request) payload = transforms.loads(request.get('payload')) filename = request.get('key') if not (filename and self.assert_xsrf_token_or_fail( request, self.XSRF_TOKEN_NAME, {'key': filename})): return if not FilesRights.can_edit(self): transforms.send_json_response( self, 401, 'Access denied.', {'key': filename}) return if not asset_paths.AllowedBases.is_path_allowed(filename): transforms.send_json_response( self, 400, 'Malformed request.', {'key': filename}) return self.app_context.fs.impl.put( os.path.join(appengine_config.BUNDLE_ROOT, filename), vfs.string_to_stream(unicode(payload.get('contents')))) transforms.send_json_response(self, 200, 'Saved.') class FilesItemRESTHandler(BaseRESTHandler): """Provides REST API for a file.""" SCHEMA_JSON = """ { "id": "Text File", "type": "object", "description": "Text File", "properties": { "key" : {"type": "string"}, "encoding" : {"type": "string"}, "content": {"type": "text"} } } """ SCHEMA_DICT = transforms.loads(SCHEMA_JSON) SCHEMA_ANNOTATIONS_DICT = [ (['title'], 'Text File'), (['properties', 'key', '_inputex'], { 'label': 'ID', '_type': 'uneditable'}), (['properties', 'encoding', '_inputex'], { 'label': 'Encoding', '_type': 'uneditable'}), (['properties', 'content', '_inputex'], { 'label': 'Content', '_type': 'text'})] REQUIRED_MODULES = [ 'inputex-string', 'inputex-textarea', 'inputex-select', 'gcb-uneditable'] URI = '/rest/files/item' FILE_ENCODING_TEXT = 'text/utf-8' FILE_ENCODING_BINARY = 'binary/base64' FILE_EXTENSION_TEXT = frozenset(['.js', '.css', '.yaml', '.html', '.csv']) @classmethod def is_text_file(cls, filename): for extention in cls.FILE_EXTENSION_TEXT: if filename.endswith(extention): return True return False def validate_content(self, filename, content): # TODO(psimakov): handle more file types here if filename == '/course.yaml': courses.Course.validate_course_yaml(content, self.get_course()) elif filename.endswith('.yaml'): yaml.safe_load(content) def get(self): """Handles REST GET verb and returns an object as JSON payload.""" assert self.app_context.is_editable_fs() key = self.request.get('key') if not FilesRights.can_view(self): transforms.send_json_response( self, 401, 'Access denied.', {'key': key}) return # Load data if possible. fs = self.app_context.fs.impl filename = fs.physical_to_logical(key) try: stream = fs.get(filename) except: # pylint: disable=bare-except stream = None if not stream: transforms.send_json_response( self, 404, 'Object not found.', {'key': key}) return # Prepare data. entity = {'key': key} if self.is_text_file(key): entity['encoding'] = self.FILE_ENCODING_TEXT entity['content'] = vfs.stream_to_string(stream) else: entity['encoding'] = self.FILE_ENCODING_BINARY entity['content'] = base64.b64encode(stream.read()) # Render JSON response. json_payload = transforms.dict_to_json(entity) transforms.send_json_response( self, 200, 'Success.', payload_dict=json_payload, xsrf_token=XsrfTokenManager.create_xsrf_token( 'file-put')) def put(self): """Handles REST PUT verb with JSON payload.""" assert self.app_context.is_editable_fs() request = transforms.loads(self.request.get('request')) key = request.get('key') if not self.assert_xsrf_token_or_fail( request, 'file-put', {'key': key}): return # TODO(psimakov): we don't allow editing of all files; restrict further if not FilesRights.can_edit(self): transforms.send_json_response( self, 401, 'Access denied.', {'key': key}) return payload = request.get('payload') entity = transforms.loads(payload) encoding = entity['encoding'] content = entity['content'] # Validate the file content. errors = [] try: if encoding == self.FILE_ENCODING_TEXT: content_stream = vfs.string_to_stream(content) elif encoding == self.FILE_ENCODING_BINARY: content_stream = base64.b64decode(content) else: errors.append('Unknown encoding: %s.' % encoding) self.validate_content(key, content) except Exception as e: # pylint: disable=W0703 errors.append('Validation error: %s' % e) if errors: transforms.send_json_response(self, 412, ''.join(errors)) return # Store new file content. fs = self.app_context.fs.impl filename = fs.physical_to_logical(key) fs.put(filename, content_stream) # Send reply. transforms.send_json_response(self, 200, 'Saved.') def delete(self): """Handles REST DELETE verb.""" key = self.request.get('key') if not self.assert_xsrf_token_or_fail( self.request, 'delete-asset', {'key': key}): return if not FilesRights.can_delete(self): transforms.send_json_response( self, 401, 'Access denied.', {'key': key}) return fs = self.app_context.fs.impl path = fs.physical_to_logical(key) if not fs.isfile(path): transforms.send_json_response( self, 403, 'File does not exist.', None) return fs.delete(path) transforms.send_json_response(self, 200, 'Deleted.') def generate_asset_rest_handler_schema(name, description, displayable=False): """Helper function for building schemas of asset-handling OEditor UIs.""" schema = schema_fields.FieldRegistry('Asset', description='Asset') schema.add_property(schema_fields.SchemaField( 'file', name, 'file', description=description)) schema.add_property(schema_fields.SchemaField( 'key', 'Key', 'string', editable=False, hidden=True)) schema.add_property(schema_fields.SchemaField( 'base', 'Base', 'string', editable=False, hidden=True)) location_dict = {} if displayable: location_dict['visu'] = { 'visuType': 'funcName', 'funcName': 'renderAsset'} schema.add_property(schema_fields.SchemaField( 'asset_url', 'Location', 'string', editable=False, optional=True, extra_schema_dict_values=location_dict)) return schema _SchemaDetails = collections.namedtuple('_SchemaDetails', ['json', 'annotations']) def _asset_schema_details(schema): return _SchemaDetails(json=schema.get_json_schema(), annotations=schema.get_schema_dict()) class AssetItemRESTHandler(BaseRESTHandler): """Provides REST API for managing assets.""" URI = '/rest/assets/item' REQUIRED_MODULES = [ 'inputex-string', 'gcb-uneditable', 'inputex-file', 'inputex-hidden', 'io-upload-iframe'] XSRF_TOKEN_NAME = 'asset-upload' # Two-tuples of JSON schema (from get_json_schema()) and annotations # dict (from get_schema_dict()) from customized schemas corresponding # to specific "base" asset path prefixes (see asset_paths.as_base). _SCHEMAS = { '/assets/css/': _asset_schema_details( generate_asset_rest_handler_schema( 'Upload New CSS', messages.IMAGES_DOCS_UPLOAD_NEW_CSS_DESCRIPTION)), '/assets/html/': _asset_schema_details( generate_asset_rest_handler_schema( 'Upload New HTML', messages.IMAGES_DOCS_UPLOAD_NEW_HTML_DESCRIPTION)), '/assets/lib/': _asset_schema_details( generate_asset_rest_handler_schema( 'Upload New JavaScript', messages.IMAGES_DOCS_UPLOAD_NEW_JS_DESCRIPTION)), '/views/': _asset_schema_details( generate_asset_rest_handler_schema( 'Upload New Template', messages.IMAGES_DOCS_UPLOAD_NEW_TEMPLATE_DESCRIPTION)), '/assets/img/': _asset_schema_details( generate_asset_rest_handler_schema( 'Upload New Image', messages.IMAGES_DOCS_UPLOAD_NEW_IMAGE_DESCRIPTION, displayable=True)), } # Two-tuple like those in _SCHEMAS above, but generic, for use when the # asset path prefix is not found in the _SCHEMAS keys. _UNKNOWN_SCHEMA = _asset_schema_details( generate_asset_rest_handler_schema( 'Upload New File', messages.IMAGES_DOCS_UPLOAD_NEW_FILE_DESCRIPTION)) @classmethod def get_schema_details(cls, path): for base in cls._SCHEMAS.keys(): if asset_paths.does_path_match_base(path, base): return cls._SCHEMAS[base] return cls._UNKNOWN_SCHEMA def _can_write_payload_to_base(self, payload, base): """Determine if a given payload type can be put in a base directory.""" # Binary data can go in images; text data can go anywhere else. if asset_paths.AllowedBases.is_path_allowed( base, bases=asset_paths.AllowedBases.binary_bases()): return True else: return (is_text_payload(payload) and asset_paths.AllowedBases.is_path_allowed( base, bases=asset_paths.AllowedBases.text_bases())) def get(self): """Provides empty initial content for asset upload editor.""" # TODO(jorr): Pass base URI through as request param when generalized. key = self.request.get('key') base = asset_paths.AllowedBases.match_allowed_bases(key) if not base: transforms.send_json_response( self, 400, 'Malformed request.', {'key': key}) return json_payload = { 'key': key, 'base': base, } fs = self.app_context.fs.impl if fs.isfile(fs.physical_to_logical(key)): json_payload['asset_url'] = key else: json_payload['asset_url'] = asset_paths.relative_base(base) transforms.send_json_response( self, 200, 'Success.', payload_dict=json_payload, xsrf_token=XsrfTokenManager.create_xsrf_token(self.XSRF_TOKEN_NAME)) def post(self): is_valid, payload, upload = self._validate_post() if is_valid: key = payload['key'] base = asset_paths.as_key(payload['base']) if key == base: # File name not given on setup; we are uploading a new file. filename = os.path.split(self.request.POST['file'].filename)[1] physical_path = os.path.join(base, filename) is_overwrite_allowed = False else: # File name already established on setup; use existing # file's name and uploaded file's data. physical_path = key is_overwrite_allowed = True self._handle_post(physical_path, is_overwrite_allowed, upload) def _validate_post(self): """Handles asset uploads.""" assert self.app_context.is_editable_fs() if not FilesRights.can_add(self): transforms.send_file_upload_response( self, 401, 'Access denied.') return False, None, None request = transforms.loads(self.request.get('request')) if not self.assert_xsrf_token_or_fail(request, self.XSRF_TOKEN_NAME, None): return False, None, None upload = self.request.POST['file'] if not isinstance(upload, cgi.FieldStorage): transforms.send_file_upload_response( self, 403, 'No file specified.') return False, None, None payload = transforms.loads(request['payload']) base = payload['base'] if not asset_paths.AllowedBases.is_path_allowed(base): transforms.send_file_upload_response( self, 400, 'Malformed request.', {'key': base}) return False, None, None content = upload.file.read() if not self._can_write_payload_to_base(content, base): transforms.send_file_upload_response( self, 403, 'Cannot write binary data to %s.' % base) return False, None, None if len(content) > MAX_ASSET_UPLOAD_SIZE_K * 1024: transforms.send_file_upload_response( self, 403, 'Max allowed file upload size is %dK' % MAX_ASSET_UPLOAD_SIZE_K) return False, None, None return True, payload, upload def _handle_post(self, physical_path, is_overwrite_allowed, upload): fs = self.app_context.fs.impl path = fs.physical_to_logical(physical_path) if fs.isfile(path): if not is_overwrite_allowed: transforms.send_file_upload_response( self, 403, 'Cannot overwrite existing file.') return else: fs.delete(path) upload.file.seek(0) fs.put(path, upload.file) transforms.send_file_upload_response(self, 200, 'Saved.')
36.439437
80
0.618584
acf668d7f223da97cf7f9b87c3a70d44b3fea68c
771
py
Python
cyder/core/task/models.py
drkitty/cyder
1babc443cc03aa51fa3c1015bcd22f0ea2e5f0f8
[ "BSD-3-Clause" ]
6
2015-04-16T23:18:22.000Z
2020-08-25T22:50:13.000Z
cyder/core/task/models.py
drkitty/cyder
1babc443cc03aa51fa3c1015bcd22f0ea2e5f0f8
[ "BSD-3-Clause" ]
267
2015-01-01T00:18:57.000Z
2015-10-14T00:01:13.000Z
cyder/core/task/models.py
drkitty/cyder
1babc443cc03aa51fa3c1015bcd22f0ea2e5f0f8
[ "BSD-3-Clause" ]
5
2015-03-23T00:57:09.000Z
2019-09-09T22:42:37.000Z
from django.db import models class DNSManager(models.Manager): def get_queryset(self): return super(DNSManager, self).get_queryset().filter(ttype='dns') class Task(models.Model): task = models.CharField(max_length=255, blank=False) ttype = models.CharField(max_length=255, blank=False) objects = models.Manager() dns = DNSManager() class Meta: app_label = 'cyder' db_table = u'task' ordering = ['task'] def __repr__(self): return "<Task: {0}>".format(self) def __str__(self): return "{0} {1}".format(self.ttype, self.task) def save(self): super(Task, self).save() @staticmethod def schedule_zone_rebuild(soa): Task(task=str(soa.pk), ttype='dns').save()
23.363636
73
0.627756
acf66a8bd443fa0d4d7915f476273290f694fece
1,079
py
Python
core/views.py
uadson/django-api-user-register
d09415c84e5a563566e83c544dd9edf47d991280
[ "MIT" ]
1
2021-11-17T02:41:45.000Z
2021-11-17T02:41:45.000Z
core/views.py
uadson/django-api-user-register
d09415c84e5a563566e83c544dd9edf47d991280
[ "MIT" ]
2
2021-11-16T15:37:39.000Z
2021-11-16T15:37:51.000Z
core/views.py
uadson/django-api-user-register
d09415c84e5a563566e83c544dd9edf47d991280
[ "MIT" ]
null
null
null
from django.http import JsonResponse from .models import Client from .forms import ClientForm from django.contrib import messages from django.views.generic import FormView from django.urls import reverse_lazy # Function Based View def json_view(request): # getting data from models and returning in json format clients = Client.objects.all() data = [client.to_dict_json() for client in clients] response = {'data': data} return JsonResponse(response) # Class Based Views class IndexFormView(FormView): template_name = 'core/index.html' form_class = ClientForm success_url = reverse_lazy('core:json_view') def form_valid(self, form, *args, **kwargs): form.save() messages.success(self.request, 'Usuário cadastrado com sucesso!') return super(IndexFormView, self).form_valid(form, *args, **kwargs) def form_invalid(self, form, *args, **kwargs): messages.error(self.request, 'Ocorreu um erro. Verifique os dados informados!') return super(IndexFormView, self).form_invalid(form, *args, **kwargs)
33.71875
87
0.723818
acf66aaf58a311bb817fbf7907d7558d00bdd03d
2,786
py
Python
TensorFlow/KernelPrediction.py
DeepBlender/DeepDenoiser
ba4cee09ea3dbd7b2d1505fcb232bdb81323122f
[ "Apache-2.0" ]
99
2018-05-06T02:10:37.000Z
2022-02-03T20:28:39.000Z
TensorFlow/KernelPrediction.py
DeepBlender/DeepDenoiser
ba4cee09ea3dbd7b2d1505fcb232bdb81323122f
[ "Apache-2.0" ]
3
2018-05-06T23:42:09.000Z
2019-05-19T11:38:21.000Z
TensorFlow/KernelPrediction.py
DeepBlender/DeepDenoiser
ba4cee09ea3dbd7b2d1505fcb232bdb81323122f
[ "Apache-2.0" ]
8
2018-10-26T14:52:12.000Z
2021-04-10T15:32:11.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from Conv2dUtilities import Conv2dUtilities class KernelPrediction: @staticmethod def kernel_prediction(inputs, kernel_inputs, kernel_size, use_softmax=True, mode='symmetric', data_format='channels_last'): assert Conv2dUtilities.has_valid_shape(inputs) assert Conv2dUtilities.height_width(inputs, data_format) == Conv2dUtilities.height_width(kernel_inputs, data_format) assert Conv2dUtilities.number_of_channels(kernel_inputs, data_format) == kernel_size ** 2 channel_axis = Conv2dUtilities.channel_axis(inputs, data_format) height_axis, width_axis = Conv2dUtilities.height_width_axis(inputs, data_format) number_of_channels = Conv2dUtilities.number_of_channels(inputs, data_format) pad = (kernel_size - 1) // 2 if use_softmax: kernel_inputs = tf.nn.softmax(kernel_inputs, axis=channel_axis) inputs_split = tf.split(inputs, number_of_channels, axis=channel_axis) # TODO: Check whether there is a more efficient way than iterating through the channels one by one (DeepBlender) for index in range(number_of_channels): input = inputs_split[index] padded_input = Conv2dUtilities.pad_equally(input, pad, mode=mode, data_format=data_format) input_stack = [] for i in range(kernel_size): for j in range(kernel_size): if Conv2dUtilities.is_batched(inputs): if data_format == 'channels_last': input_stack.append( padded_input[ :, i:padded_input.shape[height_axis] - 2 * pad + i, j:padded_input.shape[width_axis] - 2 * pad + j, :]) else: input_stack.append( padded_input[ :, :, i:padded_input.shape[height_axis] - 2 * pad + i, j:padded_input.shape[width_axis] - 2 * pad + j]) else: if data_format == 'channels_last': input_stack.append( padded_input[ i:padded_input.shape[height_axis] - 2 * pad + i, j:padded_input.shape[width_axis] - 2 * pad + j, :]) else: input_stack.append( padded_input[ :, i:padded_input.shape[height_axis] - 2 * pad + i, j:padded_input.shape[width_axis] - 2 * pad + j]) input_stack = tf.concat(input_stack, axis=channel_axis) input = tf.reduce_sum(tf.multiply(input_stack, kernel_inputs), axis=channel_axis, keepdims=True) inputs_split[index] = input inputs = tf.concat(inputs_split, axis=channel_axis) return inputs
43.53125
125
0.647164
acf66ad1c781b33cebacfec1b01eb82c480a49aa
367
py
Python
Problem_15_medium.py
alucardthefish/DailyCodingProblem
c2c3e1e3d30765e6e770bdda19795cf6d0a94f06
[ "MIT" ]
null
null
null
Problem_15_medium.py
alucardthefish/DailyCodingProblem
c2c3e1e3d30765e6e770bdda19795cf6d0a94f06
[ "MIT" ]
null
null
null
Problem_15_medium.py
alucardthefish/DailyCodingProblem
c2c3e1e3d30765e6e770bdda19795cf6d0a94f06
[ "MIT" ]
null
null
null
""" This problem was asked by Facebook. Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability. """ import random def picker(stream): size = len(stream) randFloat = random.uniform(0, size) pick = int(randFloat) return stream[pick] print("picker: ", picker([3, 4, 3, 5, 2]))
18.35
63
0.675749
acf66b06240944ef7ae6c24bd1105ddc7bf5e8f9
3,495
py
Python
tareas/3/RosalesRicardo/tarea3.py
Ricardo191998/sistop-2020-1
a37d2a880995a870ebfeebe7e098e4aefb3cd179
[ "CC-BY-4.0" ]
13
2019-08-07T13:48:14.000Z
2021-08-31T23:23:35.000Z
tareas/3/RosalesRicardo/tarea3.py
Ricardo191998/sistop-2020-1
a37d2a880995a870ebfeebe7e098e4aefb3cd179
[ "CC-BY-4.0" ]
48
2019-08-07T03:15:54.000Z
2019-11-21T16:53:45.000Z
tareas/3/RosalesRicardo/tarea3.py
Ricardo191998/sistop-2020-1
a37d2a880995a870ebfeebe7e098e4aefb3cd179
[ "CC-BY-4.0" ]
47
2019-08-07T01:44:34.000Z
2021-11-05T02:31:25.000Z
from __future__ import print_function import random import sys #Menu incial def main(): print('ASIGNACION DE MEMORIA !!') print('***En caso de salir agrege -1 en unidades de memoria ***') print('(No se permiten mas de 1000 unidades de memoria)') noUnidades = int(input('Ingrese numero de unidades de memoria : ')) if(noUnidades == -1 || noUnidades > 1000): return mapeo(noUnidades) #Genera aleatoriamente el mapeo de memoria, con los procesos y sus unidades de procesos tambien generadas de forma aleatoria def mapeo(unidadesMemoria): alpha = 'ABCDEFGHIJKLMNOPQRSTUVXYZ' mapeo = [] procesos = [] while(len(mapeo)<= unidadesMemoria): temp = alpha[random.randrange(24)] try: mapeo.index(temp) except: if(len(mapeo)<= unidadesMemoria): procesos.append(temp) uniProceso = random.randrange(15) for n in range(uniProceso): mapeo.append(temp) if(len(mapeo)>= unidadesMemoria): break if(random.randint(0,1) == 1): empty = random.randint(0,4) for n in range(empty): mapeo.append('-') if(len(mapeo)>= unidadesMemoria): break asignacionActual(mapeo, procesos) #Muestra lo que hay que hacer si liberar procesos o agregar uno nuevo def asignacionActual(mapeo, procesos): print('Asiganacion Actual:') print(' ') for n in range(len(mapeo)): print(mapeo[n],end="") print('\n') opc = int(input('Asignar (0) o liberar (1) : ')) if opc == 0: nProceso = nuevoProceso(mapeo) tamProceso = int(input("Nuevo proceso (%s): " %(nProceso))) nuevaAsignacion(mapeo, procesos, nProceso, tamProceso) try: mapeo.index(nProceso) print("Nueva Asigancion: ") for n in range(len(mapeo)): print(mapeo[n],end="") print('\n') except: print("**Compactacion requerida**") print("Nueva situacion: ") compactacion(mapeo) for n in range(len(mapeo)): print(mapeo[n],end="") print('\n') nuevaAsignacion(mapeo, procesos, nProceso, tamProceso) try: mapeo.index(nProceso) print("Asignando a %c:" %(nProceso)) for n in range(len(mapeo)): print(mapeo[n],end="") print('\n') asignacionActual(mapeo, procesos) except: print("**El proceso no puede ser ingresado**") elif opc == 1: procesoLib = raw_input("Proceso a liberar (%s) :" %(','.join(procesos))) liberar(mapeo, procesos, procesoLib) asignacionActual(mapeo, procesos) else: print('---Ingresa un numero valido----') asignacionActual(mapeo, procesos) #Genera un nuevo proceso aleaotrio sin repetir def nuevoProceso(procesos): alpha = 'ABCDEFGHIJKLMNOPQRSTUVXYZ' temp = alpha[random.randrange(24)] try: procesos.index(temp) return nuevoProceso(procesos) except: return temp #La nueva asignacion primer ajuste def nuevaAsignacion(mapeo, procesos, nProceso, tamProceso): cont = 0 procesos.append(nProceso) for n,i in enumerate(mapeo): if i=='-': if cont == 0: inicio = n cont += 1 else: cont = 0 if cont == tamProceso: for i in range(inicio , inicio+tamProceso): mapeo[i] = nProceso break #Funcion que fompata los proeceso dejando la parte vacia hasta el final def compactacion(mapeo): ban = True cont = 0 while(ban): try: mapeo.remove('-') cont += 1 except: ban = False for i in range(0, cont): mapeo.append('-') #Libera el mapeo del elemento y lo elimina de la lista de procesos def liberar(mapeo, procesos, procesoLib): for n,i in enumerate(mapeo): if i==procesoLib: mapeo[n]= '-' procesos.remove(procesoLib) main()
26.278195
125
0.675823
acf66b942758067529bf913b17d10ac1f9182fb5
274
py
Python
spectate/mvc.py
bollwyvl/spectate
0d89afac9caf849b85c84e3580278bebb3d22eda
[ "MIT" ]
30
2017-08-10T17:13:36.000Z
2022-03-03T18:48:49.000Z
spectate/mvc.py
bollwyvl/spectate
0d89afac9caf849b85c84e3580278bebb3d22eda
[ "MIT" ]
26
2016-08-18T20:21:36.000Z
2021-07-13T02:52:13.000Z
spectate/mvc.py
bollwyvl/spectate
0d89afac9caf849b85c84e3580278bebb3d22eda
[ "MIT" ]
4
2017-08-10T17:13:39.000Z
2021-03-02T19:57:43.000Z
"""A modules which exports specate's Model-View-Controller utilities in a common namespace For more info: - :mod:`spectate.base` - :mod:`spectate.events` - :mod:`spectate.models` """ from .base import * # noqa from .events import * # noqa from .models import * # noqa
21.076923
90
0.70073
acf66be33b4ad629399d2809953d9a9b7020e140
11,173
py
Python
10dpoisson-cube-ls.py
lichun0503/DeepRitz
ca6a2fbec3ae5b89ab840300dd6ec09f288d01f4
[ "MIT" ]
16
2020-07-09T02:41:08.000Z
2022-03-08T18:13:37.000Z
10dpoisson-cube-ls.py
lichun0503/DeepRitz
ca6a2fbec3ae5b89ab840300dd6ec09f288d01f4
[ "MIT" ]
null
null
null
10dpoisson-cube-ls.py
lichun0503/DeepRitz
ca6a2fbec3ae5b89ab840300dd6ec09f288d01f4
[ "MIT" ]
9
2020-07-02T02:48:13.000Z
2022-02-25T07:04:19.000Z
import numpy as np import math, torch, generateData, time import torch.nn.functional as F from torch.optim.lr_scheduler import MultiStepLR, StepLR import torch.nn as nn import matplotlib.pyplot as plt import sys, os import writeSolution from areaVolume import areaVolume # Network structure class RitzNet(torch.nn.Module): def __init__(self, params): super(RitzNet, self).__init__() self.params = params # self.linearIn = nn.Linear(self.params["d"], self.params["width"]) self.linear = nn.ModuleList() for _ in range(params["depth"]): self.linear.append(nn.Linear(self.params["width"], self.params["width"])) self.linearOut = nn.Linear(self.params["width"], self.params["dd"]) def forward(self, x): # x = torch.tanh(self.linearIn(x)) # Match dimension for i in range(len(self.linear)//2): x_temp = torch.tanh(self.linear[2*i](x)) x_temp = torch.tanh(self.linear[2*i+1](x_temp)) x = x_temp+x return self.linearOut(x) def initWeights(m): if type(m) == nn.Linear: torch.nn.init.xavier_normal_(m.weight) torch.nn.init.zeros_(m.bias) def preTrain(model,device,params,preOptimizer,preScheduler,fun): model.train() file = open("lossData.txt","w") for step in range(params["preStep"]): # The volume integral data = torch.from_numpy(generateData.sampleFromDisk10(params["radius"],params["bodyBatch"])).float().to(device) output = model(data) target = fun(params["radius"],data) loss = output-target loss = torch.mean(loss*loss) if step%params["writeStep"] == params["writeStep"]-1: with torch.no_grad(): ref = exact(params["radius"],data) error = errorFun(output,ref,params) # print("Loss at Step %s is %s."%(step+1,loss.item())) print("Error at Step %s is %s."%(step+1,error)) file.write(str(step+1)+" "+str(error)+"\n") model.zero_grad() loss.backward() # Update the weights. preOptimizer.step() # preScheduler.step() def train(model,device,params,optimizer,scheduler): model.train() data1 = torch.rand(params["bodyBatch"],params["d"]).float().to(device) data2 = torch.rand(2*params["d"]*(params["bdryBatch"]//(2*params["d"])),params["d"]).float().to(device) temp = params["bdryBatch"]//(2*params["d"]) for i in range(params["d"]): data2[(2*i+0)*temp:(2*i+1)*temp,i] = 0.0 data2[(2*i+1)*temp:(2*i+2)*temp,i] = 1.0 x_shift = torch.from_numpy(np.eye(10)*params["diff"]).float().to(device) data1_shift0 = data1+x_shift[0] data1_shift1 = data1+x_shift[1] data1_shift2 = data1+x_shift[2] data1_shift3 = data1+x_shift[3] data1_shift4 = data1+x_shift[4] data1_shift5 = data1+x_shift[5] data1_shift6 = data1+x_shift[6] data1_shift7 = data1+x_shift[7] data1_shift8 = data1+x_shift[8] data1_shift9 = data1+x_shift[9] data1_nshift0 = data1-x_shift[0] data1_nshift1 = data1-x_shift[1] data1_nshift2 = data1-x_shift[2] data1_nshift3 = data1-x_shift[3] data1_nshift4 = data1-x_shift[4] data1_nshift5 = data1-x_shift[5] data1_nshift6 = data1-x_shift[6] data1_nshift7 = data1-x_shift[7] data1_nshift8 = data1-x_shift[8] data1_nshift9 = data1-x_shift[9] for step in range(params["trainStep"]-params["preStep"]): output1 = model(data1) output1_shift0 = model(data1_shift0) output1_shift1 = model(data1_shift1) output1_shift2 = model(data1_shift2) output1_shift3 = model(data1_shift3) output1_shift4 = model(data1_shift4) output1_shift5 = model(data1_shift5) output1_shift6 = model(data1_shift6) output1_shift7 = model(data1_shift7) output1_shift8 = model(data1_shift8) output1_shift9 = model(data1_shift9) output1_nshift0 = model(data1_nshift0) output1_nshift1 = model(data1_nshift1) output1_nshift2 = model(data1_nshift2) output1_nshift3 = model(data1_nshift3) output1_nshift4 = model(data1_nshift4) output1_nshift5 = model(data1_nshift5) output1_nshift6 = model(data1_nshift6) output1_nshift7 = model(data1_nshift7) output1_nshift8 = model(data1_nshift8) output1_nshift9 = model(data1_nshift9) dfdx20 = (output1_shift0+output1_nshift0-2*output1)/(params["diff"]**2) dfdx21 = (output1_shift1+output1_nshift1-2*output1)/(params["diff"]**2) dfdx22 = (output1_shift2+output1_nshift2-2*output1)/(params["diff"]**2) dfdx23 = (output1_shift3+output1_nshift3-2*output1)/(params["diff"]**2) dfdx24 = (output1_shift4+output1_nshift4-2*output1)/(params["diff"]**2) dfdx25 = (output1_shift5+output1_nshift5-2*output1)/(params["diff"]**2) dfdx26 = (output1_shift6+output1_nshift6-2*output1)/(params["diff"]**2) dfdx27 = (output1_shift7+output1_nshift7-2*output1)/(params["diff"]**2) dfdx28 = (output1_shift8+output1_nshift8-2*output1)/(params["diff"]**2) dfdx29 = (output1_shift9+output1_nshift9-2*output1)/(params["diff"]**2) model.zero_grad() # Loss function 1 fTerm = ffun(data1).to(device) loss1 = torch.mean((dfdx20+dfdx21+dfdx22+dfdx23+dfdx24+dfdx25+dfdx26+dfdx27+dfdx28+dfdx29+fTerm)*\ (dfdx20+dfdx21+dfdx22+dfdx23+dfdx24+dfdx25+dfdx26+dfdx27+dfdx28+dfdx29+fTerm)) # Loss function 2 output2 = model(data2) target2 = exact(params["radius"],data2) loss2 = torch.mean((output2-target2)*(output2-target2) * params["penalty"] *params["area"]) loss = loss1+loss2 if step%params["writeStep"] == params["writeStep"]-1: with torch.no_grad(): target = exact(params["radius"],data1) error = errorFun(output1,target,params) # print("Loss at Step %s is %s."%(step+params["preStep"]+1,loss.item())) print("Error at Step %s is %s."%(step+params["preStep"]+1,error)) file = open("lossData.txt","a") file.write(str(step+params["preStep"]+1)+" "+str(error)+"\n") if step%params["sampleStep"] == params["sampleStep"]-1: data1 = torch.rand(params["bodyBatch"],params["d"]).float().to(device) data2 = torch.rand(2*params["d"]*(params["bdryBatch"]//(2*params["d"])),params["d"]).float().to(device) temp = params["bdryBatch"]//(2*params["d"]) for i in range(params["d"]): data2[(2*i+0)*temp:(2*i+1)*temp,i] = 0.0 data2[(2*i+1)*temp:(2*i+2)*temp,i] = 1.0 data1_shift0 = data1+x_shift[0] data1_shift1 = data1+x_shift[1] data1_shift2 = data1+x_shift[2] data1_shift3 = data1+x_shift[3] data1_shift4 = data1+x_shift[4] data1_shift5 = data1+x_shift[5] data1_shift6 = data1+x_shift[6] data1_shift7 = data1+x_shift[7] data1_shift8 = data1+x_shift[8] data1_shift9 = data1+x_shift[9] data1_nshift0 = data1-x_shift[0] data1_nshift1 = data1-x_shift[1] data1_nshift2 = data1-x_shift[2] data1_nshift3 = data1-x_shift[3] data1_nshift4 = data1-x_shift[4] data1_nshift5 = data1-x_shift[5] data1_nshift6 = data1-x_shift[6] data1_nshift7 = data1-x_shift[7] data1_nshift8 = data1-x_shift[8] data1_nshift9 = data1-x_shift[9] if 10*(step+1)%params["trainStep"] == 0: print("%s%% finished..."%(100*(step+1)//params["trainStep"])) loss.backward() optimizer.step() scheduler.step() def errorFun(output,target,params): error = output-target error = math.sqrt(torch.mean(error*error)) # Calculate the L2 norm error. ref = math.sqrt(torch.mean(target*target)) return error/ref def test(model,device,params): numQuad = params["numQuad"] data = torch.rand(numQuad,10).float().to(device) output = model(data) target = exact(params["radius"],data).to(device) error = output-target error = math.sqrt(torch.mean(error*error)) # Calculate the L2 norm error. ref = math.sqrt(torch.mean(target*target)) return error/ref def ffun(data): # f = 0 return 0.0*torch.ones([data.shape[0],1],dtype=torch.float) # f = 20 # return 20.0*torch.ones([data.shape[0],1],dtype=torch.float) def exact(r,data): # f = 20 ==> u = r^2-x^2-y^2-... # output = r**2-torch.sum(data*data,dim=1) # f = 0 ==> u = x1x2+x3x4+x5x6+... output = data[:,0]*data[:,1] + data[:,2]*data[:,3] + data[:,4]*data[:,5] + \ data[:,6]*data[:,7] + data[:,8]*data[:,9] return output.unsqueeze(1) def rough(r,data): # output = r**2-r*torch.sum(data*data,dim=1)**0.5 output = torch.zeros(data.shape[0],dtype=torch.float) return output.unsqueeze(1) def count_parameters(model): return sum(p.numel() for p in model.parameters()) # if p.requires_grad def main(): # Parameters # torch.manual_seed(21) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") params = dict() params["radius"] = 1 params["d"] = 10 # 10D params["dd"] = 1 # Scalar field params["bodyBatch"] = 1024 # Batch size params["bdryBatch"] = 2000 # Batch size for the boundary integral params["lr"] = 0.016 # Learning rate params["preLr"] = params["lr"] # Learning rate (Pre-training) params["width"] = 10 # Width of layers params["depth"] = 4 # Depth of the network: depth+2 params["numQuad"] = 40000 # Number of quadrature points for testing params["trainStep"] = 50000 params["penalty"] = 500 params["preStep"] = 0 params["diff"] = 0.001 params["writeStep"] = 50 params["sampleStep"] = 10 params["area"] = 20 params["step_size"] = 5000 params["milestone"] = [5000,10000,20000,35000,48000] params["gamma"] = 0.5 params["decay"] = 0.00001 startTime = time.time() model = RitzNet(params).to(device) model.apply(initWeights) print("Generating network costs %s seconds."%(time.time()-startTime)) # torch.seed() preOptimizer = torch.optim.Adam(model.parameters(),lr=params["preLr"]) optimizer = torch.optim.Adam(model.parameters(),lr=params["lr"],weight_decay=params["decay"]) # scheduler = StepLR(optimizer,step_size=params["step_size"],gamma=params["gamma"]) scheduler = MultiStepLR(optimizer,milestones=params["milestone"],gamma=params["gamma"]) startTime = time.time() preTrain(model,device,params,preOptimizer,None,rough) train(model,device,params,optimizer,scheduler) print("Training costs %s seconds."%(time.time()-startTime)) model.eval() testError = test(model,device,params) print("The test error (of the last model) is %s."%testError) print("The number of parameters is %s,"%count_parameters(model)) torch.save(model.state_dict(),"last_model.pt") if __name__=="__main__": main()
39.066434
119
0.624004
acf66c0ec37f27be18ad8d21f40cf1f635c22775
4,587
py
Python
aydin/gui/tabs/qt/denoise.py
fengwang/aydin
22d7db71de168510bd3aa98fc22384deb8d9916f
[ "BSD-3-Clause" ]
null
null
null
aydin/gui/tabs/qt/denoise.py
fengwang/aydin
22d7db71de168510bd3aa98fc22384deb8d9916f
[ "BSD-3-Clause" ]
null
null
null
aydin/gui/tabs/qt/denoise.py
fengwang/aydin
22d7db71de168510bd3aa98fc22384deb8d9916f
[ "BSD-3-Clause" ]
null
null
null
from qtpy.QtCore import Qt from qtpy.QtWidgets import ( QWidget, QVBoxLayout, QHBoxLayout, QStackedWidget, QListWidget, ) from aydin.gui._qt.custom_widgets.denoise_tab_method import DenoiseTabMethodWidget from aydin.gui._qt.custom_widgets.horizontal_line_break_widget import ( QHorizontalLineBreakWidget, ) from aydin.gui._qt.custom_widgets.readmoreless_label import QReadMoreLessLabel from aydin.restoration.denoise.util.denoise_utils import ( get_list_of_denoiser_implementations, ) class DenoiseTab(QWidget): """ Now it is time to denoise the previously selected and cropped images. <br><br> Aydin comes with a growing variety of self-supervised, auto-tuned, and unsupervised denoising algorithms, each with their own strengths and weaknesses in terms of speed, denoising performance, artifacts, and propensity to hallucinate unsubstantiated details. We recommend you check our <a href='https://royerlab.github.io/aydin/use_cases/introduction.html'>use cases</a> to learn how to choose the best algorithm and parameters for your image(s). <moreless> Quick guide: The first algorithm to try is 'Butterworth' which is remarkably simple, fast, and sometimes embarrassingly effective compared to more sophisticated methods. Next you can try the Gaussian-Median mixed denoiser (gm) which is in some cases quite effective. 'Spectral' can give extremely good results too but can take longer, as do in general patch and dictionary based methods. <split> Our own favourite is a novel variant on the Noise2Self theme which relies on carefully crafted features and gradient boosting (N2S-FGR-cb or -lgbm). CNN-based Noise2Self denoising is also available but is currently on of our least favourites because of its propensity to hallucinate detail, slowness, and overall worse performance. In fine, there is no silver bullet, there is not a single denoising algorithm that can tackle all denoising challenges, instead you need to choose and play with a variety of algorithms to find the one that will fit you needs both in terms of processing speed, visual appearance, and downstream analysis constraints. Denoising is a form of image analysis that consists in separating signal from noise, with the definition of signal and noise being to some extent, subjective and context dependent. """ def __init__(self, parent): super(DenoiseTab, self).__init__(parent) self.parent = parent self.tab_layout = QVBoxLayout() self.tab_layout.setAlignment(Qt.AlignTop) self.tab_layout.addWidget(QReadMoreLessLabel(self, self.__doc__)) # Horizontal Line Break self.tab_layout.addWidget(QHorizontalLineBreakWidget(self)) self.leftlist = QListWidget() ( backend_options, backend_options_descriptions, ) = get_list_of_denoiser_implementations() backend_options, backend_options_descriptions = ( list(t) for t in zip(*sorted(zip(backend_options, backend_options_descriptions))) ) self.stacked_widget = QStackedWidget(self) default_option_index = 0 for idx, (backend_option, description) in enumerate( zip(backend_options, backend_options_descriptions) ): self.leftlist.insertItem(idx, backend_option) # self.leftlist.item(idx).setToolTip(tooltip) self.stacked_widget.addWidget( DenoiseTabMethodWidget( self, name=backend_option, description=description ) ) if backend_option == "Classic-butterworth": default_option_index = idx self.leftlist.item(default_option_index).setSelected(True) self.change_current_method(default_option_index) self.leftlist.currentRowChanged.connect(self.change_current_method) hbox = QHBoxLayout() hbox.addWidget(self.leftlist, 15) hbox.addWidget(self.stacked_widget, 85) self.tab_layout.addLayout(hbox) self.setLayout(self.tab_layout) def change_current_method(self, new_index): self.stacked_widget.setCurrentIndex(new_index) @property def selected_backend(self): return self.stacked_widget.currentWidget().name @property def current_backend_qwidget(self): return self.stacked_widget.currentWidget() @property def lower_level_args(self): return self.stacked_widget.currentWidget().lower_level_args()
40.236842
117
0.721605
acf66d4af6532987a187ee22646086eb5f5b51b2
16,055
py
Python
tests/extra_regress/tests.py
dadoeyad/django
802dd1ffc5cfa3d547efeb285dac70884b99e16d
[ "PSF-2.0", "BSD-3-Clause" ]
1
2020-10-21T02:20:06.000Z
2020-10-21T02:20:06.000Z
tests/extra_regress/tests.py
dadoeyad/django
802dd1ffc5cfa3d547efeb285dac70884b99e16d
[ "PSF-2.0", "BSD-3-Clause" ]
null
null
null
tests/extra_regress/tests.py
dadoeyad/django
802dd1ffc5cfa3d547efeb285dac70884b99e16d
[ "PSF-2.0", "BSD-3-Clause" ]
null
null
null
from __future__ import unicode_literals import datetime from collections import OrderedDict from django.contrib.auth.models import User from django.test import TestCase from .models import Order, RevisionableModel, TestObject class ExtraRegressTests(TestCase): def setUp(self): self.u = User.objects.create_user( username="fred", password="secret", email="fred@example.com" ) def test_regression_7314_7372(self): """ Regression tests for #7314 and #7372 """ rm = RevisionableModel.objects.create( title='First Revision', when=datetime.datetime(2008, 9, 28, 10, 30, 0) ) self.assertEqual(rm.pk, rm.base.pk) rm2 = rm.new_revision() rm2.title = "Second Revision" rm.when = datetime.datetime(2008, 9, 28, 14, 25, 0) rm2.save() self.assertEqual(rm2.title, 'Second Revision') self.assertEqual(rm2.base.title, 'First Revision') self.assertNotEqual(rm2.pk, rm.pk) self.assertEqual(rm2.base.pk, rm.pk) # Queryset to match most recent revision: qs = RevisionableModel.objects.extra( where=["%(table)s.id IN (SELECT MAX(rev.id) FROM %(table)s rev GROUP BY rev.base_id)" % { 'table': RevisionableModel._meta.db_table, }] ) self.assertQuerysetEqual( qs, [('Second Revision', 'First Revision')], transform=lambda r: (r.title, r.base.title) ) # Queryset to search for string in title: qs2 = RevisionableModel.objects.filter(title__contains="Revision") self.assertQuerysetEqual( qs2, [ ('First Revision', 'First Revision'), ('Second Revision', 'First Revision'), ], transform=lambda r: (r.title, r.base.title), ordered=False ) # Following queryset should return the most recent revision: self.assertQuerysetEqual( qs & qs2, [('Second Revision', 'First Revision')], transform=lambda r: (r.title, r.base.title), ordered=False ) def test_extra_stay_tied(self): # Extra select parameters should stay tied to their corresponding # select portions. Applies when portions are updated or otherwise # moved around. qs = User.objects.extra( select=OrderedDict((("alpha", "%s"), ("beta", "2"), ("gamma", "%s"))), select_params=(1, 3) ) qs = qs.extra(select={"beta": 4}) qs = qs.extra(select={"alpha": "%s"}, select_params=[5]) self.assertEqual( list(qs.filter(id=self.u.id).values('alpha', 'beta', 'gamma')), [{'alpha': 5, 'beta': 4, 'gamma': 3}] ) def test_regression_7957(self): """ Regression test for #7957: Combining extra() calls should leave the corresponding parameters associated with the right extra() bit. I.e. internal dictionary must remain sorted. """ self.assertEqual( (User.objects .extra(select={"alpha": "%s"}, select_params=(1,)) .extra(select={"beta": "%s"}, select_params=(2,))[0].alpha), 1 ) self.assertEqual( (User.objects .extra(select={"beta": "%s"}, select_params=(1,)) .extra(select={"alpha": "%s"}, select_params=(2,))[0].alpha), 2 ) def test_regression_7961(self): """ Regression test for #7961: When not using a portion of an extra(...) in a query, remove any corresponding parameters from the query as well. """ self.assertEqual( list(User.objects.extra(select={"alpha": "%s"}, select_params=(-6,)) .filter(id=self.u.id).values_list('id', flat=True)), [self.u.id] ) def test_regression_8063(self): """ Regression test for #8063: limiting a query shouldn't discard any extra() bits. """ qs = User.objects.all().extra(where=['id=%s'], params=[self.u.id]) self.assertQuerysetEqual(qs, ['<User: fred>']) self.assertQuerysetEqual(qs[:1], ['<User: fred>']) def test_regression_8039(self): """ Regression test for #8039: Ordering sometimes removed relevant tables from extra(). This test is the critical case: ordering uses a table, but then removes the reference because of an optimization. The table should still be present because of the extra() call. """ self.assertQuerysetEqual( (Order.objects .extra(where=["username=%s"], params=["fred"], tables=["auth_user"]) .order_by('created_by')), [] ) def test_regression_8819(self): """ Regression test for #8819: Fields in the extra(select=...) list should be available to extra(order_by=...). """ self.assertQuerysetEqual( User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}).distinct(), ['<User: fred>'] ) self.assertQuerysetEqual( User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}, order_by=['extra_field']), ['<User: fred>'] ) self.assertQuerysetEqual( User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}, order_by=['extra_field']).distinct(), ['<User: fred>'] ) def test_dates_query(self): """ When calling the dates() method on a queryset with extra selection columns, we can (and should) ignore those columns. They don't change the result and cause incorrect SQL to be produced otherwise. """ RevisionableModel.objects.create( title='First Revision', when=datetime.datetime(2008, 9, 28, 10, 30, 0) ) self.assertSequenceEqual( RevisionableModel.objects.extra(select={"the_answer": 'id'}).datetimes('when', 'month'), [datetime.datetime(2008, 9, 1, 0, 0)], ) def test_values_with_extra(self): """ Regression test for #10256... If there is a values() clause, Extra columns are only returned if they are explicitly mentioned. """ obj = TestObject(first='first', second='second', third='third') obj.save() self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values() ), [{ 'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first' }] ) # Extra clauses after an empty values clause are still included self.assertEqual( list( TestObject.objects .values() .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) ), [{ 'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first' }] ) # Extra columns are ignored if not mentioned in the values() clause self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values('first', 'second') ), [{'second': 'second', 'first': 'first'}] ) # Extra columns after a non-empty values() clause are ignored self.assertEqual( list( TestObject.objects .values('first', 'second') .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) ), [{'second': 'second', 'first': 'first'}] ) # Extra columns can be partially returned self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values('first', 'second', 'foo') ), [{'second': 'second', 'foo': 'first', 'first': 'first'}] ) # Also works if only extra columns are included self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values('foo', 'whiz') ), [{'foo': 'first', 'whiz': 'third'}] ) # Values list works the same way # All columns are returned for an empty values_list() self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values_list() ), [('first', 'second', 'third', obj.pk, 'first', 'second', 'third')] ) # Extra columns after an empty values_list() are still included self.assertEqual( list( TestObject.objects .values_list() .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) ), [('first', 'second', 'third', obj.pk, 'first', 'second', 'third')] ) # Extra columns ignored completely if not mentioned in values_list() self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values_list('first', 'second') ), [('first', 'second')] ) # Extra columns after a non-empty values_list() clause are ignored completely self.assertEqual( list( TestObject.objects .values_list('first', 'second') .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) ), [('first', 'second')] ) self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values_list('second', flat=True) ), ['second'] ) # Only the extra columns specified in the values_list() are returned self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values_list('first', 'second', 'whiz') ), [('first', 'second', 'third')] ) # ...also works if only extra columns are included self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values_list('foo', 'whiz') ), [('first', 'third')] ) self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values_list('whiz', flat=True) ), ['third'] ) # ... and values are returned in the order they are specified self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values_list('whiz', 'foo') ), [('third', 'first')] ) self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values_list('first', 'id') ), [('first', obj.pk)] ) self.assertEqual( list( TestObject.objects .extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))) .values_list('whiz', 'first', 'bar', 'id') ), [('third', 'first', 'second', obj.pk)] ) def test_regression_10847(self): """ Regression for #10847: the list of extra columns can always be accurately evaluated. Using an inner query ensures that as_sql() is producing correct output without requiring full evaluation and execution of the inner query. """ obj = TestObject(first='first', second='second', third='third') obj.save() self.assertEqual( list(TestObject.objects.extra(select={'extra': 1}).values('pk')), [{'pk': obj.pk}] ) self.assertQuerysetEqual( TestObject.objects.filter( pk__in=TestObject.objects.extra(select={'extra': 1}).values('pk') ), ['<TestObject: TestObject: first,second,third>'] ) self.assertEqual( list(TestObject.objects.values('pk').extra(select={'extra': 1})), [{'pk': obj.pk}] ) self.assertQuerysetEqual( TestObject.objects.filter( pk__in=TestObject.objects.values('pk').extra(select={'extra': 1}) ), ['<TestObject: TestObject: first,second,third>'] ) self.assertQuerysetEqual( TestObject.objects.filter(pk=obj.pk) | TestObject.objects.extra(where=["id > %s"], params=[obj.pk]), ['<TestObject: TestObject: first,second,third>'] ) def test_regression_17877(self): """ Ensure that extra WHERE clauses get correctly ANDed, even when they contain OR operations. """ # Test Case 1: should appear in queryset. t = TestObject(first='a', second='a', third='a') t.save() # Test Case 2: should appear in queryset. t = TestObject(first='b', second='a', third='a') t.save() # Test Case 3: should not appear in queryset, bug case. t = TestObject(first='a', second='a', third='b') t.save() # Test Case 4: should not appear in queryset. t = TestObject(first='b', second='a', third='b') t.save() # Test Case 5: should not appear in queryset. t = TestObject(first='b', second='b', third='a') t.save() # Test Case 6: should not appear in queryset, bug case. t = TestObject(first='a', second='b', third='b') t.save() self.assertQuerysetEqual( TestObject.objects.extra( where=["first = 'a' OR second = 'a'", "third = 'a'"], ), ['<TestObject: TestObject: a,a,a>', '<TestObject: TestObject: b,a,a>'], ordered=False ) def test_extra_values_distinct_ordering(self): t1 = TestObject.objects.create(first='a', second='a', third='a') t2 = TestObject.objects.create(first='a', second='b', third='b') qs = TestObject.objects.extra( select={'second_extra': 'second'} ).values_list('id', flat=True).distinct() self.assertSequenceEqual(qs.order_by('second_extra'), [t1.pk, t2.pk]) self.assertSequenceEqual(qs.order_by('-second_extra'), [t2.pk, t1.pk]) # Note: the extra ordering must appear in select clause, so we get two # non-distinct results here (this is on purpose, see #7070). self.assertSequenceEqual(qs.order_by('-second_extra').values_list('first', flat=True), ['a', 'a'])
36.571754
116
0.520897
acf66e9c99524b94423535899f23bebaf6b06a30
13,442
py
Python
html_sanitizer/sanitizer.py
aiselio/html-sanitizer
0b9bd196adbabc4f79fa98b9954028961152a5bd
[ "BSD-3-Clause" ]
null
null
null
html_sanitizer/sanitizer.py
aiselio/html-sanitizer
0b9bd196adbabc4f79fa98b9954028961152a5bd
[ "BSD-3-Clause" ]
null
null
null
html_sanitizer/sanitizer.py
aiselio/html-sanitizer
0b9bd196adbabc4f79fa98b9954028961152a5bd
[ "BSD-3-Clause" ]
null
null
null
import re import unicodedata from collections import deque import lxml.html import lxml.html.clean __all__ = ("Sanitizer",) def sanitize_href(href): """ Verify that a given href is benign and allowed. This is a stupid check, which probably should be much more elaborate to be safe. """ if href.startswith(("/", "mailto:", "http:", "https:", "#", "tel:")): return href return "#" typographic_whitespace_names = [ "NO-BREAK SPACE", "EN QUAD", "EM QUAD", "EN SPACE", "EM SPACE", "THREE-PER-EM SPACE", "FOUR-PER-EM SPACE", "SIX-PER-EM SPACE", "FIGURE SPACE", "PUNCTUATION SPACE", "THIN SPACE", "HAIR SPACE", "NARROW NO-BREAK SPACE", "MEDIUM MATHEMATICAL SPACE", "IDEOGRAPHIC SPACE", ] typographic_whitespace = "".join( {unicodedata.lookup(n) for n in typographic_whitespace_names} ) def normalize_overall_whitespace( html, keep_typographic_whitespace=False, whitespace_re=None ): # remove all sorts of newline and nbsp characters whitespace = ["\n", "&#10;", "&#xa;", "\r", "&#13;", "&#xd;"] if not keep_typographic_whitespace: # non-breaking space representations whitespace += ["\xa0", "&nbsp;", "&#160;", "&#xa0;"] if whitespace_re is None: whitespace_re = r"\s+" for ch in whitespace: html = html.replace(ch, " ") html = re.sub(whitespace_re, " ", html) return html def bold_span_to_strong(element): if element.tag == "span" and "bold" in element.get("style", ""): element.tag = "strong" return element def italic_span_to_em(element): if element.tag == "span" and "italic" in element.get("style", ""): element.tag = "em" return element def tag_replacer(from_, to_): def replacer(element): if element.tag == from_: element.tag = to_ return element return replacer def target_blank_noopener(element): if ( element.tag == "a" and element.attrib.get("target") == "_blank" and "noopener" not in element.attrib.get("rel", "") ): element.attrib["rel"] = " ".join( part for part in (element.attrib.get("rel", ""), "noopener") if part ) return element def anchor_id_to_name(element): if ( element.tag == "a" and element.attrib.get("id") and not element.attrib.get("name") ): element.attrib["name"] = element.attrib["id"] return element def normalize_whitespace_in_text_or_tail(element, whitespace_re=None): if whitespace_re is None: whitespace_re = re.compile(r"\s+") if element.text: while True: text = whitespace_re.sub(" ", element.text) if element.text == text: break element.text = text if element.tail: while True: text = whitespace_re.sub(" ", element.tail) if element.tail == text: break element.tail = text return element DEFAULT_SETTINGS = { "tags": { "a", "h1", "h2", "h3", "strong", "em", "p", "ul", "ol", "li", "br", "sub", "sup", "hr", }, "attributes": {"a": ("href", "name", "target", "title", "rel")}, "empty": {"hr", "a", "br"}, "separate": {"a", "p", "li"}, "whitespace": {"br"}, "keep_typographic_whitespace": False, "add_nofollow": False, "autolink": False, "sanitize_href": sanitize_href, "element_preprocessors": [ # convert span elements into em/strong if a matching style rule # has been found. strong has precedence, strong & em at the same # time is not supported bold_span_to_strong, italic_span_to_em, tag_replacer("b", "strong"), tag_replacer("i", "em"), tag_replacer("form", "p"), target_blank_noopener, anchor_id_to_name, ], "element_postprocessors": [], } class Sanitizer(object): def __init__(self, settings=None): self.__dict__.update(DEFAULT_SETTINGS) self.__dict__.update(settings or {}) # Allow iterables of any kind, not just sets. self.tags = set(self.tags) self.empty = set(self.empty) self.separate = set(self.separate) self.whitespace = set(self.whitespace) if self.keep_typographic_whitespace: re_whitespace = r"[^\S%s]" % typographic_whitespace else: re_whitespace = r"\s" import sys if int(sys.version.split(".")[0]) == 2: force_unicode_prefix = "(?u)" else: force_unicode_prefix = "" self.only_whitespace_re = re.compile( r"%s^%s*$" % (force_unicode_prefix, re_whitespace) ) self.whitespace_re = re.compile( r"%s%s+" % (force_unicode_prefix, re_whitespace) ) # Validate the settings. if not self.tags: raise TypeError( "Empty list of allowed tags is not supported by the underlying" " lxml cleaner. If you really do not want to pass any tags" " pass a made-up tag name which will never exist in your" " document." ) if not self.tags.issuperset(self.empty): raise TypeError( 'Tags in "empty", but not allowed: %r' % (self.empty - self.tags,) ) if not self.tags.issuperset(self.separate): raise TypeError( 'Tags in "separate", but not allowed: %r' % (self.separate - self.tags,) ) if not self.tags.issuperset(self.attributes.keys()): raise TypeError( 'Tags in "attributes", but not allowed: %r' % (set(self.attributes.keys()) - self.tags,) ) anchor_attributes = self.attributes.get("a", ()) if "target" in anchor_attributes and "rel" not in anchor_attributes: raise TypeError( 'Always allow "rel" when allowing "target" as anchor' " attribute" ) @staticmethod def is_mergeable(e1, e2): """ Decide if the adjacent elements of the same type e1 and e2 can be merged. This can be overriden to honouring distinct classes etc. """ return True def sanitize(self, html): """ Clean HTML code from ugly copy-pasted CSS and empty elements Removes everything not explicitly allowed in ``self.allowed_tags``. Requires ``lxml`` and, for especially broken HTML, ``beautifulsoup4``. """ html = normalize_overall_whitespace( html, keep_typographic_whitespace=self.keep_typographic_whitespace, whitespace_re=self.whitespace_re, ) html = "<div>%s</div>" % html try: doc = lxml.html.fromstring(html) lxml.html.tostring(doc, encoding="utf-8") except Exception: # We could and maybe should be more specific... from lxml.html import soupparser doc = soupparser.fromstring(html) lxml.html.clean.Cleaner( remove_unknown_tags=False, # Remove style *tags* if not explicitly allowed style="style" not in self.tags, # Do not strip out style attributes; we still need the style # information to convert spans into em/strong tags safe_attrs_only=False, inline_style=False, # Do not strip all form tags; we will filter them below forms=False, kill_tags=('head', 'title'), )(doc) # walk the tree recursively, because we want to be able to remove # previously emptied elements completely backlog = deque(doc.iterdescendants()) while True: try: element = backlog.pop() except IndexError: break for processor in self.element_preprocessors: element = processor(element) element = normalize_whitespace_in_text_or_tail( element, whitespace_re=self.whitespace_re ) # remove empty tags if they are not explicitly allowed if ( (not element.text or self.only_whitespace_re.match(element.text)) and element.tag not in self.empty and not len(element) ): element.drop_tag() continue # remove tags which only contain whitespace and/or <br>s if ( element.tag not in self.empty and self.only_whitespace_re.match(element.text or "") and {e.tag for e in element} <= self.whitespace and all(self.only_whitespace_re.match(e.tail or "") for e in element) ): element.drop_tree() continue if element.tag in {"li", "p"}: # remove p-in-li and p-in-p tags for p in element.findall("p"): if getattr(p, "text", None): p.text = " " + p.text + " " p.drop_tag() # remove list markers, maybe copy-pasted from word or whatever if element.text: element.text = re.sub(r"^\s*(-|\*|&#183;)\s+", "", element.text) elif element.tag in self.whitespace: # Drop the next element if # 1. it is a <br> too and 2. there is no content in-between nx = element.getnext() if ( nx is not None and nx.tag == element.tag and ( not element.tail or self.only_whitespace_re.match(element.tail) ) ): nx.drop_tag() continue if not element.text: # No text before first child and first child is a <br>: Drop it first = list(element)[0] if list(element) else None if first is not None and first.tag in self.whitespace: first.drop_tag() # Maybe we have more than one <br> backlog.append(element) continue if element.tag in (self.tags - self.separate): # Check whether we should merge adjacent elements of the same # tag type nx = element.getnext() if ( self.only_whitespace_re.match(element.tail or "") and nx is not None and nx.tag == element.tag and self.is_mergeable(element, nx) ): # Yes, we should. Tail is empty, that is, no text between # tags of a mergeable type. if nx.text: if len(element): list(element)[-1].tail = "%s %s" % ( list(element)[-1].tail or "", nx.text, ) else: element.text = "%s %s" % (element.text or "", nx.text) for child in nx: element.append(child) # tail is merged with previous element. nx.drop_tree() # Process element again backlog.append(element) continue for processor in self.element_postprocessors: element = processor(element) # remove all attributes which are not explicitly allowed allowed = self.attributes.get(element.tag, []) for key in element.keys(): if key not in allowed: del element.attrib[key] # Clean hrefs so that they are benign href = element.get("href") if href is not None: element.set("href", self.sanitize_href(href)) element = normalize_whitespace_in_text_or_tail( element, whitespace_re=self.whitespace_re ) if self.autolink is True: lxml.html.clean.autolink(doc) elif isinstance(self.autolink, dict): lxml.html.clean.autolink(doc, **self.autolink) # Run cleaner again, but this time with even more strict settings lxml.html.clean.Cleaner( allow_tags=self.tags, remove_unknown_tags=False, safe_attrs_only=False, # Our attributes allowlist is sufficient. add_nofollow=self.add_nofollow, forms=False, kill_tags=('head', 'title'), )(doc) html = lxml.html.tostring(doc, encoding="unicode") # add a space before the closing slash in empty tags html = re.sub(r"<([^/>]+)/>", r"<\1 />", html) # remove wrapping tag needed by XML parser html = re.sub(r"^<div>|</div>$", "", html) # normalize unicode if self.keep_typographic_whitespace: html = unicodedata.normalize("NFC", html) else: html = unicodedata.normalize("NFKC", html) return html
32.3125
88
0.535114
acf6707f38202dfc7dbfc361587ecba542c7cfdb
7,164
py
Python
config/settings/production.py
johnedwardfry/Business_Website
0a243c39f0bba586c7e43954ac8d835089b56abd
[ "BSD-3-Clause" ]
null
null
null
config/settings/production.py
johnedwardfry/Business_Website
0a243c39f0bba586c7e43954ac8d835089b56abd
[ "BSD-3-Clause" ]
null
null
null
config/settings/production.py
johnedwardfry/Business_Website
0a243c39f0bba586c7e43954ac8d835089b56abd
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- ''' Production Configurations - Use djangosecure - Use Amazon's S3 for storing static files and uploaded media - Use mailgun to send emails - Use Redis on Heroku - Use sentry for error logging ''' from __future__ import absolute_import, unicode_literals from boto.s3.connection import OrdinaryCallingFormat from django.utils import six import logging from .common import * # noqa # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ SECRET_KEY = env("DJANGO_SECRET_KEY") # This ensures that Django will be able to detect a secure connection # properly on Heroku. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # django-secure # ------------------------------------------------------------------------------ INSTALLED_APPS += ("djangosecure", ) # raven sentry client # See https://docs.getsentry.com/hosted/clients/python/integrations/django/ INSTALLED_APPS += ('raven.contrib.django.raven_compat', ) SECURITY_MIDDLEWARE = ( 'djangosecure.middleware.SecurityMiddleware', ) RAVEN_MIDDLEWARE = ('raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware', 'raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware',) MIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + \ RAVEN_MIDDLEWARE + MIDDLEWARE_CLASSES # set this to 60 seconds and then to 518400 when you can prove it works SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool( "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True) SECURE_FRAME_DENY = env.bool("DJANGO_SECURE_FRAME_DENY", default=True) SECURE_CONTENT_TYPE_NOSNIFF = env.bool( "DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True) SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = False SESSION_COOKIE_HTTPONLY = True SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) # SITE CONFIGURATION # ------------------------------------------------------------------------------ # Hosts/domain names that are valid for this site # See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['example.com']) # END SITE CONFIGURATION INSTALLED_APPS += ("gunicorn", ) # STORAGE CONFIGURATION # ------------------------------------------------------------------------------ # Uploaded Media Files # ------------------------ # See: http://django-storages.readthedocs.org/en/latest/index.html INSTALLED_APPS += ( 'storages', ) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') AWS_AUTO_CREATE_BUCKET = True AWS_QUERYSTRING_AUTH = False AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat() # AWS cache settings, don't change unless you know what you're doing: AWS_EXPIRY = 60 * 60 * 24 * 7 # TODO See: https://github.com/jschneier/django-storages/issues/47 # Revert the following and use str after the above-mentioned bug is fixed in # either django-storage-redux or boto AWS_HEADERS = { 'Cache-Control': six.b('max-age=%d, s-maxage=%d, must-revalidate' % ( AWS_EXPIRY, AWS_EXPIRY)) } # URL that handles the media served from MEDIA_ROOT, used for managing # stored files. MEDIA_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME # Static Assets # ------------------------ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # EMAIL # ------------------------------------------------------------------------------ DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL', default='small_business_project <noreply@example.com>') EMAIL_BACKEND = 'django_mailgun.MailgunBackend' MAILGUN_ACCESS_KEY = env('DJANGO_MAILGUN_API_KEY') MAILGUN_SERVER_NAME = env('DJANGO_MAILGUN_SERVER_NAME') EMAIL_SUBJECT_PREFIX = env("DJANGO_EMAIL_SUBJECT_PREFIX", default='[small_business_project] ') SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL) # TEMPLATE CONFIGURATION # ------------------------------------------------------------------------------ # See: # https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader TEMPLATES[0]['OPTIONS']['loaders'] = [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), ] # DATABASE CONFIGURATION # ------------------------------------------------------------------------------ # Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ DATABASES['default'] = env.db("DATABASE_URL") # CACHING # ------------------------------------------------------------------------------ # Heroku URL does not pass the DB number, so we parse it in CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "{0}/{1}".format(env.cache_url('REDIS_URL', default="redis://127.0.0.1:6379"), 0), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "IGNORE_EXCEPTIONS": True, # mimics memcache behavior. # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior } } } # Sentry Configuration SENTRY_DSN = env('DJANGO_SENTRY_DSN') SENTRY_CLIENT = env('DJANGO_SENTRY_CLIENT', default='raven.contrib.django.raven_compat.DjangoClient') LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'WARNING', 'handlers': ['sentry'], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'sentry': { 'level': 'ERROR', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console'], 'propagate': False, }, 'raven': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'django.security.DisallowedHost': { 'level': 'ERROR', 'handlers': ['console', 'sentry'], 'propagate': False, }, }, } SENTRY_CELERY_LOGLEVEL = env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO) RAVEN_CONFIG = { 'CELERY_LOGLEVEL': env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO), 'DSN': SENTRY_DSN } # Your production stuff: Below this line define 3rd party library settings
35.29064
117
0.626326
acf67082920c7296f2b199523ec7a1f94c4cf9a3
7,948
py
Python
numba/cuda/tests/nocuda/test_library_lookup.py
auderson/numba
3d67c9850ab56457f418cf40af6245fd9c337705
[ "BSD-2-Clause" ]
6,620
2015-01-04T08:51:04.000Z
2022-03-31T12:52:18.000Z
numba/cuda/tests/nocuda/test_library_lookup.py
auderson/numba
3d67c9850ab56457f418cf40af6245fd9c337705
[ "BSD-2-Clause" ]
6,457
2015-01-04T03:18:41.000Z
2022-03-31T17:38:42.000Z
numba/cuda/tests/nocuda/test_library_lookup.py
auderson/numba
3d67c9850ab56457f418cf40af6245fd9c337705
[ "BSD-2-Clause" ]
930
2015-01-25T02:33:03.000Z
2022-03-30T14:10:32.000Z
import sys import os import multiprocessing as mp import warnings from numba.core.config import IS_WIN32, IS_OSX from numba.core.errors import NumbaWarning from numba.cuda.cudadrv import nvvm from numba.cuda.testing import ( unittest, skip_on_cudasim, SerialMixin, skip_unless_conda_cudatoolkit, ) from numba.cuda.cuda_paths import ( _get_libdevice_path_decision, _get_nvvm_path_decision, _get_cudalib_dir_path_decision, get_system_ctk, ) has_cuda = nvvm.is_available() has_mp_get_context = hasattr(mp, 'get_context') class LibraryLookupBase(SerialMixin, unittest.TestCase): def setUp(self): ctx = mp.get_context('spawn') qrecv = ctx.Queue() qsend = ctx.Queue() self.qsend = qsend self.qrecv = qrecv self.child_process = ctx.Process( target=check_lib_lookup, args=(qrecv, qsend), daemon=True, ) self.child_process.start() def tearDown(self): self.qsend.put(self.do_terminate) self.child_process.join(3) # Ensure the process is terminated self.assertIsNotNone(self.child_process) def remote_do(self, action): self.qsend.put(action) out = self.qrecv.get() self.assertNotIsInstance(out, BaseException) return out @staticmethod def do_terminate(): return False, None def remove_env(name): try: del os.environ[name] except KeyError: return False else: return True def check_lib_lookup(qout, qin): status = True while status: try: action = qin.get() except Exception as e: qout.put(e) status = False else: try: with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always", NumbaWarning) status, result = action() qout.put(result + (w,)) except Exception as e: qout.put(e) status = False @skip_on_cudasim('Library detection unsupported in the simulator') @unittest.skipUnless(has_mp_get_context, 'mp.get_context not available') @skip_unless_conda_cudatoolkit('test assumes conda installed cudatoolkit') class TestLibDeviceLookUp(LibraryLookupBase): def test_libdevice_path_decision(self): # Check that the default is using conda environment by, info, warns = self.remote_do(self.do_clear_envs) if has_cuda: self.assertEqual(by, 'Conda environment') else: self.assertEqual(by, "<unknown>") self.assertIsNone(info) self.assertFalse(warns) # Check that CUDA_HOME works by removing conda-env by, info, warns = self.remote_do(self.do_set_cuda_home) self.assertEqual(by, 'CUDA_HOME') self.assertEqual(info, os.path.join('mycudahome', 'nvvm', 'libdevice')) self.assertFalse(warns) if get_system_ctk() is None: # Fake remove conda environment so no cudatoolkit is available by, info, warns = self.remote_do(self.do_clear_envs) self.assertEqual(by, '<unknown>') self.assertIsNone(info) self.assertFalse(warns) else: # Use system available cudatoolkit by, info, warns = self.remote_do(self.do_clear_envs) self.assertEqual(by, 'System') self.assertFalse(warns) @staticmethod def do_clear_envs(): remove_env('CUDA_HOME') remove_env('CUDA_PATH') return True, _get_libdevice_path_decision() @staticmethod def do_set_cuda_home(): os.environ['CUDA_HOME'] = os.path.join('mycudahome') _fake_non_conda_env() return True, _get_libdevice_path_decision() @skip_on_cudasim('Library detection unsupported in the simulator') @unittest.skipUnless(has_mp_get_context, 'mp.get_context not available') @skip_unless_conda_cudatoolkit('test assumes conda installed cudatoolkit') class TestNvvmLookUp(LibraryLookupBase): def test_nvvm_path_decision(self): # Check that the default is using conda environment by, info, warns = self.remote_do(self.do_clear_envs) if has_cuda: self.assertEqual(by, 'Conda environment') else: self.assertEqual(by, "<unknown>") self.assertIsNone(info) self.assertFalse(warns) # Check that CUDA_HOME works by removing conda-env by, info, warns = self.remote_do(self.do_set_cuda_home) self.assertEqual(by, 'CUDA_HOME') self.assertFalse(warns) if IS_WIN32: self.assertEqual(info, os.path.join('mycudahome', 'nvvm', 'bin')) elif IS_OSX: self.assertEqual(info, os.path.join('mycudahome', 'nvvm', 'lib')) else: self.assertEqual(info, os.path.join('mycudahome', 'nvvm', 'lib64')) if get_system_ctk() is None: # Fake remove conda environment so no cudatoolkit is available by, info, warns = self.remote_do(self.do_clear_envs) self.assertEqual(by, '<unknown>') self.assertIsNone(info) self.assertFalse(warns) else: # Use system available cudatoolkit by, info, warns = self.remote_do(self.do_clear_envs) self.assertEqual(by, 'System') self.assertFalse(warns) @staticmethod def do_clear_envs(): remove_env('CUDA_HOME') remove_env('CUDA_PATH') return True, _get_nvvm_path_decision() @staticmethod def do_set_cuda_home(): os.environ['CUDA_HOME'] = os.path.join('mycudahome') _fake_non_conda_env() return True, _get_nvvm_path_decision() @skip_on_cudasim('Library detection unsupported in the simulator') @unittest.skipUnless(has_mp_get_context, 'mp.get_context not available') @skip_unless_conda_cudatoolkit('test assumes conda installed cudatoolkit') class TestCudaLibLookUp(LibraryLookupBase): def test_cudalib_path_decision(self): # Check that the default is using conda environment by, info, warns = self.remote_do(self.do_clear_envs) if has_cuda: self.assertEqual(by, 'Conda environment') else: self.assertEqual(by, "<unknown>") self.assertIsNone(info) self.assertFalse(warns) # Check that CUDA_HOME works by removing conda-env self.remote_do(self.do_clear_envs) by, info, warns = self.remote_do(self.do_set_cuda_home) self.assertEqual(by, 'CUDA_HOME') self.assertFalse(warns) if IS_WIN32: self.assertEqual(info, os.path.join('mycudahome', 'bin')) elif IS_OSX: self.assertEqual(info, os.path.join('mycudahome', 'lib')) else: self.assertEqual(info, os.path.join('mycudahome', 'lib64')) if get_system_ctk() is None: # Fake remove conda environment so no cudatoolkit is available by, info, warns = self.remote_do(self.do_clear_envs) self.assertEqual(by, "<unknown>") self.assertIsNone(info) self.assertFalse(warns) else: # Use system available cudatoolkit by, info, warns = self.remote_do(self.do_clear_envs) self.assertEqual(by, 'System') self.assertFalse(warns) @staticmethod def do_clear_envs(): remove_env('CUDA_HOME') remove_env('CUDA_PATH') return True, _get_cudalib_dir_path_decision() @staticmethod def do_set_cuda_home(): os.environ['CUDA_HOME'] = os.path.join('mycudahome') _fake_non_conda_env() return True, _get_cudalib_dir_path_decision() def _fake_non_conda_env(): """ Monkeypatch sys.prefix to hide the fact we are in a conda-env """ sys.prefix = '' if __name__ == '__main__': unittest.main()
33.25523
79
0.639658
acf670f91d5ef2ba26c9213649053d4659b16120
12,241
py
Python
trax/predict_drop.py
stephenjfox/trax
918b1ce2ad63a24cb957ebc8e8ea0af1ee272666
[ "Apache-2.0" ]
null
null
null
trax/predict_drop.py
stephenjfox/trax
918b1ce2ad63a24cb957ebc8e8ea0af1ee272666
[ "Apache-2.0" ]
null
null
null
trax/predict_drop.py
stephenjfox/trax
918b1ce2ad63a24cb957ebc8e8ea0af1ee272666
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2022 The Trax 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. # Lint as: python3 """Prediction binary for the Drop task. Binary that loads a checkpoint and runs inference on selected problems from the Drop dataset. For more details about Drop see https://arxiv.org/pdf/1903.00161.pdf. """ import json import os import re import time from absl import app as absl_app from absl import flags import gin import jax import numpy as np from seqio import vocabularies as t5_spc_vocab from t5 import data import tensorflow as tf from trax import data as trax_data from trax import layers as tl from trax import shapes from trax.supervised import decoding FLAGS = flags.FLAGS flags.DEFINE_string('checkpoint_dir', '', 'Path to model checkpoint.') flags.DEFINE_integer('max_answer_len', 1024, 'Maximum length of answers to produce.') flags.DEFINE_integer('batch_size', 1, 'Batch size for eval.') flags.DEFINE_integer('num_examples', 1, 'Number of examples to infer.') flags.DEFINE_integer('n_hashes', None, 'n_hashes parameter to override in attentions.') flags.DEFINE_integer('example_repetitions', 1, 'How many times to infer an example.') flags.DEFINE_bool('use_eval_mode', False, 'If True, use the slower but easier to debug eval mode.') flags.DEFINE_bool('use_eval_set', False, 'If True, use eval set for evaluation.') flags.DEFINE_bool( 'use_beam_search', False, 'If True, use beam search, otherwise use autoregresive sampling.') flags.DEFINE_float('autoregressive_sample_temp', 1, 'The temperature for autoregressive sampling.') flags.DEFINE_integer('n_beams', 4, 'How many beams to use in beam search.') flags.DEFINE_string( 'output_dir', '', 'Path to the output directory where articles, abstracts, ' 'and predictions would be stored.') flags.DEFINE_integer('starting_example', 0, 'Example index for starting decoding.') flags.DEFINE_integer('reload_after', 1000, 'Reload checkpoint after reload_after examples.') flags.DEFINE_multi_string('config_file', None, 'Configuration file with parameters (.gin).') def _check_exists(file_path): if not tf.io.gfile.exists(file_path): print('No such file: %s' % file_path, flush=True) exit(1) def multiply_examples(example): for i in range(FLAGS.example_repetitions): yield i, example def prepare_model(model_file, batch_size=1): """Prepare the model.""" mode = 'eval' if FLAGS.use_eval_mode else 'predict' print('Initializing the model in %s mode.' % mode, flush=True) # Read the model name from the gin file model_reference = gin.query_parameter( 'trax.supervised.trainer_lib.train.model') model = model_reference.scoped_configurable_fn(mode=mode) dec_len = 32 if FLAGS.use_eval_mode else 1 batch_size_pd = max(1, batch_size // jax.local_device_count()) shape11 = shapes.ShapeDtype((batch_size_pd, dec_len), dtype=np.int32) # shape11 = shapes.ShapeDtype((1, 1), dtype=np.int32) model.init_from_file( model_file, weights_only=True, input_signature=(shape11, shape11)) model = tl.Accelerate(model) initial_state = model.state vocab = t5_spc_vocab.SentencePieceVocabulary(data.DEFAULT_SPM_PATH) return vocab, model, initial_state def is_number(s): try: float(s) return True except ValueError: return False def main(argv): if len(argv) > 1: raise absl_app.UsageError('Too many command-line arguments.') if not FLAGS.output_dir: raise absl_app.UsageError('--output_dir needs to be provided.') tf.compat.v1.enable_eager_execution() # Check that checkpoint_dir is correct: should contain model.pkl.gz file. model_file = os.path.join(FLAGS.checkpoint_dir, 'model.pkl.gz') _check_exists(model_file) gin.parse_config_file(os.path.join(FLAGS.checkpoint_dir, 'config.gin')) # Batching on our own because of possible repetitions of examples. gin.bind_parameter('data.Batch.batch_size', 1) if FLAGS.n_hashes is not None: gin.bind_parameter('LSHSelfAttention.n_hashes', FLAGS.n_hashes) gin.bind_parameter('ref2_encoder/LSHSelfAttention.n_hashes', FLAGS.n_hashes) vocab, model, initial_state = prepare_model(model_file, FLAGS.batch_size) host_id, host_count = jax.host_id(), jax.host_count() print('Running on host %d out of %d.' % (host_id, host_count)) example_count = 0 start_time = time.time() # Creates all intermediate directories if they do not exist tf.io.gfile.makedirs(FLAGS.output_dir) json_to_write = os.path.join(FLAGS.output_dir, 'output%d.json' % host_id) all_jsons = [] # In a case of a reset we have to check how much work was already done. # We can check whether the processing of an example was finished, but # currently we are only checking whether it was started. done = FLAGS.starting_example reload_count = 0 all_existing_files = tf.io.gfile.listdir(FLAGS.output_dir) for filename in all_existing_files: if 'processing' in filename: # The definition of digits looks for a number after the infix "processing" # in the file name. Example: tom_processing_532 will lead to # digits = "processing_532" and number equal to "532". digits = filename[filename.find('processing'):] number = ''.join(d for d in digits if d.isdigit()) if is_number( number) and int(number) < FLAGS.num_examples + FLAGS.starting_example: done = max(done, int(number)) print('The done number is {}'.format(done)) if FLAGS.use_eval_set: drop_gen = trax_data.CreateDropInputs(train=False)() else: drop_gen = trax_data.CreateDropInputs(train=True)() padding_fun = trax_data.PadToLength() # TODO(henrykm): improve managment of the counters. # example_count_total - all numeric examples # example_count - all numeric examples above starting_example # reload_count - if we processed FLAGS.reload_after examples, # then the checkpoint should be reloaded. # idx - total number of exaples example_count_total = 0 reload_count += 1 for idx, e in enumerate(drop_gen): if reload_count >= FLAGS.reload_after: vocab, model, initial_state = prepare_model(model_file, FLAGS.batch_size) reload_count = 0 if example_count >= FLAGS.num_examples: print('Reached the example_count {} - breaking'.format(example_count)) break if not is_number(e[1]): continue target_answer = float(e[1]) # We count numeric starting examples example_count_total += 1 if example_count_total <= FLAGS.starting_example: print('Skipping example_count_total {} because it is below {}'.format( example_count_total, FLAGS.starting_example)) continue if example_count % 10 == 0: elapsed_time = time.time() - start_time start_time = time.time() print('Starting inference on example %d, %.2fs since last log' % (example_count, elapsed_time), flush=True) example_count += 1 if example_count <= done - FLAGS.starting_example + 1: print('Skipping example_count {} because it is below {}'.format( example_count, done - FLAGS.starting_example)) # We are increasing the example_count because the example # was processed before continue if example_count % host_count != host_id: continue # At this point we are committed to the processing of an example with # index example_count processing_file = os.path.join(FLAGS.output_dir, 'processing_') data_id = str(example_count + FLAGS.starting_example) with tf.io.gfile.GFile(processing_file + data_id, 'w') as w: w.write('Procesing started.') for repetition_id, example in multiply_examples(e): question = example[0] question_text = question[question.find(':') + 2:] question_text = question_text.replace('-', ' - ') question = 'infer full calculation: ' + question_text list_num = [ float(num.replace(',', '').rstrip('.')) for num in re.findall( r'[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?', question) ] for i in range(len(list_num)): question += ' n{} = {}'.format(i, list_num[i]) # print('Question {}'.format(question)) tokenized_question = next( padding_fun( trax_data.tokenize([ question, ], vocab_file=gin.query_parameter( 'trax.data.Tokenize.vocab_file')))) state = model.state if FLAGS.use_beam_search: answer_beams = decoding.beam_search( model, tokenized_question[None, :], n_beams=FLAGS.n_beams, max_length=FLAGS.max_answer_len, accelerate=False) model.state = state else: answer_beams = [] # We recycle the n_beams flag to control the number # of autoregressive samples. for i in range(FLAGS.n_beams): answer = decoding.autoregressive_sample( model, tokenized_question[None, :], temperature=FLAGS.autoregressive_sample_temp, max_length=FLAGS.max_answer_len, accelerate=False) model.state = state answer_beams.append(answer) correct_example_index = -1 for i in range(len(answer_beams)): if FLAGS.use_beam_search: answer = trax_data.detokenize( answer_beams[i][0][0], vocab_file=gin.query_parameter('trax.data.Tokenize.vocab_file')) else: answer = trax_data.detokenize( answer_beams[i][0], vocab_file=gin.query_parameter('trax.data.Tokenize.vocab_file')) print('Proposed computation {}'.format(answer)) list_op = answer.split('|') if not list_op[-1]: list_op = list_op[:-1] try: result = trax_data.tf_inputs.compute_result(list_op, list_num) if target_answer in result: correct_example_index = result.index(target_answer) break # This is a temporary hack with "broad" exceptions - the computations # must fail sometime, because we evaluate arbitrary sequences; I am in # the process of checking what are possible failure modes. except Exception as e: # pylint: disable=broad-except print(e) try: result = trax_data.tf_inputs.compute_result(list_op[:-1], list_num) if target_answer in result: correct_example_index = result.index(target_answer) break except Exception as e: # pylint: disable=broad-except print(e) print('Infered incorrect computation.') if correct_example_index == -1: continue json_record = { 'question': question_text, 'input': question, 'calculation': '|'.join(list_op[:correct_example_index + 1]), 'target_answer': target_answer } all_jsons.append(json.dumps(json_record) + '\n') # Outputting the inferred data in JSONL format. data_id = str(example_count + FLAGS.starting_example) with tf.io.gfile.GFile(json_to_write + data_id, 'w') as w: w.write(json.dumps(json_record) + '\n') with tf.io.gfile.GFile(processing_file + data_id, 'w') as w: w.write('Procesing finished.') with tf.io.gfile.GFile(json_to_write + '_' + str(FLAGS.starting_example), 'w') as w: for record in all_jsons: w.write(record) if __name__ == '__main__': absl_app.run(main)
37.206687
80
0.670942
acf6719965624e7ca59e2507b1500f57dcc898c5
2,027
py
Python
foolbox/attacks/blur.py
schoyc/foolbox
e0f400be8fa393467d3db598576e985727edb310
[ "MIT" ]
4
2021-01-07T12:33:36.000Z
2022-03-12T07:16:43.000Z
foolbox/attacks/blur.py
alvarorobledo/foolbox
25d995b1a50f4926e07bc51877d385c0518982f8
[ "MIT" ]
null
null
null
foolbox/attacks/blur.py
alvarorobledo/foolbox
25d995b1a50f4926e07bc51877d385c0518982f8
[ "MIT" ]
1
2021-04-14T11:12:28.000Z
2021-04-14T11:12:28.000Z
import numpy as np from collections import Iterable from scipy.ndimage.filters import gaussian_filter from .base import Attack from .base import call_decorator class GaussianBlurAttack(Attack): """Blurs the image until it is misclassified.""" @call_decorator def __call__(self, input_or_adv, label=None, unpack=True, epsilons=1000): """Blurs the image until it is misclassified. Parameters ---------- input_or_adv : `numpy.ndarray` or :class:`Adversarial` The original, unperturbed input as a `numpy.ndarray` or an :class:`Adversarial` instance. label : int The reference label of the original input. Must be passed if `a` is a `numpy.ndarray`, must not be passed if `a` is an :class:`Adversarial` instance. unpack : bool If true, returns the adversarial input, otherwise returns the Adversarial object. epsilons : int or Iterable[float] Either Iterable of standard deviations of the Gaussian blur or number of standard deviations between 0 and 1 that should be tried. """ a = input_or_adv del input_or_adv del label del unpack image = a.original_image min_, max_ = a.bounds() axis = a.channel_axis(batch=False) hw = [image.shape[i] for i in range(image.ndim) if i != axis] h, w = hw size = max(h, w) if not isinstance(epsilons, Iterable): epsilons = np.linspace(0, 1, num=epsilons + 1)[1:] for epsilon in epsilons: # epsilon = 1 will correspond to # sigma = size = max(width, height) sigmas = [epsilon * size] * 3 sigmas[axis] = 0 blurred = gaussian_filter(image, sigmas) blurred = np.clip(blurred, min_, max_) _, is_adversarial = a.predictions(blurred) if is_adversarial: return
31.671875
72
0.590528
acf672979d5c2601a5ef6f1ab31696f66949cf00
758
py
Python
graphs/cycleInGraph.py
saketvikram/algorithms-ds-in-python
8b100182df8fcc4350b2458f2148481c7e0fb043
[ "MIT" ]
null
null
null
graphs/cycleInGraph.py
saketvikram/algorithms-ds-in-python
8b100182df8fcc4350b2458f2148481c7e0fb043
[ "MIT" ]
null
null
null
graphs/cycleInGraph.py
saketvikram/algorithms-ds-in-python
8b100182df8fcc4350b2458f2148481c7e0fb043
[ "MIT" ]
null
null
null
def cycleInGraph(edges): numberOfNodes = len(edges) visited = [False for _ in range(numberOfNodes)] currentlyInStack = [False for _ in range(numberOfNodes)] for node in range(numberOfNodes): if visited[node]: continue containsCycle = isNodeInCycle(node, edges, visited, currentlyInStack) if containsCycle: return True return False def isNodeInCycle(node, edges, visited, currentlyInStack): visited[node] = True currentlyInStack[node] = True neighbors = edges[node] for neighbor in neighbors: if not visited[neighbor]: containsCycle = isNodeInCycle(neighbor, edges, visited, currentlyInStack) if containsCycle: return True elif currentlyInStack[neighbor]: return True currentlyInStack[node] = False return False
28.074074
76
0.754617
acf6733ba7fd9fe5bee01ebb0ff9f27751ec5ec1
1,384
py
Python
neutron/plugins/ml2/drivers/cisco/ucsm/exceptions.py
venkataanil/juno_neutron
2e62e150c264ccae2dd75fb78caae453eaa77e9f
[ "Apache-2.0" ]
8
2016-02-12T01:25:29.000Z
2019-01-13T14:19:25.000Z
neutron/plugins/ml2/drivers/cisco/ucsm/exceptions.py
venkataanil/juno_neutron
2e62e150c264ccae2dd75fb78caae453eaa77e9f
[ "Apache-2.0" ]
25
2016-01-28T12:33:41.000Z
2016-07-28T21:18:03.000Z
neutron/plugins/ml2/drivers/cisco/ucsm/exceptions.py
venkataanil/juno_neutron
2e62e150c264ccae2dd75fb78caae453eaa77e9f
[ "Apache-2.0" ]
9
2015-05-07T02:47:55.000Z
2019-10-18T15:25:27.000Z
# Copyright 2015 Cisco Systems, 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. """Exceptions used by Cisco UCSM ML2 mechanism driver.""" from neutron.common import exceptions class UcsmConnectFailed(exceptions.NeutronException): message = _("Unable to connect to UCS Manager %(ucsm_ip)s. " "Reason: %(exc)s.") class UcsmConfigReadFailed(exceptions.NeutronException): message = _("Unable to read config from UCS Manager %(ucsm_ip)s. " "Reason: %(exc)s.") class UcsmConfigFailed(exceptions.NeutronException): message = _("Failed to configure %(config)s on UCS Manager %(ucsm_ip)s. " "Reason: %(exc)s.") class UcsmDisconnectFailed(exceptions.NeutronException): message = _("Disconnect to UCS Manager %(ucsm_ip)s failed. " "Reason: %(exc)s.")
35.487179
78
0.694364
acf6739633e757f2a01f1e562daf432217ae9a5e
625
py
Python
wagtail_localize_rws_languagecloud/management/commands/sync_rws.py
zerolab/wagtail-localize-rws-languagecloud
35c67c014c195e4e77896c7449643ea78a6aae68
[ "BSD-3-Clause" ]
null
null
null
wagtail_localize_rws_languagecloud/management/commands/sync_rws.py
zerolab/wagtail-localize-rws-languagecloud
35c67c014c195e4e77896c7449643ea78a6aae68
[ "BSD-3-Clause" ]
6
2022-01-29T14:59:50.000Z
2022-03-31T12:09:06.000Z
wagtail_localize_rws_languagecloud/management/commands/sync_rws.py
zerolab/wagtail-localize-rws-languagecloud
35c67c014c195e4e77896c7449643ea78a6aae68
[ "BSD-3-Clause" ]
null
null
null
import logging from django.core.management.base import BaseCommand from ...sync import SyncManager class Command(BaseCommand): def handle(self, **options): log_level = logging.INFO if options["verbosity"] > 1: log_level = logging.DEBUG logger = logging.getLogger(__name__) # Enable logging to console console = logging.StreamHandler() console.setLevel(log_level) console.setFormatter(logging.Formatter("%(levelname)s - %(message)s")) logger.addHandler(console) logger.setLevel(log_level) SyncManager(logger=logger).sync()
26.041667
78
0.664
acf6739a7c0a39864b73b8092e9ead50daadbd6f
5,669
py
Python
scripts/SEAM/infer_aff.py
IssamLaradji/affinity_lcfcn
2c38500c83dc9c063ea2c910aadc94f14a18f3a5
[ "Apache-2.0" ]
15
2020-09-30T14:28:29.000Z
2022-03-16T11:53:15.000Z
scripts/SEAM/infer_aff.py
IssamLaradji/affinity_lcfcn
2c38500c83dc9c063ea2c910aadc94f14a18f3a5
[ "Apache-2.0" ]
2
2020-11-25T00:57:55.000Z
2021-06-16T20:07:08.000Z
scripts/SEAM/infer_aff.py
IssamLaradji/affinity_lcfcn
2c38500c83dc9c063ea2c910aadc94f14a18f3a5
[ "Apache-2.0" ]
2
2020-11-06T22:38:56.000Z
2020-12-02T04:45:05.000Z
import torch import torchvision from .tool import imutils import argparse import importlib import numpy as np from .voc12 import data from torch.utils.data import DataLoader import scipy.misc import torch.nn.functional as F import os.path from .network import resnet38_aff from torchvision.transforms import ToPILImage, ToTensor def get_indices_in_radius(height, width, radius): search_dist = [] for x in range(1, radius): search_dist.append((0, x)) for y in range(1, radius): for x in range(-radius+1, radius): if x*x + y*y < radius*radius: search_dist.append((y, x)) full_indices = np.reshape(np.arange(0, height * width, dtype=np.int64), (height, width)) radius_floor = radius-1 cropped_height = height - radius_floor cropped_width = width - 2 * radius_floor indices_from = np.reshape(full_indices[:-radius_floor, radius_floor:-radius_floor], [-1]) indices_from_to_list = [] for dy, dx in search_dist: indices_to = full_indices[dy:dy + cropped_height, radius_floor + dx:radius_floor + dx + cropped_width] indices_to = np.reshape(indices_to, [-1]) indices_from_to = np.stack((indices_from, indices_to), axis=1) indices_from_to_list.append(indices_from_to) concat_indices_from_to = np.concatenate(indices_from_to_list, axis=0) return concat_indices_from_to def HCW_to_CHW(tensor, sal=False): if sal: tensor = np.expand_dims(tensor, axis=0) else: tensor = np.transpose(tensor, (1, 2, 0)) return tensor def name_img(name, img, SEAM_model): name = name # label = ToTensor()(label) # img = ToPILImage()(img) model = SEAM_model unit = 1 scales = [0.5, 1.0, 1.5, 2.0] inter_transform = torchvision.transforms.Compose( [np.asarray, model.normalize, # ToTensor(), imutils.HWC_to_CHW ]) intera_transform = torchvision.transforms.Compose( [ToTensor(), HCW_to_CHW ]) img = inter_transform(img) img = intera_transform(img) img = img[None] return name, img def infer_aff(name, img, cam_dict, weights_dir = "", model=None): weights =weights_dir # network ="network.resnet38_aff" alpha = 6 beta = 8 logt = 6 crf = False if model is None: model = resnet38_aff.Net() model.load_state_dict(torch.load(weights), strict=False) model.eval() model.cuda() # infer_dataset = voc12.data.VOC12ImageDataset(infer_list, voc12_root=voc12_root, # transform=torchvision.transforms.Compose( # [np.asarray, # model.normalize, # imutils.HWC_to_CHW])) # infer_data_loader = DataLoader(infer_dataset, shuffle=False, num_workers=num_workers, pin_memory=True) name, img = name_img(name, img, model) # for iter, (name, img) in enumerate(infer_data_loader): # name = name[0] # print(iter) orig_shape = img.shape padded_size = (int(np.ceil(img.shape[2]/8)*8), int(np.ceil(img.shape[3]/8)*8)) p2d = (0, padded_size[1] - img.shape[3], 0, padded_size[0] - img.shape[2]) img = F.pad(img, p2d) dheight = int(np.ceil(img.shape[2]/8)) dwidth = int(np.ceil(img.shape[3]/8)) # cam = np.load(os.path.join(cam_dir, name + '.npy'), allow_pickle=True).item() cam = cam_dict cam_full_arr = np.zeros((21, orig_shape[2], orig_shape[3]), np.float32) for k, v in cam.items(): cam_full_arr[k+1] = v cam_full_arr[0] = (1 - np.max(cam_full_arr[1:], (0), keepdims=False))**alpha #cam_full_arr[0] = 0.2 cam_full_arr = np.pad(cam_full_arr, ((0, 0), (0, p2d[3]), (0, p2d[1])), mode='constant') with torch.no_grad(): aff_mat = torch.pow(model.forward(img.cuda(), True), beta) trans_mat = aff_mat / torch.sum(aff_mat, dim=0, keepdim=True) for _ in range(logt): trans_mat = torch.matmul(trans_mat, trans_mat) cam_full_arr = torch.from_numpy(cam_full_arr) cam_full_arr = F.avg_pool2d(cam_full_arr, 8, 8) cam_vec = cam_full_arr.view(21, -1) cam_rw = torch.matmul(cam_vec.cuda(), trans_mat) cam_rw = cam_rw.view(1, 21, dheight, dwidth) cam_rw = torch.nn.Upsample((img.shape[2], img.shape[3]), mode='bilinear')(cam_rw) if crf: img_8 = img[0].numpy().transpose((1,2,0))#F.interpolate(img, (dheight,dwidth), mode='bilinear')[0].numpy().transpose((1,2,0)) img_8 = np.ascontiguousarray(img_8) mean = (0.485, 0.456, 0.406) std = (0.229, 0.224, 0.225) img_8[:,:,0] = (img_8[:,:,0]*std[0] + mean[0])*255 img_8[:,:,1] = (img_8[:,:,1]*std[1] + mean[1])*255 img_8[:,:,2] = (img_8[:,:,2]*std[2] + mean[2])*255 img_8[img_8 > 255] = 255 img_8[img_8 < 0] = 0 img_8 = img_8.astype(np.uint8) cam_rw = cam_rw[0].cpu().numpy() cam_rw = imutils.crf_inference(img_8, cam_rw, t=1) cam_rw = torch.from_numpy(cam_rw).view(1, 21, img.shape[2], img.shape[3]).cuda() _, cam_rw_pred = torch.max(cam_rw, 1) preds = np.uint8(cam_rw_pred.cpu().data[0])[:orig_shape[2], :orig_shape[3]] probs = cam_rw.cpu().data[0][:, :orig_shape[2], :orig_shape[3]] # scipy.misc.imsave(os.path.join(out_rw, name + '.png'), res) # print("saved : %s" %os.path.join(out_rw, name + '.png')) assert probs.shape[1] == preds.shape[0] assert probs.shape[2] == preds.shape[1] print("Done infer_aff") return preds, probs
32.028249
137
0.609455
acf673be827f9f04bf11f5839f1339c2cb536d13
2,420
py
Python
pepipost/controllers/subaccounts_delete_controller.py
kanhaiya2012/Sample
6c3d549525b7883913a4677c3eb6f14c8da34b9b
[ "MIT" ]
null
null
null
pepipost/controllers/subaccounts_delete_controller.py
kanhaiya2012/Sample
6c3d549525b7883913a4677c3eb6f14c8da34b9b
[ "MIT" ]
null
null
null
pepipost/controllers/subaccounts_delete_controller.py
kanhaiya2012/Sample
6c3d549525b7883913a4677c3eb6f14c8da34b9b
[ "MIT" ]
1
2020-05-17T17:55:30.000Z
2020-05-17T17:55:30.000Z
# -*- coding: utf-8 -*- """ pepipost This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ from pepipost.api_helper import APIHelper from pepipost.configuration import Configuration from pepipost.controllers.base_controller import BaseController from pepipost.http.auth.custom_header_auth import CustomHeaderAuth from pepipost.exceptions.api_exception import APIException class SubaccountsDeleteController(BaseController): """A Controller to access Endpoints in the pepipost API.""" def delete_subaccounts_delete_delete(self, body): """Does a DELETE request to /subaccounts/delete. Lets you delete a subaccount Args: body (DeleteSubacoount): delete subaccount Returns: object: Response from the API. API Response Raises: APIException: When an error occurs while fetching the data from the remote API. This exception includes the HTTP Response code, an error message, and the HTTP body that was received in the request. """ # Prepare query URL _url_path = '/subaccounts/delete' _query_builder = Configuration.base_uri _query_builder += _url_path _query_url = APIHelper.clean_url(_query_builder) # Prepare headers _headers = { 'content-type': 'application/json; charset=utf-8' } # Prepare and execute request _request = self.http_client.delete(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body)) CustomHeaderAuth.apply(_request) _context = self.execute_request(_request) # Endpoint and global error handling using HTTP status codes. if _context.response.status_code == 400: raise APIException('API Response', _context) elif _context.response.status_code == 401: raise APIException('API Response', _context) elif _context.response.status_code == 403: raise APIException('API Response', _context) elif _context.response.status_code == 405: raise APIException('Invalid input', _context) self.validate_response(_context) # Return appropriate type return _context.response.raw_body
35.072464
116
0.645041
acf67409aec0a8b6ae0c2d46d42e8c3ae5dc8409
639
py
Python
webdev/fornecedores/migrations/0013_auto_20210515_1915.py
h-zanetti/jewelry-manager
74166b89f492303b8ebf5ff8af058f394eb2a28b
[ "MIT" ]
null
null
null
webdev/fornecedores/migrations/0013_auto_20210515_1915.py
h-zanetti/jewelry-manager
74166b89f492303b8ebf5ff8af058f394eb2a28b
[ "MIT" ]
103
2021-04-25T21:28:11.000Z
2022-03-15T01:36:31.000Z
webdev/fornecedores/migrations/0013_auto_20210515_1915.py
h-zanetti/jewelry-manager
74166b89f492303b8ebf5ff8af058f394eb2a28b
[ "MIT" ]
null
null
null
# Generated by Django 3.1.5 on 2021-05-15 22:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fornecedores', '0012_auto_20210515_1912'), ] operations = [ migrations.RenameField( model_name='documento', old_name='documento', new_name='numero', ), migrations.AddField( model_name='documento', name='nome', field=models.CharField(default=1, help_text='Exemplos: CNPJ, IE', max_length=20, verbose_name='Documento'), preserve_default=False, ), ]
25.56
119
0.593114
acf674cd5b3d5e1ad530c7a64d6383926a9a879c
1,108
py
Python
measures/speed_modify.py
jordic/guillotina_rediscache
69287c21eeb49e5361c2ecb3785868979ecc721e
[ "BSD-2-Clause" ]
2
2019-04-09T20:04:46.000Z
2019-07-09T12:44:12.000Z
measures/speed_modify.py
jordic/guillotina_rediscache
69287c21eeb49e5361c2ecb3785868979ecc721e
[ "BSD-2-Clause" ]
1
2019-03-25T12:31:07.000Z
2019-09-29T17:05:31.000Z
measures/speed_modify.py
jordic/guillotina_rediscache
69287c21eeb49e5361c2ecb3785868979ecc721e
[ "BSD-2-Clause" ]
1
2018-03-30T20:26:53.000Z
2018-03-30T20:26:53.000Z
from guillotina.content import create_content_in_container from guillotina.transactions import get_tm from guillotina.transactions import get_transaction from guillotina.utils import get_current_request import time import uuid ITERATIONS = 100 # ---------------------------------------------------- # Measure performance of retrieval from cache # # Lessons: # ---------------------------------------------------- async def run_modify(container): request = get_current_request() txn = get_transaction(request) tm = get_tm(request) id_ = uuid.uuid4().hex await create_content_in_container(container, 'Item', id_) await tm.commit(txn=txn) await tm.begin(request=request) print(f'Test content modify') start = time.time() for idx in range(ITERATIONS): ob = await container.async_get(id_) ob.title = str(idx) ob._p_register() await tm.commit(txn=txn) await tm.begin(request=request) end = time.time() print(f'Done with {ITERATIONS} in {end - start} seconds') async def run(container): await run_modify(container)
27.02439
61
0.646209
acf674d8f7f234daaa3ba99eced089c61d4472cf
8,447
py
Python
examples/FasterRCNN/modeling/backbone.py
layolu/tensorpack
97360e5b8ca9ce03d8a18b3abef5abfc92cb9907
[ "Apache-2.0" ]
5
2020-10-16T07:11:24.000Z
2021-07-19T06:48:23.000Z
examples/FasterRCNN/modeling/backbone.py
layolu/tensorpack
97360e5b8ca9ce03d8a18b3abef5abfc92cb9907
[ "Apache-2.0" ]
14
2020-09-25T22:35:13.000Z
2022-02-10T01:45:31.000Z
examples/FasterRCNN/modeling/backbone.py
layolu/tensorpack
97360e5b8ca9ce03d8a18b3abef5abfc92cb9907
[ "Apache-2.0" ]
4
2020-12-25T20:24:30.000Z
2021-08-31T14:10:10.000Z
# -*- coding: utf-8 -*- # File: backbone.py import numpy as np import tensorflow as tf from contextlib import ExitStack, contextmanager from tensorpack.models import BatchNorm, Conv2D, MaxPooling, layer_register from tensorpack.tfutils import argscope from tensorpack.tfutils.scope_utils import auto_reuse_variable_scope from tensorpack.tfutils.varreplace import custom_getter_scope, freeze_variables from config import config as cfg @layer_register(log_shape=True) def GroupNorm(x, group=32, gamma_initializer=tf.constant_initializer(1.)): """ More code that reproduces the paper can be found at https://github.com/ppwwyyxx/GroupNorm-reproduce/. """ shape = x.get_shape().as_list() ndims = len(shape) assert ndims == 4, shape chan = shape[1] assert chan % group == 0, chan group_size = chan // group orig_shape = tf.shape(x) h, w = orig_shape[2], orig_shape[3] x = tf.reshape(x, tf.stack([-1, group, group_size, h, w])) mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True) new_shape = [1, group, group_size, 1, 1] beta = tf.get_variable('beta', [chan], initializer=tf.constant_initializer()) beta = tf.reshape(beta, new_shape) gamma = tf.get_variable('gamma', [chan], initializer=gamma_initializer) gamma = tf.reshape(gamma, new_shape) out = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-5, name='output') return tf.reshape(out, orig_shape, name='output') def freeze_affine_getter(getter, *args, **kwargs): # custom getter to freeze affine params inside bn name = args[0] if len(args) else kwargs.get('name') if name.endswith('/gamma') or name.endswith('/beta'): kwargs['trainable'] = False ret = getter(*args, **kwargs) tf.add_to_collection(tf.GraphKeys.MODEL_VARIABLES, ret) else: ret = getter(*args, **kwargs) return ret def maybe_reverse_pad(topleft, bottomright): if cfg.BACKBONE.TF_PAD_MODE: return [topleft, bottomright] return [bottomright, topleft] @contextmanager def backbone_scope(freeze): """ Args: freeze (bool): whether to freeze all the variables under the scope """ def nonlin(x): x = get_norm()(x) return tf.nn.relu(x) with argscope([Conv2D, MaxPooling, BatchNorm], data_format='channels_first'), \ argscope(Conv2D, use_bias=False, activation=nonlin, kernel_initializer=tf.variance_scaling_initializer( scale=2.0, mode='fan_out')), \ ExitStack() as stack: if cfg.BACKBONE.NORM in ['FreezeBN', 'SyncBN']: if freeze or cfg.BACKBONE.NORM == 'FreezeBN': stack.enter_context(argscope(BatchNorm, training=False)) else: stack.enter_context(argscope( BatchNorm, sync_statistics='nccl' if cfg.TRAINER == 'replicated' else 'horovod')) if freeze: stack.enter_context(freeze_variables(stop_gradient=False, skip_collection=True)) else: # the layers are not completely freezed, but we may want to only freeze the affine if cfg.BACKBONE.FREEZE_AFFINE: stack.enter_context(custom_getter_scope(freeze_affine_getter)) yield def image_preprocess(image, bgr=True): with tf.name_scope('image_preprocess'): if image.dtype.base_dtype != tf.float32: image = tf.cast(image, tf.float32) mean = cfg.PREPROC.PIXEL_MEAN std = np.asarray(cfg.PREPROC.PIXEL_STD) if bgr: mean = mean[::-1] std = std[::-1] image_mean = tf.constant(mean, dtype=tf.float32) image_invstd = tf.constant(1.0 / std, dtype=tf.float32) image = (image - image_mean) * image_invstd return image def get_norm(zero_init=False): if cfg.BACKBONE.NORM == 'None': return lambda x: x if cfg.BACKBONE.NORM == 'GN': Norm = GroupNorm layer_name = 'gn' else: Norm = BatchNorm layer_name = 'bn' return lambda x: Norm(layer_name, x, gamma_initializer=tf.zeros_initializer() if zero_init else None) def resnet_shortcut(l, n_out, stride, activation=tf.identity): n_in = l.shape[1] if n_in != n_out: # change dimension when channel is not the same # TF's SAME mode output ceil(x/stride), which is NOT what we want when x is odd and stride is 2 # In FPN mode, the images are pre-padded already. if not cfg.MODE_FPN and stride == 2: l = l[:, :, :-1, :-1] return Conv2D('convshortcut', l, n_out, 1, strides=stride, activation=activation) else: return l def resnet_bottleneck(l, ch_out, stride): shortcut = l if cfg.BACKBONE.STRIDE_1X1: if stride == 2: l = l[:, :, :-1, :-1] l = Conv2D('conv1', l, ch_out, 1, strides=stride) l = Conv2D('conv2', l, ch_out, 3, strides=1) else: l = Conv2D('conv1', l, ch_out, 1, strides=1) if stride == 2: l = tf.pad(l, [[0, 0], [0, 0], maybe_reverse_pad(0, 1), maybe_reverse_pad(0, 1)]) l = Conv2D('conv2', l, ch_out, 3, strides=2, padding='VALID') else: l = Conv2D('conv2', l, ch_out, 3, strides=stride) if cfg.BACKBONE.NORM != 'None': l = Conv2D('conv3', l, ch_out * 4, 1, activation=get_norm(zero_init=True)) else: l = Conv2D('conv3', l, ch_out * 4, 1, activation=tf.identity, kernel_initializer=tf.constant_initializer()) ret = l + resnet_shortcut(shortcut, ch_out * 4, stride, activation=get_norm(zero_init=False)) return tf.nn.relu(ret, name='output') def resnet_group(name, l, block_func, features, count, stride): with tf.variable_scope(name): for i in range(0, count): with tf.variable_scope('block{}'.format(i)): l = block_func(l, features, stride if i == 0 else 1) return l def resnet_c4_backbone(image, num_blocks): assert len(num_blocks) == 3 freeze_at = cfg.BACKBONE.FREEZE_AT with backbone_scope(freeze=freeze_at > 0): l = tf.pad(image, [[0, 0], [0, 0], maybe_reverse_pad(2, 3), maybe_reverse_pad(2, 3)]) l = Conv2D('conv0', l, 64, 7, strides=2, padding='VALID') l = tf.pad(l, [[0, 0], [0, 0], maybe_reverse_pad(0, 1), maybe_reverse_pad(0, 1)]) l = MaxPooling('pool0', l, 3, strides=2, padding='VALID') with backbone_scope(freeze=freeze_at > 1): c2 = resnet_group('group0', l, resnet_bottleneck, 64, num_blocks[0], 1) with backbone_scope(freeze=False): c3 = resnet_group('group1', c2, resnet_bottleneck, 128, num_blocks[1], 2) c4 = resnet_group('group2', c3, resnet_bottleneck, 256, num_blocks[2], 2) # 16x downsampling up to now return c4 @auto_reuse_variable_scope def resnet_conv5(image, num_block): with backbone_scope(freeze=False): l = resnet_group('group3', image, resnet_bottleneck, 512, num_block, 2) return l def resnet_fpn_backbone(image, num_blocks): freeze_at = cfg.BACKBONE.FREEZE_AT shape2d = tf.shape(image)[2:] mult = float(cfg.FPN.RESOLUTION_REQUIREMENT) new_shape2d = tf.cast(tf.ceil(tf.cast(shape2d, tf.float32) / mult) * mult, tf.int32) pad_shape2d = new_shape2d - shape2d assert len(num_blocks) == 4, num_blocks with backbone_scope(freeze=freeze_at > 0): chan = image.shape[1] pad_base = maybe_reverse_pad(2, 3) l = tf.pad(image, tf.stack( [[0, 0], [0, 0], [pad_base[0], pad_base[1] + pad_shape2d[0]], [pad_base[0], pad_base[1] + pad_shape2d[1]]])) l.set_shape([None, chan, None, None]) l = Conv2D('conv0', l, 64, 7, strides=2, padding='VALID') l = tf.pad(l, [[0, 0], [0, 0], maybe_reverse_pad(0, 1), maybe_reverse_pad(0, 1)]) l = MaxPooling('pool0', l, 3, strides=2, padding='VALID') with backbone_scope(freeze=freeze_at > 1): c2 = resnet_group('group0', l, resnet_bottleneck, 64, num_blocks[0], 1) with backbone_scope(freeze=False): c3 = resnet_group('group1', c2, resnet_bottleneck, 128, num_blocks[1], 2) c4 = resnet_group('group2', c3, resnet_bottleneck, 256, num_blocks[2], 2) c5 = resnet_group('group3', c4, resnet_bottleneck, 512, num_blocks[3], 2) # 32x downsampling up to now # size of c5: ceil(input/32) return c2, c3, c4, c5
38.395455
105
0.630875
acf6765f0ed1d75b3fdd19f4d65657e17ef1f86b
457
py
Python
saleor/account/migrations/0019_auto_20180528_1205.py
elwoodxblues/saleor
5e4e4a4259a011d24b04ebd24c77c689de843fa1
[ "CC-BY-4.0" ]
15,337
2015-01-12T02:11:52.000Z
2021-10-05T19:19:29.000Z
saleor/account/migrations/0019_auto_20180528_1205.py
elwoodxblues/saleor
5e4e4a4259a011d24b04ebd24c77c689de843fa1
[ "CC-BY-4.0" ]
7,486
2015-02-11T10:52:13.000Z
2021-10-06T09:37:15.000Z
saleor/account/migrations/0019_auto_20180528_1205.py
aminziadna/saleor
2e78fb5bcf8b83a6278af02551a104cfa555a1fb
[ "CC-BY-4.0" ]
5,864
2015-01-16T14:52:54.000Z
2021-10-05T23:01:15.000Z
# Generated by Django 2.0.3 on 2018-05-28 17:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("account", "0018_auto_20180426_0641")] operations = [ migrations.AlterField( model_name="user", name="addresses", field=models.ManyToManyField( blank=True, related_name="user_addresses", to="account.Address" ), ) ]
24.052632
79
0.606127
acf6775eb257ac22fd7e50742d64f0bfce32cfc9
1,200
py
Python
dpixelmonster/du_utils.py
LarsDu/DeepPixelMonster
37ec766af76a850d66e93c290e6f5d5b87654b96
[ "Apache-2.0" ]
1
2017-11-19T14:06:02.000Z
2017-11-19T14:06:02.000Z
dpixelmonster/du_utils.py
LarsDu/DeepPixelMonster
37ec766af76a850d66e93c290e6f5d5b87654b96
[ "Apache-2.0" ]
null
null
null
dpixelmonster/du_utils.py
LarsDu/DeepPixelMonster
37ec766af76a850d66e93c290e6f5d5b87654b96
[ "Apache-2.0" ]
null
null
null
import tensorflow as tf def tanh_to_sig_scale(tanh_input,scale_multiplier=1.): """For image data scaled between [-1,1], rescale to [0,1] * scale_multiplier (e.g. 255 for RGB images) """ #Due to operator overloading, this also works with tensors return ((tanh_input+1.)/2.)*scale_multiplier def random_image_transforms(image): #input should be [0,1] rand_flip=True rand_bright=True rand_contrast=True rand_hue=True rand_sat=False do_rescale_tanh = True if rand_flip: image = tf.image.random_flip_left_right(image) if rand_bright: image = tf.image.random_brightness(image,max_delta=.15) if rand_contrast: image=tf.image.random_contrast(image,lower=0.80,upper=1.2) if rand_hue: image=tf.image.random_hue(image,max_delta=0.07) if rand_sat: image=tf.image.random_saturation(image,lower=.95,upper=1.05) # Limit pixel values to [0, 1] #https://github.com/tensorflow/tensorflow/issues/3816 image = tf.minimum(image, 1.0) image = tf.maximum(image, 0.) if do_rescale_tanh: #Scale from [0,1] to [-1,1] image = (2*image)-1 return image
28.571429
68
0.660833
acf6779c9eabd8c1e858d314b6ef292e95ce1818
5,658
py
Python
references/detection/evaluate_pytorch.py
Mindee/doctr
b9d8feb1b4a2206e4944ef2dea109acc19585074
[ "Apache-2.0" ]
628
2021-02-13T21:49:37.000Z
2022-03-31T19:48:57.000Z
references/detection/evaluate_pytorch.py
Mindee/doctr
b9d8feb1b4a2206e4944ef2dea109acc19585074
[ "Apache-2.0" ]
694
2021-02-08T15:23:38.000Z
2022-03-31T07:24:59.000Z
references/detection/evaluate_pytorch.py
Mindee/doctr
b9d8feb1b4a2206e4944ef2dea109acc19585074
[ "Apache-2.0" ]
90
2021-04-28T05:39:02.000Z
2022-03-31T06:48:36.000Z
# Copyright (C) 2021, Mindee. # This program is licensed under the Apache License version 2. # See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details. import os os.environ['USE_TORCH'] = '1' import logging import multiprocessing as mp import time from pathlib import Path import torch from torch.utils.data import DataLoader, SequentialSampler from torchvision.transforms import Normalize from tqdm import tqdm from doctr import datasets from doctr import transforms as T from doctr.models import detection from doctr.utils.metrics import LocalizationConfusion @torch.no_grad() def evaluate(model, val_loader, batch_transforms, val_metric, amp=False): # Model in eval mode model.eval() # Reset val metric val_metric.reset() # Validation loop val_loss, batch_cnt = 0, 0 for images, targets in tqdm(val_loader): if torch.cuda.is_available(): images = images.cuda() images = batch_transforms(images) targets = [t['boxes'] for t in targets] if amp: with torch.cuda.amp.autocast(): out = model(images, targets, return_boxes=True) else: out = model(images, targets, return_boxes=True) # Compute metric loc_preds = out['preds'] for boxes_gt, boxes_pred in zip(targets, loc_preds): # Remove scores val_metric.update(gts=boxes_gt, preds=boxes_pred[:, :-1]) val_loss += out['loss'].item() batch_cnt += 1 val_loss /= batch_cnt recall, precision, mean_iou = val_metric.summary() return val_loss, recall, precision, mean_iou def main(args): print(args) if not isinstance(args.workers, int): args.workers = min(16, mp.cpu_count()) torch.backends.cudnn.benchmark = True # Load docTR model model = detection.__dict__[args.arch]( pretrained=not isinstance(args.resume, str), assume_straight_pages=not args.rotation ).eval() if isinstance(args.size, int): input_shape = (args.size, args.size) else: input_shape = model.cfg['input_shape'][-2:] mean, std = model.cfg['mean'], model.cfg['std'] st = time.time() ds = datasets.__dict__[args.dataset]( train=True, download=True, rotated_bbox=args.rotation, sample_transforms=T.Resize(input_shape), ) # Monkeypatch subfolder = ds.root.split("/")[-2:] ds.root = str(Path(ds.root).parent.parent) ds.data = [(os.path.join(*subfolder, name), target) for name, target in ds.data] _ds = datasets.__dict__[args.dataset](train=False, rotated_bbox=args.rotation) subfolder = _ds.root.split("/")[-2:] ds.data.extend([(os.path.join(*subfolder, name), target) for name, target in _ds.data]) test_loader = DataLoader( ds, batch_size=args.batch_size, drop_last=False, num_workers=args.workers, sampler=SequentialSampler(ds), pin_memory=torch.cuda.is_available(), collate_fn=ds.collate_fn, ) print(f"Test set loaded in {time.time() - st:.4}s ({len(ds)} samples in " f"{len(test_loader)} batches)") batch_transforms = Normalize(mean=mean, std=std) # Resume weights if isinstance(args.resume, str): print(f"Resuming {args.resume}") checkpoint = torch.load(args.resume, map_location='cpu') model.load_state_dict(checkpoint) # GPU if isinstance(args.device, int): if not torch.cuda.is_available(): raise AssertionError("PyTorch cannot access your GPU. Please investigate!") if args.device >= torch.cuda.device_count(): raise ValueError("Invalid device index") # Silent default switch to GPU if available elif torch.cuda.is_available(): args.device = 0 else: logging.warning("No accessible GPU, targe device set to CPU.") if torch.cuda.is_available(): torch.cuda.set_device(args.device) model = model.cuda() # Metrics metric = LocalizationConfusion(rotated_bbox=args.rotation, mask_shape=input_shape) print("Running evaluation") val_loss, recall, precision, mean_iou = evaluate(model, test_loader, batch_transforms, metric, amp=args.amp) print(f"Validation loss: {val_loss:.6} (Recall: {recall:.2%} | Precision: {precision:.2%} | " f"Mean IoU: {mean_iou:.2%})") def parse_args(): import argparse parser = argparse.ArgumentParser(description='docTR evaluation script for text detection (PyTorch)', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('arch', type=str, help='text-detection model to evaluate') parser.add_argument('--dataset', type=str, default="FUNSD", help='Dataset to evaluate on') parser.add_argument('-b', '--batch_size', type=int, default=2, help='batch size for evaluation') parser.add_argument('--device', default=None, type=int, help='device') parser.add_argument('--size', type=int, default=None, help='model input size, H = W') parser.add_argument('-j', '--workers', type=int, default=None, help='number of workers used for dataloading') parser.add_argument('--rotation', dest='rotation', action='store_true', help='inference with rotated bbox') parser.add_argument('--resume', type=str, default=None, help='Checkpoint to resume') parser.add_argument("--amp", dest="amp", help="Use Automatic Mixed Precision", action="store_true") args = parser.parse_args() return args if __name__ == "__main__": args = parse_args() main(args)
35.142857
113
0.661718
acf67be36d17f98f663e7d1432af12bc5b73848a
419
py
Python
shareyourmeal/wsgi.py
swathi-kannan/shareyourmeal
dfb1030f4dd514256a124150c7cd2f1131091841
[ "Apache-2.0" ]
null
null
null
shareyourmeal/wsgi.py
swathi-kannan/shareyourmeal
dfb1030f4dd514256a124150c7cd2f1131091841
[ "Apache-2.0" ]
null
null
null
shareyourmeal/wsgi.py
swathi-kannan/shareyourmeal
dfb1030f4dd514256a124150c7cd2f1131091841
[ "Apache-2.0" ]
null
null
null
""" WSGI config for shareyourmeal project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shareyourmeal.settings') application = get_wsgi_application()
24.647059
79
0.761337
acf67ca38bd50a643d3c7cbdb89fdb9d5661e6a9
567
py
Python
main.py
Exaltead/wallpaper-changer
13a8983e43ae587dc47d65f918cf39907c8009a9
[ "MIT" ]
null
null
null
main.py
Exaltead/wallpaper-changer
13a8983e43ae587dc47d65f918cf39907c8009a9
[ "MIT" ]
null
null
null
main.py
Exaltead/wallpaper-changer
13a8983e43ae587dc47d65f918cf39907c8009a9
[ "MIT" ]
null
null
null
import json import praw import selection import changer def _load_secret_config(filename: str): with open(filename, mode='r') as f: return json.load(f) def main(): config = _load_secret_config("keys.secret.json") reddit = praw.Reddit(client_id=config['client_id'], client_secret=config['client_secret'], user_agent=config['user_agent']) submission = selection.select_submission(config, reddit) changer.set_desktop_background(submission, "pics") if __name__ == "__main__": main()
24.652174
63
0.664903
acf67d34b0eb281070e07a3fe3d255038f80e50b
360
py
Python
python_modules/libraries/dagster-aws/dagster_aws/s3/types.py
shahvineet98/dagster
2471d39c52f660e23e8c0d8e8ded873ddc3df036
[ "Apache-2.0" ]
3
2020-04-28T16:27:33.000Z
2020-07-22T07:43:30.000Z
python_modules/libraries/dagster-aws/dagster_aws/s3/types.py
shahvineet98/dagster
2471d39c52f660e23e8c0d8e8ded873ddc3df036
[ "Apache-2.0" ]
null
null
null
python_modules/libraries/dagster-aws/dagster_aws/s3/types.py
shahvineet98/dagster
2471d39c52f660e23e8c0d8e8ded873ddc3df036
[ "Apache-2.0" ]
1
2021-02-21T12:16:47.000Z
2021-02-21T12:16:47.000Z
from dagster import Enum, EnumValue S3ACL = Enum( 'S3ACL', enum_values=[ EnumValue('private'), EnumValue('public-read'), EnumValue('public-read-write'), EnumValue('authenticated-read'), EnumValue('aws-exec-read'), EnumValue('bucket-owner-read'), EnumValue('bucket-owner-full-control'), ], )
24
47
0.597222
acf67d9f7dc77dc33b0192e4eaa085698d8e925c
146
py
Python
TF-Lambda/lambda/example.py
Keimille/Terraform-Projects
85e590a9828f9c9953bf5210a1305f81df10c90b
[ "MIT" ]
null
null
null
TF-Lambda/lambda/example.py
Keimille/Terraform-Projects
85e590a9828f9c9953bf5210a1305f81df10c90b
[ "MIT" ]
null
null
null
TF-Lambda/lambda/example.py
Keimille/Terraform-Projects
85e590a9828f9c9953bf5210a1305f81df10c90b
[ "MIT" ]
null
null
null
import os def lambda_handler(event, context): print('### Environment Variables') print(os.environ) print'### Event') print(event)
20.857143
38
0.657534
acf67ed95bb52232c5b443e5418e0f99fee2ded6
4,676
py
Python
setup.py
Sokowatch/incubator-superset
e8e54b18fc561a3559fcaa5cc8e0a432f171711a
[ "Apache-2.0" ]
null
null
null
setup.py
Sokowatch/incubator-superset
e8e54b18fc561a3559fcaa5cc8e0a432f171711a
[ "Apache-2.0" ]
7
2021-03-10T23:36:26.000Z
2022-03-29T22:29:00.000Z
setup.py
Sokowatch/incubator-superset
e8e54b18fc561a3559fcaa5cc8e0a432f171711a
[ "Apache-2.0" ]
2
2019-07-19T09:34:24.000Z
2019-09-20T10:02:04.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import io import json import os import subprocess import sys from setuptools import find_packages, setup if sys.version_info < (3, 6): sys.exit("Sorry, Python < 3.6 is not supported") BASE_DIR = os.path.abspath(os.path.dirname(__file__)) PACKAGE_JSON = os.path.join(BASE_DIR, "superset-frontend", "package.json") with open(PACKAGE_JSON, "r") as package_file: version_string = json.load(package_file)["version"] with io.open("README.md", "r", encoding="utf-8") as f: long_description = f.read() def get_git_sha(): try: s = subprocess.check_output(["git", "rev-parse", "HEAD"]) return s.decode().strip() except Exception: return "" GIT_SHA = get_git_sha() version_info = {"GIT_SHA": GIT_SHA, "version": version_string} print("-==-" * 15) print("VERSION: " + version_string) print("GIT SHA: " + GIT_SHA) print("-==-" * 15) VERSION_INFO_FILE = os.path.join(BASE_DIR, "superset", "static", "version_info.json") with open(VERSION_INFO_FILE, "w") as version_file: json.dump(version_info, version_file) setup( name="apache-superset", description=("A modern, enterprise-ready business intelligence web application"), long_description=long_description, long_description_content_type="text/markdown", version=version_string, packages=find_packages(), include_package_data=True, zip_safe=False, scripts=["superset/bin/superset"], install_requires=[ "backoff>=1.8.0", "bleach>=3.0.2, <4.0.0", "cachelib>=0.1,<0.2", "celery>=4.3.0, <5.0.0, !=4.4.1", "click<8", "colorama", "contextlib2", "croniter>=0.3.28", "cryptography>=2.4.2", "dataclasses<0.7", "flask>=1.1.0, <2.0.0", "flask-appbuilder>=2.3.4, <2.4.0", "flask-caching", "flask-compress", "flask-talisman", "flask-migrate", "flask-wtf", "geopy", "gunicorn>=20.0.2, <20.1", "humanize", "isodate", "markdown>=3.0", "msgpack>=1.0.0, <1.1", "pandas>=1.0.3, <1.1", "parsedatetime", "pathlib2", "polyline", "python-dateutil", "python-dotenv", "python-geohash", "pyarrow>=0.17.0, <0.18", "pyyaml>=5.1", "retry>=0.9.2", "selenium>=3.141.0", "simplejson>=3.15.0", "sqlalchemy>=1.3.16, <2.0", # Breaking change in sqlalchemy-utils==0.36.6, upgrading will probably # require a migration on EncryptedType columns. For more information, see # https://github.com/kvesteri/sqlalchemy-utils/issues/444 "sqlalchemy-utils>=0.33.2,<0.36.5", "sqlparse>=0.3.0, <0.4", "wtforms-json", ], extras_require={ "bigquery": ["pybigquery>=0.4.10", "pandas_gbq>=0.10.0"], "cors": ["flask-cors>=2.0.0"], "gsheets": ["gsheetsdb>=0.1.9"], "hive": ["pyhive[hive]>=0.6.1", "tableschema", "thrift>=0.11.0, <1.0.0"], "mysql": ["mysqlclient==1.4.2.post1"], "postgres": ["psycopg2-binary==2.7.5"], "presto": ["pyhive[presto]>=0.4.0"], "elasticsearch": ["elasticsearch-dbapi>=0.1.0, <0.2.0"], "druid": ["pydruid==0.5.7", "requests==2.22.0"], "hana": ["hdbcli==2.4.162", "sqlalchemy_hana==0.4.0"], "dremio": ["sqlalchemy_dremio>=1.1.0"], "cockroachdb": ["cockroachdb==0.3.3"], "thumbnails": ["Pillow>=7.0.0, <8.0.0"], }, python_requires="~=3.6", author="Apache Software Foundation", author_email="dev@superset.incubator.apache.org", url="https://superset.apache.org/", download_url="https://www.apache.org/dist/incubator/superset/" + version_string, classifiers=[ "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", ], tests_require=["flask-testing==0.8.0"], )
33.640288
85
0.614842
acf67f0a625d9e9856124be4f8cdbe0c290ffd62
8,244
py
Python
dgraph/dgraph-indy.py
didx-xyz/indy-ledger-graph
166e754b624b35612e86a2016470fa637944b939
[ "Apache-2.0" ]
null
null
null
dgraph/dgraph-indy.py
didx-xyz/indy-ledger-graph
166e754b624b35612e86a2016470fa637944b939
[ "Apache-2.0" ]
null
null
null
dgraph/dgraph-indy.py
didx-xyz/indy-ledger-graph
166e754b624b35612e86a2016470fa637944b939
[ "Apache-2.0" ]
null
null
null
import datetime import json import pydgraph from tinydb import TinyDB, Query as DbQuery from tinydb.storages import JSONStorage from tinydb.middlewares import CachingMiddleware from tinydb_smartcache import SmartCacheTable TinyDB.table_class = SmartCacheTable db = TinyDB('../ledger_data/indy_mainnet_tinydb.json' '', storage=CachingMiddleware(JSONStorage)) # Create a client stub. def create_client_stub(): return pydgraph.DgraphClientStub('localhost:9080') # Create a client. def create_client(client_stub): return pydgraph.DgraphClient(client_stub) # Drop All - discard all data and start from a clean slate. def drop_all(client): return client.alter(pydgraph.Operation(drop_all=True)) def resolve_txn_type(item): txn_type_int = item["data"]["txn"]["type"] if txn_type_int == '1': txn_type = 'NYM' elif txn_type_int == '100': txn_type = 'ATTRIB' elif txn_type_int == '101': txn_type = 'SCHEMA' elif txn_type_int == '102': txn_type = 'CLAIM_DEF' elif txn_type_int == '113': txn_type = 'REVOC_REG_DEF' elif txn_type_int == '114': txn_type = 'REVOC_REG_ENTRY' elif txn_type_int == '200': txn_type = 'SET_CONTEXT' elif txn_type_int == '0': txn_type = 'NODE' elif txn_type_int == '10': txn_type = 'POOL_UPGRADE' elif txn_type_int == '11': txn_type = 'NODE_UPGRADE' elif txn_type_int == '11': txn_type = 'POOL_CONFIG' elif txn_type_int == '12': txn_type = 'AUTH_RULE' elif txn_type_int == '12': txn_type = 'AUTH_RULES' elif txn_type_int == '4': txn_type = 'TXN_AUTHOR_AGREEMENT' elif txn_type_int == '5': txn_type = 'TXN_AUTHOR_AGREEMENT_AML' elif txn_type_int == '20000': txn_type = 'SET_FEES' else: txn_type = 'ERROR' return txn_type def resolve_txn_time(item): if 'txnTime' in item["data"]["txnMetadata"]: txn_time_epoch = item["data"]["txnMetadata"]["txnTime"] return str(datetime.datetime.fromtimestamp(txn_time_epoch)) else: return None def resolve_endorser(item): # print("ENDORSER METADATA", parent["data"]["txn"]["metadata"]) if 'endorser' in item["data"]["txn"]["metadata"]: endorser = item["data"]["txn"]["metadata"]["endorser"] TXN = DbQuery() return db.get((TXN['data']['txn']['data']['dest'] == endorser)) else: return None # elif 'from' in item["data"]["txn"]["metadata"]: # TXN = DbQuery() # from_did = item["data"]["txn"]["metadata"]['from'] # # print(from_did) # return db.get((TXN['data']['txn']['data']['dest'] == from_did) & (TXN['data']['txn']['type'] == "1")) def resolve_author(item): if 'from' in item["data"]["txn"]["metadata"]: TXN = DbQuery() from_did = item["data"]["txn"]["metadata"]['from'] # print(from_did) return db.get((TXN['data']['txn']['data']['dest'] == from_did) & (TXN['data']['txn']['type'] == "1")) else: return None # Set schema. def set_schema(client): schema = """ seqNo: @index(exact) . type: string . time: string . endorser: [uid] . author: [uid] . did: string . verkey: string . role: string . alias: string . attribs: [uid] @reverse . authoredDefinitions: [uid] @reverse . authoredSchema: [uid] @reverse . authoredDids: [uid] @reverse . endorsedDefinitions: [uid] @reverse . endorsedSchema: [uid] @reverse . endorsedDids: [uid] @reverse . type DID { id seqNo type time endorser author did verkey role alias attribs authoredDefinitions authoredSchema authoredDids endorsedDefinitions endorsedSchema endorsedDids } """ return client.alter(pydgraph.Operation(schema=schema)) # Create data using JSON. """ type AddDIDInput { seqNo: String! type: String! time: String! endorser: DIDRef author: DIDRef! did: String! verkey: String! role: String alias: String attribs: [AttributeRef]! authoredDefinitions: [CredDefRef]! authoredSchema: [SchemaRef]! authoredDids: [DIDRef]! endorsedDefinitions: [CredDefRef]! endorsedSchema: [SchemaRef]! endorsedDids: [DIDRef]! } """ def create_data(client): # Create a new transaction. print('in create data') txn = client.txn() TXN = DbQuery() item = db.get((TXN['data']['txn']['data']['dest'] == "UoFyxT8BAqotbkhiehxHCn") & (TXN['data']['txn']['type'] == "1")) # # Create data. # print(item) # print(db) # for item in db: # print(type(item)) print(item['seqNo']) type =item["data"]["txn"]["type"] print(type) if type == "1": did = item['data']['txn']['data']['dest'] # did = item['data']['txn']['data']['from'] verkey = item['data']['txn']['data']["verkey"] role = item['data']['txn']['data']['role'] alias = item['data']['txn']['data']['alias'] print(did,verkey,role,alias) try: json_payload = { # 'uid': '_:did', 'Transaction.seqNo': item['seqNo'], 'Transaction.type': resolve_txn_type(item), 'Transaction.time': resolve_txn_time(item), 'Transaction.endorser': None, 'Transaction.author': None, 'DID.did': did, 'DID.verkey': verkey, 'DID.role': role, 'DID.alias': alias, 'DID.attribs': [], 'DID.authoredDefinitions': [], 'DID.authoredSchema': [], 'DID.authoredDids': [], 'DID.endorsedDefinitions': [], 'DID.endorsedSchema': [], 'DID.endorsedDids': [], } print('JSON UPDATE IS',json_payload) # Run mutation. response = txn.mutate(set_obj=json_payload) # print('response is', response) # Commit transaction. txn.commit() # Get uid of the outermost object (person named "Alice"). # response.uids returns a map from blank node names to uids. # print('Created Transaction with uid = {}'.format(response.uids['did'])) print('Created Transaction with seqNo = {} and DID {}'.format(item['seqNo'], did)) finally: # Clean up. Calling this after txn.commit() is a no-op and hence safe. # print('discarding tx') txn.discard() # pass # txn.commit() # Query for data. def query_did(client): # Run query. query = """query all($a: string) { all(func: eq(did, $a)) { uid id seqNo type verkey } }""" variables = {'$a': 'NMjQb59rKTJXKNqVYfcZFi'} res = client.txn(read_only=True).query(query, variables=variables) dids = json.loads(res.json) # Print results. print('Number of transactions with DID "NMjQb59rKTJXKNqVYfcZFi": {}'.format(len(dids['all']))) def main(): client_stub = create_client_stub() client = create_client(client_stub) # drop_all(client) # set_schema(client) # query_did(client) # query for DID create_data(client) # Close the client stub. client_stub.close() # def main(): # client_stub = pydgraph.DgraphClientStub('localhost:9080') # client = pydgraph.DgraphClient(client_stub) # txn = client.txn() # print('Connection opened!') # query = """{ # V as var(func: type(Org)) @filter(eq(OrgLocation, \"D\")) # }""" # nquad = """ # uid(V) * * . # """ # mutation = txn.create_mutation(del_nquads=nquad) # request = txn.create_request(query=query, mutations=[mutation], commit_now=True) # txn.do_request(request) # print('Transaction executed!') # # # Close the client stub. # client_stub.close() if __name__ == '__main__': # try: main() print('DONE!') # except Exception as e: # # pass # print('Error: {}'.format(e))
28.525952
121
0.569869
acf67f1f01d6eed061dd9f4c8e0746870c7bc8d7
6,214
py
Python
app/recipe/views.py
theumairahmed/recipe-app-api
e4d086f27a4f3a9c89a326dc6912ec70e1af943d
[ "MIT" ]
null
null
null
app/recipe/views.py
theumairahmed/recipe-app-api
e4d086f27a4f3a9c89a326dc6912ec70e1af943d
[ "MIT" ]
null
null
null
app/recipe/views.py
theumairahmed/recipe-app-api
e4d086f27a4f3a9c89a326dc6912ec70e1af943d
[ "MIT" ]
null
null
null
from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets, mixins, status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from core.models import Tag, Ingredient, Recipe from recipe import serializers # viewsets.GenericViewSet extended to implement changes in get_queryset # functionality that is to be used for ListModelMixin # mixins.ListModelMixin extended to get the boilerplate code for 'list' viewset # operation # mixins.CreateModelMixin extended to get the boilerplate code for 'create' # viewset operation class BaseRecipeAttrViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): """Base viewset for user owned recipe attributes""" authentication_classes = (TokenAuthentication, ) permission_classes = (IsAuthenticated, ) # We override this function present in GenericViewSet(GenericAPIView) class # which is then used by ListModelMixin to get the queryset that it should # list in response. def get_queryset(self): """Return objects for the current authenticated user only""" # Convert the assigned only query parameter to True or False assigned_only = bool(int( self.request.query_params.get('assigned_only', 0) )) queryset = self.queryset if assigned_only: # Filter the queryset, and return the tags which are assigned # to some recipe. Although tags doesn't have a recipe field but # since tags is a ManyToMany field, Django automatically creates # a reverse reference to it. Explanation: # https://www.udemy.com/course/django-python-advanced/learn/lecture # /12712757#questions/6793838 queryset = queryset.filter(recipe__isnull=False) return queryset.filter(user=self.request.user)\ .order_by('-name')\ .distinct() # We override this function present in CreateModelMixin to define the # functionality that we should perform while creating the model def perform_create(self, serializer): """Create a new object""" serializer.save(user=self.request.user) class TagViewSet(BaseRecipeAttrViewSet): """Manage tags in the database""" queryset = Tag.objects.all() serializer_class = serializers.TagSerializer class IngredientViewSet(BaseRecipeAttrViewSet): """Manage ingredients in the database""" queryset = Ingredient.objects.all() serializer_class = serializers.IngredientSerializer class RecipeViewSet(viewsets.ModelViewSet): """Manage recipes in the database""" serializer_class = serializers.RecipeSerializer queryset = Recipe.objects.all() authentication_classes = (TokenAuthentication, ) permission_classes = (IsAuthenticated, ) def _params_to_ints(self, qs): """Convert a list of string IDs to a list of integers""" return [int(str_id) for str_id in qs.split(',')] def get_queryset(self): """Retrieve the recipes for the authenticated user""" # Fetch the tags and ingredients params from the query tags = self.request.query_params.get('tags') ingredients = self.request.query_params.get('ingredients') # basic queryset queryset = self.queryset # filter the query further based on the tags or ingredients if tags: tag_ids = self._params_to_ints(tags) queryset = queryset.filter(tags__id__in=tag_ids) if ingredients: ingredient_ids = self._params_to_ints(ingredients) queryset = queryset.filter(ingredients__id__in=ingredient_ids) # Finally return the query filtered on user now return queryset.filter(user=self.request.user) def get_serializer_class(self): """Return appropriate serializer based on list or retrieve""" if self.action == 'retrieve': # If the action is retrieve (means detail of a recipe is retrieved) # return the detail serializer otherwise just return the default return serializers.RecipeDetailSerializer # self.action is upload_image and not upload-image because the action # is same as the function name defined elif self.action == 'upload_image': # If the action is to upload the image, then return image-upload # serializer return serializers.RecipeImageSerializer return self.serializer_class def perform_create(self, serializer): """Create a new Recipe""" serializer.save(user=self.request.user) @action(methods=['POST'], detail=True, url_path='upload-image') def upload_image(self, request, pk=None): """Upload an image to a recipe""" # As we have set the detail=True in the decorator, that means that we # will be accessing a single specific recipe item in the DB and not the # full collection of recipes so the URL will be: # /recipe/recipes/<ID>/upload-image and not the standard: # /recipe/recipes/upload-image # The function self.get_object() hence retrieves the object which is # being addressed recipe = self.get_object() # The get serializer helper function returns the serializer defined # for this view. The recipe object is passed so that when we call the # serializer's save method, that particular object is saved # the second argument 'data' is used to validate the data passed in the # request. Explanation: https://www.udemy.com/course/django-python- # advanced/learn/lecture/12712743#questions/9787036 serializer = self.get_serializer( recipe, data=request.data ) if serializer.is_valid(): serializer.save() return Response( serializer.data, status=status.HTTP_200_OK ) return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST )
40.350649
79
0.679755
acf67f44899f36f73e6e4709e30765a00cd45788
1,655
py
Python
webrecorder/test/test_add_cookie.py
ssteo/webrecorder
8690608171f35c475842df8fabbe666f5058193d
[ "Apache-2.0" ]
1,217
2015-10-16T06:37:32.000Z
2020-06-08T14:02:08.000Z
webrecorder/test/test_add_cookie.py
ssteo/webrecorder
8690608171f35c475842df8fabbe666f5058193d
[ "Apache-2.0" ]
476
2015-10-15T22:24:07.000Z
2020-06-11T07:43:29.000Z
webrecorder/test/test_add_cookie.py
nla/webrecorder
29be63e71999de6a4bc1144a47d59137fab34239
[ "Apache-2.0" ]
101
2015-10-16T01:24:07.000Z
2020-05-18T00:49:49.000Z
from .testutils import FullStackTests import os import gevent # ============================================================================ class TestAddCookie(FullStackTests): def test_record_1(self): self.set_uuids('Recording', ['rec-a']) params = {'coll': 'temp', 'url': 'http://httpbin.org/get?food=bar', 'is_content': True, 'mode': 'record' } res = self.testapp.post_json('/api/v1/new', params=params) assert res.json['url'] res = self.testapp.get(res.json['url'], status=200) assert '"food": "bar"' in res.text assert self.testapp.cookies['__test_sesh'] != '' def test_record_add_cookie_1(self): res = self.testapp.get('/{user}/temp/rec-a/record/mp_/http://test.httpbin.org/cookies'.format(user=self.anon_user)) # no cookies assert res.json['cookies'] == {} params = {'url': 'http://httpbin.org/get?food=bar', 'path': '/', 'rec': 'rec-a', 'domain': '.httpbin.org', 'name': 'extra', 'value': 'cookie!' } assert self.testapp.cookies['__test_sesh'] != '' res = self.testapp.post_json('/api/v1/auth/cookie?user={user}&coll=temp'.format(user=self.anon_user), params=params) assert res.json == {'success': '.httpbin.org'} res = self.testapp.get('/{user}/temp/rec-a/record/mp_/http://test.httpbin.org/cookies'.format(user=self.anon_user)) # cookies passed to server assert res.json['cookies']['extra'] == 'cookie!'
31.826923
124
0.523263
acf6803b21adc8a75c29fbc76807cb9f2f68195e
4,674
py
Python
astroquery/mpc/tests/test_mpc_remote.py
stargaser/astroquery
44d1ec9b7fc549dfca5f0657beaa13aa516ba7b6
[ "BSD-3-Clause" ]
1
2020-08-26T21:11:13.000Z
2020-08-26T21:11:13.000Z
astroquery/mpc/tests/test_mpc_remote.py
stargaser/astroquery
44d1ec9b7fc549dfca5f0657beaa13aa516ba7b6
[ "BSD-3-Clause" ]
1
2018-11-07T21:00:18.000Z
2018-11-07T21:00:18.000Z
astroquery/mpc/tests/test_mpc_remote.py
stargaser/astroquery
44d1ec9b7fc549dfca5f0657beaa13aa516ba7b6
[ "BSD-3-Clause" ]
1
2020-08-26T21:11:16.000Z
2020-08-26T21:11:16.000Z
# Licensed under a 3-clause BSD style license - see LICENSE.rst import requests import pytest from ...exceptions import InvalidQueryError from ... import mpc @pytest.mark.remote_data class TestMPC(object): @pytest.mark.parametrize('type, name', [ ('asteroid', 'ceres'), ('asteroid', 'eros'), ('asteroid', 'pallas')]) def test_query_object_valid_object_by_name(self, type, name): response = mpc.core.MPC.query_object_async(target_type=type, name=name) assert response.status_code == requests.codes.ok assert len(response.json()) == 1 assert response.json()[0]['name'].lower() == name @pytest.mark.parametrize('type, number', [ ('comet', '103P')]) def test_query_object_valid_object_by_number(self, type, number): response = mpc.core.MPC.query_object_async( target_type=type, number=number) assert response.status_code == requests.codes.ok assert len(response.json()) == 1 assert str(response.json()[0]['number']) + \ response.json()[0]['object_type'] == number @pytest.mark.parametrize('type, designation', [ ('comet', 'C/2012 S1')]) def test_query_object_valid_object_by_designation(self, type, designation): response = mpc.core.MPC.query_object_async( target_type=type, designation=designation) assert response.status_code == requests.codes.ok assert len(response.json()) == 1 assert response.json()[0]['designation'].lower() == designation.lower() @pytest.mark.parametrize('name', [ ('ceres'), ('eros'), ('pallas')]) def test_query_object_get_query_payload_remote(self, name): request_payload = mpc.core.MPC.query_object_async( get_query_payload=True, target_type='asteroid', name=name) assert request_payload == {"name": name, "json": 1, "limit": 1} def test_query_multiple_objects(self): response = mpc.core.MPC.query_objects_async( target_type='asteroid', epoch_jd=2458200.5, limit=5) assert response.status_code == requests.codes.ok assert len(response.json()) == 5 def test_query_object_by_nonexistent_name(self): response = mpc.core.MPC.query_object_async( target_type='asteroid', name="invalid object") assert response.status_code == requests.codes.ok assert len(response.json()) == 0 def test_query_object_invalid_parameter(self): response = mpc.core.MPC.query_object_async( target_type='asteroid', blah="blah") assert response.status_code == requests.codes.ok assert "Unrecognized parameter" in str(response.content) def test_get_observatory_codes(self): response = mpc.core.MPC.get_observatory_codes() greenwich = ['000', 0.0, 0.62411, 0.77873, 'Greenwich'] assert all([r == g for r, g in zip(response[0], greenwich)]) @pytest.mark.parametrize('target', ['(3202)', 'C/2003 A2']) def test_get_ephemeris_by_target(self, target): # test that query succeeded response = mpc.core.MPC.get_ephemeris(target) assert len(response) > 0 def test_get_ephemeris_target_fail(self): # test that query failed with pytest.raises(InvalidQueryError): mpc.core.MPC.get_ephemeris('test fail') def test_get_observations(self): # asteroids a = mpc.core.MPC.get_observations(2) assert a['number'][0] == 2 a = mpc.core.MPC.get_observations(12893) assert a['number'][0] == 12893 assert a['desig'][-1] == '1998 QS55' a = mpc.core.MPC.get_observations("2019 AA") assert a['desig'][0] == '2019 AA' a = mpc.core.MPC.get_observations("2017 BC136") assert a['desig'][0] == '2017 BC136' # comets a = mpc.core.MPC.get_observations('2P') assert a['number'][0] == 2 assert a['comettype'][0] == 'P' a = mpc.core.MPC.get_observations('258P') assert a['number'][0] == 258 assert a['comettype'][0] == 'P' a = mpc.core.MPC.get_observations("P/2018 P4") assert a['desig'][0] == "2018 P4" with pytest.raises(ValueError): a = mpc.core.MPC.get_observations("2018 P4") a = mpc.core.MPC.get_observations("P/2018 P4") assert a['desig'][0] == "2018 P4" a = mpc.core.MPC.get_observations("C/2013 K1") assert a['desig'][0] == "2013 K1" a = mpc.core.MPC.get_observations("P/2019 A4") assert a['desig'][0] == "2019 A4" with pytest.raises(TypeError): a = mpc.core.MPC.get_observations()
39.948718
79
0.626444
acf680ace29c34f21d04612ba0d4730e804c0359
726
py
Python
couchbase_v2/views/__init__.py
kulabh/couchbase-python-client
eb52c53302dfa563e289f04af518d40b3921767b
[ "Apache-2.0" ]
1
2019-10-01T19:06:29.000Z
2019-10-01T19:06:29.000Z
couchbase_v2/views/__init__.py
kulabh/couchbase-python-client
eb52c53302dfa563e289f04af518d40b3921767b
[ "Apache-2.0" ]
null
null
null
couchbase_v2/views/__init__.py
kulabh/couchbase-python-client
eb52c53302dfa563e289f04af518d40b3921767b
[ "Apache-2.0" ]
null
null
null
# # Copyright 2019, Couchbase, Inc. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import couchbase_core.views import sys sys.modules[__name__] = couchbase_core.views from couchbase_core.views import *
31.565217
74
0.768595
acf68163bae61b009a36d3ae6bdb9c3fae71281b
2,866
py
Python
tests/integration/test_masks.py
nipeone/histolab
78854423df04c95c7168d03a95ae8665e3e957d8
[ "Apache-2.0" ]
149
2020-06-23T17:56:04.000Z
2022-03-26T05:51:08.000Z
tests/integration/test_masks.py
nipeone/histolab
78854423df04c95c7168d03a95ae8665e3e957d8
[ "Apache-2.0" ]
245
2020-06-22T22:56:06.000Z
2022-03-28T03:18:11.000Z
tests/integration/test_masks.py
nipeone/histolab
78854423df04c95c7168d03a95ae8665e3e957d8
[ "Apache-2.0" ]
31
2020-06-23T17:56:36.000Z
2022-02-07T07:41:26.000Z
# encoding: utf-8 import os import numpy as np import pytest from histolab.masks import BiggestTissueBoxMask, TissueMask from histolab.slide import Slide from histolab.tile import Tile from ..fixtures import RGB, SVS, TIFF, TILES from ..util import load_expectation class DescribeBiggestTissueBoxMask: @pytest.mark.parametrize( "wsi, expected_array", ( ( SVS.CMU_1_SMALL_REGION, "mask-arrays/biggest-tissue-box-cmu-1-small-region", ), ( SVS.TCGA_CR_7395_01A_01_TS1, "mask-arrays/biggest-tissue-box-tcga-cr-7395", ), ( TIFF.KIDNEY_48_5, "mask-arrays/biggest-tissue-box-kidney-48-5", ), ), ) def it_can_construct_big_tissue_box_mask(self, wsi, expected_array): slide = Slide(wsi, "") expected_array = load_expectation(expected_array, type_="npy") biggest_tissue_box = BiggestTissueBoxMask() mask = biggest_tissue_box(slide) np.testing.assert_array_almost_equal(mask, expected_array) class DescribeTissueMask: @pytest.mark.parametrize( "wsi, expected_array", ( ( SVS.CMU_1_SMALL_REGION, "mask-arrays/tissue-mask-cmu-1-small-region", ), ( SVS.TCGA_CR_7395_01A_01_TS1, "mask-arrays/tissue-mask-tcga-cr-7395", ), ( TIFF.KIDNEY_48_5, "mask-arrays/tissue-mask-kidney-48-5", ), ), ) def it_can_construct_tissue_mask_slide(self, wsi, expected_array): slide = Slide(wsi, os.path.join(wsi, "processed")) expected_array = load_expectation(expected_array, type_="npy") tissue_mask = TissueMask() slide_mask = tissue_mask(slide) np.testing.assert_array_almost_equal(slide_mask, expected_array) @pytest.mark.parametrize( "tile, expected_array", ( ( RGB.DIAGNOSTIC_SLIDE_THUMB_RGB, # pen marks get considered as tissue "mask-arrays/tissue-mask-diagnostic-slide-thumb-rgb", ), ( RGB.TCGA_LUNG_RGB, "mask-arrays/tissue-mask-tcga-lung-rgb", ), ( TILES.TISSUE_LEVEL2_3000_7666_7096_11763, "mask-arrays/tissue-mask-tissue-level2-3000-7666-7096-11763", ), ), ) def it_can_construct_tissue_mask_tile(self, tile, expected_array): tile = Tile(tile, None, None) expected_array = load_expectation(expected_array, type_="npy") tissue_mask = TissueMask() tile_mask = tissue_mask(tile) np.testing.assert_array_almost_equal(tile_mask, expected_array)
30.168421
85
0.585485
acf6816c6daa125d24f0cac321acef344cdf84ae
4,865
py
Python
utils/process_args.py
psanch21/imp_bigan
5164c8c2d4379363344ac858ae39355ebf750b04
[ "MIT" ]
8
2019-11-22T07:06:47.000Z
2021-09-07T09:53:56.000Z
utils/process_args.py
psanch21/imp_bigan
5164c8c2d4379363344ac858ae39355ebf750b04
[ "MIT" ]
null
null
null
utils/process_args.py
psanch21/imp_bigan
5164c8c2d4379363344ac858ae39355ebf750b04
[ "MIT" ]
1
2021-05-15T23:33:39.000Z
2021-05-15T23:33:39.000Z
import argparse import os import utils.constants as cte def get_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--n_epochs', type=int, default=50, help='Number of epochs to train') parser.add_argument('--l_rate', type=float, default=2e-4, help='Learning rate') parser.add_argument('--beta1', type=float, default=0.5, help='Learning rate') parser.add_argument('--beta2', type=float, default=0.999, help='Learning rate') parser.add_argument('--n_critic', type=int, default=5, help='Ratio between # updates distriminator and # update generator') parser.add_argument('--save_every', type=int, default=10, help='Save model every n epochs') parser.add_argument('--print_every', type=int, default=10, help='Print result every n epochs') parser.add_argument('--z_dim', type=int, default=256, help='Dimension of z') parser.add_argument('--batch_size', type=int, default=128, help='Constraints to z') parser.add_argument('--clip', type=int, default=5, help='Set to 1 to restore model') parser.add_argument('--dataset', type=str, default='c10', help='Dataset to train the model') parser.add_argument('--data_path', type=str, default='../Data', help='Root directory for data') parser.add_argument('--ckpt_dir', type=str, default='saves', help='Parent directory to save models') parser.add_argument('--ckpt_file', type=str, default=None, help='Checkpoint file to restore model') parser.add_argument('--probs_file', type=str, default=None, help='Checkpoint file to restore model') parser.add_argument('--loss_type', type=str, default=cte.BCE, help='Root directory for data') parser.add_argument('--gpu', type=str, default='-1', help='Select gpu') parser.add_argument('--gan_type', type=str, default=cte.BiGAN, help='Select GAN arquitecture') # Hyperparameter for X reconstruction regularization parser.add_argument('--lr', type=float, default=1, help='Regularization parameter for reconstruction loss') # Hyperparameter for E(x) regularization parser.add_argument('--ln', type=float, default=0.0, help='Initial Regularization parameter for E(X) regularization ') # Hyperparameters for non-uniform sampling parser.add_argument('--lp', type=float, default=0.0, help='Percentage of non-uniform sampling') parser.add_argument('--ld', type=int, default=0, help='Exponent to compute probabilities for non-uniform sampling') args = parser.parse_args() return validate_args(args) def validate_args(args): assert args.n_epochs > 0, "Number of epochs in non positive" assert args.l_rate > 0 assert args.beta1 >= 0 assert args.beta2 >= 0.9 assert args.n_critic > 0 assert args.z_dim > 0 assert args.batch_size > 0 assert args.clip > 0 assert args.loss_type in cte.GAN_LOSS_LIST assert args.dataset in cte.DATASET_LIST assert args.gan_type in cte.BiGAN_LIST assert args.lr >= 0 assert args.ln >= 0 assert args.lp >= 0 assert args.ld >= 0 if args.gan_type in [cte.MLPMDGAN]: assert args.ld >= 0 assert args.probs_file is not None assert str(args.ld) in args.probs_file.split('/')[-1] assert isinstance(args.ld, int) return args def get_args_evaluate(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--data_path', type=str, default='../Data', help='Parent directory to save models') parser.add_argument('--dataset', type=str, default=None, help='Dataset to train the model') parser.add_argument('--output_dir', type=str, default=None, help='Parent directory to save models') parser.add_argument('--ckpt_name', type=str, default=None, help='Parent directory to save models') parser.add_argument('--folder', type=str, default=None, help='Parent directory to save models') parser.add_argument('--operation', type=str, default=None, help='Parent directory to save models') parser.add_argument('--l_dist', type=int, default=-1, help='Parent directory to save models') parser.add_argument('--T', type=int, default=-40, help='PSNR Threshold') parser.add_argument('--gpu', type=str, default='-1', help='Select gpu') args = parser.parse_args() return validate_args_evaluate(args) def validate_args_evaluate(args): assert args.dataset is not None, "Select a datset" assert args.folder is not None assert args.operation is not None assert args.T > 0 args.output_dir = args.folder if cte.NON_UNI_PROBS in args.operation: assert args.l_dist > 0 return args def get_device(gpu): if (int(gpu) == -1): device = 'cpu' else: os.environ['CUDA_VISIBLE_DEVICES'] = gpu device = 'cuda' print('Using GPU: {}'.format(gpu)) return device
41.228814
119
0.692703
acf6817a96d31dbdbddd53b8c1f72fb66885355c
10,270
py
Python
performances/performance_test_plugin_cmake/cmake/generate_script.py
Joeyyzhao/ros2-performance
f1325e29dfc19cc778c9b3b335bce3a664cc1b07
[ "BSD-3-Clause" ]
160
2019-04-15T20:42:23.000Z
2022-03-26T09:34:33.000Z
performances/performance_test_plugin_cmake/cmake/generate_script.py
Joeyyzhao/ros2-performance
f1325e29dfc19cc778c9b3b335bce3a664cc1b07
[ "BSD-3-Clause" ]
31
2019-06-12T15:41:29.000Z
2022-03-31T09:20:00.000Z
performances/performance_test_plugin_cmake/cmake/generate_script.py
Joeyyzhao/ros2-performance
f1325e29dfc19cc778c9b3b335bce3a664cc1b07
[ "BSD-3-Clause" ]
43
2019-04-23T01:25:07.000Z
2022-03-26T09:34:29.000Z
#!/usr/bin/env python3 # Software License Agreement (BSD License) # # Copyright (c) 2019, iRobot ROS # All rights reserved. # # This file is part of ros2-performance, which is released under BSD-3-Clause. # You may use, distribute and modify this code under the BSD-3-Clause license. # import argparse import os import re import sys def get_interface_name_from_path(interface_path): ''' path has the form msg/PoseWithCovariance.msg the name is only PoseWithCovariance ''' # get filename from path name_with_extension = os.path.basename(interface_path) # remove extension from filename name = os.path.splitext(name_with_extension)[0] return name def get_lowercased_name(interface_name): ''' interface_name has the PoseWithCovariance the lowercased version is pose_with_covariance ''' # Remove consecutive upper-case letters: HelloWORLD becomes HelloWorld last_upper = False for idx, c in enumerate(interface_name): if c.isupper(): if last_upper: interface_name = interface_name[:idx] + c.lower() + interface_name[idx+1:] last_upper = True else: last_upper = False # This regular expression splits the name at each capital letter parts = re.sub( r"([A-Z])", r" \1", interface_name).split() lowercase_parts = [x.lower() for x in parts] lowercased_name = "_".join(lowercase_parts) return lowercased_name def get_cpp_include_statement(interface_name, package, interface_type): ''' interface_name has the form PoseWithCovariance, in package geometry_msgs and its a "msg" the include statement will be #include "geometry_msgs/msg/pose_with_covariance.hpp" ''' include_file_name = get_lowercased_name(interface_name) + ".hpp" statement = "#include \"" + package + "/" + interface_type + "/" + include_file_name + "\"" return statement def get_namespaced_cpp_class_name(interface_name, package, interface_type): ''' interface_name has the form PoseWithCovariance, in package geometry_msgs and its a "msg" the namespaced cpp class name will be geometry_msgs::msg::PoseWithCovariance" ''' class_name = package + "::" + interface_type + "::" + interface_name return class_name def get_include_paths(msgs, srvs, package): ''' create include definitions for all the messages and services ''' content = "\n" for msg_name in msgs: statement = get_cpp_include_statement(msg_name, package, "msg") content += statement + "\n" content += "\n" for srv_name in srvs: statement = get_cpp_include_statement(srv_name, package, "srv") content += statement + "\n" return content def get_sub_factory(msgs, package, node_type): if len(msgs) == 0: return "" if node_type == "Node": content = """ extern "C" void add_subscriber_impl( """ elif node_type == "LifecycleNode": content = """ extern "C" void add_subscriber_impl_lifecycle( """ else: return "" content += "\n std::shared_ptr<performance_test::" + node_type + "> n," content += """ std::string msg_type, std::string topic_name, performance_test::Tracker::TrackingOptions tracking_options, msg_pass_by_t msg_pass_by, rmw_qos_profile_t custom_qos_profile) { const std::map<std::string, std::function<void()>> subscribers_factory{ """ function = "add_subscriber" user_args = "msg_pass_by, tracking_options, custom_qos_profile" for msg_name in msgs: msg_class_name = get_namespaced_cpp_class_name(msg_name, package, "msg") topic = "performance_test::Topic<" + msg_class_name + ">(topic_name)" lowercased_name = get_lowercased_name(msg_name) map_key = "\"" + lowercased_name + "\"" map_entry = "{" + map_key +", [&] { n->" + function + "(" + topic +", " + user_args + "); } }," content += "\n" + map_entry if content.endswith(","): content = content[:-1] content += """ };""" content += """ if (subscribers_factory.find(msg_type) == subscribers_factory.end()){ throw std::runtime_error("unknown msg type passed to subscribers factory: " + msg_type); } subscribers_factory.at(msg_type)(); } """ return content def get_pub_factory(msgs, package, node_type): if len(msgs) == 0: return "" if node_type == "Node": content = """ extern "C" void add_publisher_impl( """ elif node_type == "LifecycleNode": content = """ extern "C" void add_publisher_impl_lifecycle( """ else: return "" content += "\n std::shared_ptr<performance_test::" + node_type + "> n," content += """ std::string msg_type, std::string topic_name, msg_pass_by_t msg_pass_by, rmw_qos_profile_t custom_qos_profile, std::chrono::microseconds period, size_t msg_size) { const std::map<std::string, std::function<void()>> publishers_factory{ """ function = "add_periodic_publisher" user_args = "period, msg_pass_by, custom_qos_profile, msg_size" for msg_name in msgs: msg_class_name = get_namespaced_cpp_class_name(msg_name, package, "msg") topic = "performance_test::Topic<" + msg_class_name + ">(topic_name)" lowercased_name = get_lowercased_name(msg_name) map_key = "\"" + lowercased_name + "\"" map_entry = "{" + map_key +", [&] { n->" + function + "(" + topic +", " + user_args + "); } }," content += "\n" + map_entry if content.endswith(","): content = content[:-1] content += """ };""" content += """ if (publishers_factory.find(msg_type) == publishers_factory.end()){ throw std::runtime_error("unknown msg type passed to publishers factory: " + msg_type); } publishers_factory.at(msg_type)(); } """ return content def get_server_factory(srvs, package, node_type): if len(srvs) == 0: return "" if node_type == "Node": content = """ extern "C" void add_server_impl( """ elif node_type == "LifecycleNode": content = """ extern "C" void add_server_impl_lifecycle( """ else: return "" content += "\n std::shared_ptr<performance_test::" + node_type + "> n," content += """ std::string srv_type, std::string service_name, rmw_qos_profile_t custom_qos_profile) { const std::map<std::string, std::function<void()>> servers_factory{ """ function = "add_server" user_args = "custom_qos_profile" for srv_name in srvs: srv_class_name = get_namespaced_cpp_class_name(srv_name, package, "srv") service = "performance_test::Service<" + srv_class_name + ">(service_name)" lowercased_name = get_lowercased_name(srv_name) map_key = "\"" + lowercased_name + "\"" map_entry = "{" + map_key +", [&] { n->" + function + "(" + service + ", " + user_args + "); } }," content += "\n" + map_entry if content.endswith(","): content = content[:-1] content += """ };""" content += """ if (servers_factory.find(srv_type) == servers_factory.end()){ throw std::runtime_error("unknown srv type passed to servers factory: " + srv_type); } servers_factory.at(srv_type)(); } """ return content def get_client_factory(srvs, package, node_type): if len(srvs) == 0: return "" if node_type == "Node": content = """ extern "C" void add_client_impl( """ elif node_type == "LifecycleNode": content = """ extern "C" void add_client_impl_lifecycle( """ else: return "" content += "\n std::shared_ptr<performance_test::" + node_type + "> n," content += """ std::string srv_type, std::string service_name, rmw_qos_profile_t custom_qos_profile, std::chrono::microseconds period) { const std::map<std::string, std::function<void()>> clients_factory{ """ function = "add_periodic_client" user_args = "period, custom_qos_profile" for srv_name in srvs: srv_class_name = get_namespaced_cpp_class_name(srv_name, package, "srv") service = "performance_test::Service<" + srv_class_name + ">(service_name)" lowercased_name = get_lowercased_name(srv_name) map_key = "\"" + lowercased_name + "\"" map_entry = "{" + map_key +", [&] { n->" + function + "(" + service +", " + user_args + "); } }," content += "\n" + map_entry if content.endswith(","): content = content[:-1] content += """ };""" content += """ if (clients_factory.find(srv_type) == clients_factory.end()){ throw std::runtime_error("unknown srv type passed to clients factory: " + srv_type); } clients_factory.at(srv_type)(); } """ return content def main(): parser = argparse.ArgumentParser(description='Python script for generating interfaces implementation') parser.add_argument('output_path', type=str) parser.add_argument('--package', type=str) parser.add_argument('--msg', type=str, nargs='+', default=[]) parser.add_argument('--srv', type=str, nargs='+', default=[]) args = parser.parse_args() output_file_path = args.output_path package = args.package msg_paths = args.msg srv_paths = args.srv if not msg_paths and not srv_paths: sys.exit('No interfaces!') msgs = [] srvs = [] for path in msg_paths: msgs.append(get_interface_name_from_path(path)) for path in srv_paths: srvs.append(get_interface_name_from_path(path)) outdir = os.path.dirname(output_file_path) os.makedirs(outdir, exist_ok=True) content = """ #include "performance_test/ros2/node.hpp" #include "performance_test/ros2/lifecycle_node.hpp" """ content += get_include_paths(msgs, srvs, package) content += get_sub_factory(msgs, package, "Node") content += get_sub_factory(msgs, package, "LifecycleNode") content += get_pub_factory(msgs, package, "Node") content += get_pub_factory(msgs, package, "LifecycleNode") content += get_server_factory(srvs, package, "Node") content += get_server_factory(srvs, package, "LifecycleNode") content += get_client_factory(srvs, package, "Node") content += get_client_factory(srvs, package, "LifecycleNode") def create(filename, content): if os.path.exists(filename): old_content = open(filename, 'r').read() if old_content == content: return open(filename, 'w').write(content) create(output_file_path, content) if __name__ == "__main__": main()
24.927184
104
0.665433
acf681f657018821c29b96d08c1cd2edd8760ab6
27,842
py
Python
octavia/tests/unit/controller/worker/v2/tasks/test_amphora_driver_tasks.py
xilousonw/octavia
2bdc7a6e08b5e6f4197f45c22a3b9e42363c0ed2
[ "Apache-2.0" ]
null
null
null
octavia/tests/unit/controller/worker/v2/tasks/test_amphora_driver_tasks.py
xilousonw/octavia
2bdc7a6e08b5e6f4197f45c22a3b9e42363c0ed2
[ "Apache-2.0" ]
null
null
null
octavia/tests/unit/controller/worker/v2/tasks/test_amphora_driver_tasks.py
xilousonw/octavia
2bdc7a6e08b5e6f4197f45c22a3b9e42363c0ed2
[ "Apache-2.0" ]
null
null
null
# Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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 cryptography import fernet import mock from oslo_config import cfg from oslo_config import fixture as oslo_fixture from oslo_utils import uuidutils from taskflow.types import failure from octavia.amphorae.driver_exceptions import exceptions as driver_except from octavia.common import constants from octavia.common import data_models from octavia.common import utils from octavia.controller.worker.v2.tasks import amphora_driver_tasks from octavia.db import repositories as repo import octavia.tests.unit.base as base AMP_ID = uuidutils.generate_uuid() COMPUTE_ID = uuidutils.generate_uuid() LISTENER_ID = uuidutils.generate_uuid() LB_ID = uuidutils.generate_uuid() CONN_MAX_RETRIES = 10 CONN_RETRY_INTERVAL = 6 FAKE_CONFIG_FILE = 'fake config file' _amphora_mock = mock.MagicMock() _amphora_mock.id = AMP_ID _amphora_mock.status = constants.AMPHORA_ALLOCATED _load_balancer_mock = mock.MagicMock() _load_balancer_mock.id = LB_ID _listener_mock = mock.MagicMock() _listener_mock.id = LISTENER_ID _load_balancer_mock.listeners = [_listener_mock] _vip_mock = mock.MagicMock() _load_balancer_mock.vip = _vip_mock _LB_mock = mock.MagicMock() _amphorae_mock = [_amphora_mock] _network_mock = mock.MagicMock() _port_mock = mock.MagicMock() _ports_mock = [_port_mock] _session_mock = mock.MagicMock() @mock.patch('octavia.db.repositories.AmphoraRepository.update') @mock.patch('octavia.db.repositories.ListenerRepository.update') @mock.patch('octavia.db.repositories.ListenerRepository.get', return_value=_listener_mock) @mock.patch('octavia.db.api.get_session', return_value=_session_mock) @mock.patch('octavia.controller.worker.v2.tasks.amphora_driver_tasks.LOG') @mock.patch('oslo_utils.uuidutils.generate_uuid', return_value=AMP_ID) @mock.patch('stevedore.driver.DriverManager.driver') class TestAmphoraDriverTasks(base.TestCase): def setUp(self): _LB_mock.amphorae = [_amphora_mock] _LB_mock.id = LB_ID conf = oslo_fixture.Config(cfg.CONF) conf.config(group="haproxy_amphora", active_connection_max_retries=CONN_MAX_RETRIES) conf.config(group="haproxy_amphora", active_connection_rety_interval=CONN_RETRY_INTERVAL) conf.config(group="controller_worker", loadbalancer_topology=constants.TOPOLOGY_SINGLE) super(TestAmphoraDriverTasks, self).setUp() def test_amp_listener_update(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): timeout_dict = {constants.REQ_CONN_TIMEOUT: 1, constants.REQ_READ_TIMEOUT: 2, constants.CONN_MAX_RETRIES: 3, constants.CONN_RETRY_INTERVAL: 4} amp_list_update_obj = amphora_driver_tasks.AmpListenersUpdate() amp_list_update_obj.execute(_load_balancer_mock, 0, [_amphora_mock], timeout_dict) mock_driver.update_amphora_listeners.assert_called_once_with( _load_balancer_mock, _amphora_mock, timeout_dict) mock_driver.update_amphora_listeners.side_effect = Exception('boom') amp_list_update_obj.execute(_load_balancer_mock, 0, [_amphora_mock], timeout_dict) mock_amphora_repo_update.assert_called_once_with( _session_mock, AMP_ID, status=constants.ERROR) def test_listener_update(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): listener_update_obj = amphora_driver_tasks.ListenersUpdate() listener_update_obj.execute(_load_balancer_mock) mock_driver.update.assert_called_once_with(_load_balancer_mock) # Test the revert amp = listener_update_obj.revert(_load_balancer_mock) repo.ListenerRepository.update.assert_called_once_with( _session_mock, id=LISTENER_ID, provisioning_status=constants.ERROR) self.assertIsNone(amp) # Test the revert with exception repo.ListenerRepository.update.reset_mock() mock_listener_repo_update.side_effect = Exception('fail') amp = listener_update_obj.revert(_load_balancer_mock) repo.ListenerRepository.update.assert_called_once_with( _session_mock, id=LISTENER_ID, provisioning_status=constants.ERROR) self.assertIsNone(amp) def test_listeners_update(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): listeners_update_obj = amphora_driver_tasks.ListenersUpdate() listeners = [data_models.Listener(id='listener1'), data_models.Listener(id='listener2')] vip = data_models.Vip(ip_address='10.0.0.1') lb = data_models.LoadBalancer(id='lb1', listeners=listeners, vip=vip) listeners_update_obj.execute(lb) mock_driver.update.assert_called_once_with(lb) self.assertEqual(1, mock_driver.update.call_count) # Test the revert amp = listeners_update_obj.revert(lb) expected_db_calls = [mock.call(_session_mock, id=listeners[0].id, provisioning_status=constants.ERROR), mock.call(_session_mock, id=listeners[1].id, provisioning_status=constants.ERROR)] repo.ListenerRepository.update.has_calls(expected_db_calls) self.assertEqual(2, repo.ListenerRepository.update.call_count) self.assertIsNone(amp) @mock.patch('octavia.controller.worker.task_utils.TaskUtils.' 'mark_listener_prov_status_error') def test_listeners_start(self, mock_prov_status_error, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): listeners_start_obj = amphora_driver_tasks.ListenersStart() mock_lb = mock.MagicMock() mock_listener = mock.MagicMock() mock_listener.id = '12345' # Test no listeners mock_lb.listeners = None listeners_start_obj.execute(mock_lb) mock_driver.start.assert_not_called() # Test with listeners mock_driver.start.reset_mock() mock_lb.listeners = [mock_listener] listeners_start_obj.execute(mock_lb) mock_driver.start.assert_called_once_with(mock_lb, None) # Test revert mock_lb.listeners = [mock_listener] listeners_start_obj.revert(mock_lb) mock_prov_status_error.assert_called_once_with('12345') def test_listener_delete(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): listener_delete_obj = amphora_driver_tasks.ListenerDelete() listener_delete_obj.execute(_listener_mock) mock_driver.delete.assert_called_once_with(_listener_mock) # Test the revert amp = listener_delete_obj.revert(_listener_mock) repo.ListenerRepository.update.assert_called_once_with( _session_mock, id=LISTENER_ID, provisioning_status=constants.ERROR) self.assertIsNone(amp) # Test the revert with exception repo.ListenerRepository.update.reset_mock() mock_listener_repo_update.side_effect = Exception('fail') amp = listener_delete_obj.revert(_listener_mock) repo.ListenerRepository.update.assert_called_once_with( _session_mock, id=LISTENER_ID, provisioning_status=constants.ERROR) self.assertIsNone(amp) def test_amphora_get_info(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): amphora_get_info_obj = amphora_driver_tasks.AmphoraGetInfo() amphora_get_info_obj.execute(_amphora_mock) mock_driver.get_info.assert_called_once_with( _amphora_mock) def test_amphora_get_diagnostics(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): amphora_get_diagnostics_obj = (amphora_driver_tasks. AmphoraGetDiagnostics()) amphora_get_diagnostics_obj.execute(_amphora_mock) mock_driver.get_diagnostics.assert_called_once_with( _amphora_mock) def test_amphora_finalize(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): amphora_finalize_obj = amphora_driver_tasks.AmphoraFinalize() amphora_finalize_obj.execute(_amphora_mock) mock_driver.finalize_amphora.assert_called_once_with( _amphora_mock) # Test revert amp = amphora_finalize_obj.revert(None, _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( _session_mock, id=AMP_ID, status=constants.ERROR) self.assertIsNone(amp) # Test revert with exception repo.AmphoraRepository.update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') amp = amphora_finalize_obj.revert(None, _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( _session_mock, id=AMP_ID, status=constants.ERROR) self.assertIsNone(amp) def test_amphora_post_network_plug(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): amphora_post_network_plug_obj = (amphora_driver_tasks. AmphoraPostNetworkPlug()) amphora_post_network_plug_obj.execute(_amphora_mock, _ports_mock) (mock_driver.post_network_plug. assert_called_once_with)(_amphora_mock, _port_mock) # Test revert amp = amphora_post_network_plug_obj.revert(None, _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( _session_mock, id=AMP_ID, status=constants.ERROR) self.assertIsNone(amp) # Test revert with exception repo.AmphoraRepository.update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') amp = amphora_post_network_plug_obj.revert(None, _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( _session_mock, id=AMP_ID, status=constants.ERROR) self.assertIsNone(amp) def test_amphorae_post_network_plug(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): mock_driver.get_network.return_value = _network_mock _amphora_mock.id = AMP_ID _amphora_mock.compute_id = COMPUTE_ID _LB_mock.amphorae = [_amphora_mock] amphora_post_network_plug_obj = (amphora_driver_tasks. AmphoraePostNetworkPlug()) port_mock = mock.Mock() _deltas_mock = {_amphora_mock.id: [port_mock]} amphora_post_network_plug_obj.execute(_LB_mock, _deltas_mock) (mock_driver.post_network_plug. assert_called_once_with(_amphora_mock, port_mock)) # Test revert amp = amphora_post_network_plug_obj.revert(None, _LB_mock, _deltas_mock) repo.AmphoraRepository.update.assert_called_once_with( _session_mock, id=AMP_ID, status=constants.ERROR) self.assertIsNone(amp) # Test revert with exception repo.AmphoraRepository.update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') amp = amphora_post_network_plug_obj.revert(None, _LB_mock, _deltas_mock) repo.AmphoraRepository.update.assert_called_once_with( _session_mock, id=AMP_ID, status=constants.ERROR) self.assertIsNone(amp) @mock.patch('octavia.db.repositories.LoadBalancerRepository.update') def test_amphora_post_vip_plug(self, mock_loadbalancer_repo_update, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): amphorae_net_config_mock = mock.Mock() amphora_post_vip_plug_obj = amphora_driver_tasks.AmphoraPostVIPPlug() amphora_post_vip_plug_obj.execute(_amphora_mock, _LB_mock, amphorae_net_config_mock) mock_driver.post_vip_plug.assert_called_once_with( _amphora_mock, _LB_mock, amphorae_net_config_mock) # Test revert amp = amphora_post_vip_plug_obj.revert(None, _amphora_mock, _LB_mock) repo.AmphoraRepository.update.assert_called_once_with( _session_mock, id=AMP_ID, status=constants.ERROR) repo.LoadBalancerRepository.update.assert_called_once_with( _session_mock, id=LB_ID, provisioning_status=constants.ERROR) self.assertIsNone(amp) # Test revert with repo exceptions repo.AmphoraRepository.update.reset_mock() repo.LoadBalancerRepository.update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mock_loadbalancer_repo_update.side_effect = Exception('fail') amp = amphora_post_vip_plug_obj.revert(None, _amphora_mock, _LB_mock) repo.AmphoraRepository.update.assert_called_once_with( _session_mock, id=AMP_ID, status=constants.ERROR) repo.LoadBalancerRepository.update.assert_called_once_with( _session_mock, id=LB_ID, provisioning_status=constants.ERROR) self.assertIsNone(amp) @mock.patch('octavia.db.repositories.LoadBalancerRepository.update') def test_amphorae_post_vip_plug(self, mock_loadbalancer_repo_update, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): amphorae_net_config_mock = mock.Mock() amphora_post_vip_plug_obj = amphora_driver_tasks.AmphoraePostVIPPlug() amphora_post_vip_plug_obj.execute(_LB_mock, amphorae_net_config_mock) mock_driver.post_vip_plug.assert_called_once_with( _amphora_mock, _LB_mock, amphorae_net_config_mock) # Test revert amp = amphora_post_vip_plug_obj.revert(None, _LB_mock) repo.LoadBalancerRepository.update.assert_called_once_with( _session_mock, id=LB_ID, provisioning_status=constants.ERROR) self.assertIsNone(amp) # Test revert with exception repo.LoadBalancerRepository.update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') amp = amphora_post_vip_plug_obj.revert(None, _LB_mock) repo.LoadBalancerRepository.update.assert_called_once_with( _session_mock, id=LB_ID, provisioning_status=constants.ERROR) self.assertIsNone(amp) def test_amphora_cert_upload(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): key = utils.get_six_compatible_server_certs_key_passphrase() fer = fernet.Fernet(key) pem_file_mock = fer.encrypt( utils.get_six_compatible_value('test-pem-file')) amphora_cert_upload_mock = amphora_driver_tasks.AmphoraCertUpload() amphora_cert_upload_mock.execute(_amphora_mock, pem_file_mock) mock_driver.upload_cert_amp.assert_called_once_with( _amphora_mock, fer.decrypt(pem_file_mock)) def test_amphora_update_vrrp_interface(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): _LB_mock.amphorae = _amphorae_mock timeout_dict = {constants.CONN_MAX_RETRIES: CONN_MAX_RETRIES, constants.CONN_RETRY_INTERVAL: CONN_RETRY_INTERVAL} amphora_update_vrrp_interface_obj = ( amphora_driver_tasks.AmphoraUpdateVRRPInterface()) amphora_update_vrrp_interface_obj.execute(_LB_mock) mock_driver.get_interface_from_ip.assert_called_once_with( _amphora_mock, _amphora_mock.vrrp_ip, timeout_dict=timeout_dict) # Test revert mock_driver.reset_mock() _LB_mock.amphorae = _amphorae_mock amphora_update_vrrp_interface_obj.revert("BADRESULT", _LB_mock) mock_amphora_repo_update.assert_called_with(_session_mock, _amphora_mock.id, vrrp_interface=None) mock_driver.reset_mock() mock_amphora_repo_update.reset_mock() failure_obj = failure.Failure.from_exception(Exception("TESTEXCEPT")) amphora_update_vrrp_interface_obj.revert(failure_obj, _LB_mock) self.assertFalse(mock_amphora_repo_update.called) # Test revert with exception mock_driver.reset_mock() mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') _LB_mock.amphorae = _amphorae_mock amphora_update_vrrp_interface_obj.revert("BADRESULT", _LB_mock) mock_amphora_repo_update.assert_called_with(_session_mock, _amphora_mock.id, vrrp_interface=None) def test_amphora_vrrp_update(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): amphorae_network_config = mock.MagicMock() amphora_vrrp_update_obj = ( amphora_driver_tasks.AmphoraVRRPUpdate()) amphora_vrrp_update_obj.execute(_LB_mock, amphorae_network_config) mock_driver.update_vrrp_conf.assert_called_once_with( _LB_mock, amphorae_network_config) def test_amphora_vrrp_stop(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): amphora_vrrp_stop_obj = ( amphora_driver_tasks.AmphoraVRRPStop()) amphora_vrrp_stop_obj.execute(_LB_mock) mock_driver.stop_vrrp_service.assert_called_once_with(_LB_mock) def test_amphora_vrrp_start(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): amphora_vrrp_start_obj = ( amphora_driver_tasks.AmphoraVRRPStart()) amphora_vrrp_start_obj.execute(_LB_mock) mock_driver.start_vrrp_service.assert_called_once_with(_LB_mock) def test_amphora_compute_connectivity_wait(self, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): amp_compute_conn_wait_obj = ( amphora_driver_tasks.AmphoraComputeConnectivityWait()) amp_compute_conn_wait_obj.execute(_amphora_mock, raise_retry_exception=True) mock_driver.get_info.assert_called_once_with( _amphora_mock, raise_retry_exception=True) mock_driver.get_info.side_effect = driver_except.TimeOutException() self.assertRaises(driver_except.TimeOutException, amp_compute_conn_wait_obj.execute, _amphora_mock) mock_amphora_repo_update.assert_called_once_with( _session_mock, AMP_ID, status=constants.ERROR) @mock.patch('octavia.amphorae.backends.agent.agent_jinja_cfg.' 'AgentJinjaTemplater.build_agent_config') def test_amphora_config_update(self, mock_build_config, mock_driver, mock_generate_uuid, mock_log, mock_get_session, mock_listener_repo_get, mock_listener_repo_update, mock_amphora_repo_update): mock_build_config.return_value = FAKE_CONFIG_FILE amp_config_update_obj = amphora_driver_tasks.AmphoraConfigUpdate() mock_driver.update_amphora_agent_config.side_effect = [ None, None, driver_except.AmpDriverNotImplementedError, driver_except.TimeOutException] # With Flavor flavor = {constants.LOADBALANCER_TOPOLOGY: constants.TOPOLOGY_ACTIVE_STANDBY} amp_config_update_obj.execute(_amphora_mock, flavor) mock_build_config.assert_called_once_with( _amphora_mock.id, constants.TOPOLOGY_ACTIVE_STANDBY) mock_driver.update_amphora_agent_config.assert_called_once_with( _amphora_mock, FAKE_CONFIG_FILE) # With no Flavor mock_driver.reset_mock() mock_build_config.reset_mock() amp_config_update_obj.execute(_amphora_mock, None) mock_build_config.assert_called_once_with( _amphora_mock.id, constants.TOPOLOGY_SINGLE) mock_driver.update_amphora_agent_config.assert_called_once_with( _amphora_mock, FAKE_CONFIG_FILE) # With amphora that does not support config update mock_driver.reset_mock() mock_build_config.reset_mock() amp_config_update_obj.execute(_amphora_mock, flavor) mock_build_config.assert_called_once_with( _amphora_mock.id, constants.TOPOLOGY_ACTIVE_STANDBY) mock_driver.update_amphora_agent_config.assert_called_once_with( _amphora_mock, FAKE_CONFIG_FILE) # With an unknown exception mock_driver.reset_mock() mock_build_config.reset_mock() self.assertRaises(driver_except.TimeOutException, amp_config_update_obj.execute, _amphora_mock, flavor)
43.435257
78
0.594318
acf68215ca9d1a712039e8d44c1c705ae6f7e6f1
8,884
py
Python
applications/DemStructuresCouplingApplication/python_scripts/dem_structures_coupling_gid_output.py
HubertBalcerzak/Kratos
c15689d53f06dabb36dc44c13eeac73d3e183916
[ "BSD-4-Clause" ]
2
2019-10-25T09:28:10.000Z
2019-11-21T12:51:46.000Z
applications/DemStructuresCouplingApplication/python_scripts/dem_structures_coupling_gid_output.py
HubertBalcerzak/Kratos
c15689d53f06dabb36dc44c13eeac73d3e183916
[ "BSD-4-Clause" ]
13
2019-10-07T12:06:51.000Z
2020-02-18T08:48:33.000Z
applications/DemStructuresCouplingApplication/python_scripts/dem_structures_coupling_gid_output.py
pyfsi/Kratos
726aa15a04d92c958ba10c8941ce074716115ee8
[ "BSD-4-Clause" ]
null
null
null
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7 import os import KratosMultiphysics as Kratos from KratosMultiphysics import MultiFileFlag from KratosMultiphysics import GiDPostMode from KratosMultiphysics import Logger from KratosMultiphysics import DEMApplication from KratosMultiphysics import DemStructuresCouplingApplication from KratosMultiphysics import StructuralMechanicsApplication from KratosMultiphysics import gid_output # this is deprecated class DemStructuresCouplingGiDOutput(gid_output.GiDOutput): def __init__(self, file_name, vol_output, post_mode, multifile, deformed_mesh, write_conditions, structures_model_part, balls_model_part, clusters_model_part, rigid_faces_model_part, contact_model_part, mixed_model_part ): gid_output.GiDOutput.__init__(self, file_name, vol_output, post_mode, multifile, deformed_mesh, write_conditions) self.GiDMultiFileFlag = multifile self.outerlistfilename = os.path.join("..", self.listfilename) self.structures_model_part = structures_model_part self.balls_model_part = balls_model_part self.clusters_model_part = clusters_model_part self.rigid_faces_model_part = rigid_faces_model_part self.contact_model_part = contact_model_part self.mixed_model_part = mixed_model_part self.structures_nodal_results = [] self.dem_nodal_results = [] self.clusters_nodal_results = [] self.rigid_faces_nodal_results = [] self.contact_gauss_points_results = [] self.mixed_nodal_results = [] self.structures_gauss_points_results = [] def initialize_dem_fem_results(self, structures_nodal_results, dem_nodal_results, clusters_nodal_results, rigid_faces_nodal_results, contact_gauss_points_results, mixed_nodal_results, structures_gauss_points_results): self.structures_nodal_results = structures_nodal_results self.dem_nodal_results = dem_nodal_results self.clusters_nodal_results = clusters_nodal_results self.rigid_faces_nodal_results = rigid_faces_nodal_results self.contact_gauss_points_results = contact_gauss_points_results self.mixed_nodal_results = mixed_nodal_results self.structures_gauss_points_results = structures_gauss_points_results if self.multi_file == MultiFileFlag.SingleFile: print("Singlefile option is not available for the DEM-Structures Coupling application!") mesh_name = 0.0 self.io.InitializeMesh(mesh_name) self.io.WriteSphereMesh(self.balls_model_part.GetMesh()) self.io.WriteMesh(self.clusters_model_part.GetMesh()) self.io.WriteMesh(self.rigid_faces_model_part.GetMesh()) self.io.WriteMesh(self.contact_model_part.GetMesh()) self.io.WriteMesh(self.mixed_model_part.GetMesh()) self.io.FinalizeMesh() self.io.InitializeResults(mesh_name, self.mixed_model_part.GetMesh()) # Initialize list file with open(self.listfilename, "w") as listfile: if self.multi_file == MultiFileFlag.MultipleFiles: listfile.write("Multiple\n") elif self.multi_file == MultiFileFlag.SingleFile: listfile.write("Single\n") if self.multi_file == MultiFileFlag.SingleFile: if self.post_mode == GiDPostMode.GiD_PostBinary: self.write_step_to_list() else: self.write_step_to_list(0) def write_step_to_list(self, step_label): if self.post_mode == GiDPostMode.GiD_PostBinary: ext = ".post.bin" elif self.post_mode == GiDPostMode.GiD_PostAscii: ext = ".post.res" elif self.post_mode == GiDPostMode.GiD_PostAsciiZipped: ext = ".post.res" with open(self.listfilename, "a") as listfile: listfile.write("Multiple\n") listfile.write(self.filename+"_"+"%.12g"%step_label+ext+"\n") def write_step_to_outer_list(self, step_label): if self.post_mode == GiDPostMode.GiD_PostBinary: ext = ".post.bin" elif self.post_mode == GiDPostMode.GiD_PostAscii: ext = ".post.res" elif self.post_mode == GiDPostMode.GiD_PostAsciiZipped: ext = ".post.res" with open(self.outerlistfilename, "a") as listfile: listfile.write("Multiple\n") folder_name = self.filename + "_Post_Files" full_string_to_write = os.path.join(folder_name,self.filename+"_"+"%.12g"%step_label+ext) listfile.write(full_string_to_write+"\n") def Writeresults(self, time): Logger.PrintInfo("DEM-Struct","") Logger.PrintInfo("DEM-Struct","******************* PRINTING RESULTS FOR GID ***************************") Logger.Flush() if self.GiDMultiFileFlag == "Multiples": self.mixed_model_part.Elements.clear() self.mixed_model_part.Nodes.clear() # here order is important! DEMApplication.PostUtilities().AddModelPartToModelPart(self.mixed_model_part, self.balls_model_part) DEMApplication.PostUtilities().AddModelPartToModelPart(self.mixed_model_part, self.rigid_faces_model_part) DEMApplication.PostUtilities().AddModelPartToModelPart(self.mixed_model_part, self.contact_model_part) DEMApplication.PostUtilities().AddModelPartToModelPart(self.mixed_model_part, self.structures_model_part) self.write_dem_fem_results(time) def write_dem_fem_results(self, label): # label = str(label) #it should be a C double # update cut data if necessary out_model_part = self.get_out_model_part(self.structures_model_part) # update cut data if necessary if not self.volume_output: self.cut_app.UpdateCutData(out_model_part, self.structures_model_part) if self.multi_file == MultiFileFlag.MultipleFiles: self.io.InitializeMesh(label) self.io.WriteSphereMesh(self.balls_model_part.GetMesh()) self.io.WriteMesh(self.mixed_model_part.GetMesh()) self.io.WriteMesh(self.rigid_faces_model_part.GetMesh()) self.io.WriteMesh(self.contact_model_part.GetMesh()) self.io.FinalizeMesh() self.io.InitializeResults(label, self.mixed_model_part.GetMesh()) for var in self.structures_nodal_results: kratos_variable = Kratos.KratosGlobals.GetVariable(var) self._write_nodal_results(label, self.structures_model_part, kratos_variable) for var in self.dem_nodal_results: kratos_variable = Kratos.KratosGlobals.GetVariable(var) self._write_nodal_results(label, self.balls_model_part, kratos_variable) for var in self.clusters_nodal_results: kratos_variable = Kratos.KratosGlobals.GetVariable(var) self._write_nodal_results(label, self.clusters_model_part, kratos_variable) for var in self.rigid_faces_nodal_results: kratos_variable = Kratos.KratosGlobals.GetVariable(var) self._write_nodal_results(label, self.rigid_faces_model_part, kratos_variable) for var in self.contact_gauss_points_results: kratos_variable = Kratos.KratosGlobals.GetVariable(var) self._write_gp_results(label, self.contact_model_part, kratos_variable) for var in self.mixed_nodal_results: kratos_variable = Kratos.KratosGlobals.GetVariable(var) self._write_nodal_results(label, self.mixed_model_part, kratos_variable) for var in self.structures_gauss_points_results: kratos_variable = Kratos.KratosGlobals.GetVariable(var) self._write_gp_results(label, self.structures_model_part, kratos_variable) if self.multi_file == MultiFileFlag.MultipleFiles: self._finalize_results() with open(self.listfilename, "a") as listfile: self.write_step_to_list(label) self.write_step_to_outer_list(label)
43.763547
134
0.648807
acf68249d9014cbb45901edeefd452e9766ee9c4
2,559
py
Python
besspin/cyberPhys/ignition/cancheck.py
mikkowus/BESSPIN-Tool-Suite
e87e9abb1156a8627aacc3272f1925b034129146
[ "Apache-2.0" ]
null
null
null
besspin/cyberPhys/ignition/cancheck.py
mikkowus/BESSPIN-Tool-Suite
e87e9abb1156a8627aacc3272f1925b034129146
[ "Apache-2.0" ]
null
null
null
besspin/cyberPhys/ignition/cancheck.py
mikkowus/BESSPIN-Tool-Suite
e87e9abb1156a8627aacc3272f1925b034129146
[ "Apache-2.0" ]
null
null
null
import argparse from cyberphyslib.demonstrator import can import cyberphyslib.canlib as canlib import logging import struct # make CAN module less noisy logging.getLogger("can").setLevel(logging.WARNING) class StatsListener(can.CanListener): canids = {getattr(canlib, name):name.split('CAN_ID_')[1] for name in dir(canlib) if 'CAN_ID' in name} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.vals = set() self.count = 0 def recv(self, id: int, data_len: int, data: bytes): if id in self.canids: val = (self.canids[id], struct.unpack( getattr(canlib, f"CAN_FORMAT_{self.canids[id]}"), data) ) self.vals |= {val} self.count += 1 print(f"{name}: {self.ids_recv}") @property def ids_recv(self): return set([v for v,_ in self.vals]) def get_vals(self, id): return set([v for k,v in self.vals if k == id]) class StatsNetwork: def __init__(self, name, ip, port, whitelist): self.can_net = can.CanUdpNetwork(name, port, ip, whitelist=whitelist) self.listener = StatsListener(name) self.can_net.register(self.listener) def start(self): self.can_net.start() if __name__ == '__main__': # Project libs from cyberphyslib.demonstrator import config import pathlib, os import argparse # ugh, this filepath access is sketchy and will complicate the deployment of ignition parser = argparse.ArgumentParser(description="BESSPIN Demonstrator Can Check") parser.add_argument("-network-config", type=str, default="", help="Path to BESSPIN Target setupEnv.json") parser.add_argument("-network-port-name", type=str, default="canbus", help="Network Port Name") args = parser.parse_args() if args.network_config == "": network_filepath = pathlib.Path(os.path.realpath(__file__)).parent / ".." / ".." / "base" / "utils" / "setupEnv.json" else: network_filepath = args.network_config assert os.path.exists(network_filepath), f"specified network config json ({network_filepath}) doesn't exist" dnc = config.DemonstratorNetworkConfig.from_setup_env(network_filepath) name = args.network_port_name port = dnc.network_ports[f'{name}Port'] whitelists = dnc.whitelists nets = [StatsNetwork(f"{net_name}_STATS", dnc.ip_SimPc, port, wl) for net_name, wl in whitelists.items()] for net in nets: net.start() while True: pass
35.054795
125
0.654943
acf682dbd045a92cbf0113c8b43e08c446257710
2,016
py
Python
prb_api_video/ext/restapi/resources.py
enphoria/ms-api-video
3cc967a16f9e94522ae697e997a544f14ca1f0ef
[ "Unlicense" ]
null
null
null
prb_api_video/ext/restapi/resources.py
enphoria/ms-api-video
3cc967a16f9e94522ae697e997a544f14ca1f0ef
[ "Unlicense" ]
null
null
null
prb_api_video/ext/restapi/resources.py
enphoria/ms-api-video
3cc967a16f9e94522ae697e997a544f14ca1f0ef
[ "Unlicense" ]
null
null
null
from flask import abort, jsonify, request from flask_restful import Resource from flask_simplelogin import login_required from prb_api_video.models import Person from prb_api_video.models import SubjectInterest from prb_api_video.request import RequestSendMessage from prb_api_video.consume import Consume from sqlalchemy.orm import join from moviepy.editor import * import json import os import datetime class PersonResource(Resource): def get(self): persons = Person.query.all() or abort(204) print(persons) return jsonify( {"persons": [person.to_dict() for person in persons]} ) class SendMessageResource(Resource): def post(self): try: obj = json.loads(str(json.dumps(request.get_json())), object_hook=lambda d: RequestSendMessage(**d)) persons = Person.query.filter(SubjectInterest.name==obj.interest) or abort(204) dateNow = datetime.datetime.now() dateNow = dateNow.strftime("%Y") + dateNow.strftime("%m") + dateNow.strftime("%d") for person in persons: if person.subject_interest.name == obj.interest: resultPath = "video/results/result_"+dateNow+"_"+person.name+"_"+person.subject_interest.name+".mp4" clipName = VideoFileClip(person.person_video.path_video) clipIniciative = VideoFileClip(person.subject_interest.path_video) clips = [clipName, clipIniciative] clipsResult = concatenate_videoclips(clips) clipsResult.write_videofile(resultPath, temp_audiofile='temp-audio.m4a', remove_temp=True, codec="libx264", audio_codec="aac") responseVideo = Consume(resultPath,str(person.cellphone)) responseVideo.sendVideo() return jsonify( {"prueba": [person.to_dict() for person in persons]} ) except Exception as e: print(str(e)) abort(400)
38.037736
146
0.652282
acf684554c4b1a51f40fcaf35616c3c8c0c14972
393
py
Python
backend/graditude/jobs/migrations/0010_post_location.py
tomvothecoder/graditude
d3bf47fce678e92d6dcc821857b606f94811e505
[ "MIT" ]
1
2019-09-15T22:59:34.000Z
2019-09-15T22:59:34.000Z
backend/graditude/jobs/migrations/0010_post_location.py
tvo25/graditude
d3bf47fce678e92d6dcc821857b606f94811e505
[ "MIT" ]
69
2019-09-04T03:35:52.000Z
2019-10-11T01:50:24.000Z
backend/graditude/jobs/migrations/0010_post_location.py
tvo25/graditude
d3bf47fce678e92d6dcc821857b606f94811e505
[ "MIT" ]
null
null
null
# Generated by Django 2.2.4 on 2019-09-08 04:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0009_auto_20190901_2145'), ] operations = [ migrations.AddField( model_name='post', name='location', field=models.CharField(max_length=255, null=True), ), ]
20.684211
62
0.597964
acf684760f8609b8890e8c3c617fb6b15c2344b4
594
py
Python
tests/test_neighbors.py
lenarother/santa-helpers
0498b9922b357c98543929a39d9755085da527b0
[ "MIT" ]
null
null
null
tests/test_neighbors.py
lenarother/santa-helpers
0498b9922b357c98543929a39d9755085da527b0
[ "MIT" ]
null
null
null
tests/test_neighbors.py
lenarother/santa-helpers
0498b9922b357c98543929a39d9755085da527b0
[ "MIT" ]
null
null
null
import pytest from santa_helpers.neighbors import neighbors EXAMPLES_PARSE_GRID_TO_DICT = ( ((1, 1), 4, None, None, {(0, 1), (1, 0), (2, 1), (1, 2)}), ((0, 0), 4, (0, 0), None, {(0, 1), (1, 0)}), ((0, 0), 4, (0, 0), (0, 0), set()), ((0, 0), 8, None, None, { (-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1), }), ) @pytest.mark.parametrize( 'p,n,p_min,p_max,expected', EXAMPLES_PARSE_GRID_TO_DICT ) def test_parse_grid_to_dict(p, n, p_min, p_max, expected): assert set(neighbors(p, n, p_min, p_max)) == expected
25.826087
62
0.506734
acf684a9feb45fc37af045e07c2c41dc8847c387
624
py
Python
MoodyBeatsRecommenderAPI/newsletter/migrations/0001_initial.py
labs12-music-stream-selector/DS
8029556547c2478a647649c89cfb834893647795
[ "MIT" ]
null
null
null
MoodyBeatsRecommenderAPI/newsletter/migrations/0001_initial.py
labs12-music-stream-selector/DS
8029556547c2478a647649c89cfb834893647795
[ "MIT" ]
19
2019-12-26T17:21:07.000Z
2022-02-17T22:21:18.000Z
MoodyBeatsRecommenderAPI/newsletter/migrations/0001_initial.py
labs12-music-stream-selector/DS
8029556547c2478a647649c89cfb834893647795
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-05-07 18:50 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Join', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('email', models.EmailField(max_length=254)), ('timestamp', models.DateTimeField(auto_now_add=True)), ], ), ]
24.96
114
0.594551
acf6861b9a277ea5c4e9a2e27dfb35853e8b282b
24,832
py
Python
tensorflow/python/distribute/mirrored_variable_test.py
dmpiergiacomo/tensorflow
0ecdc6dc2dbc2381c9317f274bd39281294dfc97
[ "Apache-2.0" ]
10
2021-05-25T17:43:04.000Z
2022-03-08T10:46:09.000Z
tensorflow/python/distribute/mirrored_variable_test.py
CaptainGizzy21/tensorflow
3457a2b122e50b4d44ceaaed5a663d635e5c22df
[ "Apache-2.0" ]
1,056
2019-12-15T01:20:31.000Z
2022-02-10T02:06:28.000Z
tensorflow/python/distribute/mirrored_variable_test.py
CaptainGizzy21/tensorflow
3457a2b122e50b4d44ceaaed5a663d635e5c22df
[ "Apache-2.0" ]
6
2016-09-07T04:00:15.000Z
2022-01-12T01:47:38.000Z
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Test MirroredVariable in MirroredStrategy and MultiWorkerMirroredStrategy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.distribute import collective_all_reduce_strategy from tensorflow.python.distribute import combinations from tensorflow.python.distribute import distribute_utils from tensorflow.python.distribute import distribution_strategy_context as ds_context from tensorflow.python.distribute import strategy_combinations from tensorflow.python.distribute import values from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.eager import test from tensorflow.python.framework import config from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import func_graph from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import rnn from tensorflow.python.ops import rnn_cell_impl from tensorflow.python.ops import state_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.saved_model import load from tensorflow.python.saved_model import save from tensorflow.python.training.tracking import util as tracking_util def _replica_id(): replica_id = ds_context.get_replica_context().replica_id_in_sync_group if not isinstance(replica_id, ops.Tensor): replica_id = constant_op.constant(replica_id) return replica_id def _mimic_two_cpus(): cpus = config.list_physical_devices("CPU") config.set_logical_device_configuration(cpus[0], [ context.LogicalDeviceConfiguration(), context.LogicalDeviceConfiguration(), ]) @combinations.generate( combinations.combine( distribution=[ strategy_combinations.mirrored_strategy_with_gpu_and_cpu, combinations.NamedDistribution( "Collective2CPUs", # pylint: disable=g-long-lambda lambda: collective_all_reduce_strategy. CollectiveAllReduceStrategy._from_local_devices(( "/device:CPU:0", "/device:CPU:1")), required_gpus=0) ], mode=["graph", "eager"])) class MirroredVariableCreationTest(test.TestCase): """Base class that tests mirrored variable creator. Currently it assumes all strategy objects have two replicas. """ @classmethod def setUpClass(cls): _mimic_two_cpus() def assertAllDifferent(self, objs): for i in range(len(objs)): for j in range(len(objs)): if i == j: continue self.assertIsNot(objs[i], objs[j]) # TODO(priyag): Modify more tests to use this helper and check more # properties. def _test_mv_properties(self, var, name, strategy): self.assertTrue(distribute_utils.is_mirrored(var)) self.assertEqual(name, var.name) self.assertIs(strategy, var.distribute_strategy) for i, d in enumerate(var._devices): self.assertEqual(d, strategy.experimental_local_results(var)[i].device) self.assertIs( strategy, strategy.experimental_local_results(var)[i]._distribute_strategy) # pylint: disable=protected-access def testVariableInFuncGraph(self, distribution): def model_fn(): v = variable_scope.variable(2.0, name="bar") ds_context.get_replica_context().merge_call(lambda _: _) return v with func_graph.FuncGraph("fg").as_default(), distribution.scope(): v1 = variable_scope.variable(1.0, name="foo") v2 = distribution.extended.call_for_each_replica(model_fn) self._test_mv_properties(v1, "foo:0", distribution) self._test_mv_properties(v2, "bar:0", distribution) def testVariableWithTensorInitialValueInFunction(self, distribution): if not context.executing_eagerly(): self.skipTest("`tf.function` is an eager-only feature") v = [None] def model_fn(): if v[0] is None: init_val = array_ops.zeros([]) v[0] = variables.Variable(init_val) ds_context.get_replica_context().merge_call(lambda _: _) return v[0] @def_function.function(autograph=False) def make_v1(): return distribution.experimental_local_results( distribution.extended.call_for_each_replica(model_fn)) self.assertAllEqual([0, 0], make_v1()) def testSingleVariable(self, distribution): def model_fn(): # This variable should be created only once across the threads because of # special variable_creator functions used by # `distribution.extended.call_for_each_replica`. v = variable_scope.variable(1.0, name="foo") ds_context.get_replica_context().merge_call(lambda _: _) return v with distribution.scope(): result = distribution.extended.call_for_each_replica(model_fn) self._test_mv_properties(result, "foo:0", distribution) def testUnnamedVariable(self, distribution): def model_fn(): v = variable_scope.variable(1.0) ds_context.get_replica_context().merge_call(lambda _: _) return v with distribution.scope(): result = distribution.extended.call_for_each_replica(model_fn) self._test_mv_properties(result, "Variable:0", distribution) def testMultipleVariables(self, distribution): def model_fn(): vs = [] for i in range(5): vs.append(variable_scope.variable(1.0, name="foo" + str(i))) ds_context.get_replica_context().merge_call(lambda _: _) return vs with distribution.scope(): result = distribution.extended.call_for_each_replica(model_fn) for i, v in enumerate(result): self._test_mv_properties(v, "foo" + str(i) + ":0", distribution) def testMultipleVariablesWithSameCanonicalName(self, distribution): def model_fn(): vs = [] vs.append(variable_scope.variable(1.0, name="foo/bar")) vs.append(variable_scope.variable(1.0, name="foo_1/bar")) vs.append(variable_scope.variable(1.0, name="foo_1/bar_1")) vs.append(variable_scope.variable(1.0, name="foo/bar_1")) ds_context.get_replica_context().merge_call(lambda _: _) return vs with distribution.scope(): result = distribution.extended.call_for_each_replica(model_fn) for v in result: self.assertTrue(distribute_utils.is_mirrored(v)) self.assertEqual(4, len(result)) self.assertEqual("foo/bar:0", result[0].name) self.assertEqual("foo_1/bar:0", result[1].name) self.assertEqual("foo_1/bar_1:0", result[2].name) self.assertEqual("foo/bar_1:0", result[3].name) def testVariableWithSameCanonicalNameAcrossThreads(self, distribution): def model_fn(): replica_id = self.evaluate(_replica_id()) v = variable_scope.variable(1.0, name="foo_" + str(replica_id)) ds_context.get_replica_context().merge_call(lambda _: _) return v with distribution.scope(): result = distribution.extended.call_for_each_replica(model_fn) self.assertTrue(distribute_utils.is_mirrored(result)) # The resulting mirrored variable will use the name from the first device. self.assertEqual("foo_0:0", result.name) def testWithVariableAndVariableScope(self, distribution): def model_fn(): v0 = variable_scope.variable(1.0, name="var0", aggregation=None) with variable_scope.variable_scope("common"): v1 = variable_scope.variable(1.0, name="var1") # This will pause the current thread, and execute the other thread. ds_context.get_replica_context().merge_call(lambda _: _) v2 = variable_scope.variable( 1.0, name="var2", synchronization=variable_scope.VariableSynchronization.ON_READ, aggregation=variable_scope.VariableAggregation.SUM) v3 = variable_scope.variable( 1.0, name="var3", synchronization=variable_scope.VariableSynchronization.ON_WRITE, aggregation=variable_scope.VariableAggregation.MEAN) return v0, v1, v2, v3 with distribution.scope(): v = variable_scope.variable(1.0, name="var-main0") self.assertEqual("var-main0:0", v.name) result = distribution.extended.call_for_each_replica(model_fn) self.assertEqual(4, len(result)) v0, v1, v2, v3 = result self.assertTrue(distribute_utils.is_mirrored(v0)) self.assertEqual("var0:0", v0.name) self.assertTrue(distribute_utils.is_mirrored(v1)) self.assertEqual("common/var1:0", v1.name) self.assertTrue(distribute_utils.is_sync_on_read(v2)) self.assertEqual("common/var2:0", v2.name) self.assertEqual(variable_scope.VariableAggregation.SUM, v2.aggregation) self.assertTrue(distribute_utils.is_mirrored(v3)) self.assertEqual("common/var3:0", v3.name) self.assertEqual(variable_scope.VariableAggregation.MEAN, v3.aggregation) def testWithGetVariableAndVariableScope(self, distribution): def model_fn(): v0 = variable_scope.get_variable("var0", [1]) with variable_scope.variable_scope("common"): v1 = variable_scope.get_variable("var1", [1]) # This will pause the current thread, and execute the other thread. ds_context.get_replica_context().merge_call(lambda _: _) v2 = variable_scope.get_variable( "var2", [1], synchronization=variable_scope.VariableSynchronization.ON_READ, aggregation=variable_scope.VariableAggregation.SUM) v3 = variable_scope.get_variable( "var3", [1], synchronization=variable_scope.VariableSynchronization.ON_WRITE, aggregation=variable_scope.VariableAggregation.MEAN) return v0, v1, v2, v3 with distribution.scope(): with variable_scope.variable_scope("main"): v = variable_scope.get_variable("var-main0", [1]) self.assertEqual("main/var-main0:0", v.name) result = distribution.extended.call_for_each_replica(model_fn) self.assertEqual(4, len(result)) v0, v1, v2, v3 = result self.assertTrue(distribute_utils.is_mirrored(v0)) self.assertEqual("main/var0:0", v0.name) self.assertTrue(distribute_utils.is_mirrored(v1)) self.assertEqual("main/common/var1:0", v1.name) self.assertTrue(distribute_utils.is_sync_on_read(v2)) self.assertEqual("main/common/var2:0", v2.name) self.assertEqual(variable_scope.VariableAggregation.SUM, v2.aggregation) self.assertTrue(distribute_utils.is_mirrored(v3)) self.assertEqual("main/common/var3:0", v3.name) self.assertEqual(variable_scope.VariableAggregation.MEAN, v3.aggregation) def testOnlyFirstReplicaUpdatesVariables(self, distribution): def create_fn(): aggregation = variable_scope.VariableAggregation.ONLY_FIRST_REPLICA v0 = variable_scope.variable( 2.0, name="on_read", synchronization=variable_scope.VariableSynchronization.ON_READ, aggregation=aggregation) v1 = variable_scope.variable( 3.0, name="on_write", synchronization=variable_scope.VariableSynchronization.ON_WRITE, aggregation=aggregation) return v0, v1 with distribution.scope(): v0, v1 = distribution.extended.call_for_each_replica(create_fn) self.evaluate(v0.initializer) self.assertEqual( 2.0, self.evaluate(distribution.experimental_local_results(v0)[0])) self.assertEqual( 2.0, self.evaluate(distribution.experimental_local_results(v0)[1])) self.assertEqual(2.0, self.evaluate(distribution.extended.read_var(v0))) self.evaluate(v1.initializer) self.assertEqual( 3.0, self.evaluate(distribution.experimental_local_results(v1)[0])) self.assertEqual( 3.0, self.evaluate(distribution.experimental_local_results(v1)[1])) self.assertEqual(3.0, self.evaluate(distribution.extended.read_var(v1))) def replica_id_plus_one(): return math_ops.cast(_replica_id() + 1, dtype=dtypes.float32) # Update using the assign_add member function. def update_member_fn(): update0 = v0.assign_add(5.0 * replica_id_plus_one()) update1 = v1.assign_add(7.0 * replica_id_plus_one()) return update0, update1 update0a, update1a = distribution.extended.call_for_each_replica( update_member_fn) # Update "sync on read" variable. self.evaluate(distribution.group(update0a)) local_results = self.evaluate(distribution.experimental_local_results(v0)) self.assertEqual(2.0 + 5.0, local_results[0]) # Writes are not synchronized for "sync on read" variables, # so device[1] can end up with a different value. self.assertEqual(2.0 + 2 * 5.0, local_results[1]) # Always reads from device 0. self.assertEqual(2.0 + 5.0, self.evaluate(distribution.extended.read_var(v0))) # Update "sync on write" variable. self.evaluate(distribution.group(update1a)) local_results1 = self.evaluate( distribution.experimental_local_results(v1)) self.assertEqual(3.0 + 7.0, local_results1[0]) # Writes are synchronized for v1, only the argument to assign_add on # device[0] is used. self.assertEqual(3.0 + 7.0, local_results1[1]) self.assertEqual(3.0 + 7.0, self.evaluate(distribution.extended.read_var(v1))) # Update using state_ops.assign_add global function. def update_state_ops_fn(): update0 = state_ops.assign_add(v0, 11.0 * replica_id_plus_one()) update1 = state_ops.assign_add(v1, 13.0 * replica_id_plus_one()) return update0, update1 update0b, update1b = distribution.extended.call_for_each_replica( update_state_ops_fn) self.evaluate(distribution.group(update0b)) # Update "sync on read" variable. local_results = self.evaluate(distribution.experimental_local_results(v0)) self.assertEqual(2.0 + 5.0 + 11.0, local_results[0]) self.assertEqual(2.0 + 2 * 5.0 + 2 * 11.0, local_results[1]) self.assertEqual(2.0 + 5.0 + 11.0, self.evaluate(distribution.extended.read_var(v0))) # Update "sync on write" variable. self.evaluate(distribution.group(update1b)) local_results1 = self.evaluate( distribution.experimental_local_results(v1)) self.assertEqual(3.0 + 7.0 + 13.0, local_results1[0]) self.assertEqual(3.0 + 7.0 + 13.0, local_results1[1]) self.assertEqual(3.0 + 7.0 + 13.0, self.evaluate(distribution.extended.read_var(v1))) def testNoneSynchronizationWithGetVariable(self, distribution): with distribution.scope(): with self.assertRaisesRegex( ValueError, "`NONE` variable synchronization mode is not " "supported with "): variable_scope.get_variable( "v", [1], synchronization=variable_scope.VariableSynchronization.NONE) def testNoneSynchronizationWithVariable(self, distribution): with distribution.scope(): with self.assertRaisesRegex( ValueError, "`NONE` variable synchronization mode is not " "supported with "): variable_scope.variable( 1.0, name="v", synchronization=variable_scope.VariableSynchronization.NONE) def testInvalidSynchronizationWithVariable(self, distribution): with distribution.scope(): with self.assertRaisesRegex( ValueError, "Invalid variable synchronization mode: Invalid for " "variable: v"): variable_scope.variable(1.0, name="v", synchronization="Invalid") def testInvalidAggregationWithGetVariable(self, distribution): with distribution.scope(): with self.assertRaisesRegex( ValueError, "Invalid variable aggregation mode: invalid for " "variable: v"): variable_scope.get_variable( "v", [1], synchronization=variable_scope.VariableSynchronization.ON_WRITE, aggregation="invalid") def testInvalidAggregationWithVariable(self, distribution): with distribution.scope(): with self.assertRaisesRegex( ValueError, "Invalid variable aggregation mode: invalid for " "variable: v"): variable_scope.variable( 1.0, name="v", synchronization=variable_scope.VariableSynchronization.ON_WRITE, aggregation="invalid") def testNonMatchingVariableCreation(self, distribution): def model_fn(name): v = variable_scope.variable(1.0, name=name) ds_context.get_replica_context().merge_call(lambda _: _) return v with distribution.scope(): names = values.PerReplica(("foo", "bar")) with self.assertRaises(RuntimeError): _ = distribution.extended.call_for_each_replica(model_fn, args=(names,)) def testSyncOnReadVariable(self, distribution): if context.executing_eagerly(): self.skipTest("Skip the test due to b/137400477.") all_v_sum = {} all_v_mean = {} components_sum = {} components_mean = {} def model_fn(): replica_id = self.evaluate(_replica_id()) v_sum = variable_scope.variable( 1.0, synchronization=variable_scope.VariableSynchronization.ON_READ, aggregation=variable_scope.VariableAggregation.SUM) v_mean = variable_scope.variable( 4.0, synchronization=variable_scope.VariableSynchronization.ON_READ, aggregation=variable_scope.VariableAggregation.MEAN) self.assertTrue(distribute_utils.is_sync_on_read(v_sum)) self.assertTrue(distribute_utils.is_sync_on_read(v_mean)) updates = [ v_sum.assign_add(2.0 + replica_id), v_mean.assign(6.0 * replica_id) ] all_v_sum[replica_id] = v_sum all_v_mean[replica_id] = v_mean c_sum = v_sum._get() c_mean = v_mean._get() components_sum[replica_id] = c_sum components_mean[replica_id] = c_mean self.assertIsNot(v_sum, c_sum) self.assertIsNot(v_mean, c_mean) return updates, v_sum, v_mean, c_sum, c_mean with distribution.scope(): # Create "sum" and "mean" versions of SyncOnReadVariables. ret_ops, ret_v_sum, ret_v_mean, regrouped_sum, regrouped_mean = ( distribution.extended.call_for_each_replica(model_fn)) # Should see the same wrapping instance in all replicas. self.assertIs(all_v_sum[0], ret_v_sum) self.assertIs(all_v_mean[0], ret_v_mean) self.assertIs(all_v_sum[0], all_v_sum[1]) self.assertIs(all_v_mean[0], all_v_mean[1]) # Regroup should recover the same wrapper. self.assertIs(ret_v_sum, regrouped_sum) self.assertIs(ret_v_mean, regrouped_mean) self.assertIsNot(components_sum[0], components_sum[1]) self.assertIsNot(components_mean[0], components_mean[1]) # Apply updates self.evaluate(variables.global_variables_initializer()) self.evaluate([ y for x in ret_ops # pylint: disable=g-complex-comprehension for y in distribution.experimental_local_results(x) ]) expected_sum = 0.0 expected_mean = 0.0 for i, _ in enumerate(distribution.extended.worker_devices): # Should see different values on different devices. v_sum_value = self.evaluate( distribution.experimental_local_results(ret_v_sum)[i].read_value()) v_mean_value = self.evaluate( distribution.experimental_local_results(ret_v_mean)[i].read_value()) expected = i + 3.0 self.assertEqual(expected, v_sum_value) expected_sum += expected expected = i * 6.0 self.assertEqual(expected, v_mean_value) expected_mean += expected expected_mean /= len(distribution.extended.worker_devices) # Without get(device), should return the value you get by # applying the reduction across all replicas (whether you use # read_var(), get(), or nothing). self.assertEqual(expected_sum, self.evaluate( distribution.extended.read_var(ret_v_sum))) self.assertEqual(expected_mean, self.evaluate( distribution.extended.read_var(ret_v_mean))) self.assertEqual(expected_sum, self.evaluate(ret_v_sum._get())) self.assertEqual(expected_mean, self.evaluate(ret_v_mean._get())) self.assertEqual(expected_sum, self.evaluate(ret_v_sum)) self.assertEqual(expected_mean, self.evaluate(ret_v_mean)) # TODO(priyag): Update this test to work in eager mode as well. def testDynamicRnnVariables(self, distribution): def model_fn(): inputs = constant_op.constant(2 * [2 * [[0.0, 1.0, 2.0, 3.0, 4.0]]]) cell_fw = rnn_cell_impl.LSTMCell(300) cell_bw = rnn_cell_impl.LSTMCell(300) (outputs, _) = rnn.bidirectional_dynamic_rnn( cell_fw, cell_bw, inputs, dtype=dtypes.float32) return outputs with context.graph_mode(), distribution.scope(): result = distribution.extended.call_for_each_replica(model_fn) # Two variables are created by the RNN layer. self.assertEqual(2, len(result)) for v in result: self.assertIsInstance(v, values.DistributedValues) _, v1 = distribution.experimental_local_results(v) self.assertStartsWith(v1._op.name, "replica_1/") def testSyncOnReadVariableUpdate(self, distribution): if context.executing_eagerly(): self.skipTest("Skip the test due to b/137400477.") def model_fn(): v_sum = variable_scope.variable( 1.0, synchronization=variable_scope.VariableSynchronization.ON_READ, aggregation=variable_scope.VariableAggregation.SUM) self.assertTrue(distribute_utils.is_sync_on_read(v_sum)) return v_sum def update(var, value): return var.assign(value) with distribution.scope(): ret_v_sum = distribution.extended.call_for_each_replica(model_fn) # Initialize variables. self.evaluate(variables.global_variables_initializer()) # Assert that the aggregated value of the sync on read var is the sum # of the individual values before running the update ops. self.assertEqual( 1.0, self.evaluate( distribution.experimental_local_results(ret_v_sum) [0].read_value())) self.assertEqual(2.0, self.evaluate(ret_v_sum)) # Apply updates. update_ops = distribution.extended.update( ret_v_sum, update, args=(5.0,), group=False) self.evaluate(update_ops) # Assert that the aggregated value of the sync on read vars is the sum # of the individual values after running the update ops. self.assertEqual( 5.0, self.evaluate( distribution.experimental_local_results(ret_v_sum) [0].read_value())) self.assertEqual(10.0, self.evaluate(ret_v_sum)) def testVarDistributeStrategy(self, distribution): with distribution.scope(): mirrored = variable_scope.variable(1.0) sync_on_read = variable_scope.variable( 1.0, synchronization=variable_scope.VariableSynchronization.ON_READ) self.assertIs(distribution, mirrored.distribute_strategy) self.assertIs(distribution, sync_on_read.distribute_strategy) def testInitializer(self, distribution, mode): if mode == "graph": self.skipTest("Skip graph mode") temp_dir = self.get_temp_dir() class Model(tracking_util.Checkpoint): def __init__(self): self._v = variables.Variable(1.0) with distribution.scope(): m = Model() save.save(m, temp_dir) g = ops.Graph() with g.as_default(): with distribution.scope(): load.load(temp_dir) for v in ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES): self.assertIsNotNone(v.initializer) if __name__ == "__main__": test.main()
39.92283
111
0.69346
acf68626b7f5786a6b27d64721b6e19e474af14f
11,200
py
Python
efficientdet/dataset/create_pascal_tfrecord.py
ahsha-lang/automl
8ee389c39d0101f407f57781e174610a8cf22b65
[ "Apache-2.0" ]
null
null
null
efficientdet/dataset/create_pascal_tfrecord.py
ahsha-lang/automl
8ee389c39d0101f407f57781e174610a8cf22b65
[ "Apache-2.0" ]
null
null
null
efficientdet/dataset/create_pascal_tfrecord.py
ahsha-lang/automl
8ee389c39d0101f407f57781e174610a8cf22b65
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Google Research. 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. # ============================================================================== r"""Convert PASCAL dataset to TFRecord. Example usage: python create_pascal_tfrecord.py --data_dir=/tmp/VOCdevkit \ --year=VOC2012 --output_path=/tmp/pascal """ import hashlib import io import json import os from absl import app from absl import flags from absl import logging from lxml import etree import PIL.Image import tensorflow as tf from dataset import tfrecord_util flags.DEFINE_string('data_dir', '', 'Root directory to raw PASCAL VOC dataset.') flags.DEFINE_string('set', 'train', 'Convert training set, validation set or ' 'merged set.') flags.DEFINE_string('annotations_dir', 'Annotations', '(Relative) path to annotations directory.') flags.DEFINE_string('year', 'VOC2007', 'Desired challenge year.') flags.DEFINE_string('output_path', '', 'Path to output TFRecord and json.') flags.DEFINE_string('label_map_json_path', None, 'Path to label map json file with a dictionary.') flags.DEFINE_boolean('ignore_difficult_instances', False, 'Whether to ignore ' 'difficult instances') flags.DEFINE_integer('num_shards', 100, 'Number of shards for output file.') flags.DEFINE_integer('num_images', None, 'Max number of imags to process.') FLAGS = flags.FLAGS SETS = ['train', 'val', 'trainval', 'test'] YEARS = ['VOC2007', 'VOC2012', 'merged'] pascal_label_map_dict = { 'background': 0, 'antenna_missing_bolt': 1, 'antenna_wrong_bolt': 2, 'bus_good': 3, 'bus_loose': 4, 'bus_missing_bolt': 5, 'bus_missing_cable': 6, 'bus_nav': 7, 'indoor_grounding': 8, 'outdoor_grounding': 9, 'radio_antenna_good': 10, 'radio_antenna_grounding': 11, 'radio_antenna_nav': 12, 'radio_antenna_nav\u200b': 13, 'radio_missing_cable': 14, 'antenna_missing_bolt': 15, } GLOBAL_IMG_ID = 0 # global image id. GLOBAL_ANN_ID = 0 # global annotation id. def get_image_id(filename): """Convert a string to a integer.""" # Warning: this function is highly specific to pascal filename!! # Given filename like '2008_000002', we cannot use id 2008000002 because our # code internally will convert the int value to float32 and back to int, which # would cause value mismatch int(float32(2008000002)) != int(2008000002). # COCO needs int values, here we just use a incremental global_id, but # users should customize their own ways to generate filename. del filename global GLOBAL_IMG_ID GLOBAL_IMG_ID += 1 return GLOBAL_IMG_ID def get_ann_id(): """Return unique annotation id across images.""" global GLOBAL_ANN_ID GLOBAL_ANN_ID += 1 return GLOBAL_ANN_ID def dict_to_tf_example(data, dataset_directory, label_map_dict, ignore_difficult_instances=False, image_subdirectory='JPEGImages', ann_json_dict=None): """Convert XML derived dict to tf.Example proto. Notice that this function normalizes the bounding box coordinates provided by the raw data. Args: data: dict holding PASCAL XML fields for a single image (obtained by running tfrecord_util.recursive_parse_xml_to_dict) dataset_directory: Path to root directory holding PASCAL dataset label_map_dict: A map from string label names to integers ids. ignore_difficult_instances: Whether to skip difficult instances in the dataset (default: False). image_subdirectory: String specifying subdirectory within the PASCAL dataset directory holding the actual image data. ann_json_dict: annotation json dictionary. Returns: example: The converted tf.Example. Raises: ValueError: if the image pointed to by data['filename'] is not a valid JPEG """ img_path = os.path.join(data['folder'], image_subdirectory, data['filename']) full_path = os.path.join(dataset_directory, img_path) with tf.io.gfile.GFile(full_path, 'rb') as fid: encoded_jpg = fid.read() encoded_jpg_io = io.BytesIO(encoded_jpg) image = PIL.Image.open(encoded_jpg_io) if image.format != 'JPEG': raise ValueError('Image format not JPEG') key = hashlib.sha256(encoded_jpg).hexdigest() width = int(data['size']['width']) height = int(data['size']['height']) image_id = get_image_id(data['filename']) if ann_json_dict: image = { 'file_name': data['filename'], 'height': height, 'width': width, 'id': image_id, } ann_json_dict['images'].append(image) xmin = [] ymin = [] xmax = [] ymax = [] area = [] classes = [] classes_text = [] truncated = [] poses = [] difficult_obj = [] if 'object' in data: for obj in data['object']: difficult = bool(int(obj['difficult'])) if ignore_difficult_instances and difficult: continue difficult_obj.append(int(difficult)) xmin.append(float(obj['bndbox']['xmin']) / width) ymin.append(float(obj['bndbox']['ymin']) / height) xmax.append(float(obj['bndbox']['xmax']) / width) ymax.append(float(obj['bndbox']['ymax']) / height) area.append((xmax[-1] - xmin[-1]) * (ymax[-1] - ymin[-1])) classes_text.append(obj['name'].encode('utf8')) classes.append(label_map_dict[obj['name']]) truncated.append(int(obj['truncated'])) poses.append(obj['pose'].encode('utf8')) if ann_json_dict: abs_xmin = int(obj['bndbox']['xmin']) abs_ymin = int(obj['bndbox']['ymin']) abs_xmax = int(obj['bndbox']['xmax']) abs_ymax = int(obj['bndbox']['ymax']) abs_width = abs_xmax - abs_xmin abs_height = abs_ymax - abs_ymin ann = { 'area': abs_width * abs_height, 'iscrowd': 0, 'image_id': image_id, 'bbox': [abs_xmin, abs_ymin, abs_width, abs_height], 'category_id': label_map_dict[obj['name']], 'id': get_ann_id(), 'ignore': 0, 'segmentation': [], } ann_json_dict['annotations'].append(ann) example = tf.train.Example( features=tf.train.Features( feature={ 'image/height': tfrecord_util.int64_feature(height), 'image/width': tfrecord_util.int64_feature(width), 'image/filename': tfrecord_util.bytes_feature(data['filename'].encode('utf8')), 'image/source_id': tfrecord_util.bytes_feature(str(image_id).encode('utf8')), 'image/key/sha256': tfrecord_util.bytes_feature(key.encode('utf8')), 'image/encoded': tfrecord_util.bytes_feature(encoded_jpg), 'image/format': tfrecord_util.bytes_feature('jpeg'.encode('utf8')), 'image/object/bbox/xmin': tfrecord_util.float_list_feature(xmin), 'image/object/bbox/xmax': tfrecord_util.float_list_feature(xmax), 'image/object/bbox/ymin': tfrecord_util.float_list_feature(ymin), 'image/object/bbox/ymax': tfrecord_util.float_list_feature(ymax), 'image/object/area': tfrecord_util.float_list_feature(area), 'image/object/class/text': tfrecord_util.bytes_list_feature(classes_text), 'image/object/class/label': tfrecord_util.int64_list_feature(classes), 'image/object/difficult': tfrecord_util.int64_list_feature(difficult_obj), 'image/object/truncated': tfrecord_util.int64_list_feature(truncated), 'image/object/view': tfrecord_util.bytes_list_feature(poses), })) return example def main(_): if FLAGS.set not in SETS: raise ValueError('set must be in : {}'.format(SETS)) if FLAGS.year not in YEARS: raise ValueError('year must be in : {}'.format(YEARS)) if not FLAGS.output_path: raise ValueError('output_path cannot be empty.') data_dir = FLAGS.data_dir years = ['VOC2007', 'VOC2012'] if FLAGS.year != 'merged': years = [FLAGS.year] output_dir = os.path.dirname(FLAGS.output_path) if not tf.io.gfile.exists(output_dir): tf.io.gfile.makedirs(output_dir) logging.info('Writing to output directory: %s', output_dir) writers = [ tf.io.TFRecordWriter(FLAGS.output_path + '-%05d-of-%05d.tfrecord' % (i, FLAGS.num_shards)) for i in range(FLAGS.num_shards) ] if FLAGS.label_map_json_path: with tf.io.gfile.GFile(FLAGS.label_map_json_path, 'rb') as f: label_map_dict = json.load(f) else: label_map_dict = pascal_label_map_dict ann_json_dict = { 'images': [], 'type': 'instances', 'annotations': [], 'categories': [] } for year in years: example_class = list(label_map_dict.keys())[1] examples_path = os.path.join(data_dir, year, 'ImageSets', 'Main', example_class + '_' + FLAGS.set + '.txt') examples_list = tfrecord_util.read_examples_list(examples_path) annotations_dir = os.path.join(data_dir, year, FLAGS.annotations_dir) for class_name, class_id in label_map_dict.items(): cls = {'supercategory': 'none', 'id': class_id, 'name': class_name} ann_json_dict['categories'].append(cls) logging.info('Reading from PASCAL %s dataset.', year) for idx, example in enumerate(examples_list): if FLAGS.num_images and idx >= FLAGS.num_images: break if idx % 100 == 0: logging.info('On image %d of %d', idx, len(examples_list)) path = os.path.join(annotations_dir, example + '.xml') with tf.io.gfile.GFile(path, 'r') as fid: xml_str = fid.read() xml = etree.fromstring(xml_str) data = tfrecord_util.recursive_parse_xml_to_dict(xml)['annotation'] tf_example = dict_to_tf_example( data, FLAGS.data_dir, label_map_dict, FLAGS.ignore_difficult_instances, ann_json_dict=ann_json_dict) writers[idx % FLAGS.num_shards].write(tf_example.SerializeToString()) for writer in writers: writer.close() json_file_path = os.path.join( os.path.dirname(FLAGS.output_path), 'json_' + os.path.basename(FLAGS.output_path) + '.json') with tf.io.gfile.GFile(json_file_path, 'w') as f: json.dump(ann_json_dict, f) if __name__ == '__main__': app.run(main)
35.555556
80
0.639464
acf686c822d1cee44625d61c15ce9a786fd881d3
94
py
Python
payroll/apps.py
masoodazhar/-school-management-system
6525b3d29d12f03e05d362d81b7c5855806f57d9
[ "Apache-2.0" ]
1
2022-01-20T10:20:05.000Z
2022-01-20T10:20:05.000Z
payroll/apps.py
masoodazhar/-school-management-system
6525b3d29d12f03e05d362d81b7c5855806f57d9
[ "Apache-2.0" ]
null
null
null
payroll/apps.py
masoodazhar/-school-management-system
6525b3d29d12f03e05d362d81b7c5855806f57d9
[ "Apache-2.0" ]
1
2022-01-20T10:20:31.000Z
2022-01-20T10:20:31.000Z
from django.apps import AppConfig class PayrollConfig(AppConfig): name = 'payroll'
15.666667
34
0.712766
acf686ed62e91d53d08c26b573fb3494cab2345f
2,381
py
Python
platform/core/tests/test_stores/test_serializers.py
hackerwins/polyaxon
ff56a098283ca872abfbaae6ba8abba479ffa394
[ "Apache-2.0" ]
null
null
null
platform/core/tests/test_stores/test_serializers.py
hackerwins/polyaxon
ff56a098283ca872abfbaae6ba8abba479ffa394
[ "Apache-2.0" ]
null
null
null
platform/core/tests/test_stores/test_serializers.py
hackerwins/polyaxon
ff56a098283ca872abfbaae6ba8abba479ffa394
[ "Apache-2.0" ]
null
null
null
import pytest from api.data_stores.serializers import DataStoreNameSerializer, DataStoreSerializer from db.models.data_stores import DataStore from factories.factory_data_stores import DataStoreFactory from tests.base.case import BaseTest @pytest.mark.stores_mark class TestDataStoresSerializer(BaseTest): serializer_class = DataStoreSerializer model_class = DataStore factory_class = DataStoreFactory expected_keys = { 'id', 'uuid', 'name', 'description', 'readme', 'tags', 'created_at', 'updated_at', 'type', 'mount_path', 'host_path', 'volume_claim', 'bucket', 'k8s_secret', 'read_only' } def setUp(self): super().setUp() self.obj1 = self.factory_class() self.obj2 = self.factory_class() self.obj1_query = DataStore.objects.get(id=self.obj1.id) def test_serialize_one(self): data = self.serializer_class(self.obj1_query).data assert set(data.keys()) == self.expected_keys data.pop('created_at') data.pop('updated_at') assert data.pop('uuid') == self.obj1.uuid.hex for k, v in data.items(): assert getattr(self.obj1, k) == v def test_serialize_many(self): data = self.serializer_class(DataStore.objects.all(), many=True).data assert len(data) == 2 for d in data: assert set(d.keys()) == self.expected_keys @pytest.mark.stores_mark class TestDataStoresNameSerializer(BaseTest): serializer_class = DataStoreNameSerializer model_class = DataStore factory_class = DataStoreFactory expected_keys = { 'id', 'name', } def setUp(self): super().setUp() self.obj1 = self.factory_class() # pylint:disable=not-callable self.obj2 = self.factory_class() # pylint:disable=not-callable def test_serialize_one(self): data = self.serializer_class(self.obj1).data assert set(data.keys()) == self.expected_keys for k, v in data.items(): assert getattr(self.obj1, k) == v def test_serialize_many(self): data = self.serializer_class(self.model_class.objects.all(), many=True).data assert len(data) == 2 for d in data: assert set(d.keys()) == self.expected_keys
28.686747
84
0.630827
acf68796a68e6255601ac0d16b5c719b8a82e52b
1,296
py
Python
app/core/tests/test_models.py
dutraleonardo/anyone-can-cook
98755959ed8ccddde8900dfe63223dcf245a01d7
[ "Apache-2.0" ]
null
null
null
app/core/tests/test_models.py
dutraleonardo/anyone-can-cook
98755959ed8ccddde8900dfe63223dcf245a01d7
[ "Apache-2.0" ]
null
null
null
app/core/tests/test_models.py
dutraleonardo/anyone-can-cook
98755959ed8ccddde8900dfe63223dcf245a01d7
[ "Apache-2.0" ]
null
null
null
from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Test creating a new user with an email is successful""" email = 'leonardo.uece@gmail.com' password = 'Testpass123' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_email_normalized(self): """Test the new email for new user is normalized.""" email = 'test@GMAIL.COM' user = get_user_model().objects.create_user(email, 'test123') self.assertEqual(user.email, email.lower()) def test_new_user_invalid_email(self): """Test creating user with no email raises error""" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'test123') def test_create_new_superuser(self): """Test creating a new superuser""" user = get_user_model().objects.create_superuser( 'test@gmail.com', 'test123' ) self.assertTrue(user.is_superuser) self.assertTrue(user.is_staff)
29.454545
69
0.652778
acf68a1f5406d6b76089a7f37bd68752c37754c0
698
py
Python
unsorted/pythonsnippets_0015.py
fiddlerwoaroof/sandbox
652acaf710a8b60f005769bde317e7bbf548cc2b
[ "BSD-3-Clause" ]
null
null
null
unsorted/pythonsnippets_0015.py
fiddlerwoaroof/sandbox
652acaf710a8b60f005769bde317e7bbf548cc2b
[ "BSD-3-Clause" ]
null
null
null
unsorted/pythonsnippets_0015.py
fiddlerwoaroof/sandbox
652acaf710a8b60f005769bde317e7bbf548cc2b
[ "BSD-3-Clause" ]
null
null
null
from twisted.spread import pb from twisted.internet import reactor def main(): foo = Foo() factory = pb.PBClientFactory() reactor.connectTCP("localhost", 8800, factory) factory.getRootObject().addCallback(foo.step1) reactor.run() class Foo: def __init__(self): self.oneRef = None def step1(self, obj): print "got one object:", obj self.oneRef = obj print "asking it to getTwo" self.oneRef.callRemote("getTwo").addCallback(self.step2) def step2(self, two): print "got two object:", two print "giving it back to one" print "one is", self.oneRef self.oneRef.callRemote("checkTwo", two) main()
25.851852
64
0.636103
acf68ae0f99b466dad10d9090dde8f0f656518c2
747
py
Python
Python/lc_853_car_fleet.py
cmattey/leetcode_problems
fe57e668db23f7c480835c0a10f363d718fbaefd
[ "MIT" ]
6
2019-07-01T22:03:25.000Z
2020-04-06T15:17:46.000Z
Python/lc_853_car_fleet.py
cmattey/leetcode_problems
fe57e668db23f7c480835c0a10f363d718fbaefd
[ "MIT" ]
null
null
null
Python/lc_853_car_fleet.py
cmattey/leetcode_problems
fe57e668db23f7c480835c0a10f363d718fbaefd
[ "MIT" ]
1
2020-04-01T22:31:41.000Z
2020-04-01T22:31:41.000Z
# Time: O(nlogn) # Space: O(1), excluding car_info else: O(n) class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: """ Sort based on distance after zipping with speed. Calculate time to target, and use that to calculate fleet. """ car_info = sorted(zip(position,speed), reverse=True) # reverse, because we want to calculate starting from cars closest # to the target, i.e. with highest position. print(car_info) prev_time = -1 fleet = 0 for pos, sp in car_info: time = (target-pos)/sp if time>prev_time: fleet+=1 prev_time = time return fleet
27.666667
82
0.572959
acf68b5542b6a801bf4c7d59bf01472ffd9c35e4
1,914
py
Python
autocomplete/lib/utils.py
cap-ntu/Autocomplete
3cd85cb8974fba55bbece0cb78beb46dcac265e5
[ "Apache-2.0" ]
1
2021-04-24T15:54:11.000Z
2021-04-24T15:54:11.000Z
autocomplete/lib/utils.py
cap-ntu/Autocomplete
3cd85cb8974fba55bbece0cb78beb46dcac265e5
[ "Apache-2.0" ]
16
2020-03-10T14:08:35.000Z
2022-02-27T02:56:46.000Z
autocomplete/lib/utils.py
cap-ntu/Autocomplete
3cd85cb8974fba55bbece0cb78beb46dcac265e5
[ "Apache-2.0" ]
null
null
null
import torch import torch.nn as nn def get_best_device(): return get_device(torch.cuda.is_available()) def get_device(cuda): return torch.device("cuda" if cuda else "cpu") def init_recurrent_layers(*layers): for layer in layers: for name, param in layer.named_parameters(): if 'bias' in name: nn.init.constant_(param, 0.0) elif 'weight' in name: nn.init.xavier_normal_(param) def init_layers_uniform(min_value, max_value, layers): for layer in layers: for name, param in layer.named_parameters(): nn.init.uniform_(param, min_value, max_value) def repackage_hidden(h): if type(h) == torch.Tensor: return h.detach().requires_grad_(h.requires_grad) else: return tuple(repackage_hidden(v) for v in h) def forget_hidden_partly_lstm_cell(h, forget_vector): return h[0].mul(forget_vector), h[1].mul(forget_vector) def forget_hidden_partly(h, forget_vector): if type(h) == torch.Tensor: return h.mul(forget_vector.unsqueeze(0)) # TODO: check else: return tuple(forget_hidden_partly(v, forget_vector) for v in h) def setup_tensor(tensor): return tensor.to(get_best_device()) def filter_requires_grad(parameters): return filter(lambda p: p.requires_grad, parameters) def register_forward_hook(module, metrics, picker): module.register_forward_hook(lambda _, m_input, m_output: metrics.report(picker(m_input, m_output))) def register_output_hook(module, metrics, picker=None): if picker is None: picker = lambda m_output: m_output register_forward_hook(module, metrics, lambda m_input, m_output: picker(m_output)) def register_input_hook(module, metrics, picker=None): if picker is None: picker = lambda m_input: m_input[0] register_forward_hook(module, metrics, lambda m_input, m_output: picker(m_input))
29
104
0.703762
acf68bd94782810be674b62c197c2b1681d9d77e
307
py
Python
hard-gists/39c2f27b581720482bc0/snippet.py
jjhenkel/dockerizeme
eaa4fe5366f6b9adf74399eab01c712cacaeb279
[ "Apache-2.0" ]
21
2019-07-08T08:26:45.000Z
2022-01-24T23:53:25.000Z
hard-gists/39c2f27b581720482bc0/snippet.py
jjhenkel/dockerizeme
eaa4fe5366f6b9adf74399eab01c712cacaeb279
[ "Apache-2.0" ]
5
2019-06-15T14:47:47.000Z
2022-02-26T05:02:56.000Z
hard-gists/39c2f27b581720482bc0/snippet.py
jjhenkel/dockerizeme
eaa4fe5366f6b9adf74399eab01c712cacaeb279
[ "Apache-2.0" ]
17
2019-05-16T03:50:34.000Z
2021-01-14T14:35:12.000Z
#!/usr/bin/env python # you may need to apt-get install python-imaging import sys from PIL import Image def red(filename): image = Image.open(filename) for r, g, b in image.getdata(): if r < g and r < b: return False return True filename = sys.argv[1] print red(filename)
19.1875
48
0.644951
acf68bdcf5bb31d0d30c188fd26c8db464f78f8e
204
py
Python
hill/data/pgp/item/packet.py
cofiem/repo-browser
95b6fe416efc77f4c4451f5b63e9fa96e2f8f618
[ "MIT" ]
null
null
null
hill/data/pgp/item/packet.py
cofiem/repo-browser
95b6fe416efc77f4c4451f5b63e9fa96e2f8f618
[ "MIT" ]
null
null
null
hill/data/pgp/item/packet.py
cofiem/repo-browser
95b6fe416efc77f4c4451f5b63e9fa96e2f8f618
[ "MIT" ]
null
null
null
class Packet: """ A PGP Message Packet. Ref: https://datatracker.ietf.org/doc/html/rfc4880#section-4 """ header: str body: str def __str__(self): return self.header
15.692308
64
0.598039
acf68c1f55eab1edc50abfe27c4d6c0bfbfa5876
1,095
py
Python
prepare_training_embeddings_data.py
countrymarmot/testFacenet
92e966930d931d41ab3bb49928b7de2034c3ac62
[ "MIT" ]
null
null
null
prepare_training_embeddings_data.py
countrymarmot/testFacenet
92e966930d931d41ab3bb49928b7de2034c3ac62
[ "MIT" ]
null
null
null
prepare_training_embeddings_data.py
countrymarmot/testFacenet
92e966930d931d41ab3bb49928b7de2034c3ac62
[ "MIT" ]
1
2019-12-09T06:59:33.000Z
2019-12-09T06:59:33.000Z
from tensorflow import keras import numpy as np def get_embedding(model, face): face = face.astype("float32") mean, std = face.mean(), face.std() face = (face - mean) / std samples = np.expand_dims(face, axis=0) yhat = model.predict(samples) return yhat[0] if __name__ == "__main__": model = keras.models.load_model("./model/facenet_keras.h5") print(model.summary()) data = np.load("./data/syna.npz") X_train, y_train, X_val, y_val = data["arr_0"], data["arr_1"], data["arr_2"], data["arr_3"] print(X_train.shape, y_train.shape) newX_train = [] for face in X_train: embedding = get_embedding(model, face) newX_train.append(embedding) newX_train = np.asarray(newX_train) newX_val = [] for face in X_val: embedding = get_embedding(model, face) newX_val.append(embedding) newX_val = np.asarray(newX_val) print(newX_train.shape) print(newX_val.shape) np.savez_compressed("data/syna_embeddings.npz", newX_train, y_train, newX_val, y_val)
27.375
96
0.63653
acf68cc86d635e7048c2b9dc81a5a73cfda49b1d
252
py
Python
TwoScoops/manage.py
wanchaosoft/TwoScoops
765ea849a04b7dce02c1900704f8ee08d8ace130
[ "MIT" ]
null
null
null
TwoScoops/manage.py
wanchaosoft/TwoScoops
765ea849a04b7dce02c1900704f8ee08d8ace130
[ "MIT" ]
2
2020-02-12T01:20:45.000Z
2020-06-05T18:43:12.000Z
TwoScoops/manage.py
dasky92/TwoScoops
765ea849a04b7dce02c1900704f8ee08d8ace130
[ "MIT" ]
null
null
null
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "TwoScoops.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
22.909091
73
0.77381
acf68d0642e9e3bc7665eb1c48e4f318ca99f3e9
9,689
py
Python
dark/genomes.py
UdoGi/dark-matter
3d49e89fa5e81f83144119f6216c5774176d203b
[ "MIT" ]
10
2016-03-09T09:43:14.000Z
2021-04-03T21:46:12.000Z
dark/genomes.py
terrycojones/dark-matter
67d16f870db6b4239e17e542bc6e3f072dc29c75
[ "MIT" ]
332
2015-01-07T12:37:30.000Z
2022-01-20T15:48:11.000Z
dark/genomes.py
terrycojones/dark-matter
67d16f870db6b4239e17e542bc6e3f072dc29c75
[ "MIT" ]
4
2016-03-08T14:56:39.000Z
2021-01-27T08:11:27.000Z
from collections import Counter from dark.errors import NoSuchGenomeError from dark.genbank import GenomeRanges from dark.reads import DNARead from dark.sam import samfile class GenomeProteinInfo(object): """ Hold information about the proteins in a genome and how they are matched by reads in SAM files. @param accession: The C{str} accession number of a genome. @param proteinGenomeDB: A L{dark.civ.proteins.SqliteIndex} instance. @param checkTranslations: If C{True}, check that the protein sequences that area supposed to have come from the genome can be obtained by translating the corresponding region of the genome. """ def __init__(self, genomeAccession, proteinGenomeDB, checkTranslations=True): self.genomeAccession = genomeAccession self.proteinGenomeDB = proteinGenomeDB # self.proteins is keyed by protein accession number. self.proteins = {} self.coveredProteins = set() # self.offsets is keyed by genome offset, values are dicts that # contain a list of protein accession numbers that overlap that # offset and a set of read ids (if any) that match at that offset. # The offsets keys are only those that correspond to one or more # proteins in the genome. self.offsets = {} # self.coveredOffsetCount holds the read counts for all offsets covered # by reads, regardless of whether the offsets correspond to proteins or # not. self.coveredOffsetCount = Counter() self.samFiles = [] self.readIdsMatchingGenome = set() self.genome = proteinGenomeDB.findGenome(genomeAccession) if self.genome is None: raise NoSuchGenomeError('Reference %r not found in protein/genome ' 'database.' % genomeAccession) for protein in proteinGenomeDB.findProteinsForGenome(genomeAccession): proteinAccession = protein['accession'] self.proteins[proteinAccession] = protein ranges = GenomeRanges(protein['offsets']).ranges # print('Protein accession', proteinAccession) # print(ranges) for (start, stop, forward) in ranges: for offset in range(start, stop): if offset not in self.offsets: self.offsets[offset] = { 'proteinAccessions': set(), 'readIds': set(), } self.offsets[offset]['proteinAccessions'].add( proteinAccession) if checkTranslations: self._checkTranslation(self.genome, ranges, protein) def _checkTranslation(self, genome, ranges, protein): """ Make sure all protein sequences supposed to be in the genome can in fact be obtained by translating the genome. @param genome: A C{dict} with genome information from our sqlite3 protein/genome database, as returned by C{dark.civ.proteins.SqliteIndex.findGenome. @param ranges: A C{list} of (start, stop, forward) nucleotide ranges for the protein in the genome. @param protein: A C{dict} with protein information from our sqlite3 protein/genome database, as returned by C{dark.civ.proteins.SqliteIndex.findProtein. """ proteinSequence = protein['sequence'] + '*' # print('protein name', protein['product'], 'ranges', ranges) sequence = ''.join([genome['sequence'][start:stop] for (start, stop, _) in ranges]) genomeRead = DNARead('id', sequence) translations = list(genomeRead.translations()) index = 0 if protein['forward'] else 3 if translations[index].sequence != proteinSequence: # TODO: improve this error to show what actually went wrong. raise ValueError( 'Could not translate genome range to get protein sequence') def addSAM(self, filename, filterAlignment=None): """ Read a SAM file and add information about the reads that match our reference id. @param filename: A C{str} SAM filename. @param filterAlignment: A 1-argument function to be used for filtering reads in the SAM file. If C{None}, all alignments will be examined. """ self.samFiles.append(filename) referenceId = self.genomeAccession with samfile(filename) as sam: for column in sam.pileup(): for read in column.pileups: alignment = read.alignment if (alignment.reference_name == referenceId and (filterAlignment is None or filterAlignment(alignment))): readId = alignment.query_name self.readIdsMatchingGenome.add(readId) offset = column.reference_pos self.coveredOffsetCount[offset] += 1 try: offsetInfo = self.offsets[offset] except KeyError: pass else: # This offset corresponds to one or more proteins. self.coveredProteins.update( offsetInfo['proteinAccessions']) offsetInfo['readIds'].add(readId) def proteinCoverageInfo(self, proteinAccession, minReadOffsetCount=None): """ Calculate coverage information for a protein. @param proteinAccession: A C{str} accession number. @param minReadOffsetCount: An C{int}, specifying the minimum number of reads offsets that must overlap the protein for the read to be considered as sufficiently intersecting the protein. Use this to prevent reads that just overlap the protein in a very small number offsets from being counted. Or C{None} to indicate that no such filtering should be applied. @raises KeyError: If C{proteinAccession} is not known. @return: A C{dict} containing * the number of covered offsets, * the total number of read bases that cover the protein, * the protein length (in nucleotides), and * the set of all matching read ids. See below for the dictionary keys. """ protein = self.proteins[proteinAccession] coveredOffsets = 0 totalBases = 0 allReadIds = set() offsetsSeen = set() proteinLength = 0 if minReadOffsetCount is not None and minReadOffsetCount < 2: # A minimum of zero or one is equivalent to not giving a value. minReadOffsetCount = None if minReadOffsetCount: readOffsetCounts = Counter() proteinRanges = GenomeRanges(protein['offsets']).ranges # Do an initial pass across all the offsets of the protein to see # which reads intersect and where. We will then do a second pass in # which we ignore reads that do not sufficiently overlap. for (start, stop, forward) in proteinRanges: proteinLength += stop - start for offset in range(start, stop): assert offset not in offsetsSeen offsetsSeen.add(offset) readIds = self.offsets[offset]['readIds'] if readIds and minReadOffsetCount: readOffsetCounts.update(readIds) # Sanity check that the sum of the range lengths is the same as the # overall length given in the database. # # The +3 in the following is because the database holds the AA # length, not including the stop codon. But the database range # covers the stop codon. dbProteinLength = self.proteins[proteinAccession]['length'] * 3 + 3 if proteinLength != dbProteinLength: raise ValueError( 'Sum of protein database ranges (%d) does not agree with ' 'database protein length (%d) for protein %s!' % (proteinLength, dbProteinLength, proteinAccession)) # If we are not reporting reads whose overlapping offset count is # too low, make a set of such reads. if minReadOffsetCount: unwanted = set(readId for readId in readOffsetCounts if readOffsetCounts[readId] < minReadOffsetCount) else: unwanted = set() # Second pass, in which we ignore unwanted (i.e., insufficiently # overlapping) reads. for (start, stop, forward) in proteinRanges: for offset in range(start, stop): readIds = set(self.offsets[offset]['readIds']) - unwanted if readIds: allReadIds.update(readIds) coveredOffsets += 1 totalBases += len(readIds) return { 'coveredOffsets': coveredOffsets, 'totalBases': totalBases, 'ntLength': proteinLength, 'readIds': allReadIds, } def readIdsForAllProteins(self): """ Get the set of read ids for reads matching any protein at all. @return: A C{set} of C{str} read ids. """ result = set() for offsetInfo in self.offsets.values(): result.update(offsetInfo['readIds']) return result
43.644144
79
0.596759