id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3385499 | <reponame>Feng-Yuze/ASP
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10
@author: jaehyuk
"""
import numpy as np
import scipy.stats as ss
import scipy.optimize as sopt
from . import normal
from . import bsm
import pyfeng as pf
'''
MC model class for Beta=1
'''
class ModelBsmMC:
beta = 1.0 # fixed (not used)
vov, rho = 0.0, 0.0
sigma, intr, divr = None, None, None
bsm_model = None
'''
You may define more members for MC: time step, etc
'''
def __init__(self, sigma, vov=0, rho=0.0, beta=1.0, intr=0, divr=0):
self.sigma = sigma
self.vov = vov
self.rho = rho
self.intr = intr
self.divr = divr
self.bsm_model = pf.Bsm(sigma, intr=intr, divr=divr)
def bsm_vol(self, strike, spot, texp=None, sigma=None):
''''
From the price from self.price() compute the implied vol
this is the opposite of bsm_vol in ModelHagan class
use bsm_model
'''
return 0
def price(self, strike, spot, texp=None, sigma=None, cp=1):
'''
Your MC routine goes here
Generate paths for vol and price first. Then get prices (vector) for all strikes
You may fix the random number seed
'''
dt = 0.01
time_num = int(texp//dt)
path_num = 10000
price_paths = np.zeros((path_num ,time_num+1))
price_paths[: ,0] = spot
sigma_paths = np.zeros((path_num , time_num+1))
sigma_paths[: ,0] = self.sigma
for i in range(time_num):
z = np.random.randn(path_num)
x = np.random.randn(path_num)
w = self.rho*z+np.sqrt(1-self.rho**2)*x
sigma_paths[:,i+1] = sigma_paths[:,i]*np.exp(self.vov*np.sqrt(dt)*z-0.5*self.vov**2*dt)
price_paths[:,i+1] = price_paths[:,i]*np.exp(sigma_paths[:,i]*np.sqrt(dt)*w-0.5*sigma_paths[:,i]**2*dt)
self.price_paths = price_paths
self.sigma_paths = sigma_paths
strikes = np.array([strike] * path_num).T
self.option_prices = np.fmax(price_paths[:,-1]-strikes,0)
self.option_prices = self.option_prices.mean(axis=1)
return self.option_prices
'''
MC model class for Beta=0
'''
class ModelNormalMC:
beta = 0.0 # fixed (not used)
vov, rho = 0.0, 0.0
sigma, intr, divr = None, None, None
normal_model = None
def __init__(self, sigma, vov=0, rho=0.0, beta=0.0, intr=0, divr=0):
self.sigma = sigma
self.vov = vov
self.rho = rho
self.intr = intr
self.divr = divr
self.normal_model = pf.Norm(sigma, intr=intr, divr=divr)
def norm_vol(self, strike, spot, texp=None, sigma=None):
''''
From the price from self.price() compute the implied vol
this is the opposite of normal_vol in ModelNormalHagan class
use normal_model
'''
return 0
def price(self, strike, spot, texp=None, sigma=None, cp=1):
'''
Your MC routine goes here
Generate paths for vol and price first. Then get prices (vector) for all strikes
You may fix the random number seed
'''
dt = 0.01
time_num = int(texp//dt)
path_num = 10000
price_paths = np.zeros((path_num ,time_num+1))
price_paths[: ,0] = spot
sigma_paths = np.zeros((path_num , time_num+1))
sigma_paths[: ,0] = self.sigma
for i in range(time_num):
z = np.random.randn(path_num)
x = np.random.randn(path_num)
w = self.rho*z+np.sqrt(1-self.rho**2)*x
sigma_paths[:,i+1] = sigma_paths[:,i]*np.exp(self.vov*np.sqrt(dt)*z-0.5*self.vov**2*dt)
price_paths[:,i+1] = price_paths[:,i]+sigma_paths[:,i]*np.sqrt(dt)*w
self.price_paths = price_paths
self.sigma_paths = sigma_paths
strikes = np.array([strike] * path_num).T
self.option_prices = np.fmax(price_paths[:,-1]-strikes,0)
self.option_prices = self.option_prices.mean(axis=1)
return self.option_prices
'''
Conditional MC model class for Beta=1
'''
class ModelBsmCondMC:
beta = 1.0 # fixed (not used)
vov, rho = 0.0, 0.0
sigma, intr, divr = None, None, None
bsm_model = None
'''
You may define more members for MC: time step, etc
'''
def __init__(self, sigma, vov=0, rho=0.0, beta=1.0, intr=0, divr=0):
self.sigma = sigma
self.vov = vov
self.rho = rho
self.intr = intr
self.divr = divr
self.bsm_model = pf.Bsm(sigma, intr=intr, divr=divr)
def bsm_vol(self, strike, spot, texp=None):
''''
From the price from self.price() compute the implied vol
this is the opposite of bsm_vol in ModelHagan class
use bsm_model
should be same as bsm_vol method in ModelBsmMC (just copy & paste)
'''
return 0
@staticmethod
def bsm_formula(strikes, spots, texp, vol, intr=0.0, divr=0.0, cp_sign=1):
div_fac = np.exp(-texp * divr)
disc_fac = np.exp(-texp * intr)
forwards = spots / disc_fac * div_fac
forwards = forwards.reshape(1,-1)
strikes = strikes.reshape(-1,1)
if (texp <= 0):
return disc_fac * np.fmax(cp_sign * (forwards - strikes), 0)
# floor vol_std above a very small number
vol_std = np.fmax(vol * np.sqrt(texp), 1e-32)
vol_std = vol_std.reshape(1,-1)
d1 = np.log(forwards/strikes) / vol_std + 0.5 * vol_std
d2 = d1 - vol_std
prices = cp_sign * disc_fac * (forwards * ss.norm.cdf(cp_sign * d1) - strikes * ss.norm.cdf(cp_sign * d2))
return prices
def price(self, strike, spot, texp, cp=1):
'''
Your MC routine goes here
Generate paths for vol only. Then compute integrated variance and BSM price.
Then get prices (vector) for all strikes
You may fix the random number seed
'''
dt = 0.01
time_num = int(texp//dt)
path_num = 10000
sigma_paths = np.zeros((path_num , time_num+1))
sigma_paths[: ,0] = self.sigma
sum_sigmasquare = np.zeros(path_num)
sum_sigmasquare = sigma_paths[:,0]**2
for i in range(time_num):
z = np.random.randn(path_num)
sigma_paths[:,i+1] = sigma_paths[:,i]*np.exp(self.vov*np.sqrt(dt)*z-0.5*self.vov**2*dt)
sum_sigmasquare = sum_sigmasquare + sigma_paths[:,i+1]**2
I_t = sum_sigmasquare/time_num
self.sigma_paths = sigma_paths
self.prices = spot*np.exp(self.rho/self.vov*(sigma_paths[:,-1]-self.sigma)-self.rho**2*self.sigma**2*texp/2*I_t)
self.sigmabs = np.sqrt((1-self.rho**2)*I_t)
self.option_prices1 = self.bsm_formula(strike,self.prices,texp,self.sigmabs)
self.option_prices = np.mean(self.option_prices1,axis=1)
return self.option_prices
'''
Conditional MC model class for Beta=0
'''
class ModelNormalCondMC:
beta = 0.0 # fixed (not used)
vov, rho = 0.0, 0.0
sigma, intr, divr = None, None, None
normal_model = None
def __init__(self, sigma, vov=0, rho=0.0, beta=0.0, intr=0, divr=0):
self.sigma = sigma
self.vov = vov
self.rho = rho
self.intr = intr
self.divr = divr
self.normal_model = pf.Norm(sigma, intr=intr, divr=divr)
def norm_vol(self, strike, spot, texp=None):
''''
From the price from self.price() compute the implied vol
this is the opposite of normal_vol in ModelNormalHagan class
use normal_model
should be same as norm_vol method in ModelNormalMC (just copy & paste)
'''
return 0
@staticmethod
def normal_formula(strikes, spots, texp, vol, intr=0.0, divr=0.0, cp_sign=1):
div_fac = np.exp(-texp*divr)
disc_fac = np.exp(-texp*intr)
forwards = spots / disc_fac * div_fac
strikes = strikes.reshape(-1,1)
forwards = forwards.reshape(1,-1)
if( texp<=0 ):
return disc_fac * np.fmax( cp_sign*(forwards-strikes), 0 )
# floor vol_std above a very small number
vol_std = np.fmax(vol*np.sqrt(texp), 1e-32)
vol_std = vol_std.reshape(1,-1)
d = (forwards-strikes)/vol_std
prices = disc_fac*(cp_sign*(forwards-strikes)*ss.norm.cdf(cp_sign*d)+vol_std*ss.norm.pdf(d))
return prices
def price(self, strike ,spot, texp, cp=1):
'''
Your MC routine goes here
Generate paths for vol only. Then compute integrated variance and normal price.
You may fix the random number seed
'''
dt = 0.01
time_num = int(texp//dt)
path_num = 10000
sigma_paths = np.zeros((path_num , time_num+1))
sigma_paths[: ,0] = self.sigma
sum_sigmasquare = np.zeros(path_num)
sum_sigmasquare = self.sigma**2
for i in range(time_num):
z = np.random.randn(path_num)
x = np.random.randn(path_num)
w = self.rho*z+np.sqrt(1-self.rho**2)*x
sigma_paths[:,i+1] = sigma_paths[:,i]*np.exp(self.vov*np.sqrt(dt)*z-0.5*self.vov**2*dt)
sum_sigmasquare = sum_sigmasquare + sigma_paths[:,i+1]**2
I_t = sum_sigmasquare/time_num
self.sigma_paths = sigma_paths
self.sigma_n = np.sqrt((1-self.rho**2)*I_t)
self.prices = spot+self.rho/self.vov*(self.sigma_paths[:,-1]-self.sigma_paths[:,0])
self_option_prices1 = self.normal_formula(strike,self.prices, texp, self.sigma_n)
self.option_prices = np.mean(self_option_prices1,axis=1)
return self.option_prices
| StarcoderdataPython |
98903 | class Solution:
def uniquePaths(self, m: int, n: int) -> int:
ans = [1]*n
for i in range(1,m):
for j in range(1,n):
ans[j] = ans[j-1] + ans[j]
return ans[-1] if m and n else 0 | StarcoderdataPython |
3241590 | import abc
from typing import List, Type
from nuplan.common.maps.abstract_map_factory import AbstractMapFactory
from nuplan.planning.scenario_builder.abstract_scenario import AbstractScenario
from nuplan.planning.scenario_builder.scenario_filter import ScenarioFilter
from nuplan.planning.utils.multithreading.worker_pool import WorkerPool
class AbstractScenarioBuilder(abc.ABC):
"""Interface for generic scenario builder."""
@classmethod
@abc.abstractmethod
def get_scenario_type(cls) -> Type[AbstractScenario]:
"""Get the type of scenarios that this builder constructs."""
pass
@abc.abstractmethod
def get_scenarios(self, scenario_filter: ScenarioFilter, worker: WorkerPool) -> List[AbstractScenario]:
"""
Retrieve filtered scenarios from the database.
:param scenario_filter: Structure that contains scenario filtering instructions.
:param worker: Worker pool for concurrent scenario processing.
:return: A list of scenarios.
"""
pass
@abc.abstractmethod
def get_map_factory(self) -> AbstractMapFactory:
"""
Get a map factory instance.
"""
pass
| StarcoderdataPython |
1747 | <reponame>kra-ts/falconpy
"""Internal API endpoint constant library.
_______ __ _______ __ __ __
| _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----.
|. 1___| _| _ | | | | _ | 1___| _| _| | <| -__|
|. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____|
|: 1 | |: 1 |
|::.. . | CROWDSTRIKE FALCON |::.. . | FalconPy
`-------' `-------'
OAuth2 API - Customer SDK
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
"""
_filevantage_endpoints = [
[
"getChanges",
"GET",
"/filevantage/entities/changes/v2",
"Retrieve information on changes",
"filevantage",
[
{
"type": "array",
"items": {
"type": "string"
},
"collectionFormat": "multi",
"description": "Comma separated values of change ids",
"name": "ids",
"in": "query",
"required": True
}
]
],
[
"queryChanges",
"GET",
"/filevantage/queries/changes/v2",
"Returns one or more change IDs",
"filevantage",
[
{
"minimum": 0,
"type": "integer",
"description": "The first change index to return in the response. "
"If not provided it will default to '0'. "
"Use with the `limit` parameter to manage pagination of results.",
"name": "offset",
"in": "query"
},
{
"type": "integer",
"description": "The maximum number of changes to return in the response "
"(default: 100; max: 500). "
"Use with the `offset` parameter to manage pagination of results",
"name": "limit",
"in": "query"
},
{
"type": "string",
"description": "Sort changes using options like:\n\n"
"- `action_timestamp` (timestamp of the change occurrence) \n\n "
"Sort either `asc` (ascending) or `desc` (descending). "
"For example: `action_timestamp|asc`.\n"
"The full list of allowed sorting options can be reviewed in our API documentation.",
"name": "sort",
"in": "query"
},
{
"type": "string",
"description": "Filter changes using a query in Falcon Query Language (FQL). \n\n"
"Common filter options include:\n\n - `host.host_name`\n - `action_timestamp`\n\n "
"The full list of allowed filter parameters can be reviewed in our API documentation.",
"name": "filter",
"in": "query"
}
]
]
]
| StarcoderdataPython |
1692609 | from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
from urllink import crawl
req = Request('https://cornellbotanicgardens.org/explore/gardens/medicinal-herbs/', headers={'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).read()
testfile = open("html/files/a-web/tid6input.txt", "w")
soup = BeautifulSoup(webpage, 'lxml')
items = soup.find_all('div', class_="img-wrap")
for link in items:
all_links = link.find_all('a', href=True)
for l1 in all_links:
crawl(l1.attrs['href'], testfile)
testfile.close() | StarcoderdataPython |
1609331 | <reponame>mikapfl/datalad<filename>datalad/cmdline/common_args.py
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""
"""
__docformat__ = 'restructuredtext'
# argument spec template
#<name> = (
# <id_as_positional>, <id_as_option>
# {<ArgumentParser.add_arguments_kwargs>}
#)
from ..cmdline.helpers import HelpAction, LogLevelAction
help = (
'help', ('-h', '--help', '--help-np'),
dict(nargs=0, action=HelpAction,
help="""show this help message. --help-np forcefully disables
the use of a pager for displaying the help message""")
)
# note: no longer used by the main `datalad` entry point, but could still
# be used by downstream software, so was left in place
version = (
'version', ('--version',),
dict(action='version',
help="show the program's version")
)
_log_level_names = ['critical', 'error', 'warning', 'info', 'debug']
log_level = (
'log-level', ('-l', '--log-level'),
dict(action=LogLevelAction,
choices=_log_level_names + [str(x) for x in range(1, 10)],
metavar="LEVEL",
default='warning',
help="""set logging verbosity level. Choose among %s. Also you can
specify an integer <10 to provide even more debugging information"""
% ', '.join(_log_level_names))
)
pbs_runner = (
'pbs-runner', ('--pbs-runner',),
dict(choices=['condor'],
default=None,
help="""execute command by scheduling it via available PBS. For settings, config file will be consulted""")
)
change_path = (
'change-path', ('-C',),
dict(action='append',
dest='change_path',
metavar='PATH',
help="""run as if datalad was started in <path> instead
of the current working directory. When multiple -C options are given,
each subsequent non-absolute -C <path> is interpreted relative to the
preceding -C <path>. This option affects the interpretations of the
path names in that they are made relative to the working directory
caused by the -C option""")
)
| StarcoderdataPython |
120211 | <gh_stars>1-10
import torch
def Spatial_loss(matrix, D):
x1 = matrix.view(-1, 4096, 1)
Sv = torch.std(x1, dim=0)
Xm = x1 - x1.mean(dim=0)
C = Xm @ Xm.view(-1, 1, 4096)
C = C.mean(dim=0)
S = Sv @ Sv.view(1, -1)
C = C / S
loss = torch.abs(C - (1.0 / (D + 1)))
kloss = loss.sum()-loss.trace()
return kloss | StarcoderdataPython |
3353726 | from dipper.graph.Graph import Graph
class Family():
"""
Model mereological/part whole relationships
Although these relations are more abstract, we often
use them to model family relationships (proteins, humans, etc.)
The naming of this class may change in the future to better
reflect the meaning of the relations it is modeling
"""
def __init__(self, graph):
if isinstance(graph, Graph):
self.graph = graph
else:
raise ValueError("{} is not a graph".format(graph))
self.globaltt = self.graph.globaltt
self.globaltcid = self.graph.globaltcid
self.curie_map = self.graph.curie_map
def addMember(self, group_id, member_id):
self.graph.addTriple(group_id, self.globaltt['has member'], member_id)
return
def addMemberOf(self, member_id, group_id):
self.graph.addTriple(member_id, self.globaltt['member of'], group_id)
return
| StarcoderdataPython |
3308677 | <gh_stars>1-10
from random import random, seed
from typing import List
from gsf.dynamic_system.dynamic_systems import DiscreteEventDynamicSystem
from examples.example_1.cell import Cell
class LinearAutomata(DiscreteEventDynamicSystem):
"""Linear Automata implementation
It has a group of cells, connected between them. The output cells of each cell are all its neighbors.
Attributes:
_cells (List[Cell]): Group of cells of the linear automata.
"""
_cells: List[Cell]
def __init__(self, cells: int = 5, random_seed: int = 42):
"""
Args:
cells (int): Number of cells of the automata.
random_seed (int): Random seed for determinate the state of the seeds.
"""
super().__init__()
seed(random_seed)
self._create_cells(cells)
self._create_relations(cells)
def _create_cells(self, cells: int):
"""Appends the cells to the automata.
Args:
cells (int): Number of cells of the automata.
"""
self._cells = []
for i in range(cells):
is_alive = random() < 0.5
self._cells.append(Cell(self, is_alive))
def _create_relations(self, cells: int):
"""Creates the connections between the left cell and the right cell.
Args:
cells (int): Number of cells of the automata.
"""
for i in range(cells):
self._cells[i - 1].add(self._cells[i])
def __str__(self):
"""Changes the format to show the linear automata when is printed"""
s = ""
for cell in self._cells:
s += str(cell)
return s
| StarcoderdataPython |
1693034 | # <NAME>
# 16-09-2020
# Final assignment for Programming
# Project: MyMusic
from functions import clearConsole, tryParseInt
from termcolor import cprint
import sys
# Everything what belongs to Menu
class Menu:
# Sets profile and starts the showMenu function
def __init__(self, profile, playlist):
self.playlist = playlist
self.profile = profile
self.showOptions()
def showOptions(self):
clearConsole()
cprint(f"Hi {self.profile.name}, make an option!", "green")
print("[1] My Information")
print("[2] My Favorite Songs")
print("[3] All Songs")
print("[4] Songs by Genre")
print("[5] Add Song")
print("[6] Add Song to \"My Favorite Songs\"")
if not self.playlist.isFilledWithSeed:
print("[7] Load Songs")
print("[0] Exit MyMusic\n")
self.optionHandler()
def optionHandler(self):
chosenMenuOption = tryParseInt(input(f"Option: "))
clearConsole()
if chosenMenuOption == 0:
cprint("Thanks for using MyMusic. See you back soon!", "green")
sys.exit()
elif chosenMenuOption == 1:
self.profile.showMyInformation()
elif chosenMenuOption == 2:
self.playlist.showFavoriteSongs()
elif chosenMenuOption == 3:
self.playlist.showAllSongs()
elif chosenMenuOption == 4:
self.playlist.songsByGenre()
elif chosenMenuOption == 5:
self.playlist.createSong()
elif chosenMenuOption == 6:
self.playlist.addToFavorite()
elif chosenMenuOption == 7 and not self.playlist.isFilledWithSeed:
self.playlist.seedListOfSongs()
else:
self.showOptions()
input("\nPress [Enter] to go back to the menu!")
self.showOptions()
| StarcoderdataPython |
152192 | from Maxwell import *
from dolfin import *
from numpy import *
import scipy as Sci
import scipy.linalg
from math import pi,sin,cos,sqrt
import scipy.sparse as sps
import scipy.io as save
import scipy
import pdb
from matrix2latex import *
print "FEniCS routine to solve Maxwell subproblem \n \n"
Mcycle = 10
n = 2
time = zeros((Mcycle,1))
N = zeros((Mcycle,1))
DoF = zeros((Mcycle,1))
cycle = zeros((Mcycle,1))
table = zeros((Mcycle,4))
for j in xrange(1,Mcycle+1):
print "cycle #",j-1,"\n"
n = 2*n
M = Maxwell(n)
mesh = M.mesh
N[j-1,0] = n
tic()
V,u,v= M.CreateTrialTestFuncs(mesh)
time[j-1,0] = toc()
u0 = Expression(('0','0'))
f=Expression(("2+x[1]*(1-x[1])","2+x[0]*(1-x[0])"))
A,b = M.AssembleSystem(V,u,v,f,u0,1,"PETSc")
DoF[j-1,0] = b.size()
cycle[j-1,0] = j-1
table[j-1,:] = [j-1,n,b.size(),time[j-1,0]]
print matrix2latex(table)
| StarcoderdataPython |
34372 | <reponame>DennyWeinberg/photoprism
import unittest
from photoprism import Client
class TestClass(unittest.TestCase):
def test_upload():
client = Client()
client.upload_photo('20210104_223259.jpg', b'TODO', album_names=['Test Album'])
| StarcoderdataPython |
1666373 | <filename>cbuild/filter_logic.py<gh_stars>1-10
minelo = self.get_min_elo()
if minelo < 2200:
self.ok = False | StarcoderdataPython |
3322227 | import sys
from pathlib import Path
def check_if_available(prg, msg):
"""
Check if the given program is available.
If not, then die with the given error message.
"""
if not Path(prg).is_file():
print(msg, file=sys.stderr)
sys.exit(1)
| StarcoderdataPython |
1785891 | max_predicate = lambda a, b: a[1] <= b[1]
class Heap:
def __init__(self):
self.heap = []
def heap_swap(self, a, b):
t = self.heap[a]
self.heap[a] = self.heap[b]
self.heap[b] = t
def _heapify(self, heap_size, x, predicate):
left = 2 * (x + 1) - 1
right = 2 * (x + 1)
largest = x
if left < heap_size and predicate(self.heap[left], self.heap[x]):
largest = left
if right < heap_size and predicate(self.heap[right], self.heap[largest]):
largest = right
if largest != x:
self.heap_swap(x, largest)
self._heapify(heap_size, largest, predicate)
def make_heap(self, h, comp=max_predicate):
for i in range(len(h)):
spectra_peak = h[i]
self.heap.append([i, 0, spectra_peak])
heap_size = len(self.heap)
for i in reversed(range(0, heap_size //2)):
self._heapify(heap_size, i, comp)
def top(self):
return self.heap[0]
def empty(self):
return self.heap == []
def size(self):
return len(self.heap)
def pop_back(self):
self.heap = self.heap[:-1]
def pop_heap(self, predicate):
pop_value = self.heap[0]
self.heap_swap(0, len(self.heap)-1)
self._heapify(len(self.heap) -1, 0, predicate)
return pop_value
def push_heap(self, value, predicate=max_predicate):
self.heap.append(value)
current = len(self.heap) - 1
while current > 0:
parent = (current - 1) // 2
if predicate(self.heap[current], self.heap[parent]):
self.heap_swap(parent, current)
current = parent
else:
break
def pop_and_feed(self, peak, comp=max_predicate):
if self.empty():
raise Exception("Heap::popAndFeed(): theVector must be non empty")
returned_peak = self.heap[0]
spectra_indx = returned_peak[0]
peak_indx = returned_peak[1] + 1
self.pop_heap(comp)
spectra = peak[spectra_indx]
if peak_indx < len(spectra):
self.heap[self.size() - 1] = [spectra_indx, peak_indx, spectra[peak_indx]]
self.push_heap(spectra, comp)
else:
self.pop_back()
return returned_peak | StarcoderdataPython |
1749238 | <reponame>chidioguejiofor/airtech-api
# Generated by Django 2.2 on 2019-04-08 17:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0007_auto_20190408_1436'),
('flight', '0014_auto_20190408_1510'),
('booking', '0005_auto_20190408_1644'),
]
operations = [
migrations.AlterUniqueTogether(
name='booking',
unique_together={('flight_id', 'created_by')},
),
]
| StarcoderdataPython |
18683 | <filename>syndata/__init__.py
# coding=utf-8
# Author: <NAME> <<EMAIL>>
#
# License: MIT
"""
The :mod:`deslib.util` This module includes various utilities. They are divided into three parts:
syndata.synthethic_datasets - Provide functions to generate several 2D classification datasets.
syndata.plot_tools - Provides some routines to easily plot datasets and decision borders of a scikit-learn classifier.
"""
from .plot_tools import *
from .synthetic_datasets import *
| StarcoderdataPython |
174528 | <reponame>ngshiheng/six-percent
from cryptography.fernet import Fernet
def generate_key() -> None:
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("secret.key", "wb") as key_file:
key_file.write(key)
def load_key() -> bytes:
"""
Loads the key named `secret.key` from the current directory
"""
return open("secret.key", "rb").read()
def encrypt_password(password: str) -> str:
"""
Returns an encrypted password
"""
encoded_password = password.encode()
f = Fernet(load_key())
return f.encrypt(encoded_password).decode()
def decrypt_password(hashed_password: str) -> str:
"""
Returns a decrypted password
"""
f = Fernet(load_key())
return f.decrypt(hashed_password.encode()).decode()
| StarcoderdataPython |
4802873 | default_app_config = 'media_server.apps.MediaServerConfig'
| StarcoderdataPython |
3911 | from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
__author__ = "<NAME>, <NAME>, and <NAME>"
__copyright__ = "Copyright 2013-2015 UKP TU Darmstadt"
__credits__ = ["<NAME>", "<NAME>", "<NAME>"]
__license__ = "ASL"
class Redirector(webapp.RequestHandler):
def get(self):
self.redirect("/argunit/home")
def post(self):
self.redirect("/argunit/home")
application = webapp.WSGIApplication(
[('/.*', Redirector)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
| StarcoderdataPython |
1788166 | <reponame>kagemeka/python
from \
kgmk.dsa.algebra.modular \
.factorial.jit \
import (
factorial,
inv_factorial,
)
import numpy as np
import numba as nb
@nb.njit
def choose(
n: int,
r: int,
) -> int:
global mod, fact, ifact
ok = (0 <= r) & (r <= n)
c = fact[n] * ok
c = c * ifact[n - r] % mod
return c * ifact[r] % mod
def test():
global mod
mod = 10 ** 9 + 7
n = 1 << 20
global fact, ifact
fact = factorial(n, mod)
ifact = inv_factorial(n, mod)
c = choose
assert (
c(40, 20) == 846527861
)
for i in range(100):
c(np.arange(1 << 20), 3)
if __name__ == '__main__':
test() | StarcoderdataPython |
1796691 | <reponame>HLOverflow/StockCat
import math
from datetime import datetime
from typing import Union, List, Any
import pandas
from alpha_vantage.fundamentaldata import FundamentalData
from pandas import DataFrame, Series
from stock_cat.alpha_vantage_ext.fundamentals_extensions import get_earnings_annual
ListTable = List[List[Any]]
DictTable = List[dict]
class IntrinsicValueRecipe:
__summary_keys = ['Symbol', 'Name', 'Exchange', 'Currency', 'EPS', 'Beta', 'PERatio',
'200DayMovingAverage', '50DayMovingAverage']
___eps_growth_avg_window_years: int = 3
# Discount rates can be also calculated automatically. For now, for simplicity we are using a hard coded
# 9%. I haven't learned the intricacies to compute it better.
# TODO: Implement an automated discount rate calculation method.
___default_discount_rate_percent: float = 9.0
def __init__(self, ticker: str, av_api_key: str) -> None:
self.__ticker = ticker
self.__av_api_key = av_api_key
fundamental_data = FundamentalData(key=av_api_key)
# The current version of alpha_vantage library doesn't have all Alpha Vantage API. Adding the missing
# get_earnings_annual method to the created FundamentalData object here so we can still use the Earnings API
fundamental_data.get_earnings_annual = get_earnings_annual
self.__fundamentals = fundamental_data
def get_default_discount_rate(self) -> float:
return self.___default_discount_rate_percent
def get_ticker_fundamentals(self, as_table: bool = False) -> Union[dict, ListTable]:
overview, _ = self.__fundamentals.get_company_overview(symbol=self.__ticker)
if as_table:
return [[x, overview[x]] for x in self.__summary_keys]
return {x: overview[x] for x in self.__summary_keys}
def get_past_eps_trend(self, max_years: int = 10) -> DataFrame:
earnings, _ = self.__fundamentals.get_earnings_annual(self.__fundamentals, self.__ticker)
trend_len = min(len(earnings), max_years + 1)
past_eps_trend_df: DataFrame = earnings.head(trend_len).copy(deep=True)
past_eps_trend_df['reportedEPS'] = past_eps_trend_df['reportedEPS'].astype(float)
past_eps_trend_df.insert(len(past_eps_trend_df.columns), 'epsGrowthPercent', 0.0)
past_eps_trend_df.insert(len(past_eps_trend_df.columns), 'avgEpsGrowthPercent', 0.0)
for i in range(0, len(past_eps_trend_df) - 1):
past_eps_trend_df.loc[i, 'epsGrowthPercent'] = \
((past_eps_trend_df.loc[i, 'reportedEPS'] / past_eps_trend_df.loc[i + 1, 'reportedEPS']) - 1.0) * 100
for i in range(0, len(past_eps_trend_df) - self.___eps_growth_avg_window_years):
past_eps_trend_df.loc[i, 'avgEpsGrowthPercent'] = \
past_eps_trend_df.loc[i:i + self.___eps_growth_avg_window_years, 'epsGrowthPercent'].mean()
ret = past_eps_trend_df.head(trend_len - 1)
return ret
def get_future_eps_trend(self, eps: float, avg_eps_growth_pct: float, discount_rate: float,
years: int = 75) -> DataFrame:
curr_year: int = datetime.now().year
future_years = [curr_year + x for x in range(0, years)]
future_eps: list[float] = []
discounted_present_values: list[float] = []
curr_eps = eps
curr_avg_eps_growth_pct = avg_eps_growth_pct
for i in range(len(future_years)):
computed_eps = curr_eps + curr_eps * (curr_avg_eps_growth_pct / 100)
future_eps.append(computed_eps)
# Present discounted EPS value = Future Value / (1+discount_rate)^n
discounted_present_value = computed_eps / math.pow(1 + discount_rate / 100, i + 1)
discounted_present_values.append(discounted_present_value)
curr_eps = computed_eps
if i % 10 == 0:
# Divide current eps growth pct to 70% of its actual value to be pessimistic here
curr_avg_eps_growth_pct = curr_avg_eps_growth_pct * 0.70
data = {
'years': future_years,
'futureEps': future_eps,
'discountedPresentValue': discounted_present_values
}
return pandas.DataFrame(data)
def get_intrinsic_value(self, discounted_present_value_series: Series):
return discounted_present_value_series.sum()
| StarcoderdataPython |
3219775 | """Merge data produced in different shards of extraction.
Namely:
1. Trajectories
2. Scene cuts
Output: single merged files trajectories.jsonl and scene_changes.json
"""
from typing import Set
import argparse
import os
import json
import glob
from utils.utils import load_images_map
def is_trajectory_valid(trajectory, images_map):
"""Check that a trajectory has associated images.
"""
# TODO: add min count instead?
for frame_index, bbs in enumerate(trajectory["bbs"], start=trajectory["start"]):
if frame_index in images_map and tuple(bbs) in images_map[frame_index]:
return True
return False
def passes_min_size(trajectory, min_face_size):
"""Check that faces have a certain minimum (pixel) size. This is useful if
we want to have reliable embedddings of images in a trajectory.
"""
for bbs in trajectory["bbs"]:
# Bounding boxes (bbs) are: x1, y1, x2, y2
w, h = (bbs[2] - bbs[0]), (bbs[3] - bbs[1])
if min(w, h) < min_face_size:
return False
return True
def save_trajectories(file, trajectories, images_map, min_face_size, traj_count, movie_id):
"""Save trajectories, and filter out trajectories that had no corresponding
images for any bounding boxes.
"""
# Write out .jsonl
n_saved = 0
for traj in trajectories:
if is_trajectory_valid(traj, images_map) and passes_min_size(traj, min_face_size):
traj["index"] = traj_count
traj["movie_id"] = movie_id
json.dump(traj, file, indent=None, separators=(",", ":"))
file.write("\n")
traj_count += 1
n_saved += 1
n_removed = len(trajectories) - n_saved
return n_saved, n_removed
def save_scene_changes(file_path, scene_cuts: Set[int], movie_id: int):
scene_cuts_list = sorted(scene_cuts)
with open(file_path, "w") as file:
obj = {"frame_indices": scene_cuts_list, "movie_id": movie_id}
json.dump(obj, file, indent=None, separators=(",", ":"))
file.write("\n")
def iou(boxA, boxB):
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
interArea = abs(max((xB - xA, 0)) * max((yB - yA), 0))
boxAArea = abs((boxA[2] - boxA[0]) * (boxA[3] - boxA[1]))
boxBArea = abs((boxB[2] - boxB[0]) * (boxB[3] - boxB[1]))
return interArea / float(boxAArea + boxBArea - interArea)
def load_trajectory(trajectory_file: str, scene_cuts: Set[int], iou_threshold: float):
"""Load a single trajectory file (from 1 shard).
Note: also merges possible trajectories that weren't caught by the face trackers
earlier, while making sure that no trajectories pass scene_cuts.
"""
with open(trajectory_file, "r") as f:
trajectories = sorted([json.loads(line) for line in f], key=lambda t: t["start"])
merged_trajectories = []
merged_indices = set()
# Loop to merge trajectories within the shard itself
for i, t1 in enumerate(trajectories):
if i in merged_indices:
continue
found_merge = True
while found_merge:
end = t1["start"] + t1["len"]
best_iou = iou_threshold
best_j = None
for j, t2 in enumerate(trajectories[i + 1:], start=i + 1):
if t2["start"] != end or j in merged_indices or end in scene_cuts:
continue
iou_value = iou(t1["bbs"][-1], t2["bbs"][0])
if iou_value > best_iou:
best_iou = iou_value
best_j = j
found_merge = (best_j is not None)
if found_merge:
t1["bbs"] = t1["bbs"] + trajectories[best_j]["bbs"]
t1["detected"] = t1["detected"] + trajectories[best_j]["detected"]
t1["len"] = len(t1["bbs"])
merged_indices.add(best_j)
merged_trajectories.append(t1)
# Return final trajectories + number of merges made
n_merges = len(trajectories) - len(merged_trajectories)
return merged_trajectories, n_merges
def merge(
data_dir: str, movie_id: int, iou_threshold: float, overlap: int, min_face_size: int
):
"""Merge trajectories that cross file boundaries in terms of frames.
"""
trajectories_dir = os.path.join(data_dir, "trajectories")
scene_changes_dir = os.path.join(data_dir, "scene_changes")
features_dir = os.path.join(data_dir, "features")
images_dir = os.path.join(data_dir, "images")
assert os.path.exists(trajectories_dir), f"Didn't find: {trajectories_dir}"
assert os.path.exists(scene_changes_dir), f"Didn't find: {scene_changes_dir}"
assert os.path.exists(features_dir), f"Didn't find: {features_dir}"
assert os.path.exists(images_dir), f"Didn't find: {images_dir}"
# Check what trajectory files we have (one for each shard)
_, _, filenames = next(os.walk(trajectories_dir))
traj_files = []
for file in filenames:
# file is like: trajectories_987654_1000-2000.jsonl
name, ext = os.path.splitext(file)
parts = name.split("_")
if parts[0] != "trajectories":
continue
start, end = [int(f) for f in parts[2].split("-")]
traj_files.append({"s": start, "e": end, "path": os.path.join(trajectories_dir, file)})
traj_files = sorted(traj_files, key=lambda d: d["s"])
# Check that we have corresponding scene cut files (one for each shard)
scene_cuts = set()
for t_file in traj_files:
start, end = t_file["s"], t_file["e"]
# Scene change files have the same format as trajectory files
filename = f"scene_changes_{movie_id}_{start}-{end}.json"
scene_change_file = os.path.join(scene_changes_dir, filename)
if os.path.exists(scene_change_file):
with open(scene_change_file, "r") as f:
shard_scene_cuts = json.load(f)["frame_indices"]
scene_cuts |= set(shard_scene_cuts)
# Merge feature files into one
_, _, filenames = next(os.walk(features_dir))
feature_files = []
for file in filenames:
# file is like: features_987654_1000-2000.jsonl
name, ext = os.path.splitext(file)
parts = name.split("_")
if parts[0] != "features":
continue
start, _ = [int(f) for f in parts[2].split("-")]
feature_files.append({"s": start, "path": os.path.join(features_dir, file)})
feature_files = sorted(feature_files, key=lambda f: f["s"])
with open(os.path.join(data_dir, "features.jsonl"), "w") as write_file:
for file_obj in feature_files:
with open(file_obj["path"], "r") as read_file:
write_file.write(read_file.read())
print(f"Processing {len(traj_files)} trajectory files.")
print(f"Read a total {len(scene_cuts)} scene changes.")
# Load image lookup map that allows to check if a frame + bbs combo has an image
image_map = load_images_map(images_dir)
out_file = open(os.path.join(data_dir, "trajectories.jsonl"), "w")
trajectories = []
n_read = 0
n_saved = 0
n_merges = 0
n_deleted = 0
# Loop to merge trajectories across different shards
for file in traj_files:
new_trajectories, n_shard_merges = load_trajectory(file["path"], scene_cuts, iou_threshold)
n_read += len(new_trajectories)
n_merges += n_shard_merges
mergables = [t for t in new_trajectories if t["start"] < file["s"] + overlap]
others = [t for t in new_trajectories if t["start"] >= file["s"] + overlap]
expired = [t for t in trajectories if (t["start"] + t["len"]) < file["s"]]
trajectories = [t for t in trajectories if (t["start"] + t["len"]) >= file["s"]]
# Save trajectories that can't be merged anymore, to disk
ns, nr = save_trajectories(out_file, expired, image_map, min_face_size, n_saved, movie_id)
n_saved += ns
n_deleted += nr
# Check if some of the new trajectories can merge into an old one
for t1 in mergables:
best_iou = iou_threshold
best_t = None
# We'll only attempt a merge if t1["start"] isn't at a scene cut
if t1["start"] not in scene_cuts:
for t2 in trajectories:
if t2["start"] >= t1["start"] or (t2["start"] + t2["len"]) <= t1["start"]:
continue
t2_bbs_i = t1["start"] - t2["start"]
assert t2_bbs_i >= 0, "Invalid index?"
iou_value = iou(t2["bbs"][t2_bbs_i], t1["bbs"][0])
if iou_value > best_iou:
best_iou = iou_value
best_t = t2
# A merge was found!
if best_t is not None:
n_merges += 1
assumed_len = t1["start"] + t1["len"] - best_t["start"]
best_t["bbs"] = best_t["bbs"][:(t1["start"] - best_t["start"])] + t1["bbs"]
best_t["detected"] = best_t["detected"][:(t1["start"] - best_t["start"])] + t1["detected"]
best_t["len"] = len(best_t["bbs"])
assert best_t["len"] == assumed_len, "Len???"
else:
others.append(t1)
trajectories += others
# Save remaining
ns, nr = save_trajectories(out_file, trajectories, image_map, min_face_size, n_saved, movie_id)
n_saved += ns
n_deleted += nr
out_file.close()
# Save merged scene cuts
scene_cuts_file = os.path.join(data_dir, "scene_changes.json")
save_scene_changes(scene_cuts_file, scene_cuts, movie_id)
print(f"Total merges: {n_merges}.")
print(f"Total removed if they had no images or had too small faces: {n_deleted}.")
print(f"Done! Read {n_read} trajectories and saved {n_saved}.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(allow_abbrev=True)
parser.add_argument("--iou-threshold", type=float, default=0.5,
help="IOU threshold when merging bounding boxes.")
parser.add_argument("--overlap", type=int, default=5,
help="""Overlap to consider when merging across shards. Should
match the max-trajectory-age that was used when extracting.""")
parser.add_argument("--min-face-size", type=int, default=50,
help="""If bigger than zero, will filter trajectories that
have faces where `min(w, h) < min-face-size`.""")
parser.add_argument("--path", type=str, default=".")
args = parser.parse_args()
data_dirs = glob.glob(args.path)
for data_dir in data_dirs:
# data_dir will be a movie directory like ./data/123456-data
data_dir = data_dir.rstrip("/")
print(f"Merging shards in: {data_dir}")
movie_id: int = int(os.path.basename(data_dir).split("-")[0])
merge(data_dir, movie_id, args.iou_threshold, args.overlap, args.min_face_size)
print()
| StarcoderdataPython |
93582 | <filename>tests/test_zero.py
import os
import sys
import json
import torch
from fmoe.layers import _fmoe_general_global_forward
from fmoe import FMoETransformerMLP
from test_ddp import _run_distributed
class ConstantGate(torch.nn.Module):
def __init__(self, d_model, num_expert, world_size, top_k=1):
super().__init__()
self.top_k = top_k
def forward(self, inp):
idx = torch.zeros((inp.shape[0], self.top_k), dtype=torch.int64,
device=inp.device)
score = torch.ones((inp.shape[0], 1, self.top_k), device=inp.device) / 2
return idx, score
def test_zero_fwd(num_expert=2, batch_size=4, d_hidden=8, world_size=1):
_run_distributed('_test_zero_fwd',
1,
{
'num_expert': num_expert,
'batch_size': batch_size,
'd_hidden': d_hidden
},
script=__file__
)
def _test_zero_fwd(num_expert=2, batch_size=4, d_hidden=8, world_size=1):
inp = torch.rand(batch_size, d_hidden).cuda()
gate = torch.zeros(batch_size, dtype=torch.int64).cuda()
x = _fmoe_general_global_forward(inp, gate, lambda x, y: x, num_expert,
world_size)
def test_zero_transformer(num_expert=2, batch_size=4, d_hidden=8, world_size=1):
_run_distributed('_test_zero_transformer',
1,
{
'num_expert': num_expert,
'batch_size': batch_size,
'd_hidden': d_hidden
},
script=__file__
)
def _test_zero_transformer(num_expert=2, batch_size=4, d_hidden=8, world_size=1):
inp = torch.rand(batch_size, d_hidden).cuda()
mask = torch.zeros(inp.shape[0], dtype=torch.long)
mask[1] = 1
mask_dict = {
1: torch.zeros(d_hidden).cuda()
}
model = FMoETransformerMLP(num_expert, d_hidden, d_hidden * 4, world_size,
gate=ConstantGate, mask=mask, mask_dict=mask_dict).cuda()
oup = model(inp)
if __name__ == '__main__':
if len(sys.argv) >= 3:
args = json.loads(sys.argv[2])
os.environ["RANK"] = os.environ.get("OMPI_COMM_WORLD_RANK", "0")
os.environ["WORLD_SIZE"] = os.environ.get("OMPI_COMM_WORLD_SIZE", "1")
os.environ["CUDA_VISIBLE_DEVICES"] = os.environ["RANK"]
torch.distributed.init_process_group(backend="nccl")
args['world_size'] = torch.distributed.get_world_size()
locals()[sys.argv[1]](**args)
else:
# test_zero_fwd(world_size=torch.distributed.get_world_size())
test_zero_transformer(num_expert=16, batch_size=4096, d_hidden=1024,
world_size=1)
print('done')
| StarcoderdataPython |
3377014 | <reponame>szperajacyzolw/streamlit_laundering
from boruta import BorutaPy
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from sklearn.naive_bayes import BernoulliNB, MultinomialNB
from sklearn.preprocessing import FunctionTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from bs4 import BeautifulSoup
from joblib import load
import nltk
import enchant # spellchecker
import requests
import streamlit as st
import os
import re
import numpy as np
import pandas as pd
with st.spinner('Downloading dependencies...'):
nltk.download('stopwords')
nltk.download('point')
nltk.download('averaged_perceptron_tagger')
from nltk.corpus import stopwords
from nltk import pos_tag
from nltk.tokenize import word_tokenize
from nltk.corpus.reader.wordnet import NOUN, ADJ, VERB, ADV
from nltk.stem.wordnet import WordNetLemmatizer
this_dir = os.getcwd()
save_dir = os.path.join(this_dir, 'saves')
lemmatizer = WordNetLemmatizer()
english_spellcheck = enchant.Dict('en_US')
stopwords = stopwords.words('english')
def get_lemma(word: str) -> str:
'returns lemmatized word based on nltk.'
tag = pos_tag([word])[0][1][0].upper()
tags = {'J': ADJ, 'N': NOUN, 'V': VERB, 'R': ADV}
return lemmatizer.lemmatize(word, tags.get(tag, NOUN))
def text_cleaner(text: list) -> str:
'''
takes list of strings(an article), produces string
without short expressions, numbers, stop words and punctuation,
all in lowercase
'''
text = text.copy()
# remove punctuation, shorts, broken words and digits
# short words are often without particular meaning or are residuals of longer, missing words
punct_dig = re.compile(r'[^a-zA-Z\s]')
shorts = re.compile(r'\b\w{1,3}\b')
# broken words with numbers and symbols inclusions, eg. bal00n, m0ney, ca$h
broken = re.compile(r'\b[a-zA-z]+[^\sa-zA-Z]+[a-zA-Z]+\b')
text_ = []
for i in range(len(text)):
br = re.sub(broken, '', text[i])
pd = re.sub(punct_dig, ' ', br)
text_.append(re.sub(shorts, '', pd))
text = text_
# split elements and lemmatize
text = [get_lemma(word) for t in text for word in word_tokenize(t)]
# aggressive lowercase
text = list(map(str.casefold, text))
# remove stop words
text = [elem for elem in text if not elem in stopwords]
# remove foreign words
text = [elem for elem in text if english_spellcheck.check(elem)]
return ' '.join(text)
def text_scraper(http: str) -> (list, list):
clean_articles = []
web_text = requests.get(http, timeout=10).text
soup = BeautifulSoup(web_text, 'html.parser').stripped_strings
raw = list(soup)
cleaned = text_cleaner(raw)
clean_articles.append(cleaned)
return clean_articles, raw
def _toarray(x: 'sparse array') -> np.array:
'''
helper function for pipeline array transformation
'''
return x.toarray()
rfc_boruta = RandomForestClassifier(n_jobs=4, class_weight='balanced', max_depth=5)
to_array = FunctionTransformer(_toarray)
boruta = BorutaPy(rfc_boruta, perc=100, verbose=1)
@st.cache(allow_output_mutation=True)
def load_models():
model_lg = load(os.path.join(save_dir, 'brenoulli_bayes_lg.gz'))
model_cs = load(os.path.join(save_dir, 'brenoulli_bayes_cs.gz'))
return model_lg, model_cs
@st.cache(allow_output_mutation=True)
def load_dataframes():
df_cs = pd.read_csv(os.path.join(save_dir, 'charges_vs_sentence_features_prob.csv'),
index_col=0)
df_lg = pd.read_csv(os.path.join(save_dir, 'generic_vs_laundering_features_prob.csv'),
index_col=0)
return df_lg, df_cs
def news_classifier(http: str, model_stage1: object, model_stage2: object):
'''
print out prediction of given http adress
http - full http://www... string
model_stage1&2 - GridSearchCV object of laundering vs generic and charges vs sentence models
'''
text, _ = text_scraper(http)
pred_stage1 = model_stage1.predict(text)[0]
if pred_stage1:
result = ['charges', 'sentence']
pred_stage2 = model_stage2.predict(text)[0]
return f'Provided website mentions money laundering {result[pred_stage2]}'
else:
return 'Provided website does not mention money laundering'
with st.spinner('Loading content...'):
df_lg, df_cs = load_dataframes()
model_lg, model_cs = load_models()
st.title('Check-for-laundering-content app')
with st.form(key='input_http'):
http_input = st.text_input(
label=r'Enter full web link here. Proper format: http://www.site...')
submit_button = st.form_submit_button(label='Submit')
if submit_button:
st.markdown(f'**{news_classifier(http_input, model_lg, model_cs)}**')
st.write("Below you can explore model's fetures probabilities given a class")
st.write('Plots are limited to first 50 features')
st.write('In the upper right corner of tables and charts you can find zoom button')
col1, col2 = st.beta_columns(2)
with col1:
st.header('Model: generic news vs laundering')
st.dataframe(df_lg)
fig, ax = plt.subplots(tight_layout=True, figsize=(20, 20))
ypos = np.arange(50)
ax.barh(ypos, df_lg.iloc[:50, 0], align='edge', color='g', height=0.4)
ax.barh(ypos, df_lg.iloc[:50, 1], align='center', color='r', height=0.4)
ax.set_yticks(ypos)
ax.set_yticklabels(df_lg.index[:50])
ax.invert_yaxis()
ax.set_xlabel('Probability')
red_patch = mpatches.Patch(color='r', label='Laundering')
green_patch = mpatches.Patch(color='g', label='Generic')
plt.legend(handles=[red_patch, green_patch])
st.pyplot(fig)
with col2:
st.header('Model: charges vs sentence')
st.dataframe(df_cs)
fig, ax = plt.subplots(tight_layout=True, figsize=(20, 20))
ypos = np.arange(50)
ax.barh(ypos, df_cs.iloc[:50, 0], align='edge', color='g', height=0.4)
ax.barh(ypos, df_cs.iloc[:50, 1], align='center', color='r', height=0.4)
ax.set_yticks(ypos)
ax.set_yticklabels(df_cs.index[:50])
ax.invert_yaxis()
ax.set_xlabel('Probability')
red_patch = mpatches.Patch(color='r', label='Sentence')
green_patch = mpatches.Patch(color='g', label='Charges')
plt.legend(handles=[red_patch, green_patch])
st.pyplot(fig)
| StarcoderdataPython |
1769960 | from gym_meme.envs.meme_env import MemeEnv
import gym_meme.envs
| StarcoderdataPython |
1609710 | <reponame>whatisjasongoldstein/scruffy-video
import mock
import requests
import helpers
from .helpers import (get_video_type, get_video_type_and_id,
youtube_id, vimeo_id, get_embed_src, call_api, get_image_url)
TEST_VIMEO_URL = "https://vimeo.com/22733150"
TEST_YOUTUBE_URL_1 = "http://www.youtube.com/watch?v=SicQi0H925g"
TEST_YOUTUBE_URL_2 = "http://www.youtube.com/v/SicQi0H925g"
TEST_YOUTUBE_URL_3 = "http://www.youtu.be/SicQi0H925g"
def test_get_video_type():
""" YouTube and Vimeo links should return their respective types. """
for link in [TEST_YOUTUBE_URL_1, TEST_YOUTUBE_URL_2, TEST_YOUTUBE_URL_3]:
assert get_video_type(link) == 'youtube'
assert get_video_type(TEST_VIMEO_URL) == 'vimeo'
assert get_video_type("http://foobar.com/whatever") == None
def test_get_video_type_and_id():
assert get_video_type_and_id(TEST_VIMEO_URL) == ('vimeo', '22733150')
def test_youtube_id():
""" Should return the video's ID regardless of the link's format. """
for link in [TEST_YOUTUBE_URL_1, TEST_YOUTUBE_URL_2, TEST_YOUTUBE_URL_3]:
assert youtube_id(link) == 'SicQi0H925g'
def test_vimeo_id():
""" Should return the video's id """
assert vimeo_id(TEST_VIMEO_URL) == '22733150'
def test_get_embed_src():
""" Should return a url we can stick in an iframe src to create a player. """
assert get_embed_src(TEST_VIMEO_URL) == "//player.vimeo.com/video/22733150"
assert get_embed_src(TEST_YOUTUBE_URL_1) == "//www.youtube.com/embed/SicQi0H925g"
@mock.patch.object(requests, 'get')
def test_call_api(mock_get):
""" Should call the right API and return parsed json. """
resp = mock.MagicMock()
resp.raise_for_status.return_value = None
resp.content = u"""{"thats":"a wrap"}"""
mock_get.return_value = resp
content = call_api(TEST_VIMEO_URL)
assert mock_get.call_args[0][0] == 'http://vimeo.com/api/v2/video/22733150.json'
assert content == {'thats': 'a wrap'}
@mock.patch.object(helpers, 'call_api')
def test_get_image_url_for_vimeo(mock_api):
""" Should return the url of the main thumbnail found in the api call. """
mock_api.return_value = [{
'thumbnail_large': 'http://b.vimeocdn.com/ts/147/229/147229620_640.jpg',
}]
url = get_image_url(TEST_VIMEO_URL)
assert url == "http://b.vimeocdn.com/ts/147/229/147229620_640.jpg"
@mock.patch.object(helpers, 'call_api')
def test_get_image_url_for_youtube(mock_api):
""" Should return the url of the main thumbnail found in the api call. """
mock_api.return_value = {'encoding': 'UTF-8',
'entry': {
'media$group': {
'media$thumbnail': [
{'height': 360,
'time': '00:02:28.500',
'url': 'http://i1.ytimg.com/vi/SicQi0H925g/0.jpg',
'width': 480},
{'height': 90,
'time': '00:01:14.250',
'url': 'http://i1.ytimg.com/vi/SicQi0H925g/1.jpg',
'width': 120}
],
},
},}
url = get_image_url(TEST_YOUTUBE_URL_3)
assert url == "http://i1.ytimg.com/vi/SicQi0H925g/0.jpg"
| StarcoderdataPython |
3359685 | import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
num_train = X.shape[0]
num_classes = W.shape[1]
num_dimensions = X.shape[1]
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
for i in range(num_train):
score = X[i].dot(W)
#the stabilty trick http://cs231n.github.io/linear-classify/
score = score - np.max(score)
loss = loss - score[y[i]] + np.log(np.exp(score).sum())
#for the gradient of softmax http://cs231n.github.io/neural-networks-case-study/#grad
dscores = np.exp(score)/np.exp(score).sum()
dscores[y[i]] -= 1 #that is it
#now make it again (1,C)
dscores = dscores.reshape(1,num_classes)
#and now
dW += np.dot(X[i].reshape(num_dimensions,1),dscores)
#now the regularization
loss = loss + 0.5 * reg * np.sum(W * W)
loss = loss/num_train
dW = dW/num_train
dW += reg*W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
num_train = X.shape[0]
num_classes = W.shape[1]
num_dimensions = X.shape[1]
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
#copy paste from http://cs231n.github.io/neural-networks-case-study/#loss
score = X.dot(W) # (N,C)
score = score - np.amax(score,axis = 1,keepdims = True)
score = np.exp(score)
probs = score/np.sum(score,axis = 1, keepdims = True)
loss = -1*np.log(probs[np.arange(num_train),y]).sum()/num_train
loss = loss + 0.5 * reg * np.sum(W * W)
#http://cs231n.github.io/neural-networks-case-study/#grad
dscores = probs #(N,C)
dscores[range(num_train),y] -= 1
dscores = dscores / num_train
dW = np.dot(X.T,dscores)
dW += reg * W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
| StarcoderdataPython |
1601591 | <filename>wcoa/migrations/0005_remove_connectpage_date.py
# Generated by Django 2.2.3 on 2019-07-25 19:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wcoa', '0004_merge_20190725_1749'),
]
operations = [
migrations.RemoveField(
model_name='connectpage',
name='date',
),
]
| StarcoderdataPython |
56361 | words = [word.upper() for word in open('gettysburg.txt').read().split()]
theDictionary = {}
for word in words:
theDictionary[word] = theDictionary.get(word,0) + 1
print(theDictionary)
| StarcoderdataPython |
7156 | from models.Model import Player, Group, Session, engine
| StarcoderdataPython |
106732 | <filename>Source/Apps/StatusClock.py
import logging
import time
import Geometry.Point as PT
import Utilities.Recurrer as AR
from PIL import ImageDraw, ImageFont
import Apps.BaseApp as BA
fontfamily = 'DejaVuSansMono.ttf'
boldfontfamily = 'DejaVuSansMono-Bold.ttf'
class StatusClockApp(BA.BaseApp):
def __init__(self, apphost, rect):
super(StatusClockApp,self).__init__(apphost, rect)
self._ar = AR.MinuteRecurrer(1,self.requestUpdate)
self._bfont = ImageFont.truetype(boldfontfamily, 22)
self.requestUpdate()
def requestUpdate(self):
self.apphost.queue(self)
def update(self, image):
logging.debug("StatusClockApp: updating")
texttoshow = time.strftime('%H:%M')
logging.debug(f"StatusClockApp: {texttoshow}")
time_draw = ImageDraw.Draw(image)
# fill background
time_draw.rectangle(self._rect.coords(), fill = 1, outline=255)
clockrect = self._rect.shrink(PT.Point(0,0), PT.Point(1,0))
time_draw.rounded_rectangle(clockrect.coords(), fill = 1, radius = 4, outline=0, width=2)
time_draw.text(clockrect.offset(PT.Point(0,-2)).coords(),texttoshow,font=self._bfont)
| StarcoderdataPython |
183770 | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
from xgboost import XGBRegressor
from lightgbm import LGBMRegressor
from statsmodels.distributions import ECDF, monotone_fn_inverter
from joblib import dump
# model = XGBRegressor(random_state=2021)
model = XGBRegressor(random_state=2021, n_estimators=900, max_depth=9, learning_rate=0.1, subsample=0.4)
# model = LGBMRegressor(random_state=2021)
# model = LGBMRegressor(random_state=2021, n_estimators=900, max_depth=9, learning_rate=0.1, subsample=0.4)
grid_search = False
save_model = True
param_grid = {
'n_estimators': [300, 500, 700, 900],
'learning_rate': [0.05, 0.1, 0.2],
'max_depth': [5, 7, 9],
'subsample': [0.4, 0.5, 1.0]}
def load_data(data):
X = pd.read_csv(data)
y = X.pop("y")
return X, y
def calculate_rmse(actual, predicted):
return np.sqrt(mean_squared_error(actual, predicted))
def calculate_percent_accuracy(actual, predicted):
return sum(abs(actual - predicted) <= 3.0) / len(actual)
def generate_scalers(model, X_train, y_train):
predictions_train = model.predict(X_train)
actual_ecdf = ECDF(y_train)
actual_ecdf_inv = monotone_fn_inverter(actual_ecdf, y_train)
actual_ecdf_inv.bounds_error = False
prediction_ecdf = ECDF(predictions_train)
return prediction_ecdf, actual_ecdf_inv
def generate_finalized_model(model, X_train, y_train):
model.fit(X_train, y_train)
prediction_ecdf, actual_ecdf_inv = generate_scalers(model, X_train, y_train)
return {"model": model, "ecdf": prediction_ecdf, "inverse_ecdf": actual_ecdf_inv}
def generate_scaled_predictions(finalized_model, data):
predictions = finalized_model["model"].predict(data)
predictions = finalized_model["ecdf"](predictions)
predictions = finalized_model["inverse_ecdf"](predictions)
min_score = finalized_model["inverse_ecdf"].y.min()
return np.nan_to_num(predictions, nan=min_score)
def print_summary(actual, predictions, identifier):
print("model " + identifier + " rmse: %.3f" % calculate_rmse(actual, predictions))
print("model " + identifier + " acc: %.3f" % calculate_percent_accuracy(actual, predictions))
def save_csv(data: np.array, filename: str) -> None:
np.savetxt(filename, data, delimiter=",")
print(f"Saved data to {filename}")
return
X,y = load_data("./input_data.csv")
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# Create sklearn Pipelines for numerical features
numeric_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='constant', fill_value=999999)),
('scaler', StandardScaler())])
# Define numerical features by dtype, in this dataset this is all columns
numeric_features = X_train.select_dtypes(include=['int64', 'float64']).columns
# Create sklearn ColumnTransformer
preprocessor = ColumnTransformer(
transformers=[('num', numeric_transformer, numeric_features)])
# Create model pipeline
model = Pipeline(steps=[('preprocessor', preprocessor),
('regressor', model)])
if grid_search:
model = GridSearchCV(model, param_grid, n_jobs=4)
finalized_model = generate_finalized_model(model, X_train, y_train)
if grid_search:
print(model.best_params_)
predictions_train = generate_scaled_predictions(finalized_model, X_train)
predictions_test = generate_scaled_predictions(finalized_model, X_test)
print_summary(y_train, predictions_train, "train")
print_summary(y_test, predictions_test, "test")
if save_model:
finalized_model = generate_finalized_model(model, X, y)
predictions_final = generate_scaled_predictions(finalized_model, X)
print_summary(y, predictions_final, "final")
save_csv(predictions_final, "final_moodel_predictions.csv")
dump(finalized_model, "saved_model.joblib", compress=True)
| StarcoderdataPython |
3253285 | <reponame>FAIRDataPipeline/FAIR-CLI<gh_stars>0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Versioning
==========
Methods for handling semantic versioning and parsing version formats
Contents
========
Functions
---------
parse_incrementer - parse version increment format
"""
__date__ = "2021-08-05"
import re
import typing
import semver
import fair.exceptions as fdp_exc
BUMP_FUNCS = {
"LATEST": None,
"MINOR": "bump_minor",
"MAJOR": "bump_major",
"PATCH": "bump_patch",
"BUILD": "bump_build",
"PRERELEASE": "bump_prerelease",
}
DEFAULT_WRITE_VERSION = "PATCH"
DEFAULT_READ_VERSION = "LATEST"
def parse_incrementer(incrementer: str) -> str:
"""Convert an incrementer string in a config to the relevant bump function
Parameters
----------
incrementer : str
config.yaml variable to describe how version increases are handled
Returns
-------
str
relevant member method of VersionInfo for 'bumping' the semantic version
"""
# Sanity check to confirm all methods are still present in semver module
for func in BUMP_FUNCS.values():
if func and func not in dir(semver.VersionInfo):
raise fdp_exc.InternalError(
f"Unrecognised 'semver.VersionInfo' method '{func}'"
)
for component in BUMP_FUNCS:
try:
if re.findall(r"\$\{\{\s*" + component + r"\s*\}\}", incrementer):
return BUMP_FUNCS[component]
except TypeError:
raise fdp_exc.InternalError(
f"Failed to parse incrementer '{incrementer}' expected string"
)
raise fdp_exc.UserConfigError(
f"Unrecognised version incrementer variable '{incrementer}'"
)
def undo_incrementer(incrementer: str) -> str:
"""Convert an incrementer string to just return the latest value
Parameters
----------
incrementer : str
config.yaml variable to describe how version increases are handled for register
Returns
-------
str
correct value for version string for read
"""
for component in BUMP_FUNCS:
if re.findall(r"\$\{\{\s*" + component + r"\s*\}\}", incrementer):
return re.sub(
r"\$\{\{\s*" + component + r"\s*\}\}",
"${{ LATEST }}",
incrementer,
)
return incrementer
def get_latest_version(results_list: typing.List = None) -> semver.VersionInfo:
if not results_list:
return semver.VersionInfo.parse("0.0.0")
_versions = [
semver.VersionInfo.parse(i["version"])
for i in results_list
if "version" in i
]
if not _versions:
return semver.VersionInfo.parse("0.0.0")
return max(_versions)
def get_correct_version(
version: str, results_list: typing.List = None, free_write: bool = True
) -> semver.VersionInfo:
_zero = semver.VersionInfo.parse("0.0.0")
if results_list:
_versions = [
semver.VersionInfo.parse(i["version"])
for i in results_list
if "version" in i
]
else:
_versions = []
try:
_bump_func = parse_incrementer(version)
if free_write:
_versions.append(_zero)
if not _versions:
raise fdp_exc.InternalError(
f"Version parsing failed for version={version}, free_write={free_write}"
)
_max_ver = max(_versions)
_new_version = (
getattr(_max_ver, _bump_func)() if _bump_func else _max_ver
)
except fdp_exc.UserConfigError: # Not a command, try an exact version
_new_version = semver.VersionInfo.parse(version)
if _new_version in _versions and free_write:
raise fdp_exc.UserConfigError(
f"Trying to create existing version: {_new_version}"
)
elif _new_version not in _versions and not free_write:
raise fdp_exc.UserConfigError(
f"Trying to read non-existing version: {_new_version}"
)
elif _new_version == _zero:
raise fdp_exc.UserConfigError(f"Trying to work with version {_zero}")
return _new_version
def default_bump(version: semver.VersionInfo) -> semver.VersionInfo:
"""Perform default version bump
For FAIR-CLI the default version increment is patch
Parameters
----------
version: semver.VersionInfo
Returns
-------
new version
"""
return getattr(version, BUMP_FUNCS[DEFAULT_WRITE_VERSION])()
| StarcoderdataPython |
3218796 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import tempfile
import shutil
# __del__形式
# class TempDir:
# def __index__(self):
# self.name = tempfile.mkdtemp()
#
# def remove(self):
# if self.name is not None:
# shutil.rmtree(self.name)
# self.name = None
#
# @property
# def removed(self):
# return self.name is None
#
# def __del__(self):
# self.remove()
# finalize形式
import weakref
class TempDir:
def __index__(self):
self.name = tempfile.mkdtemp()
self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)
def remove(self):
self._finalizer()
@property
def removed(self):
return not self._finalizer.alive
| StarcoderdataPython |
1669882 | import numpy as np
import pandas as pd
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt
import statsmodels.tsa.stattools as ts
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller
import ffn
import warnings
warnings.filterwarnings('ignore')
def ind_marker(stock):
index_marker = 0
data = pd.read_csv('/.../ingestable_csvs/daily/{}.csv'.format(stock))
prices = data.close
for i in range(len(prices)):
if pd.isna(prices[i]) == False:
index_marker = i
break
return index_marker
def kt(spread):
C, D = 0 , 0
for i in range(len(spread)):
base = spread.iloc[i]
for a in range(i+1, len(spread)):
if base <= spread.iloc[a]:
C += 1
else:
D += 1
kt = (C-D)/(C+D)
return round(kt,2)
def half_life(spread): #function to calculate the halflfie of a mean reverting time series
spread_lag = spread.shift(1)
spread_lag.iloc[0] = spread_lag.iloc[1]
spread_ret = spread - spread_lag
spread_ret.iloc[0] = spread_ret.iloc[1]
spread_lag2 = sm.add_constant(spread_lag)
model = sm.OLS(spread_ret,spread_lag2)
res = model.fit()
halflife = int(round(-np.log(2) / res.params[1],0))
if halflife <= 0:
halflife = 1
return halflife
#manual backtest of pairs trading using Cointegrated Kendall's Tau (CKT) test
def kt_backtest(sym1, sym2):
stock1 = pd.read_csv('/.../ingestable_csvs/daily/{}.csv'.format(sym1))
stock2 = pd.read_csv('/.../ingestable_csvs/daily/{}.csv'.format(sym2))
s1 = stock1.close
s2 = stock2.close
yr_ret = []
yr_sharpe = []
#define the time_line
max_start = max(ind_marker(sym1), ind_marker(sym2))
time_line = [*range(max_start+240,len(s1), 240)]
#iterating each year and running the backtest
main_df = pd.DataFrame(columns = ['x', 'y', 'spread', 'hr', 'zScore', 'long entry', 'long exit',
'num units long', 'short entry', 'short exit', 'num units short',
'numUnits'])
count = 0
for i in time_line:
if i == time_line[-1]:
start = i
end = len(s1) - 1
else:
start = i
end = i+240
x, y = s1[start-240:end], s2[start-240:end] #calculates the hr real time using the past month series
ax, ay = s1[start:end], s2[start:end] #the actual df to use for the trading and return calc
df1 = pd.DataFrame({'x':ax, 'y':ay})
df1 = df1.reset_index(drop = True)
hr = []
test_spread = []
for d in range(start-220,end):
model = sm.OLS(y.loc[d-20:d], x.loc[d-20:d]).fit()
beta = model.params.tolist()[0]
hr.append(beta)
spread = y.loc[d] - (x.loc[d]*beta)
test_spread.append(spread)
final_spread = pd.Series(test_spread[220:]).reset_index(drop=True) #used for adf, avg, and zscores
test_spread = pd.Series(test_spread)
test_spread.index = range(start-220, end)
df1['spread'] = final_spread
hf = []
for i in range(start,end):
halflife = half_life(test_spread.loc[i-60:i]) #using past 6mon spread to calc. halflife
hf.append(halflife)
hf = pd.Series(hf)
hf.index = range(start, end)
#hf = half_life(tx*hr + ty)
zsc = []
for i in range(start, end):
m = test_spread.loc[:i].rolling(window = int(hf.loc[i])).mean()
s = test_spread.loc[:i].rolling(window = int(hf.loc[i])).std()
z = (test_spread.loc[:i] - m)/s
val = z.iloc[-1]
zsc.append(val)
zScore = pd.Series(zsc).reset_index(drop=True)
df1['hr'] = pd.Series(hr)
df1['zScore'] = zScore
#####################################
entryZscore = 1.5
exitZscore = 0
#stopZscore = 2.5
# Set up num units long
df1['long entry'] = ((df1.zScore < - entryZscore) & ( df1.zScore.shift(1) > - entryZscore))
df1['long exit'] = ((df1.zScore > - exitZscore) & (df1.zScore.shift(1) < - exitZscore))
df1['num units long'] = np.nan
df1.loc[df1['long entry'],'num units long'] = 1
df1.loc[df1['long exit'],'num units long'] = 0
df1['num units long'][0] = 0
df1['num units long'] = df1['num units long'].fillna(method='pad')
# Set up num units short
df1['short entry'] = ((df1.zScore > entryZscore) & ( df1.zScore.shift(1) < entryZscore))
df1['short exit'] = ((df1.zScore < exitZscore) & (df1.zScore.shift(1) > exitZscore))
df1.loc[df1['short entry'],'num units short'] = -1
df1.loc[df1['short exit'],'num units short'] = 0
df1['num units short'][0] = 0
df1['num units short'] = df1['num units short'].fillna(method='pad')
df1['numUnits'] = df1['num units long'] + df1['num units short']
###STOP LOSS for extreme movments in spread
#### OPTION 1: CADF check:- using 1mon mov avg of 2mon adf pval of spread
adf = []
for i in range(start-20,end):
val = ts.adfuller(test_spread.loc[i-40:i])[1]
adf.append(val)
adf_m = pd.Series(adf[20:])
avg = pd.Series(adf).rolling(window = 20).mean()# create avg
avg_m = avg.iloc[19:].reset_index(drop=True)
df1['adf_pval'] = adf_m
df1['avg'] = avg_m
#df1['cadf_test'] = (avg_m >= 0.5) #remove the hash to use this option
#df1.loc[df1['cadf_test'], 'numUnits'] = 0 #remove the hash to use this option
###STOP LOSS for extreme movments in spread
#### OPTION 2: Cointegrated Kendall's Tau test:- using Kendal's Tau to measure trending in spread series
kt_test = []
for i in range(start,end):
val = kt(test_spread.loc[i-60:i])
kt_test.append(val)
kt_test = pd.Series(kt_test)
df1['kt'] = kt_test
df1['kt_stop'] = ((kt_test <= -0.5) | (kt_test >= 0.3))
df1.loc[df1['kt_stop'], 'numUnits'] = 0
###################
df1['spread pct ch'] = (df1['spread'] - df1['spread'].shift(1)) / ((df1['x'] * abs(df1['hr'])) + df1['y'])
df1['port rets'] = df1['spread pct ch'] * df1['numUnits'].shift(1)
df1['cum rets'] = df1['port rets'].cumsum()
df1['cum rets'] = df1['cum rets'] + 1
try:
sharpe = ((df1['port rets'].mean() / df1['port rets'].std()) * sqrt(252))
except ZeroDivisionError:
sharpe = 0.0
#add the ret and hr to a list
yr_ret.append(df1['cum rets'].iloc[-1])
yr_sharpe.append(sharpe)
main_df = pd.concat([main_df, df1])
count += 1
print('Year {} done'.format(count))
main_df = main_df.reset_index(drop=True)
port_val = (main_df['port rets'].dropna()+1).cumprod()
avg_daily_return = main_df['port rets'].mean()
avg_daily_std = main_df['port rets'].std()
annualised_sharpe = (avg_daily_return/avg_daily_std) * sqrt(252)
total_return = port_val.iloc[-1]-1
#refine port_val to fit the timeline
port_val = port_val.reset_index(drop=True)
shift_amt = len(s1)-len(port_val)
port_val = port_val.reindex(range(len(s1))).shift(shift_amt)
return main_df, port_val,total_return,annualised_sharpe, yr_sharpe, yr_ret
def pairs_trade(pairs, chosen_list = None):
#assign variables to output
if chosen_list == None:
chosen_list = [*range(len(pairs))]
else:
chosen_lsit = chosen_list
#to get size of data / index
s1 = pd.read_csv('/.../ingestable_csvs/daily/OMC.csv').close
port_val_df = pd.DataFrame(columns = [list(pairs.keys())[index] for index in chosen_list],
index = range(len(s1))) #create a port_df
#loop over a list of pairs
for i in chosen_list:
#assign stock names to variables
stock1 = pairs['Pair ' + str(i)][0]
stock2 = pairs['Pair ' + str(i)][1]
#run manual backtest and save output
res = kt_backtest(stock1, stock2)
portfolio_value = res[1]
port_val_df['Pair '+str(i)] = portfolio_value #add the portfolio value to the df
print('Done backtesting pair {}'.format(i))
total_val = []
for row in range(len(s1)):
num_null = port_val_df.loc[row].isnull().sum()
if num_null == len(chosen_list):
alloc = 0
total_val.append(np.nan)
else:
alloc = 1/(len(chosen_list) - num_null)
port_val = (port_val_df.loc[row] * alloc).sum()
total_val.append(port_val)
total_port_val = pd.Series(total_val)
avg_daily_return = ((total_port_val/total_port_val.shift(1))-1).mean()
avg_daily_std = ((total_port_val/total_port_val.shift(1))-1).std()
overall_sharpe = (avg_daily_return/avg_daily_std) * sqrt(252)
overall_vol = ((total_port_val/total_port_val.shift(1))-1).std() * sqrt(252) # annualised vol of strat
overall_return = total_port_val.iloc[-1]
result = [overall_return, overall_vol, overall_sharpe, total_port_val]
return result
def read_data():
pairs_data = pd.read_csv('/.../Mean Reversion Pairs.csv') #reading the main list of pairs
pairs_data = pairs_data[['S1 ticker', 'S2 ticker']]
pairs = {}
for i in range(len(pairs_data)): #creating a dictionary of pairs data
pairs['Pair ' + str(i)] = pairs_data.loc[i].tolist()
chosen_list = [0,1,2,4,5,6,13,15,21,23,25,26,29] #list of stock pairs with strong cointegration
return pairs, chosen_list
def read_results(result):
overall_return, overall_vol, overall_sharpe, total_port_val = result
plt.plot(total_port_val)
print(f'total return: {round(overall_return,3)}')
print(f'total vol: {round(overall_vol,3)}')
print(f'total sharpe: {round(overall_sharpe,3)}')
return
if __name__ == "__main__":
print("Reading Data...")
pairs, chosen_list = read_data()
print("Running Cointegrated Kendall Tau's Backtest...")
result = pairs_trade(pairs, chosen_list = chosen_list)
print("*********** Backtest Results ***********")
read_results(result)
| StarcoderdataPython |
4842746 | <gh_stars>0
"""
Round precomputed pixel instance embeddings and evaluate performance.
"""
import argparse
import numpy as np
def batch_eval(args):
"""
:param args:
"""
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("dataset_dir",
help='Path to directory containing instance ID PNG files. Files must match pattern'
'{imagename}_instanceIds.png, e.g. frankfurt_000001_080091_instanceIds.png')
parser.add_argument("log_dir",
help='Path to directory containing pixel embedding files. Files must match pattern'
'{imagename}.npy')
args = parser.parse_args()
batch_eval(args) | StarcoderdataPython |
148749 | <filename>tests/test_enasearch.py
#!/usr/bin/env python
from pprint import pprint
import enasearch
def cmp(la, lb):
"""Compare two lists"""
return all(s in lb for s in la) and all(s in la for s in lb)
def test_get_results():
"""Test get_results function"""
results = enasearch.get_results(verbose=False)
exp_results = [
'wgs_set', 'analysis_study', 'study', 'read_run', 'coding_release',
'coding_update', 'analysis', 'environmental', 'tsa_set',
'sequence_update', 'noncoding_update', 'noncoding_release', 'sample',
'read_experiment', 'read_study', 'assembly', 'taxon',
'sequence_release']
assert len(results) == 18 and cmp(results.keys(), exp_results)
def test_get_taxonomy_results():
"""Test get_taxonomy_results function"""
results = enasearch.get_taxonomy_results(verbose=False)
exp_taxo_results = [
'sequence_release', 'sequence_update', 'coding_release',
'coding_update', 'noncoding_release', 'noncoding_update',
'sample', 'study', 'analysis', 'analysis_study', 'read_run',
'read_experiment', 'read_study', 'read_trace']
assert cmp(results.keys(), exp_taxo_results)
def test_get_search_result_number():
"""Test get_search_result_number function"""
nb = enasearch.get_search_result_number(
free_text_search=False,
query="tax_eq(10090)",
result="assembly",
need_check_result=True)
assert nb == 19
nb = enasearch.get_search_result_number(
free_text_search=False,
query="tax_tree(7147) AND dataclass=STD",
result="coding_update",
need_check_result=True)
assert nb >= 17123
nb = enasearch.get_search_result_number(
free_text_search=True,
query="SMP1+homo",
result="sequence_release",
need_check_result=True)
assert nb >= 12
def test_get_filter_types():
"""Test get_filter_types function"""
filter_types = enasearch.get_filter_types(verbose=False)
assert "Boolean" in filter_types
assert "geo_box1" in filter_types["Geospatial"]
def test_get_display_options():
"""Test get_display_options function"""
display_options = enasearch.get_display_options(verbose=False)
assert "html" in display_options
assert "fasta" in display_options
def test_get_download_options():
"""Test get_download_options function"""
download_options = enasearch.get_download_options(verbose=False)
assert "gzip" in download_options
assert "txt" in download_options
def test_get_filter_fields():
"""Test get_filter_fields function"""
filter_fields = enasearch.get_filter_fields(
result="assembly",
verbose=False)
assert "accession" in filter_fields
def test_get_returnable_fields():
"""Test get_returnable_fields function"""
returnable_fields = enasearch.get_returnable_fields(
result="read_study",
verbose=False)
assert "secondary_study_accession" in returnable_fields
def test_get_sortable_fields():
"""Test get_sortable_fields function"""
sortable_fields = enasearch.get_returnable_fields(
result="sequence_update",
verbose=False)
assert "haplotype" in sortable_fields
def test_search_data():
"""Test search_data function"""
search_data = enasearch.search_data(
free_text_search=False,
query="tax_tree(7147) AND dataclass=STD",
result="coding_release",
display="fasta",
offset=0,
length=20,
download=None,
file=None,
fields=None,
sortfields=None)
assert len([seq.id for seq in search_data]) > 0
def test_search_all_data():
"""Test search_all_data function"""
search_data = enasearch.search_all_data(
free_text_search=True,
query="kinase+homo+sapiens",
result="sequence_update",
display="fasta",
download=None,
file=None)
nb = enasearch.get_search_result_number(
free_text_search=True,
query="kinase+homo+sapiens",
result="sequence_update",
need_check_result=True)
assert len([seq.id for seq in search_data]) == nb
def test_retrieve_data():
"""Test retrieve_data function"""
data = enasearch.retrieve_data(
ids="ERA000010-ERA000020",
display="xml",
download=None,
file=None,
offset=None,
length=None,
subseq_range=None,
expanded=None,
header=None)
assert "ROOT" in data
data = enasearch.retrieve_data(
ids="A00145",
display="fasta",
download=None,
file=None,
offset=0,
length=100000,
subseq_range="3-63",
expanded=None,
header=None)
pprint([seq.id for seq in data])
assert 'ENA|A00145|A00145.1' in [seq.id for seq in data]
data = enasearch.retrieve_data(
ids="AL513382",
display="text",
download=None,
file=None,
offset=0,
length=100000,
subseq_range=None,
expanded="true",
header=None)
pprint(data)
assert "AL513382" in data and len(data.split("\n")) >= 200000
data = enasearch.retrieve_data(
ids="AL513382",
display="text",
download=None,
file=None,
offset=0,
length=100000,
subseq_range=None,
expanded=None,
header="true")
pprint(data)
assert "AL513382" in data and len(data.split("\n")) >= 745
data = enasearch.retrieve_data(
ids="PRJEB2772",
display="xml",
download=None,
file=None,
offset=0,
length=100000,
subseq_range=None,
expanded=None,
header=None)
pprint(data)
assert "ROOT" in data
def test_retrieve_taxons():
"""Test retrieve_taxons function"""
data = enasearch.retrieve_taxons(
ids="6543",
display="fasta",
result="sequence_release",
download=None,
file=None,
offset=0,
length=100000,
subseq_range=None,
expanded=None,
header=None)
assert 'ENA|KT626607|KT626607.1' in [seq.id for seq in data]
data = enasearch.retrieve_taxons(
ids="Human,Cat,Mouse,Zebrafish",
display="xml",
result=None,
download=None,
file=None,
offset=0,
length=100000,
subseq_range=None,
expanded=None,
header=None)
assert "ROOT" in data
def test_retrieve_run_report():
"""Test retrieve_run_report function"""
report = enasearch.retrieve_run_report(
accession="SRX017289",
fields=None,
file=None)
assert "small RNAs_wild type" in report
exp_fields = ["run_accession", "fastq_ftp", "fastq_md5", "fastq_bytes"]
report = enasearch.retrieve_run_report(
accession="SRX017289",
fields=",".join(exp_fields),
file=None)
assert cmp(report.split("\n")[0].split("\t"), exp_fields)
def test_retrieve_analysis_report():
"""Test retrieve_analysis_report function"""
exp_fields = ["analysis_accession", "sample_accession", "scientific_name"]
report = enasearch.retrieve_analysis_report(
accession="PRJNA123835",
fields=",".join(exp_fields),
file=None)
assert cmp(report.split("\n")[0].split("\t"), exp_fields)
| StarcoderdataPython |
3366203 | <filename>test/defense/ckks/test_core.py
def test_sigma():
import numpy as np
from aijack.defense import CKKSEncoder
M = 8
scale = 1 << 20
encoder = CKKSEncoder(M, scale)
b = np.array([1, 2, 3, 4])
p = encoder.sigma_inverse(b)
b_reconstructed = encoder.sigma(p)
np.testing.assert_array_almost_equal(b, b_reconstructed, decimal=6)
m1 = np.array([1, 2, 3, 4])
m2 = np.array([1, -2, 3, -4])
p1 = encoder.sigma_inverse(m1)
p2 = encoder.sigma_inverse(m2)
p_add = p1 + p2
p_mult = p1 * p2
np.testing.assert_array_almost_equal(m1 + m2, encoder.sigma(p_add), decimal=6)
np.testing.assert_array_almost_equal(m1 * m2, encoder.sigma(p_mult), decimal=6)
def test_encoder():
import numpy as np
from aijack.defense import CKKSEncoder
M = 8
scale = 1 << 20
encoder = CKKSEncoder(M, scale)
z1 = np.array(
[
3 + 4j,
2 - 1j,
]
)
p1 = encoder.encode(z1)
z2 = np.array(
[
5 + 2j,
1 - 6j,
]
)
p2 = encoder.encode(z2)
np.testing.assert_array_almost_equal(z1, encoder.decode(p1), decimal=4)
p_add = p1 + p2
p_mult = p1 * p2
np.testing.assert_array_almost_equal(z1 + z2, encoder.decode(p_add), decimal=4)
np.testing.assert_array_almost_equal(z1 * z2, encoder.decode(p_mult), decimal=4)
def test_encrypter():
import numpy as np
from aijack.defense import CKKSEncoder, CKKSEncrypter
M = 8
scale = 1 << 20
encoder = CKKSEncoder(M, scale)
N = M // 2
q = 2**26
alice = CKKSEncrypter(encoder, q)
bob = CKKSEncrypter(encoder, q)
pk, _ = alice.keygen(N)
bob.set_pk(pk)
z1 = np.array(
[
1 + 2j,
1 - 1j,
]
)
c1 = bob.encrypt(z1)
z2 = np.array(
[
2 + 3j,
3 - 1j,
]
)
c2 = bob.encrypt(z2)
np.testing.assert_array_almost_equal(z1, alice.decrypt(c1), decimal=4)
np.testing.assert_array_almost_equal(z2, alice.decrypt(c2), decimal=4)
np.testing.assert_array_almost_equal(z1 + z2, alice.decrypt(c1 + c2), decimal=4)
# np.testing.assert_array_almost_equal(z1 * z2, alice.decrypt(c1 * p2), decimal=4)
| StarcoderdataPython |
3335162 | import math
import pylev
from .en2kr_dict import disease_dict, species_dict
# Use minimum edit distance (Levenshtein distance) to map different strings (e.g., African Swine Fever, africa swine fever, etc.)
# into one predefined term (african swine fever)
def disease_convert(word):
closest_word = ("", math.inf)
for key in disease_dict:
levenshtein_distance = pylev.levenshtein(word, key)
if levenshtein_distance < closest_word[1]:
closest_word = (key, levenshtein_distance)
return disease_dict[closest_word[0]]
def species_convert(word):
closest_word = ("", math.inf)
for key in species_dict:
levenshtein_distance = pylev.levenshtein(word, key)
if levenshtein_distance < closest_word[1]:
closest_word = (key, levenshtein_distance)
return species_dict[closest_word[0]]
if __name__ == "__main__":
sample = "african swine fever"
print(disease_convert(sample))
sample = "wild boar (sus scrofa)"
print(species_convert(sample))
| StarcoderdataPython |
3281868 | <reponame>nor3th/client-python
# coding: utf-8
class StixSightingRelationship:
def __init__(self, opencti):
self.opencti = opencti
self.properties = """
id
entity_type
parent_types
spec_version
created_at
updated_at
standard_id
description
first_seen
last_seen
attribute_count
x_opencti_negative
created
modified
confidence
createdBy {
... on Identity {
id
standard_id
entity_type
parent_types
identity_class
name
description
roles
contact_information
x_opencti_aliases
created
modified
objectLabel {
edges {
node {
id
value
color
}
}
}
}
... on Organization {
x_opencti_organization_type
x_opencti_reliability
}
... on Individual {
x_opencti_firstname
x_opencti_lastname
}
}
objectMarking {
edges {
node {
id
standard_id
entity_type
definition_type
definition
created
modified
x_opencti_order
x_opencti_color
}
}
}
objectLabel {
edges {
node {
id
value
color
}
}
}
externalReferences {
edges {
node {
id
standard_id
entity_type
source_name
description
url
hash
external_id
created
modified
}
}
}
from {
... on BasicObject {
id
entity_type
parent_types
}
... on BasicRelationship {
id
entity_type
parent_types
}
... on StixObject {
standard_id
spec_version
created_at
updated_at
}
... on AttackPattern {
name
}
... on Campaign {
name
}
... on CourseOfAction {
name
}
... on Individual {
name
}
... on Organization {
name
}
... on Sector {
name
}
... on System {
name
}
... on Indicator {
name
}
... on Infrastructure {
name
}
... on IntrusionSet {
name
}
... on Position {
name
}
... on City {
name
}
... on Country {
name
}
... on Region {
name
}
... on Malware {
name
}
... on ThreatActor {
name
}
... on Tool {
name
}
... on Vulnerability {
name
}
... on Incident {
name
}
... on StixCyberObservable {
observable_value
}
... on StixCoreRelationship {
standard_id
spec_version
created_at
updated_at
}
}
to {
... on BasicObject {
id
entity_type
parent_types
}
... on BasicRelationship {
id
entity_type
parent_types
}
... on StixObject {
standard_id
spec_version
created_at
updated_at
}
... on AttackPattern {
name
}
... on Campaign {
name
}
... on CourseOfAction {
name
}
... on Individual {
name
}
... on Organization {
name
}
... on Sector {
name
}
... on System {
name
}
... on Indicator {
name
}
... on Infrastructure {
name
}
... on IntrusionSet {
name
}
... on Position {
name
}
... on City {
name
}
... on Country {
name
}
... on Region {
name
}
... on Malware {
name
}
... on ThreatActor {
name
}
... on Tool {
name
}
... on Vulnerability {
name
}
... on Incident {
name
}
... on StixCyberObservable {
observable_value
}
... on StixCoreRelationship {
standard_id
spec_version
created_at
updated_at
}
}
"""
"""
List stix_sightings objects
:param fromId: the id of the source entity of the relation
:param toId: the id of the target entity of the relation
:param firstSeenStart: the first_seen date start filter
:param firstSeenStop: the first_seen date stop filter
:param lastSeenStart: the last_seen date start filter
:param lastSeenStop: the last_seen date stop filter
:param first: return the first n rows from the after ID (or the beginning if not set)
:param after: ID of the first row for pagination
:return List of stix_sighting objects
"""
def list(self, **kwargs):
element_id = kwargs.get("elementId", None)
from_id = kwargs.get("fromId", None)
from_types = kwargs.get("fromTypes", None)
to_id = kwargs.get("toId", None)
to_types = kwargs.get("toTypes", None)
first_seen_start = kwargs.get("firstSeenStart", None)
first_seen_stop = kwargs.get("firstSeenStop", None)
last_seen_start = kwargs.get("lastSeenStart", None)
last_seen_stop = kwargs.get("lastSeenStop", None)
filters = kwargs.get("filters", [])
first = kwargs.get("first", 100)
after = kwargs.get("after", None)
order_by = kwargs.get("orderBy", None)
order_mode = kwargs.get("orderMode", None)
get_all = kwargs.get("getAll", False)
with_pagination = kwargs.get("withPagination", False)
if get_all:
first = 100
self.opencti.log(
"info",
"Listing stix_sighting with {type: stix_sighting, from_id: "
+ str(from_id)
+ ", to_id: "
+ str(to_id)
+ "}",
)
query = (
"""
query StixSightingRelationships($elementId: String, $fromId: String, $fromTypes: [String], $toId: String, $toTypes: [String], $firstSeenStart: DateTime, $firstSeenStop: DateTime, $lastSeenStart: DateTime, $lastSeenStop: DateTime, $filters: [StixSightingRelationshipsFiltering], $first: Int, $after: ID, $orderBy: StixSightingRelationshipsOrdering, $orderMode: OrderingMode) {
stixSightingRelationships(elementId: $elementId, fromId: $fromId, fromTypes: $fromTypes, toId: $toId, toTypes: $toTypes, firstSeenStart: $firstSeenStart, firstSeenStop: $firstSeenStop, lastSeenStart: $lastSeenStart, lastSeenStop: $lastSeenStop, filters: $filters, first: $first, after: $after, orderBy: $orderBy, orderMode: $orderMode) {
edges {
node {
"""
+ self.properties
+ """
}
}
pageInfo {
startCursor
endCursor
hasNextPage
hasPreviousPage
globalCount
}
}
}
"""
)
result = self.opencti.query(
query,
{
"elementId": element_id,
"fromId": from_id,
"fromTypes": from_types,
"toId": to_id,
"toTypes": to_types,
"firstSeenStart": first_seen_start,
"firstSeenStop": first_seen_stop,
"lastSeenStart": last_seen_start,
"lastSeenStop": last_seen_stop,
"filters": filters,
"first": first,
"after": after,
"orderBy": order_by,
"orderMode": order_mode,
},
)
if get_all:
final_data = []
data = self.opencti.process_multiple(
result["data"]["stixSightingRelationships"]
)
final_data = final_data + data
while result["data"]["stixSightingRelationships"]["pageInfo"][
"hasNextPage"
]:
after = result["data"]["stixSightingRelationships"]["pageInfo"][
"endCursor"
]
self.opencti.log(
"info", "Listing StixSightingRelationships after " + after
)
result = self.opencti.query(
query,
{
"elementId": element_id,
"fromId": from_id,
"fromTypes": from_types,
"toId": to_id,
"toTypes": to_types,
"firstSeenStart": first_seen_start,
"firstSeenStop": first_seen_stop,
"lastSeenStart": last_seen_start,
"lastSeenStop": last_seen_stop,
"filters": filters,
"first": first,
"after": after,
"orderBy": order_by,
"orderMode": order_mode,
},
)
data = self.opencti.process_multiple(
result["data"]["stixSightingRelationships"]
)
final_data = final_data + data
return final_data
else:
return self.opencti.process_multiple(
result["data"]["stixSightingRelationships"], with_pagination
)
"""
Read a stix_sighting object
:param id: the id of the stix_sighting
:param fromId: the id of the source entity of the relation
:param toId: the id of the target entity of the relation
:param firstSeenStart: the first_seen date start filter
:param firstSeenStop: the first_seen date stop filter
:param lastSeenStart: the last_seen date start filter
:param lastSeenStop: the last_seen date stop filter
:return stix_sighting object
"""
def read(self, **kwargs):
id = kwargs.get("id", None)
element_id = kwargs.get("elementId", None)
from_id = kwargs.get("fromId", None)
to_id = kwargs.get("toId", None)
first_seen_start = kwargs.get("firstSeenStart", None)
first_seen_stop = kwargs.get("firstSeenStop", None)
last_seen_start = kwargs.get("lastSeenStart", None)
last_seen_stop = kwargs.get("lastSeenStop", None)
custom_attributes = kwargs.get("customAttributes", None)
if id is not None:
self.opencti.log("info", "Reading stix_sighting {" + id + "}.")
query = (
"""
query StixSightingRelationship($id: String!) {
stixSightingRelationship(id: $id) {
"""
+ (
custom_attributes
if custom_attributes is not None
else self.properties
)
+ """
}
}
"""
)
result = self.opencti.query(query, {"id": id})
return self.opencti.process_multiple_fields(
result["data"]["stixSightingRelationship"]
)
elif from_id is not None and to_id is not None:
result = self.list(
elementId=element_id,
fromId=from_id,
toId=to_id,
firstSeenStart=first_seen_start,
firstSeenStop=first_seen_stop,
lastSeenStart=last_seen_start,
lastSeenStop=last_seen_stop,
)
if len(result) > 0:
return result[0]
else:
return None
else:
self.opencti.log("error", "Missing parameters: id or from_id and to_id")
return None
"""
Create a stix_sighting object
:param name: the name of the Attack Pattern
:return stix_sighting object
"""
def create(self, **kwargs):
from_id = kwargs.get("fromId", None)
to_id = kwargs.get("toId", None)
stix_id = kwargs.get("stix_id", None)
description = kwargs.get("description", None)
first_seen = kwargs.get("first_seen", None)
last_seen = kwargs.get("last_seen", None)
count = kwargs.get("count", None)
x_opencti_negative = kwargs.get("x_opencti_negative", False)
created = kwargs.get("created", None)
modified = kwargs.get("modified", None)
confidence = kwargs.get("confidence", None)
created_by = kwargs.get("createdBy", None)
object_marking = kwargs.get("objectMarking", None)
object_label = kwargs.get("objectLabel", None)
external_references = kwargs.get("externalReferences", None)
x_opencti_stix_ids = kwargs.get("x_opencti_stix_ids", None)
update = kwargs.get("update", False)
self.opencti.log(
"info",
"Creating stix_sighting {" + from_id + ", " + str(to_id) + "}.",
)
query = """
mutation StixSightingRelationshipAdd($input: StixSightingRelationshipAddInput!) {
stixSightingRelationshipAdd(input: $input) {
id
standard_id
entity_type
parent_types
}
}
"""
result = self.opencti.query(
query,
{
"input": {
"fromId": from_id,
"toId": to_id,
"stix_id": stix_id,
"description": description,
"first_seen": first_seen,
"last_seen": last_seen,
"attribute_count": count,
"x_opencti_negative": x_opencti_negative,
"created": created,
"modified": modified,
"confidence": confidence,
"createdBy": created_by,
"objectMarking": object_marking,
"objectLabel": object_label,
"externalReferences": external_references,
"x_opencti_stix_ids": x_opencti_stix_ids,
"update": update,
}
},
)
return self.opencti.process_multiple_fields(
result["data"]["stixSightingRelationshipAdd"]
)
"""
Update a stix_sighting object field
:param id: the stix_sighting id
:param input: the input of the field
:return The updated stix_sighting object
"""
def update_field(self, **kwargs):
id = kwargs.get("id", None)
input = kwargs.get("input", None)
if id is not None and input is not None:
self.opencti.log("info", "Updating stix_sighting {" + id + "}")
query = """
mutation StixSightingRelationshipEdit($id: ID!, $input: [EditInput]!) {
stixSightingRelationshipEdit(id: $id) {
fieldPatch(input: $input) {
id
}
}
}
"""
result = self.opencti.query(
query,
{
"id": id,
"input": input,
},
)
return self.opencti.process_multiple_fields(
result["data"]["stixSightingRelationshipEdit"]["fieldPatch"]
)
else:
self.opencti.log(
"error",
"[opencti_stix_sighting] Missing parameters: id and key and value",
)
return None
"""
Add a Marking-Definition object to stix_sighting_relationship object (object_marking_refs)
:param id: the id of the stix_sighting_relationship
:param marking_definition_id: the id of the Marking-Definition
:return Boolean
"""
def add_marking_definition(self, **kwargs):
id = kwargs.get("id", None)
marking_definition_id = kwargs.get("marking_definition_id", None)
if id is not None and marking_definition_id is not None:
custom_attributes = """
id
objectMarking {
edges {
node {
id
standard_id
entity_type
definition_type
definition
x_opencti_order
x_opencti_color
created
modified
}
}
}
"""
stix_core_relationship = self.read(
id=id, customAttributes=custom_attributes
)
if stix_core_relationship is None:
self.opencti.log(
"error", "Cannot add Marking-Definition, entity not found"
)
return False
if marking_definition_id in stix_core_relationship["objectMarkingIds"]:
return True
else:
self.opencti.log(
"info",
"Adding Marking-Definition {"
+ marking_definition_id
+ "} to stix_sighting_relationship {"
+ id
+ "}",
)
query = """
mutation StixSightingRelationshipEdit($id: ID!, $input: StixMetaRelationshipAddInput) {
stixSightingRelationshipEdit(id: $id) {
relationAdd(input: $input) {
id
}
}
}
"""
self.opencti.query(
query,
{
"id": id,
"input": {
"toId": marking_definition_id,
"relationship_type": "object-marking",
},
},
)
return True
else:
self.opencti.log(
"error", "Missing parameters: id and marking_definition_id"
)
return False
"""
Remove a Marking-Definition object to stix_sighting_relationship
:param id: the id of the stix_sighting_relationship
:param marking_definition_id: the id of the Marking-Definition
:return Boolean
"""
def remove_marking_definition(self, **kwargs):
id = kwargs.get("id", None)
marking_definition_id = kwargs.get("marking_definition_id", None)
if id is not None and marking_definition_id is not None:
self.opencti.log(
"info",
"Removing Marking-Definition {"
+ marking_definition_id
+ "} from stix_sighting_relationship {"
+ id
+ "}",
)
query = """
mutation StixSightingRelationshipEdit($id: ID!, $toId: String!, $relationship_type: String!) {
stixSightingRelationshipEdit(id: $id) {
relationDelete(toId: $toId, relationship_type: $relationship_type) {
id
}
}
}
"""
self.opencti.query(
query,
{
"id": id,
"toId": marking_definition_id,
"relationship_type": "object-marking",
},
)
return True
else:
self.opencti.log("error", "Missing parameters: id and label_id")
return False
"""
Update the Identity author of a stix_sighting_relationship object (created_by)
:param id: the id of the stix_sighting_relationship
:param identity_id: the id of the Identity
:return Boolean
"""
def update_created_by(self, **kwargs):
id = kwargs.get("id", None)
identity_id = kwargs.get("identity_id", None)
if id is not None:
self.opencti.log(
"info",
"Updating author of stix_sighting_relationship {"
+ id
+ "} with Identity {"
+ str(identity_id)
+ "}",
)
custom_attributes = """
id
createdBy {
... on Identity {
id
standard_id
entity_type
parent_types
name
x_opencti_aliases
description
created
modified
}
... on Organization {
x_opencti_organization_type
x_opencti_reliability
}
... on Individual {
x_opencti_firstname
x_opencti_lastname
}
}
"""
stix_domain_object = self.read(id=id, customAttributes=custom_attributes)
if stix_domain_object["createdBy"] is not None:
query = """
mutation StixSightingRelationshipEdit($id: ID!, $toId: String! $relationship_type: String!) {
stixSightingRelationshipEdit(id: $id) {
relationDelete(toId: $toId, relationship_type: $relationship_type) {
id
}
}
}
"""
self.opencti.query(
query,
{
"id": id,
"toId": stix_domain_object["createdBy"]["id"],
"relationship_type": "created-by",
},
)
if identity_id is not None:
# Add the new relation
query = """
mutation StixSightingRelationshipEdit($id: ID!, $input: StixMetaRelationshipAddInput) {
stixSightingRelationshipEdit(id: $id) {
relationAdd(input: $input) {
id
}
}
}
"""
variables = {
"id": id,
"input": {
"toId": identity_id,
"relationship_type": "created-by",
},
}
self.opencti.query(query, variables)
else:
self.opencti.log("error", "Missing parameters: id")
return False
"""
Delete a stix_sighting
:param id: the stix_sighting id
:return void
"""
def delete(self, **kwargs):
id = kwargs.get("id", None)
if id is not None:
self.opencti.log("info", "Deleting stix_sighting {" + id + "}.")
query = """
mutation StixSightingRelationshipEdit($id: ID!) {
stixSightingRelationshipEdit(id: $id) {
delete
}
}
"""
self.opencti.query(query, {"id": id})
else:
self.opencti.log("error", "[opencti_stix_sighting] Missing parameters: id")
return None
| StarcoderdataPython |
3246365 |
from django.db import models
# Create your models here.
from django.db import models
from cloudinary.models import CloudinaryField
# Create your models here.
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Project(models.Model):
image = CloudinaryField('image')
project_name = models.TextField(max_length=30)
description = models.TextField()
significance = models.TextField()
category = models.TextField()
url = models.URLField(blank=True)
future_improvements= models.TextField()
date_posted = models.DateTimeField(auto_now=True)
# Save image method
def save_project(self):
self.save()
# Get all images method
@classmethod
def get_project_by_id(cls, id):
project = cls.objects.get(id=id)
return project
@classmethod
def get_all_projects(cls):
projects = cls.objects.all()
return projects
@classmethod
def get_all_projects_by_user(cls, user):
projects = cls.objects.filter(user=user)
return projects
@classmethod
def search_image(cls,search_term):
images = cls.objects.filter(category__icontains=search_term)
return images
# @classmethod
# def search_image(cls,search):
# image = cls.objects.filter(name__icontains=search)
# return image
def __str__(self):
return self.name | StarcoderdataPython |
138236 | from django.urls import reverse
from rest_framework import serializers
from redirink.links.models import Link
class LinkSerializer(serializers.ModelSerializer):
"""
Serializer to dict for link.
"""
user = serializers.HiddenField(default=serializers.CurrentUserDefault())
from_url = serializers.SerializerMethodField()
class Meta:
model = Link
fields = ["pk", "from_url", "to_url", "create_time", "user"]
extra_kwargs = {
"pk": {"read_only": True},
"create_time": {"read_only": True},
}
def validate(self, data: dict) -> dict:
return data
def get_from_url(self, obj):
request = self.context["request"]
redirect_path = reverse("links:redirect", kwargs={"pk": obj.pk})
return f"{request.scheme}://{request.get_host()}{redirect_path}"
| StarcoderdataPython |
1720480 | MQTT = {
'enabled': True,
'host': 'mosquitto',
}
INFLUXDB = {
'enabled': False,
'base_url': 'http://influxdb:8086',
# Time when data should be written, even if value has not changed
'write_through_time': 60 * 60,
'database': 'heatpump',
'measurement': 'heatpump',
}
BINDING = {
'update_interval': 15,
'heat_pump_id': 'wpl_10_ac',
# If true, also messages not requested by us get handled
'handle_all_messages': True,
}
| StarcoderdataPython |
3349152 | <filename>spharpy/special.py
"""
Subpackage implementing or wrapping special functions required in the
spharpy package.
"""
from itertools import count
import numpy as np
import scipy.special as _spspecial
from scipy.optimize import brentq
def spherical_bessel(n, z, derivative=False):
r"""
Spherical bessel function of order n evaluated at z.
.. math::
j_n(z) = \sqrt{\frac{\pi}{2z}} J_{n+\frac{1}{2}} (z)
Parameters
----------
n : int, ndarray
Order of the spherical bessel function
z : double, ndarray
Argument of the spherical bessel function. Has to be real valued.
derivative : bool
Return the derivative of the spherical Bessel function
Returns
-------
jn : double, ndarray
Spherical bessel function. Array with dimensions [N x Z], where N is
the number of elements in n and Z is the number of elements in z.
Note
----
This is a wrapper around the Scipy implementation of the spherical Bessel
function.
"""
ufunc = _spspecial.spherical_jn
n = np.asarray(n, dtype=np.int)
z = np.asarray(z, dtype=np.double)
bessel = np.zeros((n.size, z.size), dtype=np.complex)
if n.size > 1:
for idx, order in zip(count(), n):
bessel[idx, :] = ufunc(order, z, derivative=derivative)
else:
bessel = ufunc(n, z, derivative=derivative)
if z.ndim <= 1 or n.ndim <= 1:
bessel = np.squeeze(bessel)
return bessel
def spherical_bessel_zeros(n_max, n_zeros):
"""Compute the zeros of the spherical Bessel function.
This function will always start at order zero which is equal
to sin(x)/x and iteratively compute the roots for higher orders.
The roots are computed using Brents algorithm from the scipy package.
Parameters
----------
n_max : int
The order of the spherical bessel function
n_zeros : int
The number of roots to be computed
Returns
-------
roots : ndarray, double
The roots of the spherical bessel function
"""
def func(x, n):
return _spspecial.spherical_jn(n, x)
zerosj = np.zeros((n_max+1, n_zeros), dtype=np.double)
zerosj[0] = np.arange(1, n_zeros+1)*np.pi
points = np.arange(1, n_zeros+n_max+1)*np.pi
roots = np.zeros(n_zeros+n_max, dtype=np.double)
for i in range(1, n_max+1):
for j in range(n_zeros+n_max-i):
roots[j] = brentq(func, points[j], points[j+1], (i,), maxiter=5000)
points = roots
zerosj[i, :n_zeros] = roots[:n_zeros]
return zerosj
def spherical_hankel(n, z, kind=2, derivative=False):
r"""
Spherical Hankel function of order n evaluated at z.
.. math::
j_n(z) = \sqrt{\frac{\pi}{2z}} J_{n+\frac{1}{2}} (z)
Parameters
----------
n : int, ndarray
Order of the spherical bessel function
z : double, ndarray
Argument of the spherical bessel function. Has to be real valued.
Returns
-------
hn : double, ndarray
Spherical bessel function. Array with dimensions [N x Z], where N is
the number of elements in n and Z is the number of elements in z.
Note
----
This is based on the Hankel functions implemented in the scipy package.
"""
if kind not in (1, 2):
raise ValueError("The spherical hankel function can \
only be of first or second kind.")
n = np.asarray(n, dtype=np.int)
z = np.asarray(z, dtype=np.double)
if derivative:
ufunc = _spherical_hankel_derivative
else:
ufunc = _spherical_hankel
if n.size > 1:
hankel = np.zeros((n.size, z.size), dtype=np.complex)
for idx, order in zip(count(), n):
hankel[idx, :] = ufunc(order, z, kind)
else:
hankel = ufunc(n, z, kind)
if z.ndim <= 1 or n.ndim <= 1:
hankel = np.squeeze(hankel)
return hankel
def _spherical_hankel(n, z, kind):
if kind == 1:
hankel = _spspecial.hankel1(n+0.5, z)
elif kind == 2:
hankel = _spspecial.hankel2(n+0.5, z)
hankel = np.sqrt(np.pi/2/z) * hankel
return hankel
def _spherical_hankel_derivative(n, z, kind):
hankel = _spherical_hankel(n-1, z, kind) - \
(n+1)/z * _spherical_hankel(n, z, kind)
return hankel
def spherical_harmonic(n, m, theta, phi):
"""The spherical harmonics of order n and degree m.
n : unsigned int
The spherical harmonic order
m : int
The spherical harmonic degree
theta : ndarray, double
The elevation angle
phi : ndarray, double
The azimuth angle
Returns
-------
spherical_harmonic : ndarray, double
The complex valued spherial harmonic of order n and degree m
Note
----
This function wraps the spherical harmonic implementation from scipy.
The only difference is that we return zeros instead of nan values
if $n < |m|$.
"""
theta = np.asarray(theta, dtype=np.double)
phi = np.asarray(phi, dtype=np.double)
if n < np.abs(m):
sph_harm = np.zeros(theta.shape)
else:
sph_harm = _spspecial.sph_harm(m, n, phi, theta)
return sph_harm
def spherical_harmonic_real(n, m, theta, phi):
r"""Real valued spherical harmonic function of order n and degree m
evaluated at the angles theta and phi.
The spherical harmonic functions are fully normalized (N3D) and follow
the AmbiX phase convention [1]_.
.. math::
Y_n^m(\theta, \phi) = \sqrt{\frac{2n+1}{4\pi} \frac{(n-|m|)!}{(n+|m|)!}} P_n^{|m|}(\cos \theta)
\begin{cases}
\displaystyle \cos(|m|\phi), & \text{if $m \ge 0$} \newline
\displaystyle \sin(|m|\phi) , & \text{if $m < 0$}
\end{cases}
References
----------
.. [1] <NAME>, <NAME>, <NAME>, and <NAME>, “Ambix - A
Suggested Ambisonics Format (revised by <NAME>),” International
Symposium on Ambisonics and Spherical Acoustics,
vol. 3, pp. 1–11, 2011.
Parameters
----------
n : unsigned int
The spherical harmonic order
m : int
The spherical harmonic degree
theta : ndarray, double
The elevation angle
phi : ndarray, double
The azimuth angle
Returns
-------
spherical_harmonic : ndarray, double
The real valued spherial harmonic of order n and degree m
"""
# careful here, scipy uses phi as the elevation angle and
# theta as the azimuth angle
Y_nm_cplx = _spspecial.sph_harm(m, n, phi, theta)
if m == 0:
Y_nm = np.real(Y_nm_cplx)
elif m > 0:
Y_nm = np.real(Y_nm_cplx) * np.sqrt(2)
elif m < 0:
Y_nm = np.imag(Y_nm_cplx) * np.sqrt(2) * np.float(-1)**(m+1)
Y_nm *= (np.float(-1)**(m))
return Y_nm
def spherical_harmonic_derivative_phi(n, m, theta, phi):
"""Calculate the derivative of the spherical harmonics with respect to
the azimuth angle phi.
Parameters
----------
n : int
Spherical harmonic order
m : int
Spherical harmonic degree
theta : double
Elevation angle 0 < theta < pi
phi : double
Azimuth angle 0 < phi < 2*pi
Returns
-------
sh_diff : complex double
Spherical harmonic derivative
"""
if m == 0 or n == 0:
res = np.zeros(phi.shape, dtype=np.complex)
else:
res = spherical_harmonic(n, m, theta, phi) * 1j * m
return res
def spherical_harmonic_gradient_phi(n, m, theta, phi):
"""Calculate the derivative of the spherical harmonics with respect to
the azimuth angle phi divided by sin(theta)
Parameters
----------
n : int
Spherical harmonic order
m : int
Spherical harmonic degree
theta : double
Elevation angle 0 < theta < pi
phi : double
Azimuth angle 0 < phi < 2*pi
Returns
-------
sh_diff : complex double
Spherical harmonic derivative
"""
if m == 0:
res = np.zeros(theta.shape, dtype=np.complex)
else:
factor = np.sqrt((2*n+1)/(2*n-1))/2
exp_phi = np.exp(1j*phi)
first = np.sqrt((n+m)*(n+m-1)) * exp_phi * \
spherical_harmonic(n-1, m-1, theta, phi)
second = np.sqrt((n-m) * (n-m-1)) / exp_phi * \
spherical_harmonic(n-1, m+1, theta, phi)
Ynm_sin_theta = (-1) * factor * (first + second)
res = Ynm_sin_theta * 1j
return res
def spherical_harmonic_derivative_theta(n, m, theta, phi):
"""Calculate the derivative of the spherical harmonics with respect to
the elevation angle theta.
Parameters
----------
n : int
Spherical harmonic order
m : int
Spherical harmonic degree
theta : double
Elevation angle 0 < theta < pi
phi : double
Azimuth angle 0 < phi < 2*pi
Returns
-------
sh_diff : complex double
Spherical harmonic derivative
"""
if n == 0:
res = np.zeros(theta.shape, dtype=np.complex)
else:
exp_phi = np.exp(1j*phi)
first = np.sqrt((n-m+1) * (n+m)) * exp_phi * \
spherical_harmonic(n, m-1, theta, phi)
second = np.sqrt((n-m) * (n+m+1)) / exp_phi * \
spherical_harmonic(n, m+1, theta, phi)
res = (first-second)/2 * (-1)
return res
def legendre_function(n, m, z, cs_phase=True):
r"""Legendre function of order n and degree m with argument z.
.. math::
P_n^m(z) = (-1)^m(1-z^2)^{m/2}\frac{d^m}{dz^m}P_n{z}
where the Condon-Shotley phase term $(-1)^m$ is dropped when cs_phase=False
is used.
Parameters
----------
n : int
The order
m : int
The degree
z : ndarray, double
The argument as an array
cs_phase : bool, optional
Whether to use include the Condon-Shotley phase term (-1)^m or not
Returns
-------
legendre : ndarray, double
The Legendre function. This will return zeros if $|m| > n$.
Note
----
This is a wrapper for the Legendre function implementation from scipy. The
scipy implementation uses the Condon-Shotley phase. Therefore, the sign
needs to be flipped here for uneven degrees when dropping the
Condon-Shotley phase.
"""
z = np.atleast_1d(z)
if np.abs(m) > n:
legendre = np.zeros(z.shape)
else:
legendre = np.zeros(z.shape)
for idx, arg in zip(count(), z):
leg, _ = _spspecial.lpmn(m, n, arg)
if np.mod(m, 2) != 0 and not cs_phase:
legendre[idx] = -leg[-1, -1]
else:
legendre[idx] = leg[-1, -1]
return legendre
def spherical_harmonic_normalization(n, m, norm='full'):
r"""The normalization factor for real valued spherical harmonics.
.. math::
N_n^m = \sqrt{\frac{2n+1}{4\pi}\frac{(n-m)!}{(n+m)!}}
Parameters
----------
n : int
The spherical harmonic order.
m : int
The spherical harmonic degree.
norm : 'full', 'semi', optional
Normalization to use. Can be either fully normalzied on the sphere or
semi-normalized.
Returns
-------
norm : double
The normalization factor.
"""
if np.abs(m) > n:
factor = 0.0
else:
if norm == 'full':
z = n+m+1
factor = _spspecial.poch(z, -2*m)
factor *= (2*n+1)/(4*np.pi)
if int(m) != 0:
factor *= 2
factor = np.sqrt(factor)
elif norm == 'semi':
z = n+m+1
factor = _spspecial.poch(z, -2*m)
if int(m) != 0:
factor *= 2
factor = np.sqrt(factor)
else:
raise ValueError("Unknown normalization.")
return factor
def spherical_harmonic_derivative_theta_real(n, m, theta, phi):
r"""The derivative of the real valued spherical harmonics with respect
to the elevation angle $\theta$.
Parameters
----------
n : int
The spherical harmonic order.
m : int
The spherical harmonic degree.
theta : ndarray, double
The elevation angle
phi : ndarray, double
The azimuth angle
Returns
-------
derivative : ndarray, double
The derivative
Note
----
This implementation does not include the Condon-Shotley phase term.
"""
m_abs = np.abs(m)
if n == 0:
res = np.zeros(theta.shape, dtype=np.double)
else:
first = (n+m_abs)*(n-m_abs+1) * \
legendre_function(
n,
m_abs-1,
np.cos(theta),
cs_phase=False)
second = legendre_function(
n,
m_abs+1,
np.cos(theta),
cs_phase=False)
legendre_diff = 0.5*(first - second)
N_nm = spherical_harmonic_normalization(n, m_abs)
if m < 0:
phi_term = np.sin(m_abs*phi)
else:
phi_term = np.cos(m_abs*phi)
res = N_nm * legendre_diff * phi_term
return res
def spherical_harmonic_derivative_phi_real(n, m, theta, phi):
r"""The derivative of the real valued spherical harmonics with respect
to the azimuth angle $\phi$.
Parameters
----------
n : int
The spherical harmonic order.
m : int
The spherical harmonic degree.
theta : ndarray, double
The elevation angle
phi : ndarray, double
The azimuth angle
Returns
-------
derivative : ndarray, double
The derivative
Note
----
This implementation does not include the Condon-Shotley phase term.
"""
m_abs = np.abs(m)
if m == 0:
res = np.zeros(theta.shape, dtype=np.double)
else:
legendre = legendre_function(n, m_abs, np.cos(theta), cs_phase=False)
N_nm = spherical_harmonic_normalization(n, m_abs)
if m < 0:
phi_term = np.cos(m_abs*phi) * m_abs
else:
phi_term = -np.sin(m_abs*phi) * m_abs
res = N_nm * legendre * phi_term
return res
def spherical_harmonic_gradient_phi_real(n, m, theta, phi):
r"""The gradient of the real valued spherical harmonics with respect
to the azimuth angle $\phi$.
Parameters
----------
n : int
The spherical harmonic order.
m : int
The spherical harmonic degree.
theta : ndarray, double
The elevation angle
phi : ndarray, double
The azimuth angle
Returns
-------
derivative : ndarray, double
The derivative
Note
----
This implementation does not include the Condon-Shotley phase term.
References
----------
.. [1] <NAME>, <NAME>, <NAME>, and <NAME>, “Non-singular spherical
harmonic expressions of geomagnetic vector and gradient tensor
fields in the local north-oriented reference frame,” Geoscientific
Model Development, vol. 8, no. 7, pp. 1979–1990, Jul. 2015.
"""
m_abs = np.abs(m)
if m == 0:
res = np.zeros(theta.shape, dtype=np.double)
else:
first = (n+m_abs)*(n+m_abs-1) * \
legendre_function(
n-1,
m_abs-1,
np.cos(theta),
cs_phase=False)
second = legendre_function(
n-1,
m_abs+1,
np.cos(theta),
cs_phase=False)
legendre_diff = 0.5*(first + second)
N_nm = spherical_harmonic_normalization(n, m_abs)
if m < 0:
phi_term = np.cos(m_abs*phi)
else:
phi_term = -np.sin(m_abs*phi)
res = N_nm * legendre_diff * phi_term
return res
def legendre_coefficients(order):
"""Calculate the coefficients of a Legendre polynomial of the
specified order.
Parameters
----------
order : int
The order of the polynomial
Returns
-------
coefficients : ndarray, double
The coefficients of the polynomial
"""
leg = np.polynomial.legendre.Legendre.basis(order)
coefficients = np.polynomial.legendre.leg2poly(leg.coef)
return coefficients
def chebyshev_coefficients(order):
"""Calculate the coefficients of a Chebyshev polynomial of the
specified order.
Parameters
----------
order : int
The order of the polynomial
Returns
-------
coefficients : ndarray, double
The coefficients of the polynomial
"""
cheb = np.polynomial.chebyshev.Chebyshev.basis(order)
coefficients = np.polynomial.chebyshev.cheb2poly(cheb.coef)
return coefficients
| StarcoderdataPython |
3293316 | <filename>kiqpo/core/ThisValue.py
def ThisValue():
return "this.value" | StarcoderdataPython |
3379251 | <reponame>coecms/dusqlite
#!/usr/bin/env python
#
# Copyright 2019 <NAME>
#
# Author: <NAME> <<EMAIL>>
#
# 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 dusqlite.handler.mdss import *
import io
import stat
import os
import pytest
def test_parse_mdss():
output = """saw562:
total 4
1511828541626 drwxrwsr-x 5 5424 5608 119 2019-01-24 11:43 (REG) .
1578400487646 drwxrws--- 11 0 5608 163 2019-02-04 10:30 (REG) ..
1511828760656 -rw-r--r-- 1 5424 5608 315973404 2016-06-22 14:23 (OFL) historical.pm-1850004001.nc
1511832938642 -rw-r--r-- 1 5424 5608 327483043840 2018-03-05 11:17 (OFL) um-ostia.tar
1513975992681 drwxrws--- 2 5424 5608 10 2016-06-10 11:38 (REG) vapjv
1733019332892 drwxrws---+ 2 5424 5608 10 2016-06-16 11:38 (REG) vapjw
1664309309747 drwxrws--- 2 5424 5608 10 2016-10-07 11:22 (REG) vapjy
"""
stream = io.StringIO(output)
r = list(parse_mdss(stream))
assert r[1]['inode'] == 1511828760656
assert r[1]['parent_inode'] == 1511828541626
assert r[1]['uid'] == 5424
assert r[1]['gid'] == 5608
assert r[1]['size'] == 315973404
def test_mode_to_octal():
mode = 'drwxrwsr-x'
omode = mode_to_octal(mode)
assert stat.filemode(omode) == mode
mode = '-rw-r--r--'
omode = mode_to_octal(mode)
assert stat.filemode(omode) == mode
mode = 'lrwxrwxrwx'
omode = mode_to_octal(mode)
assert stat.filemode(omode) == mode
mode = '---s--x---'
omode = mode_to_octal(mode)
assert stat.filemode(omode) == mode
@pytest.mark.skipif(not os.environ.get('HOSTNAME', '').startswith('raijin'),
reason="Only available at NCI")
def test_scan_mdss(conn):
from dusqlite.scan import scan
scan('mdss://w35/saw562', conn)
| StarcoderdataPython |
3225591 | <reponame>fkwai/geolearn
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
sd = np.datetime64('2000-01-01')
ed = np.datetime64('2000-12-31')
t = pd.date_range(sd, ed)
td = t.dayofyear.values-1
fig, ax = plt.subplots(1, 1)
nt = td.max()
# tLst = ['2000-01-01', '2000-03-01', '2000-06-01', '2000-09-01']
tLst = ['2000-{:02d}-01'.format(m+1) for m in range(12)]
for k in range(len(tLst)):
tt = pd.to_datetime(tLst[k]).dayofyear-1
xx = np.cos(tt/nt*np.pi*2)
yy = np.sin(tt/nt*np.pi*2)
ax.plot([0, xx], [0, yy], 'k-')
ax.text(xx, yy, tLst[k][5:])
x = np.cos(td/nt*np.pi*2)
y = np.sin(td/nt*np.pi*2)
ax.scatter(x, y, c=td, cmap='hsv',s=100)
ax.set_yticklabels([])
ax.set_xticklabels([])
ax.set_yticks([])
ax.set_xticks([])
ax.set_aspect('equal', 'box')
fig.show()
| StarcoderdataPython |
1733152 | from Grove_Fingerprint import Fingerprint
import sys
import wiringpi2
fp = Fingerprint()
if fp.verifyPassword():
print 'Found device.'
else:
print 'Device not found'
sys.exit(0)
def getFingerprintIDez():
p = fp.getImage()
if p != fp.FINGERPRINT_OK:
return -1
p = fp.image2Tz()
if p != fp.FINGERPRINT_OK:
return -1
p = fp.fingerFastSearch()
if p != fp.FINGERPRINT_OK:
return -1
print ' Found ID #', fp.fingerID
def getFingerprintEnroll(id):
p = -1
print 'waiting fort valid finger to enroll...'
while p != fp.FINGERPRINT_OK:
p = fp.getImage()
if p == fp.FINGERPRINT_OK:
print 'image taken.'
elif p == fp.FINGERPRINT_NOFINGER:
sys.stdout.write('.')
elif p == fp.FINGERPRINT_PACKETRECIEVEERR:
print 'Communication error'
elif p == fp.FINGERPRINT_IMAGEFAIL:
print 'Image error.'
else:
print 'Unknow error.'
# Success
p = fp.image2Tz(1)
if p == fp.FINGERPRINT_OK:
print 'image converted.'
elif p == fp.FINGERPRINT_IMAGEMESS:
print 'Image too messy'
return p
elif p == fp.FINGERPRINT_PACKETRECIEVEERR:
print 'Communication error'
return p
elif p == fp.FINGERPRINT_FEATUREFAIL:
print 'Cound not find fingerprint features'
return p
elif p == fp.FINGERPRINT_INVALIDIMAGE:
print 'Cound not find fingerprint features'
return p
else:
print 'Unknow error.'
return p
print 'Remove finger.'
wiringpi2.delay(2000)
p = 0
while p != fp.FINGERPRINT_NOFINGER:
p = fp.getImage()
p = -1
print 'Place same finger again'
while p != fp.FINGERPRINT_OK:
p = fp.getImage()
if p == fp.FINGERPRINT_OK:
print 'image taken.'
elif p == fp.FINGERPRINT_NOFINGER:
sys.stdout.write('.')
elif p == fp.FINGERPRINT_PACKETRECIEVEERR:
print 'Communication error'
elif p == fp.FINGERPRINT_IMAGEFAIL:
print 'Image error.'
else:
print 'Unknow error.'
# Success
p = fp.image2Tz(2)
if p == fp.FINGERPRINT_OK:
print 'image converted.'
elif p == fp.FINGERPRINT_IMAGEMESS:
print 'Image too messy'
return p
elif p == fp.FINGERPRINT_PACKETRECIEVEERR:
print 'Communication error'
return p
elif p == fp.FINGERPRINT_FEATUREFAIL:
print 'Cound not find fingerprint features'
return p
elif p == fp.FINGERPRINT_INVALIDIMAGE:
print 'Cound not find fingerprint features'
return p
else:
print 'Unknow error.'
return p
# ok converted
p = fp.createModel()
if p == fp.FINGERPRINT_OK:
print 'Prints matched.'
elif p == fp.FINGERPRINT_PACKETRECIEVEERR:
print 'Communication error.'
return p
elif p == fp.FINGERPRINT_ENROLLMISMATCH:
print 'Fingerprints did not match.'
return p
else:
print 'Unknow error'
return p
p = fp.storModel(id)
if p == fp.FINGERPRINT_OK:
print 'Stored!'
elif p == fp.FINGERPRINT_PACKETRECIEVEERR:
print 'Communication error.'
return p
elif p == fp.FINGERPRINT_BADLOCATION:
print 'Could not store in that location.'
return p
elif p == fp.FINGERPRINT_FLASHERR:
print 'Error writing to flash.'
return p
else:
print 'Unknow error'
return p
while True:
# getFingerprintIDez()
print 'Type in the ID # you want to save this finger as...'
content = raw_input('input')
id = content
print 'Enroll ID #', content
while 0 == getFingerprintEnroll(id):
pass
| StarcoderdataPython |
154278 | from systemcheck.checks.models.checks import Check
from systemcheck.models.meta import Base, ChoiceType, Column, ForeignKey, Integer, QtModelMixin, String, qtRelationship, \
relationship, RichString, generic_repr, OperatorMixin, BaseMixin, TableNameMixin
from systemcheck.systems.ABAP.models import ActionAbapClientSpecificMixin
from sqlalchemy import inspect
@generic_repr
class ActionAbapCountTableEntries__params(QtModelMixin, Base, OperatorMixin, BaseMixin, TableNameMixin):
__table_args__ = {'extend_existing':True}
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('ActionAbapCountTableEntries.id'))
param_set_name = Column(String,
nullable=False,
qt_description='Name of the parameter set. It is easier to navigate a large list of parameter sets, if they have a descriptive name',
qt_label='Parameter Set Name',
qt_show=False,
default = 'Please Maintain'
)
table_name = Column(String,
nullable=False,
qt_description='Table Name',
qt_label='Table Name',
qt_show=False,
default = 'Please Maintain'
)
table_fields = Column(String,
nullable=True,
qt_description='Table Fields, separated by a ";"',
qt_label='Table Fields',
qt_show=False
)
where_clause = Column(String,
nullable=True,
qt_description='Where Clause',
qt_label='Where Clause',
qt_show=False
)
expected_count = Column(Integer,
nullable=True,
qt_description = 'Expected Count',
qt_label = 'Expected Count',
qt_show = False,
)
check = relationship("ActionAbapCountTableEntries", back_populates="params")
__qtmap__ = [param_set_name, table_name, table_fields, where_clause, expected_count, OperatorMixin.operator]
@generic_repr
class ActionAbapCountTableEntries(Check, ActionAbapClientSpecificMixin):
__tablename__ = 'ActionAbapCountTableEntries'
__table_args__ = {'extend_existing':True}
id = Column(Integer, ForeignKey('checks_metadata.id'), primary_key=True, qt_show=False)
params = qtRelationship('ActionAbapCountTableEntries__params',
qt_show=True,
cascade="all, delete-orphan",
back_populates="check")
__mapper_args__ = {
'polymorphic_identity':'ActionAbapCountTableEntries',
}
__qtmap__ = [Check.name, Check.description, Check.failcriteria, Check.criticality,
ActionAbapClientSpecificMixin.client_specific]
| StarcoderdataPython |
3201858 | import importlib
from pydashery import Widget
def find_function(search_def):
"""
Dynamically load the function based on the search definition.
:param str search_def: A string to tell us the function to load, e.g.
module:funcname or module.path:class.staticmethod
:raises ValueError: In case configuration is invalid
:return function: A function
"""
try:
module_name, funcspec = search_def.split(":")
except ValueError:
raise ValueError("Function definition \"{}\" is not valid.".format(
search_def
))
try:
module = importlib.import_module(module_name)
except ImportError:
raise ValueError(
"Function definition \"{}\" is not valid. The module specified "
"was not found.".format(
search_def
)
)
if "." in funcspec:
class_name, func_name = funcspec.split(".")
try:
source = getattr(module, class_name)
except AttributeError:
raise ValueError(
"Function definition \"{}\" is not valid. The module does not "
"contain the specified class.".format(
search_def
)
)
else:
source = module
func_name = funcspec
try:
func = getattr(source, func_name)
except AttributeError:
raise ValueError(
"Function definition \"{}\" is not valid. The function specified "
"could not be found.".format(
search_def
)
)
return func
class FunctionResultWidget(Widget):
TYPE = "FunctionResult"
TEMPLATE = "functionresult.html"
DEFAULT_SETTINGS = {
"update_minutes": 1.0
}
def get_update_interval(self):
return float(self.settings["update_minutes"]) * 60.0
def update(self):
self.set_value(self.get_result())
def get_result(self):
f = find_function(self.settings["func"])
return f()
| StarcoderdataPython |
4808573 | from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.error import AlreadyCalled
class TimeOutError(Exception): pass
class DeferredWithTimeout(Deferred):
"""
Deferred with a timeout. If neither the callback nor the errback method
is not called within the given time, the deferred's errback will be called
with a TimeOutError() exception.
All other uses are the same as of Deferred().
"""
def __init__(self, timeout=1.0):
Deferred.__init__(self)
self._timeout = timeout
self.timer = reactor.callLater(timeout, self.timed_out)
def timed_out(self):
self.errback(
TimeOutError('timed out after {} seconds'.format(self._timeout)))
def callback(self, result):
self._cancel_timer()
return Deferred.callback(self, result)
def errback(self, fail):
self._cancel_timer()
return Deferred.errback(self, fail)
def cancel(self):
self._cancel_timer()
return Deferred.cancel(self)
def _cancel_timer(self):
try:
self.timer.cancel()
except AlreadyCalled:
pass
| StarcoderdataPython |
1777954 | <reponame>thoughteer/edera
import datetime
import multiprocessing
import time
import pytest
from edera.exceptions import ExcusableError
from edera.exceptions import ExcusableMasterSlaveInvocationError
from edera.exceptions import MasterSlaveInvocationError
from edera.invokers import MultiProcessInvoker
from edera.routine import routine
def test_invoker_runs_actions_in_parallel():
def add_index(index):
collection.put(index)
collection = multiprocessing.Queue()
actions = {
"A": lambda: add_index(2),
"B": lambda: add_index(1),
"C": lambda: add_index(0),
}
MultiProcessInvoker(actions).invoke()
assert {collection.get(timeout=3.0) for _ in range(3)} == {0, 1, 2}
def test_invoker_notifies_about_stops():
def add_index(index):
if index % 2 == 0:
raise ExcusableError("index must be odd")
collection.put(index)
collection = multiprocessing.Queue()
actions = {
"A": lambda: add_index(3),
"B": lambda: add_index(2),
"C": lambda: add_index(1),
"D": lambda: add_index(0),
}
with pytest.raises(ExcusableMasterSlaveInvocationError) as info:
MultiProcessInvoker(actions).invoke()
assert len(info.value.stopped_slaves) == 2
assert {collection.get(timeout=3.0) for _ in range(2)} == {1, 3}
def test_invoker_notifies_about_failures():
def add_index(index):
if index % 2 == 0:
raise RuntimeError("index must be odd")
collection.put(index)
collection = multiprocessing.Queue()
actions = {
"A": lambda: add_index(3),
"B": lambda: add_index(2),
"C": lambda: add_index(1),
"D": lambda: add_index(0),
}
with pytest.raises(MasterSlaveInvocationError) as info:
MultiProcessInvoker(actions).invoke()
assert len(info.value.failed_slaves) == 2
assert {collection.get(timeout=3.0) for _ in range(2)} == {1, 3}
def test_invoker_can_replicate_single_action():
def increment():
with mutex:
counter.put(counter.get(timeout=1.0) + 1)
mutex = multiprocessing.Lock()
counter = multiprocessing.Queue()
counter.put(0)
MultiProcessInvoker.replicate(increment, count=15, prefix="P").invoke()
assert counter.get(timeout=3.0) == 15
def test_invoker_interrupts_slaves_after_being_interrupted():
@routine
def wait():
while True:
time.sleep(1.0)
yield
def interrupt():
raise RuntimeError
actions = {
"A": wait,
"B": wait,
}
start_time = time.time()
with pytest.raises(RuntimeError):
MultiProcessInvoker(
actions, interruption_timeout=datetime.timedelta(seconds=3.0)).invoke[interrupt]()
assert time.time() - start_time < 6.0
def test_invoker_kills_hanging_slaves():
def hang():
while True:
time.sleep(5.0)
def interrupt():
raise RuntimeError
actions = {
"A": hang,
"B": hang,
}
with pytest.raises(RuntimeError):
MultiProcessInvoker(
actions, interruption_timeout=datetime.timedelta(seconds=1.0)).invoke[interrupt]()
| StarcoderdataPython |
4826490 | import math
import os
import re
from multiprocessing import Pool
from collections import defaultdict
import tables
import numpy as np
from astropy.io import fits
from astropy.table import Table
from beast.observationmodel.noisemodel.generic_noisemodel import get_noisemodelcat
from beast.physicsmodel.grid import SEDGrid
# from beast.external import eztables
from beast.fitting.fit import save_pdf1d
from beast.fitting.fit_metrics import percentile
from beast.tools import read_beast_data
def uniform_slices(num_points, num_slices):
q = num_points // num_slices
r = num_points % num_slices
slices = []
for i in range(num_slices):
if i < r:
start = i * (q + 1)
stop = start + q + 1
# After the remainder has been taken care of, do strides of q
else:
start = r * (q + 1) + (i - r) * q
stop = start + q
slices.append(slice(start, stop))
return slices
def split_grid(grid_fname, num_subgrids, overwrite=False):
"""
Splits a spectral or sed grid (they are the same class actually)
according to grid point index (so basically, arbitrarily).
Parameters
----------
grid_fname: string
file name of the existing grid to be split up
num_subgrids: integer
the number of parts the grid should be split into
overwrite: bool
any subgrids that already exist will be deleted if set to True.
If set to False, skip over any grids that are already there.
Returns
-------
list of string
the names of the newly created subgrid files
"""
g = SEDGrid(grid_fname, backend="disk")
fnames = []
num_seds = len(g.seds)
slices = uniform_slices(num_seds, num_subgrids)
for i, slc in enumerate(slices):
subgrid_fname = grid_fname.replace(".hd5", "sub{}.hd5".format(i))
fnames.append(subgrid_fname)
if os.path.isfile(subgrid_fname):
if overwrite:
os.remove(subgrid_fname)
else:
print("{} already exists. Skipping.".format(subgrid_fname))
continue
print("constructing subgrid " + str(i))
# Load a slice as a SEDGrid object
sub_g = SEDGrid(
g.lamb[:], seds=g.seds[slc], grid=Table(g.grid[slc]), backend="memory",
)
if g.filters is not None:
sub_g.header["filters"] = " ".join(g.filters)
# Save it to a new file
sub_g.write(subgrid_fname, append=False)
return fnames
def merge_grids(seds_fname, sub_names):
"""
Merges a set of grids into one big grid. The grids need to have the
same columns
Parameters
----------
seds_fname: string
path for the output file
sub_names: list of strings
paths for the input grids
"""
if not os.path.isfile(seds_fname):
for n in sub_names:
print("Appending {} to {}".format(n, seds_fname))
g = SEDGrid(n)
g.write(seds_fname, append=True)
else:
print("{} already exists".format(seds_fname))
def subgrid_info(grid_fname, noise_fname=None):
"""
Generates a list of mins and maxes of all the quantities in the given grid
Parameters
----------
grid_fname: string
path to a beast grid file (hd5 format)
noise_fname: string
Path to the noise model file for the given grid (hd5 format)
(optional). If this is given, the mins/maxes for the full model
fluxes are added too, under the name 'log'+filter+'_wd_bias'
(needs to conform to the name used in fit.py).
Returns
-------
info_dict: dictionary
{name of quantity [string]: {'min': min, 'max': max, 'unique': unique values}}
"""
# Use the disk backend to minimize the memory usage
sedgrid = SEDGrid(grid_fname, backend="disk")
seds = sedgrid.seds
info_dict = {}
qnames = sedgrid.keys()
for q in qnames:
qvals = sedgrid[q]
qmin = np.amin(qvals)
qmax = np.amax(qvals)
qunique = np.unique(qvals)
info_dict[q] = {}
info_dict[q]["min"] = qmin
info_dict[q]["max"] = qmax
info_dict[q]["unique"] = qunique
if noise_fname is not None:
noisemodel = get_noisemodelcat(noise_fname)
# The following is also in fit.py, so we're kind of doing double
# work here, but it's necessary if we want to know the proper
# ranges for these values.
full_model_flux = seds[:] + noisemodel["bias"]
logtempseds = np.array(full_model_flux)
full_model_flux = (
np.sign(logtempseds)
* np.log1p(np.abs(logtempseds * math.log(10)))
/ math.log(10)
)
filters = sedgrid.filters
for i, f in enumerate(filters):
f_fluxes = full_model_flux[:, i]
# Be sure to cut out the -100's in the calculation of the minimum
qmin = np.amin(f_fluxes[f_fluxes > -99.99])
qmax = np.amax(f_fluxes)
qunique = np.unique(qvals)
q = "symlog" + f + "_wd_bias"
info_dict[q] = {}
info_dict[q]["min"] = qmin
info_dict[q]["max"] = qmax
info_dict[q]["unique"] = qunique
print("Gathered grid info for {}".format(grid_fname))
return info_dict
def unpack_and_subgrid_info(x):
"""
Utility to call this function in parallel, with multiple arguments
"""
return subgrid_info(*x)
def reduce_grid_info(grid_fnames, noise_fnames=None, nprocs=1, cap_unique=1000):
"""
Computes the total minimum and maximum of the necessary quantities
across all the subgrids. Can run in parallel.
Parameters
----------
grid_fnames: list of str
subgrid file paths
noise_fnames: list of str (optional)
noise file for each subgrid
nprocs: int
Number of processes to use
cap_unique: int
Stop keeping track of the number of unique values once it
reaches this cap. This reduces the memory usage. (Typically, for
the fluxes, there are as many unique values as there are grid
points. Since we need to store all these values to check if
they're unique, a whole column of the grid is basically being
stored. This cap fixes this, and everything should keep working
in the rest of the code as long as cap_unique is larger than
whatever number of bins is being used.).
Returns
-------
info_dict: dictionary
{name of quantity: (min, max), ...}
"""
# Gather the mins and maxes for the subgrid
if noise_fnames is None:
arguments = [(g, None) for g in grid_fnames]
else:
arguments = list(zip(grid_fnames, noise_fnames))
# Use generators here for memory efficiency
parallel = nprocs > 1
if parallel:
p = Pool(nprocs)
info_dicts_generator = p.imap(unpack_and_subgrid_info, arguments)
else:
info_dicts_generator = (subgrid_info(*a) for a in arguments)
# Assume that all info dicts have the same keys
first_info_dict = next(info_dicts_generator)
qs = [q for q in first_info_dict]
union_min = {}
union_max = {}
union_unique = {}
# This last field can take up a lot of memory. A solution would be
# to allow a maximum number of values (50 is the default maximum
# number of bins anyway, and this value is needed to determine the
# number of bins).
for q in qs:
# Combine the values of the first subgrid
union_min[q] = first_info_dict[q]["min"]
union_max[q] = first_info_dict[q]["max"]
union_unique[q] = first_info_dict[q]["unique"]
# And all the other subgrids (the generator just continues)
for individual_dict in info_dicts_generator:
for q in qs:
union_min[q] = min(union_min[q], individual_dict[q]["min"])
union_max[q] = max(union_max[q], individual_dict[q]["max"])
if len(union_unique[q]) < cap_unique:
union_unique[q] = np.union1d(
union_unique[q], individual_dict[q]["unique"]
)
result_dict = {}
for q in qs:
result_dict[q] = {
"min": union_min[q],
"max": union_max[q],
"num_unique": len(union_unique[q]),
}
return result_dict
def merge_pdf1d_stats(
subgrid_pdf1d_fnames, subgrid_stats_fnames, re_run=False, output_fname_base=None
):
"""
Merge a set of 1d pdfs that were generated by fits on different
grids. It is necessary (and checked) that all the 1d pdfs have the
same limits, bin values, and number of bins.
The stats files are also combined; some values for the total grid
can be calculated by simply comparing them across all the grids,
others are recalculated after obtaining the new 1dpdfs.
Parameters
----------
subgrid_pdf1d_fnames: list of string
file names of all the pdf1d fits files
subgrid_stats_fnames: list of string
file names of the stats files. Should be in the same order as
subgrid_pdf1d_fnames. These files are needed to help with
averaging the pdf1d files as they contain the total weight of
each subgrid.
re_run: boolean (default=False)
If True, re-run the merging, even if the merged files already
exist. If False, will only merge files if they don't exist.
output_fname_base: string (default=None)
If set, this will prepend the output 1D PDF and stats file names
Returns
-------
merged_pdf1d_fname, merged_stats_fname: string, string
file name of the resulting pdf1d and stats fits files (newly
created by this function)
"""
# -------------
# before running, check if the files already exist
# (unless the user wants to re-create them regardless)
# 1D PDF
if output_fname_base is not None:
pdf1d_fname = output_fname_base + "_pdf1d.fits"
else:
pdf1d_fname = "combined_pdf1d.fits"
# stats
if output_fname_base is None:
stats_fname = "combined_stats.fits"
else:
stats_fname = output_fname_base + "_stats.fits"
if (
os.path.isfile(pdf1d_fname)
and os.path.isfile(stats_fname)
and (re_run is False)
):
print(str(len(subgrid_pdf1d_fnames)) + " files already merged, skipping")
return pdf1d_fname, stats_fname
# -------------
nsubgrids = len(subgrid_pdf1d_fnames)
if not len(subgrid_stats_fnames) == nsubgrids:
raise AssertionError()
nbins = {}
with fits.open(subgrid_pdf1d_fnames[0]) as hdul_0:
# Get this useful information
qnames = [hdu.name for hdu in hdul_0[1:]]
nbins = {q: hdul_0[q].data.shape[1] for q in qnames}
bincenters = {q: hdul_0[q].data[-1, :] for q in qnames}
nobs = hdul_0[qnames[0]].data.shape[0] - 1
# Check the following bin parameters for each of the other
# subgrids
for pdf1d_f in subgrid_pdf1d_fnames[1:]:
with fits.open(pdf1d_f) as hdul:
for q in qnames:
pdf1d_0 = hdul_0[q].data
pdf1d = hdul[q].data
# the number of bins
if not pdf1d_0.shape[1] == pdf1d.shape[1]:
raise AssertionError()
# the number of stars + 1
if not pdf1d_0.shape[0] == pdf1d.shape[0]:
raise AssertionError()
# the bin centers (stored in the last row of the
# image) should be equal (or both nan)
if not (
np.isnan(pdf1d_0[-1, 0])
and np.isnan(pdf1d[-1, 0])
or (pdf1d_0[-1, :] == pdf1d[-1, :]).all()
):
raise AssertionError()
# Load all the stats files
stats = [Table.read(f, hdu=1) for f in subgrid_stats_fnames]
try:
filters_tab = Table.read(subgrid_stats_fnames[0], hdu=2)
except ValueError:
filters_tab = None
# First, let's read the arrays of weights (each subgrid has an array
# of weights, containing one weight for each source).
logweight = np.zeros((nobs, nsubgrids))
for i, s in enumerate(stats):
logweight[:, i] = s["total_log_norm"]
# Best grid for each star (take max along grid axis)
maxweight_index_per_star = np.argmax(logweight, axis=1)
# Grab the max values, too
max_logweight = logweight[range(len(logweight)), maxweight_index_per_star]
# Get linear weights for each object/grid. By casting the maxima
# into a column shape, the subtraction will be done for each column
# (broadcasted).
weight = np.exp(logweight - max_logweight[:, np.newaxis])
# ------------------------------------------------------------------------
# PDF1D
# ------------------------------------------------------------------------
# We will try to reuse the save function defined in fit.py
save_pdf1d_vals = []
for i, q in enumerate(qnames):
# Prepare the ouput array
save_pdf1d_vals.append(np.zeros((nobs + 1, nbins[q])))
# Copy the bin centers
save_pdf1d_vals[i][-1, :] = bincenters[q]
# Now, go over all the pdf1d files, and sum the weighted pdf1d values
for g, pdf1d_f in enumerate(subgrid_pdf1d_fnames):
with fits.open(pdf1d_f) as hdul:
for i, q in enumerate(qnames):
pdf1d_g = hdul[q].data[:-1, :]
weight_column = weight[:, [g]] # use [g] to keep dimension
save_pdf1d_vals[i][:-1, :] += pdf1d_g * weight_column
# Normalize all the pdfs of the final result
for i in range(len(save_pdf1d_vals)):
# sum for each source in a column
norms_col = np.sum(save_pdf1d_vals[i][:-1, :], axis=1, keepdims=True)
# non zero mask as 1d array
nonzero = norms_col[:, 0] > 0
save_pdf1d_vals[i][:-1][nonzero, :] /= norms_col[nonzero]
# Save the combined 1dpdf file
save_pdf1d(pdf1d_fname, save_pdf1d_vals, qnames)
# ------------------------------------------------------------------------
# STATS
# ------------------------------------------------------------------------
# Grid with highest Pmax, for each star
pmaxes = np.zeros((nobs, nsubgrids))
for gridnr in range(nsubgrids):
pmaxes[:, gridnr] = stats[gridnr]["Pmax"]
max_pmax_index_per_star = pmaxes.argmax(axis=1)
# Rebuild the stats
stats_dict = {}
for col in stats[0].colnames:
suffix = col.split("_")[-1]
if suffix == "Best":
# For the best values, we take the 'Best' value of the grid
# with the highest Pmax
stats_dict[col] = [
stats[gridnr][col][e]
for e, gridnr in enumerate(max_pmax_index_per_star)
]
elif suffix == "Exp":
# Sum and weigh the expectation values
stats_dict[col] = np.zeros(nobs)
total_weight_per_star = np.zeros(nobs)
for gridnr, s in enumerate(stats):
grid_weight_per_star = weight[:, gridnr]
stats_dict[col] += stats[gridnr][col] * grid_weight_per_star
total_weight_per_star += grid_weight_per_star
stats_dict[col] /= total_weight_per_star
elif re.compile(r"p\d{1,2}$").match(suffix):
# Grab the percentile value
digits = suffix[1:]
p = int(digits)
# Find the correct quantity (the col name without the
# '_'+suffix), and its position in save_pdf1d_vals.
qname = col[: -len(suffix) - 1]
qindex = qnames.index(qname)
# Recalculate the new percentiles from the newly obtained
# 1dpdf. For each star, call the percentile function.
stats_dict[col] = np.zeros(nobs)
for e in range(nobs):
bins = save_pdf1d_vals[qindex][-1]
vals = save_pdf1d_vals[qindex][e]
if vals.max() > 0:
stats_dict[col][e] = percentile(bins, [p], vals)[0]
else:
stats_dict[col][e] = 0
elif col == "chi2min":
# Take the lowest chi2 over all the grids
all_chi2s = np.zeros((nobs, nsubgrids))
for gridnr, s in enumerate(stats):
all_chi2s[:, gridnr] = s[col]
stats_dict[col] = np.amin(all_chi2s, axis=1)
elif col == "Pmax":
all_pmaxs = np.zeros((nobs, nsubgrids))
for gridnr, s in enumerate(stats):
all_pmaxs[:, gridnr] = s[col]
stats_dict[col] = np.amax(all_pmaxs, axis=1)
elif col == "Pmax_indx":
# index of the Pmax (to be useful, must be combined with best_gridsub_tag)
all_pmax_ind = np.zeros((nobs, nsubgrids), dtype=int)
for gridnr, s in enumerate(stats):
all_pmax_ind[:, gridnr] = s[col]
stats_dict[col] = all_pmax_ind[np.arange(nobs), max_pmax_index_per_star]
elif col == "total_log_norm":
stats_dict[col] = np.log(weight.sum(axis=1)) + max_logweight
# For anything else, just copy the values from grid 0. Except
# for the index fields. Those don't make sense when using
# subgrids. They might in the future though. The grid split
# function and some changes to the processesing might help with
# this. Actually specgrid_indx might make sense, since in my
# particular case I'm splitting after the spec grid has been
# created. Still leaving this out though.
elif not col == "chi2min_indx" and not col == "specgrid_indx":
stats_dict[col] = stats[0][col]
# also save the highest Pmax grid number
stats_dict["best_gridsub_tag"] = max_pmax_index_per_star
# save table to a file
ohdu = fits.HDUList()
ohdu.append(fits.table_to_hdu(Table(stats_dict)))
if filters_tab is not None:
ohdu.append(fits.table_to_hdu(filters_tab))
ohdu.writeto(stats_fname, overwrite=True)
print("Saved combined 1dpdfs in " + pdf1d_fname)
print("Saved combined stats in " + stats_fname)
return pdf1d_fname, stats_fname
def merge_lnp(
subgrid_lnp_fnames, re_run=False, output_fname_base=None, threshold=None,
):
"""
Merge a set of sparsely sampled log likelihood (lnp) files. It is assumed
that they are for each part of a subgrid, such that a given star_# in each
file corresponds to the same star_# in the other file(s). Note that this
should NOT be used to combine files across source density or background bin.
Parameters
----------
subgrid_lnp_fnames: list of string
file names of all the lnp fits files
re_run: boolean (default=False)
If True, re-run the merging, even if the merged files already
exist. If False, will only merge files if they don't exist.
output_fname_base: string (default=None)
If set, this will prepend the output lnp file name
threshold : float (default=None)
If set: for a given star, any lnP values below max(lnP)-threshold will
be deleted
Returns
-------
merged_lnp_fname : string
file name of the resulting lnp fits file (newly created by this function)
"""
# create filename
if output_fname_base is None:
merged_lnp_fname = "combined_lnp.hd5"
else:
merged_lnp_fname = output_fname_base + "_lnp.hd5"
# check if we need to rerun
if os.path.isfile(merged_lnp_fname) and (re_run is False):
print(str(len(subgrid_lnp_fnames)) + " files already merged, skipping")
return merged_lnp_fname
# dictionaries to compile all the info
merged_lnp = defaultdict(list)
merged_subgrid = defaultdict(list)
merged_idx = defaultdict(list)
for fname in subgrid_lnp_fnames:
# extract subgrid number from filename
subgrid_num = [i for i in fname.split("_") if "gridsub" in i][0][7:]
# read in the SED indices and lnP values
lnp_data = read_beast_data.read_lnp_data(fname, shift_lnp=False)
n_lnp, n_star = lnp_data["vals"].shape
# save each star's values into the master dictionary
for i in range(n_star):
merged_lnp["star_" + str(i)] += lnp_data["vals"][:, i].tolist()
merged_idx["star_" + str(i)] += lnp_data["indxs"][:, i].tolist()
merged_subgrid["star_" + str(i)] += np.full(
n_lnp, int(subgrid_num)
).tolist()
# go through each star and remove values that are too small
if threshold is not None:
# keep track of how long the list of good values is
good_list_len = np.zeros(n_star)
# go through each star
for i in range(n_star):
star_label = "star_" + str(i)
# good indices
keep_ind = np.where(
(np.array(merged_lnp[star_label]) - max(merged_lnp[star_label]))
> threshold
)[0]
good_list_len[i] = len(keep_ind)
# save just those
merged_lnp[star_label] = np.array(merged_lnp[star_label])[keep_ind].tolist()
merged_idx[star_label] = np.array(merged_idx[star_label])[keep_ind].tolist()
merged_subgrid[star_label] = np.array(merged_subgrid[star_label])[
keep_ind
].tolist()
# figure out how many padded -inf/nan values need to be appended to make
# each list the same length
n_list_pad = np.max(good_list_len) - good_list_len
else:
# no list padding if there's no trimming for threshold
n_list_pad = np.zeros(n_star)
# write out the things in a new file
with tables.open_file(merged_lnp_fname, "w") as out_table:
for i in range(n_star):
star_label = "star_" + str(i)
star_group = out_table.create_group("/", star_label, title=star_label)
out_table.create_array(
star_group,
"idx",
np.array(merged_idx[star_label] + int(n_list_pad[i]) * [np.nan]),
)
out_table.create_array(
star_group,
"lnp",
np.array(merged_lnp[star_label] + int(n_list_pad[i]) * [-np.inf]),
)
out_table.create_array(
star_group,
"subgrid",
np.array(merged_subgrid[star_label] + int(n_list_pad[i]) * [np.nan]),
)
return merged_lnp_fname
| StarcoderdataPython |
1742137 | """
Know more, visit my Python tutorial page: https://morvanzhou.github.io/tutorials/
My Youtube Channel: https://www.youtube.com/user/MorvanZhou
Dependencies:
tensorflow: 1.1.0
numpy
"""
import tensorflow as tf
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
tf.set_random_seed(1)
np.random.seed(1)
# fake data
x = np.linspace(-1, 1, 100)[:, np.newaxis] # shape (100, 1)
noise = np.random.normal(0, 0.1, size=x.shape)
y = np.power(x, 2) + noise # shape (100, 1) + some noise
with tf.variable_scope('Inputs'):
tf_x = tf.placeholder(tf.float32, x.shape, name='x')
tf_y = tf.placeholder(tf.float32, y.shape, name='y')
with tf.variable_scope('Net'):
l1 = tf.layers.dense(tf_x, 10, tf.nn.relu, name='hidden_layer')
output = tf.layers.dense(l1, 1, name='output_layer')
# add to histogram summary
tf.summary.histogram('h_out', l1)
tf.summary.histogram('pred', output)
loss = tf.losses.mean_squared_error(tf_y, output, scope='loss')
train_op = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(loss)
tf.summary.scalar('loss', loss) # add loss to scalar summary
sess = tf.Session()
sess.run(tf.global_variables_initializer())
writer = tf.summary.FileWriter('./log', sess.graph) # write to file
merge_op = tf.summary.merge_all() # operation to merge all summary
for step in range(100):
# train and net output
_, result = sess.run([train_op, merge_op], {tf_x: x, tf_y: y})
writer.add_summary(result, step)
# Lastly, in your terminal or CMD, type this :
# $ tensorboard --logdir path/to/log
# open you google chrome, type the link shown on your terminal or CMD. (something like this: http://localhost:6006) | StarcoderdataPython |
36111 | <filename>instances/migrations/0001_initial.py
# Generated by Django 2.2.10 on 2020-01-28 07:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('computes', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Instance',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=120)),
('uuid', models.CharField(max_length=36)),
('is_template', models.BooleanField(default=False)),
('created', models.DateField(auto_now_add=True)),
('compute', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='computes.Compute')),
],
),
]
| StarcoderdataPython |
4829042 | <gh_stars>0
from paperplane.cli.parser import cli
from paperplane.parser.main import parse_and_execute # noqa: F401
def main():
"""Entry point for the application script"""
cli()
| StarcoderdataPython |
3228586 | import string
from collections import defaultdict
from collections.abc import Callable, Mapping
from functools import partial
from typing import Any, Iterable, Optional
import parse
from arti.fingerprints import Fingerprint
from arti.internal.utils import frozendict
from arti.partitions import CompositeKey, CompositeKeyTypes, PartitionKey
InputFingerprints = frozendict[CompositeKey, Fingerprint]
class Placeholder:
def __init__(self, key: str) -> None:
self._key = key
class FormatPlaceholder(Placeholder):
def __format__(self, spec: str) -> str:
result = self._key
if spec:
result += ":" + spec
return "{" + result + "}"
def __getitem__(self, key: Any) -> "FormatPlaceholder":
self._key = f"{self._key}[{key}]"
return self
def __getattr__(self, attr: str) -> "FormatPlaceholder":
self._key = f"{self._key}.{attr}"
return self
# Used to convert things like `/{date_key.Y[1970]` to `/{date_key.Y` so we can format in
# *real* partition key values.
class StripIndexPlaceholder(FormatPlaceholder):
def __getitem__(self, key: Any) -> "StripIndexPlaceholder":
return self
class WildcardPlaceholder(Placeholder):
def __init__(self, key: str, key_types: CompositeKeyTypes):
super().__init__(key)
if key not in key_types:
raise ValueError(f"No '{key}' partition key found, expected one of {tuple(key_types)}")
self._key_type = key_types[key]
self._attribute: Optional[str] = None # What field/key_component is being accessed
@classmethod
def with_key_types(
cls, key_types: Mapping[str, type[PartitionKey]]
) -> Callable[[str], "WildcardPlaceholder"]:
return partial(cls, key_types=key_types)
def _err_if_no_attribute(self) -> None:
if self._attribute is None:
example = sorted(self._key_type.key_components)[0]
raise ValueError(
f"'{self._key}' cannot be used directly in a partition path; access one of the key components (eg: '{self._key}.{example}')."
)
def __getattr__(self, name: str) -> "WildcardPlaceholder":
if self._attribute is not None:
raise ValueError(
f"'{self._key}.{self._attribute}.{name}' cannot be used in a partition path; only immediate '{self._key}' attributes (such as '{self._attribute}') can be used."
)
if name not in self._key_type.key_components:
raise AttributeError(
f"'{self._key_type.__name__}' has no field or key component '{name}'"
)
self._attribute = name
return self
def __getitem__(self, key: Any) -> Any:
self._err_if_no_attribute()
# Pass through "hard coded" partition parts, eg: "{date.Y:2021}" -> format_spec="2021".
#
# TODO: Should we validate the key against the key_type/attribute type?
return key
def __str__(self) -> str:
self._err_if_no_attribute()
return "*"
# NOTE: We might pre-populate this with the Graph tags so the hard coded templates are already available (rather than
# being filled in with a WildcardPlaceholder).
class FormatDict(dict[str, Any]):
def __init__(
self,
placeholder_type: Callable[[str], Placeholder],
/,
*args: Iterable[tuple[str, Any]],
**kwargs: Any,
) -> None:
super().__init__(*args, **kwargs)
self.placeholder_type = placeholder_type
def __missing__(self, key: str) -> Placeholder:
return self.placeholder_type(key)
def partial_format(spec: str, **kwargs: Any) -> str:
return string.Formatter().vformat(spec, (), FormatDict(FormatPlaceholder, **kwargs))
# This is hacky...
def strip_partition_indexes(spec: str) -> str:
return string.Formatter().vformat(spec, (), FormatDict(StripIndexPlaceholder))
def spec_to_wildcard(spec: str, key_types: Mapping[str, type[PartitionKey]]) -> str:
return string.Formatter().vformat(
spec.replace("{input_fingerprint}", "*"),
(),
FormatDict(WildcardPlaceholder.with_key_types(key_types)),
)
def extract_placeholders(
*,
error_on_no_match: bool = True,
key_types: Mapping[str, type[PartitionKey]],
parser: parse.Parser,
path: str,
spec: str,
) -> Optional[tuple[Fingerprint, CompositeKey]]:
parsed_value = parser.parse(path)
if parsed_value is None:
if error_on_no_match:
raise ValueError(f"Unable to parse '{path}' with '{spec}'.")
return None
input_fingerprint = Fingerprint.empty()
key_components = defaultdict[str, dict[str, str]](dict)
for k, v in parsed_value.named.items():
if k == "input_fingerprint":
assert isinstance(v, str)
input_fingerprint = Fingerprint.from_int(int(v))
continue
key, component = k.split(".")
# parsing a string like "{date.Y[1970]}" will return a dict like {'1970': '1970'}.
if isinstance(v, dict):
v = tuple(v)[0]
key_components[key][component] = v
keys = {
key: key_types[key].from_key_components(**components)
for key, components in key_components.items()
}
if set(keys) != set(key_types):
raise ValueError(
f"Expected to find partition keys for {sorted(key_types)}, only found {sorted(keys)}. Is the partitioning spec ('{spec}') complete?"
)
return input_fingerprint, frozendict(keys)
def parse_spec(
paths: set[str],
*,
input_fingerprints: InputFingerprints = InputFingerprints(),
key_types: Mapping[str, type[PartitionKey]],
spec: str,
) -> Mapping[str, tuple[Fingerprint, CompositeKey]]:
parser = parse.compile(spec, case_sensitive=True)
path_placeholders = (
(path, placeholders)
for path in paths
if (
placeholders := extract_placeholders(
parser=parser, path=path, spec=spec, key_types=key_types
)
)
is not None
)
return {
path: (input_fingerprint, keys)
for (path, (input_fingerprint, keys)) in path_placeholders
if input_fingerprints.get(keys, Fingerprint.empty()) == input_fingerprint
}
| StarcoderdataPython |
3297534 | from functools import reduce
from math import exp, log
from random import uniform
from datasetloader.Dataset import Dataset
def sigmoid(x: float) -> float:
return 1 / (1 + exp(-x))
class Neuron:
ins: [float]
weights: [float]
out: float
def __init__(self, nb_ins: int):
self.weights = [uniform(-2, 2) for _ in range(nb_ins + 1)]
def activate(self, entries: [float]) -> None:
sp = reduce(self.ponderate, zip(entries, self.weights[1:]), self.weights[0])
self.out = sigmoid(sp)
@staticmethod
def ponderate(acc: float, e: (float, float)) -> float:
return acc + e[0] * e[1]
def calc_loss(self, ds: Dataset) -> float:
ds.normalize()
loss = 0
for e in ds.examples:
self.activate(e.ins)
loss += self.loss_func(e.outs, [self.out])
return loss / len(ds.examples)
@staticmethod
def loss_func(yrange: [float], hxrange: [float]) -> float:
return -sum([
(y * log(hx) + (1 - y) * log(1 - hx)) for y, hx in zip(yrange, hxrange)
])
| StarcoderdataPython |
1685202 | <filename>TagScriptEngine/interface/__init__.py
from .adapter import Adapter
from .block import Block, verb_required_block
__all__ = ("Adapter", "Block", "verb_required_block")
| StarcoderdataPython |
3252998 | <reponame>mhostetter/galois<filename>tests/fields/test_field_trace.py
"""
A pytest module to test the traces over finite fields.
Sage:
F = GF(2**5, repr="int")
y = []
for x in range(0, F.order()):
x = F.fetch_int(x)
y.append(x.trace())
print(y)
"""
import pytest
import numpy as np
import galois
def test_exceptions():
with pytest.raises(TypeError):
GF = galois.GF(3)
x = GF.Elements()
y = x.field_trace()
def test_shapes():
# NOTE: 1-D arrays are tested in other tests
GF = galois.GF(3**3)
x = GF.Elements()
y_truth = [0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]
# Scalar
y0 = x[0].field_trace()
assert np.array_equal(y0, y_truth[0])
assert isinstance(y0, GF.prime_subfield)
# N-D
y = x.reshape((3,3,3)).field_trace()
assert np.array_equal(y, np.array(y_truth).reshape(3,3,3))
assert isinstance(y0, GF.prime_subfield)
def test_binary_extension_1():
GF = galois.GF(2**3)
x = GF.Elements()
y = x.field_trace()
y_truth = [0, 1, 0, 1, 0, 1, 0, 1]
assert np.array_equal(y, y_truth)
assert isinstance(y, GF.prime_subfield)
def test_binary_extension_2():
GF = galois.GF(2**4)
x = GF.Elements()
y = x.field_trace()
y_truth = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]
assert np.array_equal(y, y_truth)
assert isinstance(y, GF.prime_subfield)
def test_binary_extension_3():
# Use an irreducible, but not primitive, polynomial
GF = galois.GF(2**4, irreducible_poly="x^4 + x^3 + x^2 + x + 1")
x = GF.Elements()
y = x.field_trace()
y_truth = [0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1]
assert np.array_equal(y, y_truth)
assert isinstance(y, GF.prime_subfield)
def test_binary_extension_4():
GF = galois.GF(2**5)
x = GF.Elements()
y = x.field_trace()
y_truth = [0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0]
assert np.array_equal(y, y_truth)
assert isinstance(y, GF.prime_subfield)
def test_prime_extension_1():
GF = galois.GF(3**2)
x = GF.Elements()
y = x.field_trace()
y_truth = [0, 2, 1, 1, 0, 2, 2, 1, 0]
assert np.array_equal(y, y_truth)
assert isinstance(y, GF.prime_subfield)
def test_prime_extension_2():
GF = galois.GF(3**3)
x = GF.Elements()
y = x.field_trace()
y_truth = [0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]
assert np.array_equal(y, y_truth)
assert isinstance(y, GF.prime_subfield)
def test_prime_extension_3():
GF = galois.GF(5**2)
x = GF.Elements()
y = x.field_trace()
y_truth = [0, 2, 4, 1, 3, 1, 3, 0, 2, 4, 2, 4, 1, 3, 0, 3, 0, 2, 4, 1, 4, 1, 3, 0, 2]
assert np.array_equal(y, y_truth)
assert isinstance(y, GF.prime_subfield)
def test_property_1():
"""
L = GF(q^n)
K = GF(q)
a in L
Tr(a^q) = Tr(a)
"""
q = 7
n = 3
L = galois.GF(q**n)
a = L.Random(10)
assert np.array_equal((a**q).field_trace(), a.field_trace())
| StarcoderdataPython |
4821956 | <gh_stars>0
from hestia.service_interface import LazyServiceWrapper
from django.conf import settings
from conf.option_manager import option_manager
from conf.service import ConfService
def get_conf_backend():
return settings.CONF_BACKEND or 'conf.cluster_conf_service.ClusterConfService'
backend = LazyServiceWrapper(
backend_base=ConfService,
backend_path=get_conf_backend(),
options={}
)
backend.expose(locals())
subscribe = option_manager.subscribe
| StarcoderdataPython |
4808528 | <reponame>gurupratap-matharu/Exercism
"""Script to find pairs of three numbers in an array whose sum is zero"""
import itertools
def find_three_sum_pairs(nums):
"""
Finds unique pairs of three numbers in the array whose sum is zero
"""
pairs = []
for t in itertools.combinations(nums, 3):
if not sum(t):
pairs.append(sorted(t))
pairs = sorted(pairs)
return [pairs for pairs, _ in itertools.groupby(pairs)]
if __name__ == "__main__":
nums = [-1, 0]
res = find_three_sum_pairs(nums)
print(res)
| StarcoderdataPython |
3277991 | <gh_stars>1-10
from hypothesis.utils.conventions import not_set
def accept(f):
def tuples(*args):
return f(*args)
return tuples
| StarcoderdataPython |
3293233 | <reponame>iroan/Practicing-Federated-Learning
import torch
from torchvision import models
def get_model(name="vgg16", pretrained=True):
if name == "resnet18":
model = models.resnet18(pretrained=pretrained)
elif name == "resnet50":
model = models.resnet50(pretrained=pretrained)
elif name == "densenet121":
model = models.densenet121(pretrained=pretrained)
elif name == "alexnet":
model = models.alexnet(pretrained=pretrained)
elif name == "vgg16":
model = models.vgg16(pretrained=pretrained)
elif name == "vgg19":
model = models.vgg19(pretrained=pretrained)
elif name == "inception_v3":
model = models.inception_v3(pretrained=pretrained)
elif name == "googlenet":
model = models.googlenet(pretrained=pretrained)
if torch.cuda.is_available():
return model.cuda()
else:
return model | StarcoderdataPython |
3230299 | import os
import csv
from shopify_csv import ShopifyRow
def get_template_rows():
with open(
os.path.join(
os.getcwd(), "shopify_csv", "tests", "fixtures", "product_template.csv"
),
"r",
) as file:
reader = csv.reader(file, delimiter=";")
return [row for row in reader]
def get_shopify_rows():
return_rows = []
return_rows.append(ShopifyRow.FIELDS)
row = ShopifyRow()
row.handle = "example-product"
row.title = "Some product"
row.vendor = "Vendor"
row.type = "product"
row.tags = "tag1"
row.published = True
row.option1_name = "Title"
row.option1_value = "Some option value"
row.variant_grams = 3629
row.variant_inventory_policy = "deny"
row.variant_fulfillment_service = "manual"
row.variant_price = 25
row.variant_requires_shipping = True
row.variant_taxable = True
row.image_src = "https://test.com/product.jpg"
row.image_position = 1
row.gift_card = False
row.seo_title = "Seo title."
row.seo_description = "Description"
row.google_shopping_google_product_category = "Products > Products"
row.google_shopping_gender = "Unisex"
row.google_shopping_age_group = "Adult"
row.google_shopping_mpn = "man"
row.google_shopping_adwords_grouping = "products"
row.google_shopping_adwords_labels = "labels"
row.google_shopping_condition = "used"
row.google_shopping_custom_product = "FALSE"
row.variant_weight_unit = "g"
row.status = "active"
row.validate_required_fields()
return_rows.append(row.writable)
row = ShopifyRow()
row.handle = "example-t-shirt"
row.option1_value = "Small"
row.variant_sku = "example-product-s"
row.variant_grams = 200
row.variant_inventory_policy = "deny"
row.variant_fulfillment_service = "manual"
row.variant_price = 29.99
row.variant_compare_at_price = 34.99
row.variant_requires_shipping = True
row.variant_taxable = True
row.variant_weight_unit = "g"
row.validate_required_fields(is_variant=True)
return_rows.append(row.writable)
row = ShopifyRow()
row.handle = "example-t-shirt"
row.option1_value = "Medium"
row.variant_sku = "example-product-m"
row.variant_grams = 200
row.variant_inventory_tracker = "shopify"
row.variant_inventory_policy = "deny"
row.variant_fulfillment_service = "manual"
row.variant_price = 29.99
row.variant_compare_at_price = 34.99
row.variant_requires_shipping = True
row.variant_taxable = True
row.variant_weight_unit = "g"
row.validate_required_fields(is_variant=True)
return_rows.append(row.writable)
return return_rows
def test_should_produce_template_csv():
template_rows = get_template_rows()
shopify_rows = get_shopify_rows()
for template_row, shopify_row in zip(template_rows, shopify_rows):
for field1, field2 in zip(template_row, shopify_row):
assert field1 == field2
| StarcoderdataPython |
1751756 | import datetime
import string
from django import forms
from django.contrib.auth import (
authenticate, get_user_model, password_validation,
)
from django.contrib.auth.forms import _unicode_ci_compare, SetPasswordForm
from django.contrib.auth.password_validation import validate_password
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ValidationError
from django.core.mail import EmailMultiAlternatives
from django.core.validators import RegexValidator
from django.forms import ModelForm
from django.template import loader
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.utils.translation import gettext_lazy as _
from meals.models import Meal
from .models import User
from orderitems.models import OrderItem
UserModel = get_user_model()
years = []
for year in range(1900,2022):
years.append(year)
class UserSignUpForm(forms.ModelForm):
"""
A custom form used by UserSignUpView for when an unauthenticated user creates an account.
Widgets for each field are assigned so that a bootstrap class of 'form-control' could be added
to each widget. The date_of_birth field's input format is set as MM/DD/YYYY in the widget.
"""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class':'form-control'}))
password2 = forms.CharField(label='<PASSWORD>', widget=forms.PasswordInput(attrs={'class':'form-control'}))
date_of_birth = forms.DateField(label='Birthday', initial= datetime.date.today(), widget=forms.SelectDateWidget(years=years, attrs={'class': 'form-control'}))
class Meta:
model = User
fields = ('email','name', 'date_of_birth', 'phone_number', 'street_address', 'city', 'state', 'zip_code')
widgets = {
'email': forms.EmailInput(attrs={'class': 'form-control'}),
'name': forms.TextInput(attrs={'class': 'form-control'}),
'phone_number': forms.TextInput(attrs={'class': 'form-control'}),
'street_address': forms.TextInput(attrs={'class': 'form-control'}),
'city': forms.TextInput(attrs={'class': 'form-control'}),
'state': forms.Select(attrs={'class': 'form-control'}),
'zip_code': forms.TextInput(attrs={'class': 'form-control'}),
}
labels = {
'name': 'Full name'
}
def clean_email(self):
email = self.cleaned_data['email']
return email.lower()
# return email
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
validate_password(password2)
return password2
def save(self, *args, **kwargs):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password2"])
user.save()
return user
class UserUpdateForm(forms.ModelForm):
"""
A custom form used by UserProfileUpdateView to allow authenticated users to update their profile
information. Widgets for each field are assigned so that a bootstrap class of 'form-control'
could be added to each widget. The date_of_birth field's input format is set as MM/DD/YYYY in the widget.
"""
class Meta:
model = User
fields = ('name', 'date_of_birth', 'phone_number', 'street_address', 'city', 'state', 'zip_code')
widgets = {
'name': forms.TextInput(attrs={'class': 'form-control'}),
'date_of_birth': forms.SelectDateWidget(years=years, attrs={'class': 'form-control'}),
'phone_number': forms.TextInput(attrs={'class': 'form-control'}),
'street_address': forms.TextInput(attrs={'class': 'form-control'}),
'city': forms.TextInput(attrs={'class': 'form-control'}),
'state': forms.Select(attrs={'class': 'form-control'}),
'zip_code': forms.TextInput(attrs={'class': 'form-control'}),
}
labels = {
'name': 'Full name'
}
#Copied from SetPasswordForm
class CustomUserSetPasswordForm(forms.Form):
"""
A form that lets a user change set their password without entering the old
password. This was copied over from SetPasswordForm, which is used by the class_form = PasswordChangeForm that is used
by the generic PasswordChangeView. This was copied over so that the bootstrap class 'form-control' could be added
to each widget to allow for bootstrap styling.
"""
error_messages = {
'password_mismatch': _('The two password fields didn’t match.'),
}
new_password1 = forms.CharField(
label=_("New password"),
widget=forms.PasswordInput(attrs={'autocomplete': 'new-password', 'class': 'form-control'}),
strip=False,
help_text=password_validation.password_validators_help_text_html(),
)
new_password2 = forms.CharField(
label=_("New password confirmation"),
strip=False,
widget=forms.PasswordInput(attrs={'autocomplete': 'new-password', 'class': 'form-control'}),
)
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
def clean_new_password2(self):
password1 = self.cleaned_data.get('<PASSWORD>')
password2 = self.cleaned_data.get('<PASSWORD>')
if password1 and password2:
if password1 != password2:
raise ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
password_validation.validate_password(password2, self.user)
return password2
def save(self, commit=True):
password = self.cleaned_data["<PASSWORD>"]
self.user.set_password(password)
if commit:
self.user.save()
return self.user
#Copied from PasswordChangeForm
class CustomUserPasswordChangeForm(CustomUserSetPasswordForm):
"""
A form that lets a user change their password by entering their old
password. This was copied from the PasswordChangeForm, which is the class_form for the generic
PasswordChangeView. This was copied over so that the bootstrap class 'form-control' could be added
to each widget to allow for bootstrap styling.
"""
error_messages = {
**SetPasswordForm.error_messages,
'password_incorrect': _("Your old password was entered incorrectly. Please enter it again."),
}
old_password = forms.CharField(
label=_("Old password"),
strip=False,
widget=forms.PasswordInput(attrs={'autocomplete': 'current-password', 'autofocus': True, 'class':'form-control'}),
)
field_order = ['old_password', 'new_password1', 'new_password2']
def clean_old_password(self):
"""
Validate that the old_password field is correct.
"""
old_password = self.cleaned_data["old_password"]
if not self.user.check_password(old_password):
raise ValidationError(
self.error_messages['password_incorrect'],
code='password_incorrect',
)
return old_password
class CustomPasswordResetForm(forms.Form):
email = forms.EmailField(
label=_("Email"),
max_length=254,
widget=forms.EmailInput(attrs={'autocomplete': 'email', 'class': 'form-control'})
)
def send_mail(self, subject_template_name, email_template_name,
context, from_email, to_email, html_email_template_name=None):
"""
Send a django.core.mail.EmailMultiAlternatives to `to_email`.
"""
subject = loader.render_to_string(subject_template_name, context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string(email_template_name, context)
email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
if html_email_template_name is not None:
html_email = loader.render_to_string(html_email_template_name, context)
email_message.attach_alternative(html_email, 'text/html')
email_message.send()
def get_users(self, email):
"""Given an email, return matching user(s) who should receive a reset.
This allows subclasses to more easily customize the default policies
that prevent inactive users and users with unusable passwords from
resetting their password.
"""
email_field_name = UserModel.get_email_field_name()
active_users = UserModel._default_manager.filter(**{
'%s__iexact' % email_field_name: email,
'is_active': True,
})
return (
u for u in active_users
if u.has_usable_password() and
_unicode_ci_compare(email, getattr(u, email_field_name))
)
def save(self, domain_override=None,
subject_template_name='registration/password_reset_subject.txt',
email_template_name='registration/password_reset_email.html',
use_https=False, token_generator=default_token_generator,
from_email=None, request=None, html_email_template_name=None,
extra_email_context=None):
"""
Generate a one-use only link for resetting password and send it to the
user.
"""
email = self.cleaned_data["email"]
if not domain_override:
current_site = get_current_site(request)
site_name = current_site.name
domain = current_site.domain
else:
site_name = domain = domain_override
email_field_name = UserModel.get_email_field_name()
for user in self.get_users(email):
user_email = getattr(user, email_field_name)
context = {
'email': user_email,
'domain': domain,
'site_name': site_name,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'user': user,
'token': token_generator.make_token(user),
'protocol': 'https' if use_https else 'http',
**(extra_email_context or {}),
}
self.send_mail(
subject_template_name, email_template_name, context, from_email,
user_email, html_email_template_name=html_email_template_name,
)
class CustomPasswordSetForm(forms.Form):
"""
A form that lets a user change set their password without entering the old
password
"""
error_messages = {
'password_mismatch': _('The two password fields didn’t match.'),
}
new_password1 = forms.CharField(
label=_("New password"),
widget=forms.PasswordInput(attrs={'autocomplete': 'new-password', 'class': 'form-control'}),
strip=False,
# help_text=password_validation.password_validators_help_text_html(),
)
new_password2 = forms.CharField(
label=_("New password confirmation"),
strip=False,
widget=forms.PasswordInput(attrs={'autocomplete': 'new-password', 'class': 'form-control'}),
)
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
def clean_new_password2(self):
password1 = self.cleaned_data.get('<PASSWORD>')
password2 = self.cleaned_data.get('<PASSWORD>')
if password1 and password2:
if password1 != <PASSWORD>:
raise ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
password_validation.validate_password(password2, self.user)
return password2
def save(self, commit=True):
password = self.cleaned_data["<PASSWORD>"]
self.user.set_password(password)
if commit:
self.user.save()
return self.user
| StarcoderdataPython |
176833 | <reponame>rajatrakesh/CDSW-Demos<filename>basketball-stats/analysis.py
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
from pyspark.sql.types import *
conf = SparkConf().setAppName("basketball-analysis")
sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)
# #set up dataframes
dfPlayers = sqlContext.sql("SELECT * from basketball.players")
pdPlayers= dfPlayers.toPandas()
dfAge = sqlContext.sql("SELECT * from basketball.age")
pdAge = dfAge.toPandas()
dfExperience = sqlContext.sql("SELECT * from basketball.experience")
pdExperience = dfExperience.toPandas()
import matplotlib.pyplot as plt
import seaborn as sb
##Let's Look at the distribution of age over the data set
pdAge[["age","valueZ_count"]].plot(kind='bar',x="age",y="valueZ_count")
##player value in years 2016 + 2015
pdPlayers[pdPlayers["year"]==2016][['name','zTOT']].sort_values(by='zTOT',ascending=0)[:25]
pdPlayers[pdPlayers["year"]==2015][['name','zTOT']].sort_values(by='zTOT',ascending=0)[:25]
pdPlayers[pdPlayers["year"]==2016][['name','nTOT']].sort_values(by='nTOT',ascending=0)[:25]
pdPlayers[pdPlayers["year"]==2015][['name','nTOT']].sort_values(by='nTOT',ascending=0)[:25]
##Some statistics on 3 point shooting
pdPlayers[pdPlayers["name"]=='<NAME>'][pdPlayers["year"]==2016][['name','zFG','zFT','z3P','zTRB','zAST','zSTL','zBLK','zTOV','zTOT']]
pdPlayers[pdPlayers["year"]==2016][['name','3P','z3P']].sort_values(by="z3P",ascending=0)[:20]
pdPlayers[['name','year','3P','z3P']].sort_values(by="3P",ascending=0)[:20]
pdPlayers[['name','year','3P','z3P']].sort_values(by="z3P",ascending=0)[:20]
pdPlayers[pdPlayers["name"]=='<NAME>'][pdPlayers["year"]==1981][['name','zFG','zFT','z3P','zTRB','zAST','zSTL','zBLK','zTOV','zTOT']]
pdPlayers[['year','3PA']].groupby('year').mean().plot(kind='bar')
##Player value by Age
pdAge[["age","valueZ_mean"]].plot(kind='bar',x="age",y="valueZ_mean")
pdAge[["age","valueN_mean"]].plot(kind='bar',x="age",y="valueN_mean")
pdAge[["age","deltaZ_mean"]].plot(kind='bar',x="age",y="deltaZ_mean")
pdAge[["age","deltaN_mean"]].plot(kind='bar',x="age",y="deltaN_mean")
##Player value by Experience
pdExperience[["Experience","valueZ_mean"]].plot(kind='bar',x="Experience",y="valueZ_mean")
pdExperience[["Experience","valueN_mean"]].plot(kind='bar',x="Experience",y="valueN_mean")
pdExperience[["Experience","deltaZ_mean"]].plot(kind='bar',x="Experience",y="deltaZ_mean")
pdExperience[["Experience","deltaN_mean"]].plot(kind='bar',x="Experience",y="deltaN_mean")
##Let's look at some player examples
#Players who fit the general pattern
pdPlayers[pdPlayers["name"] == '<NAME>'][["age","nTOT"]].plot(kind='bar',x='age',y='nTOT')
pdPlayers[pdPlayers["name"] == '<NAME>'][["age","nTOT"]].plot(kind='bar',x='age',y='nTOT')
pdPlayers[pdPlayers["name"] == '<NAME>'][["age","nTOT"]].plot(kind='bar',x='age',y='nTOT')
#players who don't fit the average pattern
pdPlayers[pdPlayers["name"] == '<NAME>'][["age","nTOT"]].plot(kind='bar',x='age',y='nTOT')
pdPlayers[pdPlayers["name"] == '<NAME>'][["age","nTOT"]].plot(kind='bar',x='age',y='nTOT')
pdPlayers[pdPlayers["name"] == '<NAME>'][["age","nTOT"]].plot(kind='bar',x='age',y='nTOT')
##The Best Seasons of All time???
pdPlayers[['name','year','age','zTOT']].sort_values(by='zTOT',ascending=0)[:50]
pdPlayers[['name','year','age','nTOT']].sort_values(by='nTOT',ascending=0)[:50]
| StarcoderdataPython |
1654437 | from django.urls import path
from . import views
urlpatterns = [
path('class/', views.ClassMessageAPIView.as_view())
# path('', views.ClassesAPIView.as_view()),
# path('shedule/', views.SheduleTimeAPIView.as_view()),
# path('invite/', views.inviteLinks),
# path('join/', views.join),
]
| StarcoderdataPython |
1620535 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from hwt.code import Or, Switch
from hwt.interfaces.std import Handshaked
from hwt.interfaces.utils import addClkRstn, propagateClkRstn
from hwt.math import log2ceil
from hwt.serializer.mode import serializeParamsUniq
from hwt.synthesizer.hObjList import HObjList
from hwt.synthesizer.param import Param
from hwtLib.amba.axi_comp.interconnect.base import AxiInterconnectBase
from hwtLib.amba.datapump.intf import AxiWDatapumpIntf
from hwtLib.handshaked.fifo import HandshakedFifo
@serializeParamsUniq
class WStrictOrderInterconnect(AxiInterconnectBase):
"""
Strict order interconnect for AxiWDatapumpIntf (N-to-1)
ensures that response on request is delivered to driver which asked for it
while transactions can overlap
.. hwt-autodoc::
"""
def _config(self):
self.DRIVER_CNT = Param(2)
self.MAX_TRANS_OVERLAP = Param(16)
AxiWDatapumpIntf._config(self)
def getDpIntf(self, unit):
return unit.wDatapump
def _declr(self):
addClkRstn(self)
with self._paramsShared():
self.drivers = HObjList(
AxiWDatapumpIntf()
for _ in range(int(self.DRIVER_CNT)))
self.wDatapump = AxiWDatapumpIntf()._m()
self.DRIVER_INDEX_WIDTH = log2ceil(self.DRIVER_CNT)
fW = self.orderInfoFifoW = HandshakedFifo(Handshaked)
fAck = self.orderInfoFifoAck = HandshakedFifo(Handshaked)
for f in [fW, fAck]:
f.DEPTH = self.MAX_TRANS_OVERLAP
f.DATA_WIDTH = self.DRIVER_INDEX_WIDTH
def wHandler(self):
w = self.wDatapump.w
fWOut = self.orderInfoFifoW.dataOut
fAckIn = self.orderInfoFifoAck.dataIn
driversW = [d.w for d in self.drivers]
selectedDriverVld = self._sig("selectedDriverWVld")
selectedDriverVld(Or(*map(lambda d: fWOut.data._eq(d[0]) & d[1].valid,
enumerate(driversW))
))
selectedDriverLast = self._sig("selectedDriverLast")
selectedDriverLast(Or(*map(lambda d: fWOut.data._eq(d[0]) & d[1].last,
enumerate(driversW))
))
Switch(fWOut.data).add_cases(
[(i, w(d, exclude=[d.valid, d.ready]))
for i, d in enumerate(driversW)]
).Default(
w.data(None),
w.strb(None),
w.last(None)
)
fAckIn.data(fWOut.data)
# handshake logic
fWOut.rd(selectedDriverVld & selectedDriverLast & w.ready & fAckIn.rd)
for i, d in enumerate(driversW):
d.ready(fWOut.data._eq(i) & w.ready & fWOut.vld & fAckIn.rd)
w.valid(selectedDriverVld & fWOut.vld & fAckIn.rd)
fAckIn.vld(selectedDriverVld & selectedDriverLast & w.ready & fWOut.vld)
#extraConds = {
# fAckIn: selectedDriverLast
# }
#for i, d in enumerate(driversW):
# extraConds[d] = fWOut.data._eq(i)
#
#StreamNode(masters=[w, fWOut],
# slaves=driversW+[fAckIn],
# extraConds=extraConds).sync()
def ackHandler(self):
ack = self.wDatapump.ack
fAckOut = self.orderInfoFifoAck.dataOut
driversAck = [d.ack for d in self.drivers]
selectedDriverAckReady = self._sig("selectedDriverAckReady")
selectedDriverAckReady(Or(*map(lambda d: fAckOut.data._eq(d[0]) & d[1].rd,
enumerate(driversAck))
))
ack.rd(fAckOut.vld & selectedDriverAckReady)
fAckOut.rd(ack.vld & selectedDriverAckReady)
for i, d in enumerate(driversAck):
d(ack, exclude=[d.vld, d.rd])
d.vld(ack.vld & fAckOut.vld & fAckOut.data._eq(i))
def _impl(self):
assert int(self.DRIVER_CNT) > 1, "It makes no sense to use interconnect in this case"
propagateClkRstn(self)
self.reqHandler(self.wDatapump.req, self.orderInfoFifoW.dataIn)
self.wHandler()
self.ackHandler()
if __name__ == "__main__":
from hwt.synthesizer.utils import to_rtl_str
u = WStrictOrderInterconnect()
print(to_rtl_str(u))
| StarcoderdataPython |
1647062 | <reponame>beny2000/TwitterScienceLiteracyProject<gh_stars>0
import csv
class Config:
def __init__(self, file):
'''
Init method for config class
:param file: config file name
'''
self.config_file = file
def __read(self):
'''
Creates csv reader for given config file
:return: csv reader obj
'''
# todo check if csv
try:
file = open(self.config_file, 'r', encoding="utf8")
reader = csv.reader(file)
return reader
except IOError as e:
return "Config file Read Error", e
def pass_params(self):
'''
Reads params from config file
:return: tuple containng inital file direcotries (raw data, cleaned data)
'''
reader = self.__read()
for row in reader:
return (row[0],row[1])
#print(row[0],row[1]) | StarcoderdataPython |
3212409 | import numpy as np
from .utils import check_dimension, check_dtype, convert_dtype, clip_to_uint
def rgb_to_gray(image):
check_dimension(image,3)
shape=image.shape
image= image.astype(np.float64)
applied=np.apply_along_axis(lambda x: x[0] *0.299 + x[1]*0.587 + x[2]*0.114,2,image )
return clip_to_uint(applied)
| StarcoderdataPython |
1709851 | #!/usr/bin/env python
# coding: utf-8
"""
Synthesizes the results of fits into a single file per harmonic.
"""
import re
import os
import math
import numpy as np
import cycle
import sys
if len(sys.argv)>1:
cycidf = sys.argv[1]
else:
cycidf = cycle.select() # cycle identifier
cycdir = cycle.directory(cycidf) # cycle directory
groups = cycle.groups(cycidf, 'fits') # groups
def load(impstm):
"""Load data from fit from a sample."""
with open(impstm, 'r') as f:
f.readline()
dst = eval(f.readline())
for i in range(4):
f.readline()
dat = np.loadtxt(f).T
res = {
'j': dat[0],
'L': dat[1],
'd': dat[3],
'R': dat[4],
'D': dst,
}
if len(dat) > 5:
res['f'] = dat[5]
return res
def analyze(dat, j):
"""Analyze a model."""
msk = dat['j']==j
d = dat['d'][msk]
R = dat['R'][msk]
res = {
'avg-d': np.abs(np.mean(d)*1e18-dat['D'])/dat['D'],
'avg-R': np.mean(R),
'std-d': np.std(d)*1e18/dat['D'],
'std-R': np.std(R),
}
if 'f' in dat:
f = dat['f'][msk]
res['avg-f'] = np.mean(f)
res['std-f'] = np.std(f)
return res
def sample(impstm, j):
"""Analyze a sample."""
res = {}
for mod in ('GUW1', 'GUW2', 'W1', 'W2'):
pth = os.path.join(impstm, f"fits_data_{mod}.dat")
dat = load(pth)
res[mod] = analyze(dat, j)
return res
def adjust(tab):
"""Make the items of a column the same width."""
for j in range(len(tab[0])):
w = max([len(tab[i][j]) for i in range(len(tab))])
for i in range(len(tab)):
tab[i][j] = format(tab[i][j], f'>{w}')
for group in groups:
expdir = os.path.join(cycdir, f"synthesis_{group}")
if not os.path.isdir(expdir):
os.makedirs(expdir)
for j in (1, 2):
lines = {'avg':[], 'std':[]}
for mtd in lines:
lines[mtd].append([
f'distribution',
f'GUW1-{mtd}-f',
f'GUW1-{mtd}-d',
f'GUW2-{mtd}-d',
f'W1-{mtd}-d',
f'W2-{mtd}-d',
f'GUW1-{mtd}-R',
f'GUW2-{mtd}-R',
f'W1-{mtd}-R',
f'W2-{mtd}-R',
])
pth0 = os.path.join(cycdir, f"fits_{group}")
for smp in os.listdir(pth0):
pth1 = os.path.join(pth0, smp)
res = sample(pth1, j)
for mtd in lines:
lines[mtd].append([
smp,
f"{res['GUW1'][f'{mtd}-f']:12.7e}",
f"{res['GUW1'][f'{mtd}-d']:12.7e}",
f"{res['GUW2'][f'{mtd}-d']:12.7e}",
f"{res['W1'][f'{mtd}-d']:12.7e}",
f"{res['W2'][f'{mtd}-d']:12.7e}",
f"{res['GUW1'][f'{mtd}-R']:12.7e}",
f"{res['GUW2'][f'{mtd}-d']:12.7e}",
f"{res['W1'][f'{mtd}-R']:12.7e}",
f"{res['W2'][f'{mtd}-R']:12.7e}",
])
for mtd in lines:
adjust(lines[mtd])
with open(os.path.join(expdir, f"{mtd}_j{j}.csv"), "w") as f:
for l in lines[mtd]:
f.write("; ".join(l)+"\n")
| StarcoderdataPython |
1617252 | <reponame>RaphaelPrevost/Back2Shops<gh_stars>0
#!/usr/bin/env python
############################################################################
# <NAME>, LBNL <EMAIL>
############################################################################
"""
script that generates a proxy certificate
"""
import proxylib
import optparse
import sys
OUTHELP = "Location of the new proxy cert."
CERTHELP = "Location of user certificate."
KEYHELP = "Location of the user key."
VALIDHELP = "h:m Proxy certificate is valid for h hours and m minutes."
FULLPROXY = "Creates a limited proxy"
def main():
parser = optparse.OptionParser()
parser.add_option('-o', '--output', dest='output', help=OUTHELP)
parser.add_option('-c', '--cert' , dest='cert', help=CERTHELP)
parser.add_option('-k', '--key', dest='key', help=KEYHELP)
parser.add_option('-v', '--valid', dest='valid', help=VALIDHELP)
parser.add_option('-l', '--limited', action="store_true",
default=False, dest='limited', help=VALIDHELP)
(opts, args) = parser.parse_args()
kw = {}
kw['cert'] = opts.cert
kw['key'] = opts.key
if opts.valid is None:
valid_tuple = (12, 0)
else:
valid = opts.valid.split(':')
valid_tuple = tuple(map(int, valid))
kw['valid'] = valid_tuple
kw['full'] = not opts.limited
try:
proxy_factory = proxylib.ProxyFactory(kw)
except IOError:
print "Can't find usercert or userkey. Use the -c or -k arguments"
sys.exit(0)
proxy_factory.generate()
proxy_cert = proxy_factory.getproxy()
if opts.output is None:
proxy_cert.write(proxylib.get_proxy_filename())
else:
proxy_cert.write(opts.output)
if __name__ == "__main__": main()
| StarcoderdataPython |
29030 | <gh_stars>0
from models.DecisionTree import DecisionTree
class Forest:
def __init__(self, hyper_parameters, training_set):
"""
Inicializa a floresta com suas árvores.
:param hyper_parameters: dictionary/hash contendo os hiper parâmetros
:param training_set: dataset de treinamento
"""
self.number_of_trees = hyper_parameters["n_trees"]
self.trees = []
self.training_set = training_set
sample_size = round(2*training_set.size() / 3)
# Cria todas as number_of_trees árvores de decisão
for i in range(self.number_of_trees):
# resampling usando bootstrap stratificado
tree_training_set = self.training_set.resample(sample_size)
tree = DecisionTree(hyper_parameters, tree_training_set)
self.trees.append(tree)
def predict(self, example):
"""
Pede que todas as árvores façam uma predição para o exemplo e retorna
o valor mais retornado / frequente [votação]
:param example: instância na forma de um Example para a qual se quer prever a classe
:return: classe predita para o example
"""
predictions = self.__trees_predictions_for(example)
max_frequency_so_far = 0
major = predictions[0]
for klass in predictions:
klass_frequency = predictions.count(klass)
if klass_frequency > max_frequency_so_far:
max_frequency_so_far = klass_frequency
major = klass
return major
def __trees_predictions_for(self, example):
return list(map(lambda tree: tree.predict(example), self.trees))
| StarcoderdataPython |
3332945 | import json
from redshift_connection import RedshiftConnection
def response_formatter(status_code='400', body={'message': 'error'}):
api_response = {
'statusCode': status_code,
'headers': {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Credentials' : True
},
'body': json.dumps(body)
}
return api_response
def handler(event, context):
# Validate user input
try:
# User input
data = json.loads(event['body'])
work_types = data
except:
payload = {'message': 'Invalid user input'}
return response_formatter(status_code='400', body=payload)
# Parse project_id from the URL
try:
project_id = (event.get('pathParameters').get('id'))
except:
payload = {"message": "Could not get id path parameter"}
return response_formatter(status_code='400', body=payload)
# Update work types
try:
insert_value_list = []
for key in work_types:
for issue in work_types[key]:
insert_value_list.append((project_id, issue, key))
redshift = RedshiftConnection()
redshift.updateTeamWorkTypes(project_id, insert_value_list)
except:
payload = {'message': 'Internal error'}
return response_formatter(status_code='500', body=payload)
finally:
redshift.closeConnection()
return response_formatter(status_code='200', body={}) | StarcoderdataPython |
4809704 | <gh_stars>0
#!usr/bin/python
# # -*- coding:utf8 -*-
class Base:
pass
class Child(Base):
pass
# 等价定义, 注意Base后面要加上逗号否则就不是tuple了
SameChild = type('Child', (Base,), {})
# 加上方法
class ChildWithMethod(Base):
bar = True
def hello(self):
print('hello')
def hello(self):
print('hello')
# 等价定义
ChildWithMethod = type(
'ChildWithMethod', (Base,), {'bar': True, 'hello': hello}
)
# 元类继承自type
class LowercaseMeta(type):
""" 修改类的属性名称为小写的元类 """
def __new__(mcs, name, bases, attrs):
lower_attrs = {}
for k, v in attrs.items():
if not k.startswith('__'): # 排除magic method
lower_attrs[k.lower()] = v
else:
lower_attrs[k] = v
return type.__new__(mcs, name, bases, lower_attrs)
class LowercaseClass(metaclass=LowercaseMeta): # python3
BAR = True
def HELLO(self):
print('hello')
print(dir(LowercaseClass)) # 'BAR'和'HELLO'都变成了小写
# 用一个类的实例调用hello方法,我们修改了类定义时候的属性名!!!
LowercaseClass().hello()
| StarcoderdataPython |
3261875 | """ Copyright 2012, 2013 UW Information Technology, University of Washington
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.
Changes
=================================================================
<EMAIL>: load the forms on application load, not every
request for a form.
^ This is being reverted back to being loaded every time SpotForm is
called. After profiling, it didn't seem like there was hardly any
speed difference, and only loading this once on application load
breaks our unit tests.
"""
from spotseeker_server.default_forms.spot import DefaultSpotForm, DefaultSpotExtendedInfoForm
from django.utils.importlib import import_module
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class SpotExtendedInfoForm(object):
@staticmethod
def implementation():
if hasattr(settings, 'SPOTSEEKER_SPOTEXTENDEDINFO_FORM'):
# This is all taken from django's static file finder
module, attr = settings.SPOTSEEKER_SPOTEXTENDEDINFO_FORM.rsplit('.', 1)
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error importing module %s: "%s"' %
(module, e))
try:
SpotExtendedInfoForm = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a "%s" '
'class.' % (module, attr))
return SpotExtendedInfoForm
else:
return DefaultSpotExtendedInfoForm
def __new__(*args, **kwargs):
return SpotExtendedInfoForm.implementation()(args[1], **kwargs)
class SpotForm(object):
@staticmethod
def implementation():
if hasattr(settings, 'SPOTSEEKER_SPOT_FORM'):
# This is all taken from django's static file finder
module, attr = settings.SPOTSEEKER_SPOT_FORM.rsplit('.', 1)
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error importing module %s: "%s"' %
(module, e))
try:
SpotForm = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a "%s" '
'class.' % (module, attr))
return SpotForm
else:
return DefaultSpotForm
def __new__(*args, **kwargs):
return SpotForm.implementation()(args[1], **kwargs)
| StarcoderdataPython |
93914 | <reponame>pangolp/pyarweb
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0002_auto_20170325_2011'),
]
operations = [
migrations.AddField(
model_name='eventparticipation',
name='gender',
field=models.CharField(verbose_name='género', blank=True, choices=[('female', 'female'), ('male', 'fale'), ('Otro', 'other')], max_length=32, default=''),
),
]
| StarcoderdataPython |
3365948 | #!/usr/bin/env python3
############################################################################################
# #
# Program purpose: Checks whether a number is in a given range. #
# Program Author : <NAME> <<EMAIL>> #
# Creation Date : February 01, 2020 #
# #
############################################################################################
def obtain_user_data(input_mess: str) -> int:
user_data, valid = '', False
while not valid:
try:
user_data = int(input(input_mess))
valid = True
except ValueError as ve:
print(f'[ERROR]: {ve}')
return user_data
def in_range(low: int, key: int, high: int, bounded: bool = False) -> bool:
if bounded:
return low <= key <= high
else:
return low < key < high
if __name__ == "__main__":
lower_bound = obtain_user_data(input_mess='Enter lower bound: ')
upper_bound = obtain_user_data(input_mess='Enter upper bound: ')
key_val = obtain_user_data(input_mess='Enter key to check: ')
temp = obtain_user_data(input_mess='Bounded (0=true, 1=false): ')
bounded = True if temp == 0 else False
print(f'Is {key_val} in range ?: '
f'{in_range(low=lower_bound, key=key_val, high=upper_bound, bounded=bounded)}')
| StarcoderdataPython |
3229758 | <gh_stars>0
import os
import inject
import pytest
from hg.core.system import SystemRegistry
from hg.core.world import World
from hg.game.components.position_component import PositionComponent
from hg.game.components.sprite_component import SpriteComponent
from hg.gfx.sprite_renderer.renderer import SpriteRenderer
from ..sprite_render_system import SpriteRenderSystem
@pytest.mark.inject()
def test_sprite_tracking(mocker):
w = World()
sysreg = SystemRegistry(w)
sprite_sys = SpriteRenderSystem()
sysreg.register_system(sprite_sys)
renderer = inject.instance(SpriteRenderer)
base_dir = os.path.join(os.getcwd(), 'hg', 'res', 'loaders', 'tests')
resource0 = os.path.join(base_dir, 'test_sprite_0.xml')
resource1 = os.path.join(base_dir, 'test_sprite_1.xml')
sprite_add = mocker.spy(renderer, 'add_sprite')
sprite_remove = mocker.spy(renderer, 'remove_sprite')
assert len(renderer.sprites) == 0
# entity with a sprite component with undefined resource
e = w.add_entity(components=(
SpriteComponent(),
PositionComponent(),
))
sysreg.tick_all()
comp = e[SpriteComponent]
assert comp.resource == ''
# only the sprite component should have been added and removed, no related
# sprites should have been created and removed, since no resource was
# specified
assert len(renderer.sprites) == 0
w.del_entity(e)
sprite_add.assert_not_called()
sprite_remove.assert_not_called()
# create an empty entity once again, but set the resource afterwards
e = w.add_entity(components=(
SpriteComponent(),
PositionComponent(),
))
comp = e[SpriteComponent]
# set the path to the sprite and tick again, the sprite should be created
comp.resource = resource0
sysreg.tick_all()
assert len(renderer.sprites) == 1
sprite_add.assert_called_once()
# destroy the entity, the sprite should be destroyed as well
w.del_entity(e)
assert len(renderer.sprites) == 0
sprite_remove.assert_called_once()
sprite_add.reset_mock()
sprite_remove.reset_mock()
# create another entity with resource specified
e = w.add_entity(components=(
SpriteComponent(resource=resource0),
PositionComponent(),
))
sysreg.tick_all()
sprite_add.assert_called_once()
assert len(renderer.sprites) == 1
comp = e[SpriteComponent]
assert comp.resource == resource0
cur_sprite_id = id(renderer.sprites[0])
# change the resource, the sprite should be replaced with a new one
comp.resource = resource1
sysreg.tick_all()
sprite_remove.assert_called_once()
assert sprite_add.call_count == 2
assert len(renderer.sprites) == 1
new_sprite_id = id(renderer.sprites[0])
assert new_sprite_id != cur_sprite_id
| StarcoderdataPython |
1679145 | import os
import yaml
import pkg_resources
class _ConfigurationItem(object):
def __init__(self, val):
self._val = val
def __getitem__(self, key):
val = self._val[key]
if isinstance(val, dict):
return _ConfigurationItem(val)
else:
return val
def __setitem__(self, key, value):
self._val[key] = value
def __contains__(self, key):
return key in self._val
def __getattr__(self, name):
if name == '_val':
return getattr(self, name)
else:
return self.__getitem__(name)
def __setattr__(self, name, value):
if name == '_val':
super().__setattr__(name, value)
else:
self.__setitem__(name, value)
def __str__(self):
return str(self._val)
def clear(self):
self._val.clear()
def update(self, b):
for key in b.keys():
if key in self:
if isinstance(b[key], dict) and isinstance(self._val[key], dict):
self[key].update(b[key])
else:
self[key] = b[key]
else:
self[key] = b[key]
class Configuration(object):
'''A configuration object that describes the current configuration status of the package.
'''
def __init__(self):
if Configuration._config is None:
self.reset()
_config = None
def __getitem__(self, key):
'''Get the value for the key.
Parameters
----------
key : string
The configuration key.
'''
return Configuration._config[key]
def __setitem__(self, key, value):
'''Set the value for the key.
Parameters
----------
key : string
The configuration key.
value : anything
The value to set this to.
'''
Configuration._config[key] = value
__getattr__ = __getitem__
__setattr__ = __setitem__
def __str__(self):
return str(Configuration._config)
def reset(self):
'''Reset the configuration to the default configuration.
This default configuration consists of the default parameters in `hcipy/data/default_config.yaml`, which
can be overridden by a configuration file in `~/.hcipy/hcipy_config.yaml`. This can in turn be overridden
by a configuration file named `hcipy_config.yaml` located in the current working directory.
'''
Configuration._config = _ConfigurationItem({})
default_config = pkg_resources.resource_stream('hcipy', 'data/default_config.yaml')
user_config = os.path.expanduser('~/.hcipy/hcipy_config.yaml')
current_working_directory = './hcipy_config.yaml'
paths = [default_config, user_config, current_working_directory]
for path in paths:
try:
contents = path.read()
except AttributeError:
try:
with open(path) as f:
contents = f.read()
except IOError:
continue
new_config = yaml.safe_load(contents)
self.update(new_config)
def update(self, b):
'''Update the configuration with the configuration `b`, as a dictionary.
Parameters
----------
b : dict
A dictionary containing the values to update in the configuration.
'''
Configuration._config.update(b)
| StarcoderdataPython |
1770927 | <gh_stars>0
from flask import request, render_template, redirect
import pyshorteners
from app import app
# from app.controllers import
# from db_config import get_collection
URL = "http://localhost:5000/"
@app.route("/", methods=["GET", "POST"])
def home():
if request.method == "GET":
return render_template('home.html')
if request.method == "POST":
long_url = request.form['url-field']
s = pyshorteners.Shortener()
tiny_url = s.tinyurl.short(long_url)
short_url_code = tiny_url.split("/")[-1]
short_url = URL + short_url_code
print(short_url)
return render_template('result.html', url=short_url)
# To expand to original URL use .tinyurl.expand(short_url)
@app.route("/<string:path>")
def redirect():
# Check if it is in the database
# IF in db redirect
# else:
# return redirect("/")
pass
| StarcoderdataPython |
1602006 | from typing import Optional, Tuple
import pandas as pd
from scipy.spatial.distance import cdist
def get_closest_node_id(
coordinates: pd.DataFrame,
x: float,
y: float,
distance="euclidean",
x_col: str = "x",
y_col: str = "y",
id_col: Optional[str] = None,
) -> int:
cols = [x_col, y_col]
if id_col is not None:
cols.append(id_col)
coordinates = coordinates[cols]
if id_col is not None:
coordinates.set_index(id_col)
closest_node_id = coordinates.iloc[
cdist([[x, y]], coordinates.values, metric=distance).argmin()
].name
return closest_node_id
def get_coordinates_bounding_box(
coordinates: pd.DataFrame,
) -> Tuple[Tuple[float, float], Tuple[float, float]]:
return (coordinates["x"].min(), coordinates["y"].min()), (
coordinates["x"].max(),
coordinates["y"].max(),
)
| StarcoderdataPython |
23972 | <reponame>jdelrue/digital_me
from jumpscale import j
JSBASE = j.application.jsbase_get_class()
class GedisProcessManager(JSBASE):
pass
| StarcoderdataPython |
1676042 | <reponame>howawong/openwancha
# Generated by Django 3.1 on 2020-10-13 11:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sample', '0002_districtminorwork'),
]
operations = [
migrations.AlterField(
model_name='districtminorwork',
name='audience',
field=models.CharField(max_length=128, null=True),
),
migrations.AlterField(
model_name='districtminorwork',
name='audience_size',
field=models.CharField(max_length=128, null=True),
),
]
| StarcoderdataPython |
4829639 | ''' puttin' books on shelves '''
import re
from django.db import models
from bookwyrm import activitypub
from .base_model import BookWyrmModel
from .base_model import OrderedCollectionMixin, PrivacyLevels
from . import fields
class Shelf(OrderedCollectionMixin, BookWyrmModel):
''' a list of books owned by a user '''
name = fields.CharField(max_length=100)
identifier = models.CharField(max_length=100)
user = fields.ForeignKey(
'User', on_delete=models.PROTECT, activitypub_field='owner')
editable = models.BooleanField(default=True)
privacy = fields.CharField(
max_length=255,
default='public',
choices=PrivacyLevels.choices
)
books = models.ManyToManyField(
'Edition',
symmetrical=False,
through='ShelfBook',
through_fields=('shelf', 'book')
)
def save(self, *args, **kwargs):
''' set the identifier '''
saved = super().save(*args, **kwargs)
if not self.identifier:
slug = re.sub(r'[^\w]', '', self.name).lower()
self.identifier = '%s-%d' % (slug, self.id)
return super().save(*args, **kwargs)
return saved
@property
def collection_queryset(self):
''' list of books for this shelf, overrides OrderedCollectionMixin '''
return self.books
def get_remote_id(self):
''' shelf identifier instead of id '''
base_path = self.user.remote_id
return '%s/shelf/%s' % (base_path, self.identifier)
class Meta:
''' user/shelf unqiueness '''
unique_together = ('user', 'identifier')
class ShelfBook(BookWyrmModel):
''' many to many join table for books and shelves '''
book = fields.ForeignKey(
'Edition', on_delete=models.PROTECT, activitypub_field='object')
shelf = fields.ForeignKey(
'Shelf', on_delete=models.PROTECT, activitypub_field='target')
added_by = fields.ForeignKey(
'User',
blank=True,
null=True,
on_delete=models.PROTECT,
activitypub_field='actor'
)
activity_serializer = activitypub.AddBook
def to_add_activity(self, user):
''' AP for shelving a book'''
return activitypub.Add(
id='%s#add' % self.remote_id,
actor=user.remote_id,
object=self.book.to_activity(),
target=self.shelf.remote_id,
).serialize()
def to_remove_activity(self, user):
''' AP for un-shelving a book'''
return activitypub.Remove(
id='%s#remove' % self.remote_id,
actor=user.remote_id,
object=self.book.to_activity(),
target=self.shelf.to_activity()
).serialize()
class Meta:
''' an opinionated constraint!
you can't put a book on shelf twice '''
unique_together = ('book', 'shelf')
| StarcoderdataPython |
169757 | <gh_stars>1-10
#!/usr/bin/env python3
"""exfi.io.gff3_to_bed.py: exfi submodule to convert a gff3 to bed3 where
coordinates are with respect to the transcriptome"""
import logging
import pandas as pd
from exfi.io.bed import BED3_COLS, BED3_DTYPES
GFF3_COLS = [
"seqid", "source", "type", "start", "end", "score", "strand", "phase",
"attributes"
]
def gff3_to_bed3(gff3_in, mode="ensembl"):
"""Read a GFF3 file and convert it to BED3, where coordinates are with
respect to the transcriptome
Modes available:
- "ensembl": for files downloaded from Ensembl,
- "gmap": for GFF3 files generated from GMAP,
- "ncbi": for GFF3 files downloaded from NCBI Genomes
"""
logging.info("Reading GFF3 file")
raw = pd.read_csv(
sep='\t',
na_values=".",
usecols=["type", "start", "end", "strand", "attributes"],
filepath_or_buffer=gff3_in,
comment="#",
header=None,
names=GFF3_COLS,
low_memory=False # Convert types at the end. Seqid is char, not int
)
if raw.shape[0] == 0:
exons = pd.DataFrame(columns=BED3_COLS)
exons = exons.astype(BED3_DTYPES)
return exons
logging.info('Extracting the transcript ids')
if mode == "gmap":
logging.info("gff3 comes from gmap")
exons = raw[raw['type'] == 'cDNA_match'].drop(columns='type')
exons['transcript_id'] = exons['attributes']\
.str.split(";").str[1]\
.str.extract(r'Name=([\w\d.-_]+)')
elif mode == "ncbi":
logging.info("gff3 comes from NCBI Genomes")
exons = raw[raw['type'] == 'exon'].drop(columns='type')
exons['transcript_id'] = exons.attributes\
.str.extract(r"transcript_id=([A-Za-z0-9_.]+)")
exons = exons.dropna()
else:
logging.info('gff3 comes from ensembl')
exons = raw[raw['type'] == 'exon'].drop(columns='type')
exons["transcript_id"] = exons["attributes"]\
.str.split(";", 1, ).str[0]\
.str.extract(r'Parent=transcript:([\w\d.-_]+)')
exons = exons[['transcript_id', 'strand', 'start', 'end']]
logging.info('Reordering exons by strand')
positive = (
exons
[exons['strand'] == '+']
.drop(columns='strand')
.sort_values(by=['transcript_id', 'start', 'end'])
)
negative = (
exons
[exons['strand'] == '-']
.drop(columns='strand')
.sort_values(
by=['transcript_id', 'start', 'end'],
ascending=[True, False, False]
)
)
merged = pd.concat([positive, negative])
logging.info('Computing lengths')
merged['length'] = merged['end'] - merged['start'] + 1
logging.info('Computing ends')
merged['transcript_end'] = (
merged
.groupby('transcript_id')
['transcript_id', 'length']
.cumsum()
)
logging.info('Computing starts')
merged['transcript_start'] = merged['transcript_end'] - merged['length']
logging.info('Tidying up')
merged = merged[['transcript_id', 'transcript_start', 'transcript_end']]
merged = merged.rename(columns={
'transcript_id': 'chrom',
'transcript_start': 'chrom_start',
'transcript_end': 'chrom_end'
})
merged = merged.astype(BED3_DTYPES)
merged = merged.reset_index(drop=True)
logging.info('Done')
return merged
| StarcoderdataPython |
1779587 | <reponame>jmalinao19/Data-Engineer-NanoDegree
from create_AWS_cluster import parse_configFile,
from cluster_status import get_cluster_status
def delete_cluster(redshift, DWH_CLUSTER_IDENTIFIER):
"""
Request a deletion for Redshift cluster
@type redshift --
@param redshift -- Redshift resource client
@type DWH_CLUSTER_IDENTIFIER -- string
@param DWH_CLUSTER_IDENTIFIER -- value from config file
@return -- None
"""
return redshift.delete_cluster(ClusterIdentifier=DWH_CLUSTER_IDENTIFIER, SkipFinalClusterSnapshot = True)
def main():
configs = parse_configFile()
redshift = aws_client('redshift','us-east-2')
if get_cluster_status(redshift,configs[10]) == 'available':
print('Cluster is available and will begin the deletion process')
delete_cluster(redshift,configs[10])
print(get_cluster_status(redshift,configs[10]))
else:
print('Cannot Delete because Cluster is not available ')
if __name__ == '__main__':
main()
| StarcoderdataPython |
1671049 | <reponame>almarklein/visvis2<gh_stars>1-10
"""
Example that implements a simple custom object and renders it.
This example draws a triangle at the appropriate position; the object's
transform and camera are taken into account. It also uses the material
to set the color. But no geometry is used.
It demonstrates:
* How you can define a new WorldObject and Material.
* How to define a render function for it.
* The basic working of the shader class.
* The use of uniforms for material properties.
* The implementation of the camera transforms in the shader.
"""
from wgpu.gui.auto import WgpuCanvas, run
import pygfx as gfx
from pygfx.renderers.wgpu._shadercomposer import Binding, WorldObjectShader
# %% Custom object, material, and matching render function
class Triangle(gfx.WorldObject):
pass
class TriangleMaterial(gfx.Material):
uniform_type = dict(
color="4xf4",
)
def __init__(self, *, color="white", **kwargs):
super().__init__(**kwargs)
self.color = color
@property
def color(self):
"""The uniform color of the triangle."""
return gfx.Color(self.uniform_buffer.data["color"])
@color.setter
def color(self, color):
self.uniform_buffer.data["color"] = gfx.Color(color)
self.uniform_buffer.update_range(0, 99999)
class TriangleShader(WorldObjectShader):
def get_code(self):
return (
self.get_definitions()
+ self.common_functions()
+ self.vertex_shader()
+ self.fragment_shader()
)
def vertex_shader(self):
return """
@stage(vertex)
fn vs_main(@builtin(vertex_index) index: u32) -> Varyings {
// Transform object positition into NDC coords
let model_pos = vec4<f32>(0.0, 0.0, 0.0, 1.0);
let world_pos = u_wobject.world_transform * model_pos;
let ndc_pos = u_stdinfo.projection_transform * u_stdinfo.cam_transform * world_pos;
// List of relative positions, in logical pixels
var positions = array<vec2<f32>, 3>(
vec2<f32>(0.0, -20.0), vec2<f32>(-17.0, 15.0), vec2<f32>(17.0, 15.0)
);
// Get position for *this* corner
let screen_factor = u_stdinfo.logical_size.xy / 2.0;
let screen_pos_ndc = ndc_pos.xy + positions[index] / screen_factor;
// Set the output
var varyings: Varyings;
varyings.position = vec4<f32>(screen_pos_ndc, ndc_pos.zw);
return varyings;
}
"""
def fragment_shader(self):
return """
@stage(fragment)
fn fs_main(varyings: Varyings) -> FragmentOutput {
var out: FragmentOutput;
let a = u_material.opacity * u_material.color.a;
out.color = vec4<f32>(u_material.color.rgb, 1.0);
return out;
}
"""
@gfx.renderers.wgpu.register_wgpu_render_function(Triangle, TriangleMaterial)
def triangle_render_function(render_info):
wobject = render_info.wobject
material = wobject.material
# Create shader object
shader = TriangleShader(render_info)
# Define bindings, and make shader create code for them
bindings = [
Binding("u_stdinfo", "buffer/uniform", render_info.stdinfo_uniform),
Binding("u_wobject", "buffer/uniform", wobject.uniform_buffer),
Binding("u_material", "buffer/uniform", material.uniform_buffer),
]
for i, binding in enumerate(bindings):
shader.define_binding(0, i, binding)
# Create dict that the Pygfx renderer needs
return [
{
"render_shader": shader,
"primitive_topology": "triangle-list",
"indices": range(3),
"bindings0": bindings,
},
]
# %% Setup scene
renderer = gfx.WgpuRenderer(WgpuCanvas())
camera = gfx.OrthographicCamera(10, 10)
t = Triangle(None, TriangleMaterial(color="cyan"))
t.position.x = 2 # set offset to demonstrate that it works
scene = gfx.Scene()
scene.add(t)
if __name__ == "__main__":
renderer.request_draw(lambda: renderer.render(scene, camera))
run()
| StarcoderdataPython |
1782900 | import base64
import json
import io
import time
import picamera
import cv2
import numpy
import requests
n=0
while n<10:
stream = io.BytesIO()
with picamera.PiCamera() as camera:
camera.resolution = (320, 240)
camera.capture(stream, format='jpeg')
buff = numpy.fromstring(stream.getvalue(), dtype=numpy.uint8)
image = cv2.imdecode(buff, 1)
face_cascade = cv2.CascadeClassifier('/home/pi/Desktop/pilocal/faces.xml')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 5)
print "Found "+str(len(faces))+" face(s)"
for (x,y,w,h) in faces:
cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,0),2)
cv2.imwrite('result'+str(n)+'.jpg',image)
n=n+1
stream.close()
cv2.destroyAllWindows()
| StarcoderdataPython |
159985 | import torch, pytz
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import numpy as np
import pandas as pd
import os, csv
# For plotting
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import streamlit as st
from PIL import Image
import Reconstruction_DNN, Reconstruct_DNN_2
# Page config
st.set_page_config(page_title="ARMOR Lab Human Digital Twin Demo", layout="wide", page_icon="/app/human_digital_twin/Deployment/EmbeddedImage.png")
app_intro = """
This website is designed for the demonstration of how functional human movement assessment can be done by using Motion Tape.
For each model/movement, the results obtained from the motion capture system are served as ground truth values to train the model.
Predictions are compared with the results obtained from the motion capture system to demonstrate the performance of Motion Tape.
* __Note__: Please change to the light theme for best user experiences.
\n
"""
# Info
st.header('Introduction')
st.write(app_intro)
st.write("")
st.write("")
image = Image.open("/app/human_digital_twin/Deployment/Picture1.png")
image2 = Image.open("/app/human_digital_twin/Deployment/UCSDLogo_JSOE_Black.png")
st.sidebar.image(image2, use_column_width=True)
st.sidebar.image(image, use_column_width=True)
# Load data
with st.sidebar.expander('Models', expanded=True):
model_name = st.selectbox(
"Select a model",
options=('Bicep Curl', 'Bicep Curl (Mixed)', 'Squat'))
file = st.file_uploader("Upload a csv file", type="csv")
if model_name == "Bicep Curl":
if file:
xy = pd.read_csv(file, header=None)
xy = xy.to_numpy()
Reconstruction_DNN.Reconstruct(xy)
st.subheader('Raw Data:')
col_left, col_mid, col_right = st.columns([1, 1, 1])
with col_left:
image = Image.open('front_arm_data.png')
st.image(image)
with col_mid:
image = Image.open('bicep_data.png')
st.image(image)
with col_right:
image = Image.open('angle_data.png')
st.image(image)
st.subheader('Prediction:')
col_left2, col_mid2, col_right2 = st.columns([1, 2, 1])
with col_mid2:
image = Image.open('plot.png')
st.image(image)
st.download_button(
label="Download Prediction Results as CSV",
data=pd.read_csv('results.csv').to_csv(index = False),
file_name='results.csv',
mime='text/csv'
)
with open("plot.png", 'rb') as figure:
st.download_button(
label="Download the Plot as PNG",
data=figure,
file_name='plot.png',
mime='image/png'
)
else:
st.header('Example:')
st.subheader('Motion Capture System:')
video_file = open('/app/human_digital_twin/Deployment/final_6174d072ebf5c9008306570d_644651.mp4', 'rb')
video_bytes = video_file.read()
st.video(video_bytes)
st.subheader('Voltage Responses from Motion Tape:')
image3 = Image.open('/app/human_digital_twin/Deployment/Picture1_watermatked.png')
st.image(image3)
st.subheader('Prediction:')
col_left, col_mid, col_right = st.columns([1, 2, 1])
with col_mid:
image4 = Image.open('/app/human_digital_twin/Deployment/Picture2_watermarked.png')
st.image(image4)
elif model_name == "Squat":
if file:
pass
else:
st.stop()
elif model_name == "Bicep Curl (Mixed)":
if file:
xy = pd.read_csv(file, header=None)
xy = xy.to_numpy()
Reconstruct_DNN_2.Reconstruct(xy)
st.subheader('Raw Data:')
col_left, col_mid, col_right = st.columns([1, 1, 1])
with col_left:
image = Image.open('front_arm_data.png')
st.image(image)
with col_mid:
image = Image.open('bicep_data.png')
st.image(image)
with col_right:
image = Image.open('angle_data.png')
st.image(image)
st.subheader('Prediction:')
col_left2, col_mid2, col_right2 = st.columns([1, 2, 1])
with col_mid2:
image = Image.open('plot.png')
st.image(image)
st.download_button(
label="Download Prediction Results as CSV",
data=pd.read_csv('results.csv').to_csv(index = False),
file_name='results.csv',
mime='text/csv'
)
with open("plot.png", 'rb') as figure:
st.download_button(
label="Download the Plot as PNG",
data=figure,
file_name='plot.png',
mime='image/png'
)
else:
st.header('Example:')
st.subheader('Motion Capture System:')
video_file = open('/app/human_digital_twin/Deployment/final_6174d072ebf5c9008306570d_644651.mp4', 'rb')
video_bytes = video_file.read()
st.video(video_bytes)
st.subheader('Voltage Responses from Motion Tape:')
image3 = Image.open('/app/human_digital_twin/Deployment/Picture1_watermatked.png')
st.image(image3)
st.subheader('Prediction:')
col_left, col_mid, col_right = st.columns([1, 2, 1])
with col_mid:
image4 = Image.open('/app/human_digital_twin/Deployment/Picture2_watermarked.png')
st.image(image4)
| StarcoderdataPython |
1697063 | <reponame>Ting-Jiang/bioinformaticLearning<filename>learning/rLearn.py
#! /usr/bin/python
# Project :
# Author: <NAME>
# Email:
print("Hello World! I would like to learn Programming from scratch")
# Flow Control
temp=False
if not temp:
print("tempt variable is False")
for i in range(10):
print(i)
| StarcoderdataPython |
172526 | <gh_stars>1-10
from django.db import models
from django_countries.fields import CountryField
from django.core.validators import MaxValueValidator, MinValueValidator
class Client(models.Model):
name = models.CharField(max_length=128)
email = models.EmailField()
phone = models.CharField(max_length=15)
business = models.CharField(max_length=128)
country = CountryField()
zip_code = models.IntegerField(validators=[
MinValueValidator(501, 'ZIP Code must be more than 500'),
MaxValueValidator(99950, 'ZIP Code must be below 99951'),
])
def __str__(self):
return self.name
| StarcoderdataPython |
1755721 | '''
Created by auto_sdk on 2015.09.07
'''
from aliyun.api.base import RestApi
class Mts20140618SubmitJobsRequest(RestApi):
def __init__(self,domain='mts.aliyuncs.com',port=80):
RestApi.__init__(self,domain, port)
self.Input = None
self.OutputBucket = None
self.OutputLocation = None
self.Outputs = None
self.PipelineId = None
def getapiname(self):
return 'mts.aliyuncs.com.SubmitJobs.2014-06-18'
| StarcoderdataPython |
129150 | #!/usr/bin/env python3
"""Solve subset sum problem."""
import argparse
import sys
import os
import platform
from collections import defaultdict
from collections import Counter
from datetime import datetime as dt
from math import log
import ctypes
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__version__ = 0.1
# within the C library everything is uint64_t
UINT64_SIZE = 18446744073709551615
class SSP_lib:
"""Class to solve Subset Sum Problem in natural numbers.
S - input multiset of numbers
k - number of elements in the set
X - sum of subset s in S
"""
def __init__(self, in_file, req_sum, v=False, d=False, deep=False,
ext_v=False):
"""Initiate the class."""
self.in_file = in_file
self.X = req_sum
self._verbose = v
self._get_d = d
self.answer = None
self._deep = deep
self._ext_v = ext_v
self.__make_input_arr()
self.f_min = self.S[:]
self.f_min += self.f_min
self.f_max = self.S[::-1]
self.f_max += self.f_max
self.elems_count = Counter()
self._lib_calls = 0
self._shifts_num = 0
self._on_leaf = False
@staticmethod
def __do_nothing(*args):
"""Just do nothing.
To mask methods if needed.
"""
pass
def __v(self, msg, end="\n"):
"""Print a verbose message."""
sys.stderr.write(msg + end) if self._verbose else None
def __make_input_arr(self):
"""Read input and check it."""
in_is_stdin_stream = self.in_file == "stdin"
f = open(self.in_file) if not in_is_stdin_stream else sys.stdin
try:
numbers = sorted([int(x.rstrip()) for x in f.readlines()
if not x.startswith("#")])
except ValueError: # there was something non-numeric!
sys.exit("Error: in input, numeric values expected.")
finally: # Q: will it work after sys.exit()?
f.close()
self.S = numbers
# check for boundaries
if any(x < 0 for x in numbers):
sys.exit("Sorry, but for now works for non-negative"
" numbers only.")
elif any(x > UINT64_SIZE for x in numbers):
sys.exit("Sorry, but input number size is limited"
" to uint64_t capacity")
# check limits
tot_sum = sum(numbers)
arr_len = len(numbers)
min_elem = numbers[0]
max_elem = numbers[-1]
if self._get_d or self._verbose:
# we were reqested to print dataset density
dens = arr_len / log(max_elem, 2)
print(f"# Dataset density is:\n# {dens}")
if tot_sum > UINT64_SIZE:
sys.exit(f"Error: overall input sum should not exceed "
"the uint64_t capacity, got {tot_sum}")
elif self.X > tot_sum:
sys.exit(f"Requested sum {self.X} > overall sum of the array {tot_sum}, abort")
elif self.X < min_elem:
sys.exit(f"Requested sum {self.X} < smallest element in the array {min_elem}, abort")
elif self.X in numbers:
print("Requested sum is in S")
self.answer = [self.X]
return
self.k = len(numbers)
self.__v(f"# /V: Input array of size {self.k}")
self.__v(f"# /V: Array sum {tot_sum}")
self.__v(f"# /V max_val: {max_elem}, min_val: {min_elem}")
def __configure_solver_lib(self):
"""Find the lib and configure it."""
lib_ext = "so" if platform.system != "Windows" else "dll"
lib_path = os.path.join(os.path.dirname(__file__), "bin",
"SSP_lib.{}".format(lib_ext))
if not os.path.isfile(lib_path):
sys.exit("Please call make or win_make.bat first")
self.lib = ctypes.cdll.LoadLibrary(lib_path)
# convert everyting into C types
self.lib.solve_SSP.argtypes = [ctypes.POINTER(ctypes.c_uint64),
ctypes.c_uint64,
ctypes.c_uint64,
ctypes.c_bool,
ctypes.c_bool]
self.c_v = ctypes.c_bool(self._verbose)
self.c_d = ctypes.c_bool(self._deep)
self.lib.solve_SSP.restype = ctypes.POINTER(ctypes.c_uint64)
def __call_solver_lib(self, arr, X, ext_v=False):
"""Call lib with the parameters given."""
self._lib_calls += 1
c_arr = (ctypes.c_uint64 * (len(arr) + 1))()
c_arr[:-1] = arr
c_arr_size = ctypes.c_uint64(len(arr))
c_X = ctypes.c_uint64(X)
# c_ext_v = ctypes.c_bool(ext_v)
result = self.lib.solve_SSP(c_arr,
c_arr_size,
c_X,
self.c_v,
self.c_d)
# get everything except 0; check the answer
_answer = []
for elem in result:
_answer.append(elem) if elem != 0 else None
if elem == 0:
break
if sum(_answer) != X:
return None
# answer is correct
return _answer
def solve_ssp(self):
"""Get answer."""
if self.answer is not None:
# answer already found
self.__v("# /V: Answer is obvious")
return self.answer
# try naïve approach from 0
self.__configure_solver_lib()
naive_ans = self.__call_solver_lib(self.S, self.X, self._ext_v)
self.answer = naive_ans
return self.answer
def parse_args():
"""Parse and check args."""
app = argparse.ArgumentParser()
app.add_argument("input", help="Text file containing input numbers, or stdin stream, "
"just write stdin for that")
app.add_argument("requested_sum", type=int, help="Sum requested")
app.add_argument("--subset_size", "-s", type=int, default=0,
help="Specify particular size of subset, look only for this")
app.add_argument("--get_density", "--gd", action="store_true", dest="get_density",
help="Compute dataset density")
app.add_argument("--deep", "-d", action="store_true", dest="deep",
help="Include deep target search, drastically increases "
"the runtime")
app.add_argument("--verbose", "-v", action="store_true", dest="verbose",
help="Show verbose messages.")
app.add_argument("--ext_out", "-e", action="store_true", dest="ext_out")
if len(sys.argv) < 3:
app.print_help()
sys.exit()
args = app.parse_args()
if args.requested_sum < 0:
sys.exit("Requested sum cannot be negative")
return args
def accumulate_sum(lst):
"""Return accumulated sum list."""
if len(lst) == 1:
return lst
accumulated_sum = [lst[0]]
for i in range(1, len(lst)):
accumulated_sum.append(accumulated_sum[i - 1] + lst[i])
return accumulated_sum
def flatten(lst):
"""Flatten a list of lists into a list."""
return [item for sublist in lst for item in sublist]
def eprint(msg, end="\n"):
"""Print for stderr."""
sys.stderr.write(msg + end)
def main(input_file, requested_sum, v, dens, deep, ext_out):
"""Entry point."""
t0 = dt.now()
ssp = SSP_lib(input_file, requested_sum, v,
dens, deep, ext_out)
answer = ssp.solve_ssp()
ans_str = str(sorted(answer, reverse=True)) if answer else "None"
if answer:
assert sum(answer) == requested_sum
print("# Answer is:\n{}".format(ans_str))
if ext_out:
print("# /E: Lib calls: {}".format(ssp._lib_calls))
print("# /E: Commited shifts: {}".format(ssp._shifts_num))
print("# /E: Elapsed time: {}".format(dt.now() - t0))
print("# /E: Answer on leaf node: {}".format(ssp._on_leaf))
if __name__ == "__main__":
args = parse_args()
main(args.input, args.requested_sum,
args.verbose, args.get_density,
args.deep, args.ext_out)
| StarcoderdataPython |
1719078 | <reponame>alexandru-m-g/hdx-ckan
import requests
import logging
import beaker.cache as bcache
import pylons.config as config
from datetime import datetime, timedelta
from collections import OrderedDict
import ckanext.hdx_theme.util.jql_queries as jql_queries
bcache.cache_regions.update({
'hdx_jql_cache': {
'expire': int(config.get('hdx.analytics.hours_for_results_in_cache', 24)) * 60 * 60,
'type': 'file',
'data_dir': config.get('hdx.caching.base_dir', '/tmp/hdx') + '/jql_cache/data',
'lock_dir': config.get('hdx.caching.base_dir', '/tmp/hdx') + '/jql_cache/lock',
'key_length': 250
}
})
CONFIG_API_SECRET = config.get('hdx.analytics.mixpanel.secret')
log = logging.getLogger(__name__)
class JqlQueryExecutor(object):
def __init__(self, query, *args):
self.payload = {
'script': query.format(*args)
}
def run_query(self, transformer):
'''
:param transformer: transforms the request result
:type transformer: MappingResultTransformer
:return: a dict mapping the key to the values
:rtype: dict
'''
nose_test = True if config.get('ckan.site_id') == 'test.ckan.net' else False
if nose_test:
return {}
else:
r = requests.post('https://mixpanel.com/api/2.0/jql', data=self.payload, auth=(CONFIG_API_SECRET, ''))
r.raise_for_status()
return transformer.transform(r)
class JqlQueryExecutorForHoursSinceNow(JqlQueryExecutor):
def __init__(self, query, hours_since_now):
super(JqlQueryExecutorForHoursSinceNow, self). \
__init__(query, *JqlQueryExecutorForHoursSinceNow._compute_period(hours_since_now))
@staticmethod
def _compute_period(hours_since_now):
'''
:param hours_since_now: for how many hours back should the mixpanel call be made
:type hours_since_now: int
:return: a list with 2 iso date strings representing the beginning and ending of the period
:rtype: list[str]
'''
until_date_str = datetime.utcnow().isoformat()[:10]
from_date_str = (datetime.utcnow() - timedelta(hours=hours_since_now)).isoformat()[
:10] if hours_since_now else '2016-08-01'
return [from_date_str, until_date_str]
class JqlQueryExecutorForWeeksSinceNow(JqlQueryExecutor):
def __init__(self, query, weeks_since, since_date):
'''
:param query:
:type query: str
:param weeks_since:
:type weeks_since: int
:param since_date:
:type since_date: datetime
'''
super(JqlQueryExecutorForWeeksSinceNow, self). \
__init__(query, *JqlQueryExecutorForWeeksSinceNow._compute_period(weeks_since, since_date))
@staticmethod
def _compute_period(weeks_since, since_date):
'''
:param weeks_since_now: for how many weeks back should the mixpanel call be made ( a week starts monday )
:type weeks_since_now: int
:param since_date:
:type since_date: datetime
:return: a list with 2 iso date strings representing the beginning and ending of the period
:rtype: list[str]
'''
until_date = since_date
until_date_str = until_date.isoformat()[:10]
from_date = until_date - timedelta(weeks=weeks_since, days=until_date.weekday())
from_date_str = from_date.isoformat()[:10]
return [from_date_str, until_date_str]
class MappingResultTransformer(object):
def __init__(self, key_name):
self.key_name = key_name
def transform(self, response):
'''
:param response: the HTTP response
:type response: requests.Response
:return:
:rtype: dict
'''
return {item.get(self.key_name): item.get('value') for item in response.json()}
class MultipleValueMappingResultTransformer(MappingResultTransformer):
def __init__(self, key_name, secondary_key_name):
super(MultipleValueMappingResultTransformer, self).__init__(key_name)
self.secondary_key_name = secondary_key_name
def transform(self, response):
result = {}
''':type : dict[str, OrderedDict]'''
for item in response.json():
main_key = item.get(self.key_name)
secondary_key = item.get(self.secondary_key_name)
if main_key not in result:
result[main_key] = OrderedDict()
result[main_key][secondary_key] = {'value': item.get('value', 0), self.secondary_key_name: secondary_key}
return result
class MultipleValueMandatoryMappingResultTransformer(MappingResultTransformer):
def __init__(self, key_name, mandatory_key, mandatory_values):
super(MultipleValueMandatoryMappingResultTransformer, self).__init__(key_name)
self.mandatory_key = mandatory_key
self.mandatory_values = mandatory_values
self.template = [(item, {mandatory_key: item, 'value': 0}) for item in mandatory_values]
def transform(self, response):
result = {}
''':type : dict[str, OrderedDict]'''
for item in response.json():
main_key = item.get(self.key_name)
secondary_key = item.get(self.mandatory_key)
if secondary_key not in self.mandatory_values:
log.error('{} not in mandatory values {}'.format(secondary_key, ','.join(self.mandatory_values)))
continue
if main_key not in result:
result[main_key] = OrderedDict(self.template)
result[main_key][secondary_key] = {'value': item.get('value', 0), self.mandatory_key: secondary_key}
return result
@bcache.cache_region('hdx_jql_cache', 'downloads_per_dataset_all_cached')
def downloads_per_dataset_all_cached():
return downloads_per_dataset()
def downloads_per_dataset(hours_since_now=None):
query_executor = JqlQueryExecutorForHoursSinceNow(jql_queries.DOWNLOADS_PER_DATASET, hours_since_now)
result = query_executor.run_query(MappingResultTransformer('dataset_id'))
return result
@bcache.cache_region('hdx_jql_cache', 'downloads_per_dataset_per_week_last_24_weeks')
def downloads_per_dataset_per_week_last_24_weeks_cached():
return downloads_per_dataset_per_week(24)
def downloads_per_dataset_per_week(weeks=24):
since = datetime.utcnow()
query_executor = JqlQueryExecutorForWeeksSinceNow(jql_queries.DOWNLOADS_PER_DATASET_PER_WEEK, weeks, since)
mandatory_values = _generate_mandatory_dates(since, weeks)
result = query_executor.run_query(
MultipleValueMandatoryMappingResultTransformer('dataset_id', 'date', mandatory_values))
return result
@bcache.cache_region('hdx_jql_cache', 'downloads_per_organization_last_30_days_cached')
def downloads_per_organization_last_30_days_cached():
return downloads_per_organization(30)
def downloads_per_organization(days_since_now=30):
query_executor = JqlQueryExecutorForHoursSinceNow(jql_queries.DOWNLOADS_PER_ORGANIZATION, days_since_now * 24)
result = query_executor.run_query(MappingResultTransformer('org_id'))
return result
@bcache.cache_region('hdx_jql_cache', 'downloads_per_organization_per_week_last_24_weeks_cached')
def downloads_per_organization_per_week_last_24_weeks_cached():
return downloads_per_organization_per_week(24)
def downloads_per_organization_per_week(weeks=24):
since = datetime.utcnow()
query_executor = JqlQueryExecutorForWeeksSinceNow(jql_queries.DOWNLOADS_PER_ORGANIZATION_PER_WEEK, weeks, since)
mandatory_values = _generate_mandatory_dates(since, weeks)
result = query_executor.run_query(
MultipleValueMandatoryMappingResultTransformer('org_id', 'date', mandatory_values))
return result
@bcache.cache_region('hdx_jql_cache', 'downloads_per_organization_per_dataset_last_24_weeks_cached')
def downloads_per_organization_per_dataset_last_24_weeks_cached():
return downloads_per_organization_per_dataset(24)
def downloads_per_organization_per_dataset(weeks=24):
since = datetime.utcnow()
query_executor = JqlQueryExecutorForWeeksSinceNow(jql_queries.DOWNLOADS_PER_ORGANIZATION_PER_DATASET, weeks, since)
result = query_executor.run_query(
MultipleValueMappingResultTransformer('org_id', 'dataset_id'))
return result
@bcache.cache_region('hdx_jql_cache', 'pageviews_per_dataset_last_14_days_cached')
def pageviews_per_dataset_last_14_days_cached():
hours = 14 * 24
return pageviews_per_dataset(hours)
def pageviews_per_dataset(hours_since_now=None):
query_executor = JqlQueryExecutorForHoursSinceNow(jql_queries.PAGEVIEWS_PER_DATASET, hours_since_now)
result = query_executor.run_query(MappingResultTransformer('dataset_id'))
return result
@bcache.cache_region('hdx_jql_cache', 'pageviews_per_organization_last_30_days_cached')
def pageviews_per_organization_last_30_days_cached():
return pageviews_per_organization(30)
def pageviews_per_organization(days_since_now=30):
query_executor = JqlQueryExecutorForHoursSinceNow(jql_queries.PAGEVIEWS_PER_ORGANIZATION, days_since_now * 24)
result = query_executor.run_query(MappingResultTransformer('org_id'))
return result
@bcache.cache_region('hdx_jql_cache', 'pageviews_per_organization_per_week_last_24_weeks_cached')
def pageviews_per_organization_per_week_last_24_weeks_cached():
return pageviews_per_organization_per_week(24)
def pageviews_per_organization_per_week(weeks=24):
since = datetime.utcnow()
query_executor = JqlQueryExecutorForWeeksSinceNow(jql_queries.PAGEVIEWS_PER_ORGANIZATION_PER_WEEK, weeks, since)
mandatory_values = _generate_mandatory_dates(since, weeks)
result = query_executor.run_query(
MultipleValueMandatoryMappingResultTransformer('org_id', 'date', mandatory_values))
return result
def _generate_mandatory_dates(since, weeks):
'''
:param since: the datetime "until" object
:type since: datetime
:param weeks:
:type weeks: int
:return: list of mandatory dates
:rtype: list[str]
'''
mandatory_dates = []
''':type : list[datetime]'''
for i in range(0, weeks+1):
mandatory_dates.insert(0, since - timedelta(weeks=i, days=since.weekday()))
mandatory_values = list(map(lambda x: x.isoformat()[:10], mandatory_dates))
return mandatory_values
| StarcoderdataPython |
3298741 | <filename>views.py
from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect, csrf_exempt
# from django.template.context_processors import csrf
from hashlib import sha512
import hashlib
# Create your views here.
def index(request):
MERCHANT_KEY = "33y8dMBB"
SALT = "HIRqERoClU"
PAYU_BASE_URL = "https://sandboxsecure.payu.in/_payment"
# PAYU_BASE_URL = "https://secure.payu.in"
action = ""
txnid = "ABC12345671234567891"
hashh = ""
hash_string = ""
posted = {}
posted['txnid'] = txnid
if request.method == 'POST':
action = PAYU_BASE_URL
for i in request.POST:
posted[i] = request.POST[i]
hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
hashVarsSeq = hashSequence.split('|')
for i in hashVarsSeq:
try:
hash_string+=str(posted[i])
except Exception:
hash_string+=""
hash_string+="|"
hash_string+=SALT
tempHash = sha512(hash_string.encode('utf-8')).hexdigest().lower()
hashh = tempHash
mycontext = {"head":"PayU Money","MERCHANT_KEY":MERCHANT_KEY, "posted":posted, "hashh":hashh, "hash_string":hash_string, "txnid":txnid, "action":action}
return render(request,'payu/paymentform.html', context=mycontext)
@csrf_protect
@csrf_exempt
def success(request):
# c = {}
# c.update(csrf(request))
status = request.POST['status']
firstname = request.POST['firstname']
amount = request.POST['amount']
txnid = request.POST['txnid']
posted_hash = request.POST['hash']
key = request.POST['key']
productinfo = request.POST['productinfo']
email = request.POST['email']
SALT = "HIRqERoClU"
try:
additionalCharges = request.POST['additionalCharges']
retHashSeq = additionalCharges+'|'+SALT+'|'+status+'|||||||||||'+email+'|'+firstname+'|'+productinfo+'|'+amount+'|'+txnid+'|'+key
except Exception:
retHashSeq = SALT+'|'+status+'|||||||||||'+email+'|'+firstname+'|'+productinfo+'|'+amount+'|'+txnid+'|'+key
hashh = hashlib.sha512(retHashSeq.encode('utf-8')).hexdigest().lower()
if (hashh != posted_hash):
paymentStatus = "Invalid Transaction. Please try again"
else:
paymentStatus = "Thank You. Your order status is %s. \n Your Transaction ID for this transaction is %s.\n We have received a payment of Rs. %s\n"%(status,txnid,amount)
t = {"finalstatus": str(paymentStatus)}
return render(request, 'payu/success.html', context=t)
@csrf_protect
@csrf_exempt
def fail(request):
# c = {}
# c.update(csrf(request))
status = request.POST['status']
firstname = request.POST['firstname']
amount = request.POST['amount']
txnid = request.POST['txnid']
posted_hash = request.POST['hash']
key = request.POST['key']
productinfo = request.POST['productinfo']
email = request.POST['email']
SALT = "HIRqERoClU"
try:
additionalCharges = request.POST['additionalCharges']
retHashSeq = additionalCharges+'|'+SALT+'|'+status+'|||||||||||'+email+'|'+firstname+'|'+productinfo+'|'+amount+'|'+txnid+'|'+key
except Exception:
retHashSeq = SALT+'|'+status+'|||||||||||'+email+'|'+firstname+'|'+productinfo+'|'+amount+'|'+txnid+'|'+key
hashh = hashlib.sha512(retHashSeq.encode('utf-8')).hexdigest().lower()
if (hashh != posted_hash):
paymentStatus = "Invalid Transaction. Please try again"
else:
paymentStatus = "Thank You. Your order status is %s. \n Your Transaction ID for this transaction is %s.\n We have received a payment of Rs. %s\n"%(status,txnid,amount)
t = {"finalstatus": str(paymentStatus)}
return render(request, 'payu/fail.html', context=t)
| StarcoderdataPython |
1701682 | '''Faça um programa que, dado um conjunto de N números, determine o menor valor, o maior valor e a soma dos valores.'''
conjunto = int(input('Quantos Números terá seu conjunto? '))
menor_valor = maior_valor = soma = 0
for cont in range (1, conjunto+1):
num = float(input(f'{cont}º número: '))
soma += num
if cont == 1:
menor_valor = num
else:
if num < menor_valor:
menor_valor = num
if num > maior_valor:
maior_valor = num
print(f'Menor valor: {menor_valor} \nMaior valor: {maior_valor} \nSoma: {soma}') | StarcoderdataPython |
1625943 | """Loads CartPole-v1 demonstrations and trains BC, GAIL, and AIRL models on that data.
"""
import pathlib
import pickle
import tempfile
import gym
import stable_baselines3 as sb3
from stable_baselines3.common import base_class
from stable_baselines3.common.torch_layers import (
BaseFeaturesExtractor,
# CombinedExtractor,
FlattenExtractor,
MlpExtractor,
NatureCNN,
create_mlp,
)
from imitation.algorithms import adversarial, bc
from imitation.algorithms.adversarial import airl, gail
from imitation.data import rollout
from imitation.util import logger, util
from imitation.policies import base, serialize
from imitation.algorithms.bc import reconstruct_policy
import os, glob
import numpy as np
import time
import torch as th
import imageio
env_name = 'NeedlePick-v0'
root_dir = "/home/zhaoogroup/code/tao_huang/SurRoL-imitation-main"
rollout_path = os.path.join(root_dir, "data/train_rollout_" + env_name + "_100x_rgbd_fixed.pkl") # train_rollout_400x
# Load pickled test demonstrations.
# with open("/home/curl/CUHK/Projects/RL/stable-baselines3-imitation/src/imitation/scripts/rollout_1x.pkl", "rb") as f:
with open(rollout_path, "rb") as f:
trajectories = pickle.load(f)
folder = '/home/zhaoogroup/code/tao_huang/SurRoL-imitation-main'
video_name = 'demo_pick_rdgd.mp4'
writer = imageio.get_writer(os.path.join(folder, video_name), fps=10)
for traj in trajectories:
for img in traj.obs:
writer.append_data(img[:,:,3])
writer.close()
transitions = rollout.flatten_trajectories(trajectories)
# Train GAIL on expert data.
# GAIL, and AIRL also accept as `expert_data` any Pytorch-style DataLoader that
# iterates over dictionaries containing observations, actions, and next_observations.
#venv = util.make_vec_camsimenv_multiple("CamEnvSim-v0", render_mode='rgbd_array', n_envs=200, batch_index=0, root_dir=traj_dir, train=True) # 81
#venv = base_class.BaseAlgorithm._wrap_env(venv, monitor_wrapper=True)
#venv_eval = util.make_vec_camsimenv_multiple("CamEnvSim-v0", render_mode='rgbd_array', n_envs=200, batch_index=0, root_dir=root_dir, train=False)
bc_logger = logger.configure(os.path.join(root_dir, 'log/tb'), ["tensorboard", "stdout"])
venv = util.make_vec_env(env_name, n_envs=1, visual=True)
#venv.observation_space = gym.spaces.Box(0, 255, shape=obs_shape, dtype='uint8')
start = time.time()
bc_trainer = bc.BC(
observation_space=venv.observation_space,
action_space=venv.action_space,
demonstrations=transitions,
custom_logger=bc_logger,
)
bc_trainer.train(n_epochs=100)
end = time.time()
print("BC training time: ", end - start)
bc_trainer.save_policy(os.path.join(root_dir, "log/policy/BC_" + env_name + "_cnn_100_rgbd_fixed.pt")) | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.