id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3385713 | from squabblegui.sqsettingswidget import SqSettingsWidget
from squabblegui.sqchatwidget import SqChatWidget
| StarcoderdataPython |
123552 |
import json
import time
import copy
import checkpoint as loader
import argparse
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from torch.autograd import Variable
from torch import nn,optim
import torch
import torchvision
import torch.nn.functional as F
from torch import nn
from PIL import Image
from torchvision import datasets,transforms,models
from collections import OrderedDict
import torch.optim as optim
from torch.optim import lr_scheduler
def imshow(image, ax=None, title=None):
if ax is None:
fig, ax = plt.subplots()
# PyTorch tensors assume the color channel is the first dimension
# but matplotlib assumes is the third dimension
image = image.transpose((1, 2, 0))
# Undo preprocessing
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
image = std * image + mean
# Image needs to be clipped between 0 and 1 or it looks like noise when displayed
image = np.clip(image, 0, 1)
ax.imshow(image)
return ax
def process_image(image_path):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
#image_pil=Image.open(image_path)
loader = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor()])
image_pl = Image.open(image_path)
imagepl_ft = loader(image_pl).float()
np_image=np.array(imagepl_ft)
#np_image=np_image/255
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
np_image = (np.transpose(np_image, (1, 2, 0)) - mean)/std
np_image = np.transpose(np_image, (2, 0, 1))
return np_image
def predict(image_path, model_name, topk=10, categories='', device='cuda'):
''' Predict the class (or classes) of an image using a trained deep learning model.
'''
if(not torch.cuda.is_available() and device=='cuda'):
device='cpu'
# TODO: Implement the code to predict the class from an image file
with open('cat_to_name.json', 'r') as f:
label_mapper = json.load(f)
gpu=(device=='cuda')
model=loader.load_checkpoint(model_name,gpu=gpu)
model.to('cpu')
img=process_image(image_path)
img=torch.from_numpy(img).type(torch.FloatTensor)
inpt=img.unsqueeze(0)
model_result=model.forward(inpt)
expResult=torch.exp(model_result)
firstTopX,SecondTopX=expResult.topk(topk)
probs = torch.nn.functional.softmax(firstTopX.data, dim=1).numpy()[0]
#classes = SecondTopX.data.numpy()[0]
#probs = firstTopX.detach().numpy().tolist()[0]
classes = SecondTopX.detach().numpy().tolist()[0]
# Convert indices to classes
idx_to_class = {val: key for key, val in
model.class_to_idx.items()}
#labels = [label_mapper[str(lab)] for lab in SecondTopX]
labels = [idx_to_class[y] for y in classes]
flowers=[categories[idx_to_class[i]] for i in classes]
return probs,flowers
def show_prediction(image_path,probabilities,labels, categories):
plt.figure(figsize=(6,10))
ax=plt.subplot(2,1,1)
flower_index=image_path.split('/')[2]
name=categories[flower_index]
img=process_image(image_path)
imshow(img,ax)
plt.subplot(2,1,2)
sns.barplot(x=probabilities,y=labels,color=sns.color_palette()[0])
plt.show()
if __name__=="__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=str)
parser.add_argument('--gpu', action='store_true')
parser.add_argument('--epochs', type=int)
parser.add_argument('--checkpoint', type=str)
parser.add_argument('--category_names', type=str)
parser.add_argument('--top_k', type=int)
args, _ = parser.parse_known_args()
if (args.input):
input_name=args.input
else:
input_name='flowers/test/28/image_05230.jpg'
if(args.checkpoint):
checkpoint=args.checkpoint
else:
checkpoint='ic-model.pth'
if(args.category_names):
category_names=args.category_names
else:
category_names='cat_to_name.json'
if(args.gpu):
device='cuda'
else:
device='cpu'
# show_prediction(image_path=input_name,model=checkpoint,category_names=category_names)
with open(category_names, 'r') as f:
categories = json.load(f)
# run the prediction
probabilities,labels=predict(input_name,checkpoint,topk=5,categories=categories,device=device)
# show prediction
print('predict results')
print(probabilities)
print(labels)
show_prediction(image_path=input_name,probabilities=probabilities,labels= labels, categories= categories)
| StarcoderdataPython |
101238 | # -------------------------------------------------------------------------------------------------
# STRING
# -------------------------------------------------------------------------------------------------
print('\n\t\tSTRING\n')
print("Hello Word!") # first example
print('Hello Word!') # second example
print("I don't think") # aphostrophe problem resolution (1)
print('He said :" Look at the sky!"...') # aphostrophe problem resolution (2)
print('I don\'t think') # aphostrophe problem resolution (3)
print(r'/home/Captain/example') # aphostrophe problem resolution (4)
print('Hi' + str(5)) #convert argument
firstName = 'Captain ' # use of variable (1)
print(firstName) # ...
print(firstName + 'Mich') # ...
print(firstName * 5) # multiply a string
# -------------------------------------------------------------------------------------------------
# WORK with STRING
# -------------------------------------------------------------------------------------------------
print('\n\t\tWORK with STRING\n')
user = 'Tuna'
print(user[0]) # use it if you want a specif letter of a string
print(user[1]) # ...
print(user[2]) # ...
print(user[3]) # ...
print('')
print(user[-1]) # ...if you want to start from the end
print(user[-2]) # ...
print(user[-3]) # ...
print(user[-4]) # ...
print('')
print(user[1:3]) # to slicing up a string[from character 'x' to(:) character 'y' not including 'y')
print(user[0:4]) # ...
print(user[1:]) # ...
print(user[:]) # ...
print('')
print(len(user)) # to measure the lenght of a string ( N.B: blank space count as character)
print(len('Tuna')) # ...
print(user.find('un')) # find the offset of a substring in 'user'; return 1 if the substring is found
print(user.replace('una', 'omb')) # replace occurencesof a string in 'user' with another
print(user) # notice that the originally string is not permanently modified
print(user.upper()) # convert all the contenent upper or lowercase
print(user.isalpha()) # find out if all the character in the string are alphabetic and return true if there is at least one character,
# false otherwise
line = 'aaa,bbb,cccccc,dd\n'
print(line.split(',')) # split on a specific delimiter into a list of substring
print(line.rstrip()) # remove whitespace characters on the right side
print(line.rstrip().split()) # combine two operation
print('%s, eggs, and %s' % ('spam', 'SPAM!')) # formatting expression
print('{}, eggs, and {}'.format('spam', 'SPAM!')) # formatting_Method
# -------------------------------------------------------------------------------------------------
# PATTERN MATCHING
# -------------------------------------------------------------------------------------------------
import re
str_example = 'Hello Python world' # search for a substring that begins with the word "Hello" followed by zero or more tabs
match = re.match('Hello[\t]*(.*)world', str_example) # or space, followed by arbitrary characters
print(match.group(1)) # saved as matched group (avaiable only if a substring is found)
pattern = '/usr/home/testuser' # another example that picks out three groups separated by slashes
match = re.match('[/:](.*)[/:](.*)[/:](.*)', pattern) # ...
print(match.groups()) # ...
match = re.split('[/:]', pattern) # in this case split give out the same result as previous example
print(match) # ...
| StarcoderdataPython |
8091864 | <filename>experimental/tau_value_determination.py
"""
Script for determining the optimal tau value for the Singular Value Decomposition (SVD) unfolding.
From http://root.cern.ch/root/html/TUnfold.html:
Note1: ALWAYS choose a higher number of bins on the reconstructed side
as compared to the generated size!
Note2: the events which are generated but not reconstructed
have to be added to the appropriate overflow bins of A
Note3: make sure all bins have sufficient statistics and their error is
non-zero. By default, bins with zero error are simply skipped;
however, this may cause problems if You try to unfold something
which depends on these input bins.
"""
from __future__ import division
from math import log10, pow
from rootpy.io import File
import matplotlib.pyplot as plt
import matplotlib
from copy import deepcopy
from ROOT import Double, TH1F, TGraph
from config.variable_binning import bin_edges
from tools.file_utilities import read_data_from_JSON
from tools.hist_utilities import value_error_tuplelist_to_hist
from tools.Unfolding import Unfolding, get_unfold_histogram_tuple
from tools.ROOT_utililities import set_root_defaults
font = {'family' : 'normal',
'weight' : 'normal',
'size' : 28}
matplotlib.rc( 'font', **font )
def drange( start, stop, step ):
r = start
while r < stop:
yield r
r += step
def get_tau_from_global_correlation( h_truth, h_measured, h_response, h_data = None ):
tau_0 = 1e-7
tau_max = 0.2
number_of_iterations = 10000
# tau_step = ( tau_max - tau_0 ) / number_of_iterations
optimal_tau = 0
minimal_rho = 9999
bias_scale = 0.
unfolding = Unfolding( h_truth,
h_measured,
h_response,
method = 'RooUnfoldTUnfold',
tau = tau_0 )
if h_data:
unfolding.unfold( h_data )
else: # closure test
unfolding.unfold( h_measured )
# cache functions and save time in the loop
Unfold = unfolding.unfoldObject.Impl().DoUnfold
GetRho = unfolding.unfoldObject.Impl().GetRhoI
# create lists
tau_values = []
rho_values = []
add_tau = tau_values.append
add_rho = rho_values.append
# for current_tau in drange(tau_0, tau_max, tau_step):
for current_tau in get_tau_range( tau_0, tau_max, number_of_iterations ):
Unfold( current_tau, h_data, bias_scale )
current_rho = GetRho( TH1F() )
add_tau( current_tau )
add_rho( current_rho )
if current_rho < minimal_rho:
minimal_rho = current_rho
optimal_tau = current_tau
return optimal_tau, minimal_rho, tau_values, rho_values
def draw_global_correlation( tau_values, rho_values, tau, rho, channel, variable ):
plt.figure( figsize = ( 16, 16 ), dpi = 200, facecolor = 'white' )
plt.plot( tau_values, rho_values )
plt.xscale('log')
plt.title(r'best $\tau$ from global correlation')
plt.xlabel( r'$\tau$', fontsize = 40 )
plt.ylabel( r'$\bar{\rho}(\tau)$', fontsize = 40 )
ax = plt.axes()
ax.annotate( r"$\tau = %.3g$" % tau,
xy = ( tau, rho ), xycoords = 'data',
xytext = ( 0.0010, 0.5 ), textcoords = 'data',
arrowprops = dict( arrowstyle = "fancy,head_length=0.4,head_width=0.4,tail_width=0.4",
connectionstyle = "arc3" ),
size = 40,
)
if use_data:
plt.savefig( 'plots/tau_from_global_correlation_%s_channel_%s_DATA.png' % ( channel, variable ) )
else:
plt.savefig( 'plots/tau_from_global_correlation_%s_channel_%s_MC.png' % ( channel, variable ) )
def get_tau_from_L_shape( h_truth, h_measured, h_response, h_data = None ):
tau_min = 1e-7
tau_max = 0.2
number_of_scans = 10000
# the best values depend on the variable!!!
# number_of_scans = 60
# tau_min = 1e-6
# tau_max = 1e-7 * 20000 + tau_min
# tau_min = 1e-7
# tau_max = 1e-2
unfolding = Unfolding( h_truth,
h_measured,
h_response,
method = 'RooUnfoldTUnfold',
tau = tau_min )
if h_data:
unfolding.unfold( h_data )
else: # closure test
unfolding.unfold( h_measured )
l_curve = TGraph()
unfolding.unfoldObject.Impl().ScanLcurve( number_of_scans, tau_min, tau_max, l_curve )
best_tau = unfolding.unfoldObject.Impl().GetTau()
x_value = unfolding.unfoldObject.Impl().GetLcurveX()
y_value = unfolding.unfoldObject.Impl().GetLcurveY()
return best_tau, l_curve, x_value, y_value
def draw_l_shape( l_shape, best_tau, x_value, y_value, channel, variable ):
total = l_shape.GetN()
x_values = []
y_values = []
add_x = x_values.append
add_y = y_values.append
for i in range( 0, total ):
x = Double( 0 )
y = Double( 0 )
l_shape.GetPoint( i, x, y )
add_x( x )
add_y( y )
plt.figure( figsize = ( 16, 16 ), dpi = 200, facecolor = 'white' )
plt.plot( x_values, y_values )
plt.xlabel( r'log10($\chi^2$)', fontsize = 40 )
plt.ylabel( 'log10(curvature)', fontsize = 40 )
ax = plt.axes()
ax.annotate( r"$\tau = %.3g$" % best_tau,
xy = ( x_value, y_value ), xycoords = 'data',
xytext = ( 0.3, 0.3 ), textcoords = 'figure fraction',
arrowprops = dict( arrowstyle = "fancy,head_length=0.4,head_width=0.4,tail_width=0.4",
connectionstyle = "arc3" ),
size = 40,
)
if use_data:
plt.savefig( 'plots/tau_from_L_shape_%s_channel_%s_DATA.png' % ( channel, variable ) )
else:
plt.savefig( 'plots/tau_from_L_shape_%s_channel_%s_MC.png' % ( channel, variable ) )
def get_data_histogram( channel, variable, met_type ):
fit_result_input = '../../data/8TeV/%(variable)s/fit_results/central/fit_results_%(channel)s_%(met_type)s.txt'
fit_results = read_data_from_JSON( fit_result_input % {'channel': channel, 'variable': variable, 'met_type':met_type} )
fit_data = fit_results['TTJet']
h_data = value_error_tuplelist_to_hist( fit_data, bin_edges[variable] )
return h_data
def get_tau_range( tau_min, tau_max, number_of_points ):
# Use 3 scan points minimum
if number_of_points < 3:
number_of_points = 3
# Setup Vector
result = [0] * number_of_points
# Find the scan points
# Use equidistant steps on a logarithmic scale
step = ( log10( tau_max ) - log10( tau_min ) ) / ( number_of_points - 1 );
for i in range ( 0, number_of_points ):
result[i] = pow( 10., ( log10( tau_min ) + i * step ) );
return result;
if __name__ == '__main__':
set_root_defaults()
use_data = True
input_file_8Tev = '/storage/TopQuarkGroup/mc/8TeV/NoSkimUnfolding/v10/TTJets_MassiveBinDECAY_TuneZ2star_8TeV-madgraph-tauola/unfolding_v10_Summer12_DR53X-PU_S10_START53_V7C-v1_NoSkim/TTJets_nTuple_53X_mc_merged_001.root'
met_type = 'patType1CorrectedPFMet'
# ST and HT have the problem of the overflow bin in the truth/response matrix
# 7 input bins and 8 output bins (includes 1 overflow bin)
variables = ['MET', 'WPT', 'MT' , 'ST', 'HT']
centre_of_mass = 8
ttbar_xsection = 225.2
luminosity = 19712
input_file = File( input_file_8Tev )
taus_from_global_correlaton = {}
taus_from_L_shape = {}
for channel in ['electron', 'muon']:
taus_from_global_correlaton[channel] = {}
taus_from_L_shape[channel] = {}
for variable in variables:
print 'Doing variable"', variable, '" in', channel, '-channel'
h_truth, h_measured, h_response, _ = get_unfold_histogram_tuple(
inputfile = input_file,
variable = variable,
channel = channel,
met_type = met_type,
centre_of_mass = centre_of_mass,
ttbar_xsection = ttbar_xsection,
luminosity = luminosity )
h_data = None
if use_data:
h_data = get_data_histogram( channel, variable, met_type )
else:
h_data = deepcopy( h_measured )
tau, rho, tau_values, rho_values = get_tau_from_global_correlation( h_truth, h_measured, h_response, h_data )
draw_global_correlation( tau_values, rho_values, tau, rho, channel, variable )
tau, l_curve, x, y = get_tau_from_L_shape( h_truth, h_measured, h_response, h_data )
draw_l_shape( l_curve, tau, x, y, channel, variable )
| StarcoderdataPython |
1772800 | <filename>netforce_mfg/netforce_mfg/models/production_qc.py
# Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
from netforce.model import Model, fields
from netforce.database import get_connection
from datetime import *
import time
class ProductionQC(Model):
_name = "production.qc"
_string = "Production Quality Control"
_fields = {
"order_id": fields.Many2One("production.order", "Production Order", required=True, on_delete="cascade"),
"test_id": fields.Many2One("qc.test", "QC Test", required=True),
"sample_qty": fields.Decimal("Sampling Qty"),
"value": fields.Char("Value"),
"min_value": fields.Decimal("Min Value", function="_get_related", function_context={"path": "test_id.min_value"}),
"max_value": fields.Decimal("Max Value", function="_get_related", function_context={"path": "test_id.max_value"}),
"result": fields.Selection([["yes", "Pass"], ["no", "Not Pass"], ["na", "N/A"]], "Result", required=True),
}
_defaults = {
"result": "no",
}
ProductionQC.register()
| StarcoderdataPython |
8180161 | <filename>ros/src/perception/src/perception/video_inference.py
import sys
from moviepy.editor import *
import perception.predict as predict
import numpy as np
import cv2
def main():
if len(sys.argv) != 2:
print("Please specify path to movie file.")
exit()
filepath = sys.argv[1]
print("Reading movie file: {0}".format(filepath))
# fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use lower case
# out = cv2.VideoWriter('output.mp4', fourcc, 10.0, (1920, 1080))
predictor = predict.Prediction()
def process_image(img):
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
prediction = predictor.infer(img.astype(np.float32), overlay=True)
return np.array(prediction)
video = VideoFileClip(filepath).subclip(50,100).fl_image(process_image)
video.write_videofile('output.mp4')
print("\nFINISH")
if __name__ == '__main__':
main()
| StarcoderdataPython |
3425201 | <reponame>vijaykumawat256/Prompt-Summarization
def solution(roman):
| StarcoderdataPython |
1712867 | from __future__ import division
import threading
import time
from src.robot import Robot
from src.drawing import Map, Canvas
import brickpi
#Initialize the interface
interface=brickpi.Interface()
interface.initialize()
Canvas = Canvas()
Map = Map(Canvas)
Robot = Robot(interface,
pid_config_file="speed_config.json",
mcl=False,
threading=False,
x=0,
y=0,
theta=0,
mode="line",
canvas = Canvas,
planning = True
)
Robot.start_obstacle_detection(interval=2)
Robot.start_challenge(interval = 1)
| StarcoderdataPython |
168189 | <gh_stars>0
import setuptools
with open("../readme.md", "r") as f:
long_description = f.read()
setuptools.setup(
name="a9a",
version="0.0.2",
author="<NAME>",
description="a9a archivator",
long_description=long_description,
long_description_content_type="text/markdown",
packages=setuptools.find_packages(),
python_requires=">=3.6",
py_modules=["a9a"],
package_dir={"": "."},
install_requires=[],
)
| StarcoderdataPython |
99350 | <filename>tests/elements/test_sextupole.py
from unittest import TestCase
import numpy as np
from pyaccelerator.elements.sextupole import SextupoleThin
class TestSextupoleThin(TestCase):
def test_init(self):
sextupole = SextupoleThin(1)
assert sextupole.length == 0
assert sextupole.name.startswith("sextupole_thin")
sextupole = SextupoleThin(1, name="sext_f")
assert sextupole.name == "sext_f"
def test_transfer_matrix(self):
sextupole = SextupoleThin(1)
# the linear part is the identity matrix
expected_transfer_matrix = np.identity(5)
m = sextupole._get_transfer_matrix()
assert np.allclose(m, expected_transfer_matrix)
assert np.allclose(sextupole.m, m)
# now the non linear part
term = sextupole._non_linear_term(np.array([2, 0, 1, 0, 0]))
assert np.allclose(term, np.array([[0, -1.5, 0, 2, 0]]))
def test_repr(self):
repr(SextupoleThin(1))
def test_serialize(self):
sextupole = SextupoleThin(0.6)
dic = sextupole._serialize()
assert dic["element"] == "SextupoleThin"
assert dic["k"] == sextupole.k
assert dic["name"] == sextupole.name
# make sure that if the instance's attribute is changed
# the serialization takes the new values.
sextupole = SextupoleThin(0.6)
sextupole.f = 0.8
dic = sextupole._serialize()
assert dic["element"] == "SextupoleThin"
assert dic["k"] == sextupole.k
assert dic["name"] == sextupole.name
def test_copy(self):
sextupole = SextupoleThin(1)
copy = sextupole.copy()
assert copy.k == sextupole.k
assert copy.name == sextupole.name
# make sure that if the instance's attribute is changed
# copying takes the new values.
sextupole = SextupoleThin(1)
sextupole.k = 2
copy = sextupole.copy()
assert copy.k == sextupole.k
assert copy.name == sextupole.name
| StarcoderdataPython |
298639 | #Edited 12/3/17 <NAME>
#Functions used to set up the algorithm and perform checks on the given
#variables
import scipy
import numpy
import sys
import random
import QJMCAA
import QJMCMath
#TESTED
def dimensionTest(H,jumpOps,eOps,psi0):
#Compare all to the hamiltonian
dim = H.get_shape()
c = 0
for item in jumpOps:
c+=1
if (item.get_shape() != dim):
sys.exit("ERROR: the "+ str(c) +" jump operator (or more) are the wrong dimension with respect to H")
c = 0
for item in eOps:
c+=1
if (item.get_shape() != dim):
sys.exit("ERROR: the "+ str(c) +" jump operator (or more) are the wrong dimension with respect to H")
if (psi0.shape[0] != dim[0]):
sys.exit("ERROR: the initial state is the wrong dimension")
if (psi0.shape[1] != 1):
sys.exit("ERROR: the initial state is the wrong dimension")
#TESTED
def typeTest(settings, savingSettings, H, jumpOps, eOps, psi0):
#Checks the settings data typeTest
if (not isinstance(settings, QJMCAA.Settings)):
sys.exit("ERROR: the settings object is not the correct class")
if (not isinstance(savingSettings, QJMCAA.SavingSettings)):
sys.exit("ERROR: the savingSettings object is not the correct class")
if (not scipy.sparse.issparse(H)):
sys.exit("ERROR: the H is not a sparse scipy array")
c = 0
for item in jumpOps:
c+=1
if (not scipy.sparse.issparse(item)):
sys.exit("ERROR: the "+ str(c) +" jump operator (or more) is not a sparse scipy array")
c = 0
for item in eOps:
c+=1
if (not scipy.sparse.issparse(item)):
sys.exit("ERROR: the "+ str(c) +" expectation operator (or more) is not a sparse scipy array")
if (not isinstance(psi0,numpy.ndarray)):
sys.exit("ERROR: the initial state is not a numpy ndarray")
#TESTED
def jumpOperatorsPaired(jumpOps):
jumpOpsPaired = []
for jumpOp in jumpOps:
jumpOpsPaired.append(jumpOp.conjugate().transpose().dot(jumpOp))
return jumpOpsPaired
#TESTED
def addExpectationSquared(eOps):
for i in range(len(eOps)):
eOps.append(eOps[i]*eOps[i])
def eResultsProduction(eOps,numberOfPoints):
eResults = []
for _ in range(len(eOps)):
eResults.append(numpy.zeros(numberOfPoints))
return eResults
def histogramProduction(histogramOptions,numberOfPoints):
histograms = []
for hist in histogramOptions:
histograms.append(numpy.zeros((numberOfPoints,hist.numberOfBars)))
return histograms
def HEffProduction(H, jumpOpsPaired):
j=complex(0,1)
HEff = H
for jOpPaired in jumpOpsPaired:
HEff = HEff - (j/2)*jOpPaired
return HEff
def HEffExponentProduction(HEff, dt):
j=complex(0,1)
return scipy.linalg.expm(HEff.multiply(-j*dt))
#TODO make this use the HEffExponentProduction function
def HEffExponentSetProduction(H,jumpOpsPaired, dt, accuracyMagnitude):
j=complex(0,1)
HEff = HEffProduction(H, jumpOpsPaired)
HEffExponentDt = scipy.linalg.expm(HEff.multiply(-j*dt))
#Defines a HEff Exponent using a small time-steps
HEffExponentDtSet = []
for i in range(1,accuracyMagnitude + 1):
HEffExponentDtSet.append(scipy.linalg.expm(
HEff.multiply(-j*(dt/(pow(10,i))))))
return HEffExponentDt, HEffExponentDtSet
#TESTED
def HEffExponentSetProductionBinary(H, jumpOpsPaired, deltaT, settings):
HEff = HEffProduction(H, jumpOpsPaired)
#Defines a HEff Exponent using a small time-steps
HEffExponentDtSet = []
dtSet = []
dt = deltaT * 2
#TODO add a safety check that the smallest dt in the list isn't smaller (if so just do the one)
while (dt > settings.smallestDt):
dt = dt/2
dtSet.append(dt)
HEffExponentDtSet.append(HEffExponentProduction(HEff, dt))
return HEffExponentDtSet, dtSet
#TESTED
def randomInitialState(H):
dim = H.get_shape()[0]
psi0 = numpy.ndarray(shape=(dim,1),dtype=complex)
for i in range(dim):
r = random.random()
u = random.random()
psi0[i] = complex(r,u)
psi0 = QJMCMath.normalise(psi0)
return psi0
| StarcoderdataPython |
1883962 | from pandas import DataFrame
from engine.pkmn.types.TypesBaseRuleSet import TypesBaseRuleSet
from models.pkmn.types.PokemonType import PokemonType
class ClassicTypesRuleSet(TypesBaseRuleSet):
def __init__(self):
# Init all at 1
type_effectiveness_chart = DataFrame({ref_pkmn_type: {pkmn_type: float(1) for pkmn_type in PokemonType}
for ref_pkmn_type in PokemonType})
# Normal is:
# ineffective against
type_effectiveness_chart[PokemonType.Normal][PokemonType.Ghost] = float(0)
# not very effective against
type_effectiveness_chart[PokemonType.Normal][PokemonType.Steel] = float(.5)
type_effectiveness_chart[PokemonType.Normal][PokemonType.Rock] = float(.5)
# Fire is:
# very effective against
type_effectiveness_chart[PokemonType.Fire][PokemonType.Steel] = float(2)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Grass] = float(2)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Ice] = float(2)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Bug] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Fire][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Water] = float(.5)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Rock] = float(.5)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Dragon] = float(.5)
# Water is:
# very effective against
type_effectiveness_chart[PokemonType.Water][PokemonType.Fire] = float(2)
type_effectiveness_chart[PokemonType.Water][PokemonType.Ground] = float(2)
type_effectiveness_chart[PokemonType.Water][PokemonType.Rock] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Water][PokemonType.Water] = float(.5)
type_effectiveness_chart[PokemonType.Water][PokemonType.Grass] = float(.5)
type_effectiveness_chart[PokemonType.Water][PokemonType.Dragon] = float(.5)
# Electric is:
# ineffective against
type_effectiveness_chart[PokemonType.Electric][PokemonType.Ground] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Electric][PokemonType.Water] = float(2)
type_effectiveness_chart[PokemonType.Electric][PokemonType.Flying] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Electric][PokemonType.Electric] = float(.5)
type_effectiveness_chart[PokemonType.Electric][PokemonType.Grass] = float(.5)
type_effectiveness_chart[PokemonType.Electric][PokemonType.Dragon] = float(.5)
# Grass is:
# very effective against
type_effectiveness_chart[PokemonType.Grass][PokemonType.Water] = float(2)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Ground] = float(2)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Rock] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Grass][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Grass] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Poison] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Flying] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Bug] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Dragon] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Steel] = float(.5)
# Ice is:
# very effective against
type_effectiveness_chart[PokemonType.Ice][PokemonType.Grass] = float(2)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Ground] = float(2)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Flying] = float(2)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Dragon] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Ice][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Water] = float(.5)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Ice] = float(.5)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Steel] = float(.5)
# Fighting is:
# ineffective against
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Ghost] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Normal] = float(2)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Ice] = float(2)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Rock] = float(2)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Dark] = float(2)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Steel] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Poison] = float(.5)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Flying] = float(.5)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Psychic] = float(.5)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Bug] = float(.5)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Fairy] = float(.5)
# Poison is:
# ineffective against
type_effectiveness_chart[PokemonType.Poison][PokemonType.Steel] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Poison][PokemonType.Grass] = float(2)
type_effectiveness_chart[PokemonType.Poison][PokemonType.Fairy] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Poison][PokemonType.Poison] = float(.5)
type_effectiveness_chart[PokemonType.Poison][PokemonType.Ground] = float(.5)
type_effectiveness_chart[PokemonType.Poison][PokemonType.Rock] = float(.5)
type_effectiveness_chart[PokemonType.Poison][PokemonType.Ghost] = float(.5)
# Ground is:
# ineffective against
type_effectiveness_chart[PokemonType.Ground][PokemonType.Flying] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Ground][PokemonType.Fire] = float(2)
type_effectiveness_chart[PokemonType.Ground][PokemonType.Electric] = float(2)
type_effectiveness_chart[PokemonType.Ground][PokemonType.Poison] = float(2)
type_effectiveness_chart[PokemonType.Ground][PokemonType.Rock] = float(2)
type_effectiveness_chart[PokemonType.Ground][PokemonType.Steel] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Ground][PokemonType.Grass] = float(.5)
type_effectiveness_chart[PokemonType.Ground][PokemonType.Bug] = float(.5)
# Flying is:
# very effective against
type_effectiveness_chart[PokemonType.Flying][PokemonType.Grass] = float(2)
type_effectiveness_chart[PokemonType.Flying][PokemonType.Fighting] = float(2)
type_effectiveness_chart[PokemonType.Flying][PokemonType.Bug] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Flying][PokemonType.Electric] = float(.5)
type_effectiveness_chart[PokemonType.Flying][PokemonType.Rock] = float(.5)
type_effectiveness_chart[PokemonType.Flying][PokemonType.Steel] = float(.5)
# Psychic is:
# ineffective against
type_effectiveness_chart[PokemonType.Psychic][PokemonType.Dark] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Psychic][PokemonType.Poison] = float(2)
type_effectiveness_chart[PokemonType.Psychic][PokemonType.Fighting] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Psychic][PokemonType.Psychic] = float(.5)
type_effectiveness_chart[PokemonType.Psychic][PokemonType.Steel] = float(.5)
# Bug is:
# very effective against
type_effectiveness_chart[PokemonType.Bug][PokemonType.Grass] = float(2)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Psychic] = float(2)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Dark] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Bug][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Fighting] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Poison] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Flying] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Rock] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Ghost] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Steel] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Fairy] = float(.5)
# Rock is:
# very effective against
type_effectiveness_chart[PokemonType.Rock][PokemonType.Fire] = float(2)
type_effectiveness_chart[PokemonType.Rock][PokemonType.Ice] = float(2)
type_effectiveness_chart[PokemonType.Rock][PokemonType.Flying] = float(2)
type_effectiveness_chart[PokemonType.Rock][PokemonType.Bug] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Rock][PokemonType.Fighting] = float(.5)
type_effectiveness_chart[PokemonType.Rock][PokemonType.Ground] = float(.5)
type_effectiveness_chart[PokemonType.Rock][PokemonType.Steel] = float(.5)
# Ghost is:
# ineffective against
type_effectiveness_chart[PokemonType.Ghost][PokemonType.Normal] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Ghost][PokemonType.Psychic] = float(2)
type_effectiveness_chart[PokemonType.Ghost][PokemonType.Ghost] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Ghost][PokemonType.Dark] = float(.5)
# Dragon is:
# ineffective against
type_effectiveness_chart[PokemonType.Dragon][PokemonType.Fairy] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Dragon][PokemonType.Dragon] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Dragon][PokemonType.Steel] = float(.5)
# Dark is:
# very effective against
type_effectiveness_chart[PokemonType.Dark][PokemonType.Psychic] = float(2)
type_effectiveness_chart[PokemonType.Dark][PokemonType.Ghost] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Dark][PokemonType.Fighting] = float(.5)
type_effectiveness_chart[PokemonType.Dark][PokemonType.Dark] = float(.5)
type_effectiveness_chart[PokemonType.Dark][PokemonType.Fairy] = float(.5)
# Steel is:
# very effective against
type_effectiveness_chart[PokemonType.Steel][PokemonType.Ice] = float(2)
type_effectiveness_chart[PokemonType.Steel][PokemonType.Rock] = float(2)
type_effectiveness_chart[PokemonType.Steel][PokemonType.Fairy] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Steel][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Steel][PokemonType.Water] = float(.5)
type_effectiveness_chart[PokemonType.Steel][PokemonType.Electric] = float(.5)
type_effectiveness_chart[PokemonType.Steel][PokemonType.Steel] = float(.5)
# Fairy is:
# very effective against
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Fighting] = float(2)
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Dark] = float(2)
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Dragon] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Poison] = float(.5)
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Steel] = float(.5)
super().__init__(type_effectiveness_chart=type_effectiveness_chart)
| StarcoderdataPython |
9779959 | <gh_stars>0
import json
def handler(context, event):
# for object bodies, just take it as is. otherwise decode
if not isinstance(event.body, dict):
body = event.body.decode('utf8')
else:
body = event.body
return json.dumps({
'id': event.id,
'triggerClass': event.trigger.klass,
'eventType': event.trigger.kind,
'contentType': event.content_type,
'headers': dict(event.headers),
'timestamp': event.timestamp.isoformat('T') + 'Z',
'path': event.path,
'url': event.url,
'method': event.method,
'type': event.type,
'typeVersion': event.type_version,
'version': event.version,
'body': body
})
| StarcoderdataPython |
3305951 | <filename>sherry/inherit/__init__.py
# encoding=utf-8
"""
create by pymu
on 2021/5/30
at 21:37
""" | StarcoderdataPython |
1842147 | """
Overview
========
This module implements the INSERT mode that implements the functionality of inserting chars
in the AreaVi instances.
Key-Commands
============
Namespace: insert-mode
Mode: NORMAL
Event: <Key-i>
Description: Get the focused AreaVi instance in INSERT mode.
"""
def insert(area):
area.chmode('INSERT')
def install(area):
# The two basic modes, insert and selection.
area.add_mode('INSERT', opt=True)
area.install('insert-mode', ('NORMAL', '<Key-i>', lambda event: insert(event.widget)))
| StarcoderdataPython |
11245260 | from .markdownify import markdownify
| StarcoderdataPython |
3448895 | <gh_stars>1-10
# -*- coding: utf-8 -*-
def main():
from itertools import combinations
n, m = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
ans = 0
for t1, t2 in list(combinations(range(m), 2)):
summed = 0
for i in range(n):
summed += max(a[i][t1], a[i][t2])
ans = max(ans, summed)
print(ans)
if __name__ == '__main__':
main()
| StarcoderdataPython |
8058579 | <reponame>EvictionLab/eviction-lab-etl<gh_stars>1-10
import sys
import pandas as pd
from data_constants import COLUMN_ORDER
if __name__ == '__main__':
df = pd.read_csv(
sys.stdin,
dtype={
'GEOID': 'object',
'name': 'object',
'parent-location': 'object'
})
# Ensure all columns are in CSV, output in order
assert all([c in df.columns.values for c in COLUMN_ORDER])
df[COLUMN_ORDER].to_csv(sys.stdout, index=False)
| StarcoderdataPython |
3313936 | <reponame>dmft-wien2k/dmft-wien2k-v2<filename>script/gsl.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
###
#
# @file gsl.py
#
# DMFT is a software package provided by Rutgers Univiversity,
# the State University of New Jersey
#
# @version 1.0.0
# @author <NAME> and <NAME>
# @date 2016-02-15
#
###
from utils import writefile, shellcmd, delfiles, downloader, geturl, getURLName,includefromlib
import sys
import os
import urllib
import shutil
import framework
import re
class Gsl(framework.Framework):
""" This class takes care of the libgsl. """
def __init__(self, config, dmft):
print "\n","="*50
print " GSL installation/verification"
print "="*50
self.config = config
self.downcmd = dmft.downcmd
#self.prefix = dmft.prefix
self.dmft = dmft
self.downgsl = dmft.downgsl
self.gslurl = "ftp://ftp.gnu.org/gnu/gsl/"+self.gslversion+".tar.gz"
#ftp://ftp.gnu.org/gnu/gsl/gsl-1.16.tar.gz
self.dmft.verbose = 1
if self.downgsl == 2:
self.down_install_gsl()
if(self.config.gsl == ""):
if (os.path.isfile(os.path.join(self.config.prefix,'gsl/lib/libgsl.a')) or\
os.path.isfile(os.path.join(self.config.prefix,'gsl/lib64/libgsl.a'))):
self.set_gsl()
ret = self.check_gsl()
if ret != 0:
if self.downgsl == 1:
self.down_install_gsl()
else:
if not os.path.isfile(os.path.join(self.config.prefix,'gsl/lib/libgsl.a')):
print """
Please provide a working GSL library using --gsl.
If the GSL library is not awailable in the system, the GSL library can be
automatically downloaded and installed by adding the --downgsl flag.
What do you want to do ?
- s : specify the path and library if you have it
- d : download and install the GSL library.
- q : quit to download and install manually the GSL.
- i : ignore are proceed
"""
answer = raw_input(">[q] ")
if answer == "d":
self.down_install_gsl()
elif answer == "s":
self.config.gsl = raw_input("> ")
ret = self.check_gsl()
if ret!=0:
sys.exit()
elif answer == "i":
pass
else:
sys.exit()
else:
print "Netlib Lapack library is already installed at "+os.path.join(self.config.prefix,'lib/liblapack.a')
print "Do you want to try it? (t) or proceed without testing (p) or quit (q) ?"
answer = raw_input(">[q] ")
if answer == "t":
self.config.gsl = '-L'+os.path.join(self.config.prefix,'gsl/lib')+' -lgsl '
self.check_gsl()
elif answer == "p":
exit
else:
sys.exit()
def check_gsl(self):
""" This function simply generates a C program
that contains few GSL calls routine and then
checks if compilation, linking and execution are succesful"""
sys.stdout.flush()
code="""#include <gsl/gsl_rng.h>
const gsl_rng_type * T = gsl_rng_default;
gsl_rng * r = gsl_rng_alloc (T);
int main(void)
{
gsl_rng_env_setup();
gsl_rng_set (r,1);
return 0;
}
"""
writefile('tmpc.cc',code)
if self.config.gsl == "" or self.config.gsl is None: # just trying default == -lgsl
self.config.gsl='-lgsl'
if self.config.gslinc == "" or self.config.gslinc is None:
self.config.gslinc = includefromlib(self.config.gsl)
ccomm = self.config.cxx+' '+self.config.gslinc+ ' -o tmpc '+'tmpc.cc '+self.config.gsl
print 'checking with:', ccomm
(output, error, retz) = shellcmd(ccomm)
print "Checking if provided GSL works...",
if(retz != 0):
if self.dmft.verbose:
print '\n\nlibgsl: provided GSL cannot be used! aborting...'
print 'error is:\n','*'*50,'\n',ccomm,'\n',error,'\n','*'*50
return -1
else:
print "no"
return -1
#sys.exit()
comm = './tmpc'
(output, error, retz) = shellcmd(comm)
if(retz != 0):
if self.dmft.verbose:
print '\n\nlibgsl: provided GSL cannot be used! aborting...'
print 'error is:\n','*'*50,'\n',comm,'\n',error,'\n','*'*50
print retz
return -1
else:
print "no"
return -1
# sys.exit()
if self.config.gslinc=='':
# It worked, but we do not know the include files, hence figuring it out
ccomm = self.config.cc+' -E tmpc.cc |grep gsl | grep include'
(output, error, retz) = shellcmd(ccomm)
#print 'output=', output
# compiler output in lines
lines = output.split('\n')
incl={}
for i,line in enumerate(lines):
dat=line.split()
for d in dat:
m = re.search('gsl',d) # take out the directory
if m is not None:
incl[os.path.dirname(d[1:-1])]=True
for inc in incl.keys():
self.config.gslinc += ' -I'+inc[:-4] # path has extra gsl. Take it out
delfiles(['tmpc.cc','tmpc'])
print 'yes'
return 0;
def down_install_gsl(self):
print "The GSL library is being installed."
sys.stdout.flush()
savecwd = os.getcwd()
# creating the build,lib and log dirs if don't exist
if not os.path.isdir(os.path.join(self.config.prefix,'gsl')):
os.mkdir(os.path.join(self.config.prefix,'gsl'))
if not os.path.isdir(os.path.join(os.getcwd(),'log')):
os.mkdir(os.path.join(os.getcwd(),'log'))
# Check if gsl.tgz is already present in the working dir
# otherwise download it
if not os.path.isfile(os.path.join(os.getcwd(),getURLName(self.gslurl))):
print "Downloading GSL ...",
#downloader(self.lapackurl,self.downcmd)
#urllib.urlretrieve(self.gslurl, "gsl.tgz")
geturl(self.gslurl, "gsl.tgz")
print "done"
# unzip and untar
os.chdir('download')
print 'Unzip and untar GSL...',
comm = 'tar zxf gsl.tgz '
(output, error, retz) = shellcmd(comm)
if retz:
print '\n\nlibgsl: cannot unzip '+self.gslversion+'.tgz'
print 'stderr:\n','*'*50,'\n',comm,'\n',error,'\n','*'*50
sys.exit()
print 'done'
# change to GSL dir
os.chdir(os.path.join(os.getcwd(), self.gslversion))
# compile and generate library
print 'Configure GSL...',
sys.stdout.flush()
comm = './configure CC='+self.config.cc+' --prefix='+os.path.join(self.config.prefix,'gsl')
(output, error, retz) = shellcmd(comm)
if retz:
print "\n\nlingsl: cannot configure GSL"
print "stderr:\n","*"*50,"\n",comm,'\n',error,"\n","*"*50
sys.exit()
log = output+error
# write log on a file
log = log+output+error
fulllog = os.path.join(savecwd,'log/log.gsl')
writefile(fulllog, log)
print 'Configuration of GSL successful.'
print '(log is in ',fulllog,')'
# compile and generate library
print 'Compile and generate GSL...',
sys.stdout.flush()
comm = self.make+' -j4; '+self.make+' install'
(output, error, retz) = shellcmd(comm)
if retz:
print "\n\nlingsl: cannot compile GSL"
print "stderr:\n","*"*50,"\n",comm,'\n',error,"\n","*"*50
sys.exit()
log = output+error
# write the log on a file
log = log+output+error
fulllog = os.path.join(savecwd,'log/log.gsl')
writefile(fulllog, log)
print 'Installation of GSL successful.'
print '(log is in ',fulllog,')'
# move libcblas.a to the lib directory
#shutil.copy('libtmg.a',os.path.join(self.config.prefix,'gsl/libtmg.a'))
# set framework variables to point to the freshly installed GSL library
self.config.gsl = '-L'+os.path.join(self.config.prefix,'gsl')+' -lgsl '
os.chdir(savecwd)
# Check if the installation is successful
self.dmft.verbose = 1
# self.check_gsl()
self.dmft.verbose = 0
def set_gsl(self):
# set framework variables to point to installed GSL library
gsllibpath = os.path.join(self.config.prefix,'gsl')+"/lib"
if(os.path.isdir(gsllibpath)):
self.config.gsl = '-L'+gsllibpath+' -lgsl -lgslcblas '
else:
gsllibpath = os.path.join(self.config.prefix,'gsl')+"/lib64"
self.config.gsl = '-L'+gsllibpath+' -lgsl -lgslcblas '
if __name__ == '__main__':
sys.path.insert(0, '../')
import configure
from dmft_install import Dmft_install
config = configure.Config((1, 0, 0))
dmft_install = Dmft_install([], config)
gsl = Gsl(config, dmft_install)
| StarcoderdataPython |
5003398 | <gh_stars>1-10
{
'targets':
[
{
# Needed declarations for the target
'target_name': 'bluetooth',
'conditions': [
[ 'OS=="freebsd" or OS=="openbsd" or OS=="solaris" or (OS=="linux")', {
'sources': [ "bluetooth.cc" ],
'libraries': ['-lopenobex', '-lobexftp', '-lbluetooth'],
'cflags':['-std=gnu++0x'] ,
},
],
[ 'OS=="win"', {
'sources': [
'bluetooth_NotImplemented.cc',
],
}]
],
},
] # end targets
}
| StarcoderdataPython |
5175383 | from . import _loader
def init():
_loader.init()
| StarcoderdataPython |
182369 | <filename>tests/simsample.py
import numpy as np
from baggingrnet.data.simulatedata import simData
from sklearn.model_selection import train_test_split
nsample=12000
simdata=simData(nsample)
simdata['gindex']=np.array([i for i in range(nsample)])
trainIndex, testIndex = train_test_split(range(nsample),test_size=0.2)
simdataTrain=simdata.iloc[trainIndex]
simdataTest=simdata.iloc[testIndex]
tfl="/dpLearnPrj/package_dev/baggingrnet/baggingrnet/data/sim_train.csv"
simdataTrain.to_csv(tfl,index=True,index_label='index')
tfl="/dpLearnPrj/package_dev/baggingrnet/baggingrnet/data/sim_test.csv"
simdataTest.to_csv(tfl,index=True,index_label='index') | StarcoderdataPython |
4944103 | import os
from functools import wraps
import subprocess
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, jsonify, Response
from deploy import commands
app = Flask('deploy.default_settings')
app.config.from_object(__name__)
app.config.from_envvar('DEPLOY_SETTINGS', silent=True)
# to avoid mishaps, you must set USERNAME. If set to blank then there is no
# auth required (for local testing only).
USERNAME = os.environ['SANDBOX_DEPLOY_USERNAME']
PASSWORD = os.environ.get('SANDBOX_DEPLOY_PASSWORD')
def check_auth(username, password):
return username == USERNAME and password == PASSWORD
def challenge():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
if USERNAME:
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return challenge()
return f(*args, **kwargs)
return decorated
@app.route('/')
@requires_auth
def show_entries():
sandboxes = commands.get_sandboxes({})
return render_template('sandboxes.html', sandboxes=sandboxes)
@app.route('/api/sandboxes', methods=['GET'])
@requires_auth
def get_sandboxes():
sandboxes = commands.get_sandboxes(args={})
return jsonify(sandboxes)
@app.route('/api/pod-statuses', methods=['GET'])
@requires_auth
def get_pod_statuses():
data = commands.get_pod_statuses(args={})
return jsonify(data)
@app.route('/api/deploy', methods=['POST'])
@requires_auth
def deploy():
request_data = request.get_json()
data = dict(
fullname=request_data['name'],
username=request_data['github'],
email=request_data['email'],
)
try:
response = commands.deploy(args=data)
except subprocess.CalledProcessError as e:
app.logger.error('Error calling deploy.sh: %s', str(e.output))
return Response('Error calling deploy', 500)
# currently just text
return jsonify({'text': response.stdout.decode('utf-8')})
@app.route('/api/delete', methods=['POST'])
@requires_auth
def delete():
request_data = request.get_json()
data = dict(username=request_data['github'])
# Delete the user
try:
response = commands.delete_user(args=data)
except subprocess.CalledProcessError as e:
app.logger.error('Error calling deploy.sh: %s', str(e.output))
return Response('Error calling deploy', 500)
# Delete the app
try:
data['chart'] = 'rstudio'
response = commands.delete_chart(args=data)
except subprocess.CalledProcessError as e:
app.logger.error('Error calling deploy.sh: %s', str(e.output))
return Response('Error calling deploy', 500)
# currently just text
return jsonify({'text': response.stdout.decode('utf-8')})
| StarcoderdataPython |
1654450 | <reponame>FreddyWordingham/arctk
import numpy as np
from math import pi as PI
import math
from scipy.special import gammainc
from matplotlib import pyplot as plt
import csv
def sample(center,radius,n_per_sphere):
r = radius
ndim = center.size
x = np.random.normal(size=(n_per_sphere, ndim))
#print("x", x)
ssq = np.sum(x**2,axis=1)
#print("ssq", ssq)
fr = r*gammainc(ndim/2,ssq/2)**(1/ndim)/np.sqrt(ssq)
#print("fr", fr)
frtiled = np.tile(fr.reshape(n_per_sphere,1),(1,ndim))
#print("frtiled", frtiled)
p = center + np.multiply(x,frtiled)
return p
f = open("input/og_sphere_calc.csv", "w")
g = open("input/sample.txt", "w")
#fig1 = plt.figure(1)
#ax1 = fig1.gca()
#center = np.array([0,0,0])
#radius = 0.001
#p = sample(center,radius,10)
#print(p)
test = []
test_x = np.linspace(0, 1, 10)
#print(PI)
for i in range(1000):
theta = np.random.uniform(0, 2*PI)
v = np.random.uniform(0,1)
phi = math.acos((2*v)-1)
r = math.pow(np.random.uniform(0,1), 1/3)
x=r*math.sin(phi)*math.cos(theta)
y=r*math.sin(phi)*math.sin(theta)
z=r*math.cos(phi)
#print(x, y, z)
#g.write(str([x, y, z]))
test.append([x, y, z])
test = np.array(test)
#plt.scatter(test[:,0], test[:,1])
#plt.axes().set_aspect('equal')
#plt.show()
with f as points_file:
for i in test:
points_writer = csv.writer(points_file, delimiter=',')
points_writer.writerow(i)
#ax1.scatter(p[:,0],p[:,1],s=0.5)
#ax1.add_artist(plt.Circle(center,radius,fill=False,color='0.5'))
#ax1.set_xlim(-1.5,1.5)
#ax1.set_ylim(-1.5,1.5)
#ax1.set_aspect('equal')
#plt.show()
| StarcoderdataPython |
3375078 | <gh_stars>1-10
"""Testing that the files can be accessed and are non-empty."""
import target_finder_model as tfm
def test_constants():
"""Test constants packaged with tfm"""
assert tfm.CROP_SIZE[0] == tfm.CROP_SIZE[1]
assert tfm.CROP_OVERLAP < tfm.CROP_SIZE[0]
assert tfm.DET_SIZE[0] == tfm.DET_SIZE[1]
assert tfm.CLF_SIZE[0] == tfm.CLF_SIZE[1]
assert len(tfm.OD_CLASSES) == 37
assert len(tfm.CLF_CLASSES) == 2 | StarcoderdataPython |
1981357 | <reponame>freepvps/hsesamples
s = 'abc'
s2 = f'{print(s)}'
print(s2)
def f():
print('a')
print(f())
| StarcoderdataPython |
6669318 | # Copyright 2016-2020 Blue Marble Analytics LLC. All rights reserved.
"""
**Relevant tables:**
+--------------------------------+------------------------------------------------+
|:code:`scenarios` table column |:code:`project_specified_capacity_scenario_id` |
+--------------------------------+------------------------------------------------+
|:code:`scenarios` table feature |N/A |
+--------------------------------+------------------------------------------------+
|:code:`subscenario_` table |:code:`subscenarios_project_specified_capacity` |
+--------------------------------+------------------------------------------------+
|:code:`input_` tables |:code:`inputs_project_specified_capacity` |
+--------------------------------+------------------------------------------------+
If the project portfolio includes project of the capacity types
:code:`gen_spec`, :code:`gen_ret_bin`, :code:`gen_ret_lin`, or
:code:`stor_spec`, the user must select that amount of project capacity that
the optimization should see as given (i.e. specified) in every period as
well as the associated fixed O&M costs (see
:ref:`specified-project-fixed-cost-section-ref`). Project
capacities are in the :code:`inputs_project_specified_capacity` table. For
:code:`gen_` capacity types, this table contains the project's power rating
and for :code:`stor_spec` it also contains the storage project's energy rating.
The primary key of this table includes the
:code:`project_specified_capacity_scenario_id`, the project name, and the
period. Note that this table can include projects that are not in the
user’s portfolio: the utilities that pull the scenario data look at the
scenario’s portfolio, pull the projects with the “specified” capacity types
from that, and then get the capacity for only those projects (and for the
periods selected based on the scenario's temporal setting). A new
:code:`project_specified_capacity_scenario_id` would be needed if a user wanted
to change the available capacity of even only a single project in a single
period (and all other project-year-capacity data points would need to be
re-inserted in the table under the new
:code:`project_specified_capacity_scenario_id`).
"""
| StarcoderdataPython |
3255034 | <gh_stars>1-10
# Copyright © 2012-2018 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import functools
import os
import pty
import sys
from nose.tools import (
assert_equal,
)
import lib.terminal as T
from . import tools
def test_strip_delay():
def t(s, r=b''):
assert_equal(T._strip_delay(s), r) # pylint: disable=protected-access
t(b'$<1>')
t(b'$<2/>')
t(b'$<3*>')
t(b'$<4*/>')
t(b'$<.5*/>')
t(b'$<0.6*>')
s = b'$<\x9B20>'
t(s, s)
def _get_colors():
return (
value
for name, value in sorted(vars(T.colors).items())
if name.isalpha()
)
def assert_tseq_equal(s, expected):
class S(str):
# assert_equal() does detailed comparison for instances of str,
# but not their subclasses. We don't want detailed comparisons,
# because diff could contain control characters.
pass
assert_equal(S(expected), S(s))
def test_dummy():
t = assert_tseq_equal
for i in _get_colors():
t(T.attr_fg(i), '')
t(T.attr_reset(), '')
def pty_fork_isolation(term):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
(master_fd, slave_fd) = pty.openpty()
os.dup2(slave_fd, pty.STDOUT_FILENO)
os.close(slave_fd)
sys.stdout = sys.__stdout__
os.environ['TERM'] = term
T.initialize()
try:
return func(*args, **kwargs)
finally:
os.close(master_fd)
return tools.fork_isolation(wrapper)
return decorator
@pty_fork_isolation('vt100')
def test_vt100():
t = assert_tseq_equal
for i in _get_colors():
t(T.attr_fg(i), '')
t(T.attr_reset(), '\x1B[m\x0F')
@pty_fork_isolation('ansi')
def test_ansi():
t = assert_tseq_equal
t(T.attr_fg(T.colors.black), '\x1B[30m')
t(T.attr_fg(T.colors.red), '\x1B[31m')
t(T.attr_fg(T.colors.green), '\x1B[32m')
t(T.attr_fg(T.colors.yellow), '\x1B[33m')
t(T.attr_fg(T.colors.blue), '\x1B[34m')
t(T.attr_fg(T.colors.magenta), '\x1B[35m')
t(T.attr_fg(T.colors.cyan), '\x1B[36m')
t(T.attr_fg(T.colors.white), '\x1B[37m')
t(T.attr_reset(), '\x1B[0;10m')
# vim:ts=4 sts=4 sw=4 et
| StarcoderdataPython |
6644131 | <reponame>wwselleck/OpenFuji
from __future__ import unicode_literals, absolute_import
import six
from jaraco.collections import KeyTransformingDict
from . import strings
class IRCDict(KeyTransformingDict):
"""
A dictionary of names whose keys are case-insensitive according to the
IRC RFC rules.
>>> d = IRCDict({'[This]': 'that'}, A='foo')
The dict maintains the original case:
>>> '[This]' in ''.join(d.keys())
True
But the keys can be referenced with a different case
>>> d['a'] == 'foo'
True
>>> d['{this}'] == 'that'
True
>>> d['{THIS}'] == 'that'
True
>>> '{thiS]' in d
True
This should work for operations like delete and pop as well.
>>> d.pop('A') == 'foo'
True
>>> del d['{This}']
>>> len(d)
0
"""
@staticmethod
def transform_key(key):
if isinstance(key, six.string_types):
key = strings.IRCFoldedCase(key)
return key
| StarcoderdataPython |
1805130 | <filename>gnome/correlation/script.py<gh_stars>0
import pickle
import openpyxl
def fetch_file(path):
with open(path, 'rb') as fp:
file = pickle.load(fp)
return file
RELATIVE_PATH = "/home/imlegend19/PycharmProjects/Research - Data Mining/gnome/"
wb = openpyxl.Workbook()
sheet = wb.active
titles = ["Assignee Id", "L1 Centrality", "L2-A Centrality", "L2-B Centrality", "L3 Centrality",
"Avg Fixed Time", "Reopened Percent",
"Assignee Component", "Total Bugs", "Average First Closed Time", "Priority", "Severity"]
sheet.append(titles)
sheet.append(["" for i in range(len(titles))])
def get_priority_points(priority):
"""
Normal
High
Urgent
Low
Immediate
:param priority:
:return: aggregate priority points
"""
points = 0
for i in priority:
if i == 'Low':
points += priority[i]
elif i == 'Normal':
points += priority[i] * 2
elif i == 'High':
points += priority[i] * 3
elif i == 'Urgent':
points += priority[i] * 4
else:
points += priority[i] * 5
return points
def get_severity_points(severity):
"""
normal
critical
major
trivial
enhancement
minor
blocker
:param severity:
:return:
"""
points = 0
for i in severity:
if i == 'normal':
points += severity[i] * 3
elif i == 'critical':
points += severity[i] * 5
elif i == 'major':
points += severity[i] * 4
elif i == 'trivial':
points += severity[i] * 1
elif i == 'minor':
points += severity[i] * 2
elif i == 'blocker':
points += severity[i] * 6
return points
who_assignee = {v: k for k, v in fetch_file(RELATIVE_PATH + "assignee/assignee_who.txt").items()}
who = []
for i in who_assignee:
who.append(i)
l1_centrality = fetch_file(RELATIVE_PATH + "layers/l1_centrality.txt")
l2_d1_centrality = fetch_file(RELATIVE_PATH + "layers/l2_d1_centrality.txt")
l2_d2_centrality = fetch_file(RELATIVE_PATH + "layers/l2_d2_centrality.txt")
l3_centrality = fetch_file(RELATIVE_PATH + "layers/l3_centrality.txt")
avg_fixed_time = fetch_file(RELATIVE_PATH + "assignee/assignee_avg_fixed_time.txt")
reopened_percent = fetch_file(RELATIVE_PATH + "assignee/assignee_reopened.txt")
assignee_comp = fetch_file(RELATIVE_PATH + "assignee/assignee_component.txt")
tot_bugs = fetch_file(RELATIVE_PATH + "assignee/assignee_total_bugs.txt")
avg_first_time = fetch_file(RELATIVE_PATH + "assignee/assignee_avg_first_fixed_time.txt")
priority = fetch_file(RELATIVE_PATH + "assignee/assignee_priority_count.txt")
severity = fetch_file(RELATIVE_PATH + "assignee/assignee_severity_count.txt")
def get_priority_points(priority):
"""
Normal = 2
Low = 1
High = 3
Urgent = 4
Immediate = 5
"""
points = 0
for i in priority:
if i == 'Low':
points += priority[1]
elif i == 'Normal':
points += priority[i] * 2
elif i == 'High':
points += priority[i] * 3
elif i == 'Urgent':
points += priority[i] * 4
else:
points += priority[i] * 5
return points
def get_severity_points(severity):
"""
normal = 3
critical = 5
major = 4
trivial = 1
minor = 2
blocker = 6
"""
points = 0
for i in severity:
if i == 'normal':
points += severity[i] * 3
elif i == 'critical':
points += severity[i] * 5
elif i == 'major':
points += severity[i] * 4
elif i == 'trivial':
points += severity[i] * 1
elif i == 'minor':
points += severity[i] * 2
elif i == 'blocker':
points += severity[i] * 6
return points
cnt = 0
for i in who:
w_a = who_assignee[i]
try:
l1 = l1_centrality[i]
l2_d1 = l2_d1_centrality[i]
l2_d2 = l2_d2_centrality[i]
l3 = l3_centrality[i]
avg = avg_fixed_time[i].days * 24 + avg_fixed_time[i].seconds / 3600
rp = reopened_percent[i]
comp = assignee_comp[i]
bugs = tot_bugs[i]
avg_ft = avg_first_time[i].days * 24 + avg_first_time[i].seconds / 3600
pri = get_priority_points(priority[i])
sev = get_severity_points(severity[i])
row = [i, l1, l2_d1, l2_d2, l3, avg, rp, comp, bugs, avg_ft, pri, sev]
sheet.append(row)
except Exception:
cnt += 1
pass
print("Error count", cnt)
wb.save("correlation_gnome_1.xlsx")
print("Finished!")
| StarcoderdataPython |
5036115 | """
:type prices: List[int]
:rtype: int
"""
class Solution:
def maxProfit(self, prices):
max = 0
min = 100000
for i in range(len(prices)):
if prices[i] < min:
min = prices[i]
if prices[i] - min > max:
max = prices[i] - min
return max
s = Solution()
a = s.maxProfit([2,3,4,5,6])
print(a)
| StarcoderdataPython |
6608698 | from setuptools import setup, find_packages
setup(
name='controllerlibs',
version='0.1.0',
description='shared libraries of controller',
url='',
author='<NAME>',
author_email='<EMAIL>',
license='',
keywords='',
packages=find_packages(),
install_requires=[
"Flask>=1.0",
"requests>=2.18",
"pytz>=2018.5",
],
classifiers=[
'Programming Language :: Python :: 3.6',
],
)
| StarcoderdataPython |
9782839 | <gh_stars>1000+
import logging
log = logging.getLogger(__name__)
__version__ = '0.9.0'
try:
from plex.client import Plex
except Exception as ex:
log.warn('Unable to import submodules - %s', ex, exc_info=True)
| StarcoderdataPython |
9656594 | # Generated by Django 3.0.6 on 2020-07-09 11:02
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("discount", "0019_auto_20200217_0350"),
]
operations = [
migrations.AlterModelOptions(
name="vouchercustomer",
options={"ordering": ("voucher", "customer_email", "pk")},
),
migrations.AlterModelOptions(
name="vouchertranslation",
options={"ordering": ("language_code", "voucher", "pk")},
),
]
| StarcoderdataPython |
9626733 | import simplejson
import cgi
class JSONFilter(object):
def __init__(self, app, mime_type='text/x-json'):
self.app = app
self.mime_type = mime_type
def __call__(self, environ, start_response):
# Read JSON POST input to jsonfilter.json if matching mime type
response = {'status': '200 OK', 'headers': []}
def json_start_response(status, headers):
response['status'] = status
response['headers'].extend(headers)
environ['jsonfilter.mime_type'] = self.mime_type
if environ.get('REQUEST_METHOD', '') == 'POST':
if environ.get('CONTENT_TYPE', '') == self.mime_type:
args = [_ for _ in [environ.get('CONTENT_LENGTH')] if _]
data = environ['wsgi.input'].read(*map(int, args))
environ['jsonfilter.json'] = simplejson.loads(data)
res = simplejson.dumps(self.app(environ, json_start_response))
jsonp = cgi.parse_qs(environ.get('QUERY_STRING', '')).get('jsonp')
if jsonp:
content_type = 'text/javascript'
res = ''.join(jsonp + ['(', res, ')'])
elif 'Opera' in environ.get('HTTP_USER_AGENT', ''):
# Opera has bunk XMLHttpRequest support for most mime types
content_type = 'text/plain'
else:
content_type = self.mime_type
headers = [
('Content-type', content_type),
('Content-length', len(res)),
]
headers.extend(response['headers'])
start_response(response['status'], headers)
return [res]
def factory(app, global_conf, **kw):
return JSONFilter(app, **kw)
| StarcoderdataPython |
5044883 | # coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
import re # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401
from acapy_wrapper.models.ld_proof_vc_detail import LDProofVCDetail
from acapy_wrapper.models.v20_cred_filter_indy import V20CredFilterIndy
class V20CredFilter(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
V20CredFilter - a model defined in OpenAPI
indy: The indy of this V20CredFilter [Optional].
ld_proof: The ld_proof of this V20CredFilter [Optional].
"""
indy: Optional[V20CredFilterIndy] = None
ld_proof: Optional[LDProofVCDetail] = None
V20CredFilter.update_forward_refs()
| StarcoderdataPython |
8149030 | <gh_stars>0
#Create Layout for impedance parameters
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.modalview import ModalView
from kivy.uix.spinner import Spinner
from kivy.properties import ObjectProperty
from kivy.clock import Clock
#Convenience editing of dictionaries
from common.dict import getsemileafs_paths, getleaf_value, setleaf_value, isleaf
from kivy.uix.popup import Popup
from kivy.logger import Logger
posible_equations=('constant','scaleOnWeightEqn', 'scaleOnSpeedEqn', 'scaleAnkleStiffnessEqn','dampingEqn', 'scaleOnWeightEqn2Up', 'scaleOnWeightEqn2Down','previousValueEqn');
parameters=dict();
# Dictionary holding the posible equations
# and their parameters, types and default values.
parameters['constant']={};
parameters['scaleOnWeightEqn']={
'C': {'default':0,'type':'float'},
'initial_value': {'default':0,'type':'float'},
'final_value': {'default':0,'type':'float'},
'value': {'default':0, 'type': 'float'}
}
parameters['scaleOnWeightEqn2Up']={
'C': {'default':0,'type':'float'},
'initial_value': {'default':0,'type':'float'},
'final_value': {'default':0,'type':'float'},
'value': {'default':0, 'type': 'float'},
'initial_w': {'default':0, 'type': 'float'},
'final_w': {'default':0, 'type': 'float'}
}
parameters['scaleOnWeightEqn2Down']={
'C': {'default':0,'type':'float'},
'initial_value': {'default':0,'type':'float'},
'final_value': {'default':0,'type':'float'},
'value': {'default':0, 'type': 'float'},
'initial_w': {'default':0, 'type': 'float'},
'final_w': {'default':0, 'type': 'float'}
}
parameters['scaleOnSpeedEqn'] = {
'A': {'default':0.141, 'type':'float'},
'B': {'default':0.264, 'type':'float'}
}
parameters['scaleAnkleStiffnessEqn'] = {
}
parameters['dampingEqn'] = {
'P': {'default': 1, 'type': 'float'}
}
parameters['previousValueEqn'] = {
'param_name': {'default': '', 'type': 'string'}
}
class OptionsDialog(ModalView):
# A class for creating a modal view with the options for a parameter
# options contain a dictionary with the equation and all its posible parameters
semileaf_dict=None
title_lbl=ObjectProperty(Label)
paramsholder=ObjectProperty(BoxLayout)
def __init__(self,semileaf_path=None,semileaf_dict=None,**kwargs):
super(OptionsDialog,self).__init__(**kwargs)
self.semileaf_dict=semileaf_dict
self.semileaf_path=semileaf_path
Clock.schedule_once(lambda dt: self.build(), 0)
def build(self):
print("Options dialog build")
self.populate()
def populate(self):
#Construct the options menu from a ROSParams object
self.clear() # Start from fresh
if self.semileaf_dict is None:
return
#Fill the label
self.title_lbl.text="Options for "+"/".join(self.semileaf_path)
semileaf=self.semileaf_dict
#Create labels+textboxes
options=semileaf['options']
equation=options['equation']
boxLayout=BoxLayout(orientation='horizontal')
boxLayout.add_widget(Label(text='equation:'))
spinner=Spinner(text=equation,values=posible_equations)
spinner.bind(text=self.spinner_callback)
boxLayout.add_widget(spinner)
self.paramsholder.add_widget(boxLayout)
#Add parameter
for parameter in options.keys():
if not parameter=='equation':
boxLayout=BoxLayout(orientation='horizontal')
boxLayout.add_widget(Label(text=parameter+':'))
newTextInput=TextInput(text=str(options[parameter]))
isfloat=False
if not equation in parameters:
#ERROR this equation is not supported default parameters to float
Logger.info('Equation not supported')
isfloat=True
else:
if parameters[equation][parameter]['type']=='float':
isfloat=True
newTextInput.bind(text=self.on_text_callback_generator(parameter,isfloat))
boxLayout.add_widget(newTextInput)
self.paramsholder.add_widget(boxLayout)
def spinner_callback(self,spinner,text):
print("selected eq:"+text)
if text in posible_equations:
# Change dictionary values for the defaults corresponding to
# this equation's parameters
new_options=dict()
new_options['equation']=text
eq_parameters=parameters[text]
if type(eq_parameters) is dict:
for parameter in eq_parameters.keys():
param=eq_parameters[parameter]
new_options[parameter]=param['default']
print("\t%s"%new_options)
self.semileaf_dict['options']=new_options
self.populate()
def on_text_callback_generator(self,key,isfloat):
#This function helps to create a callback function for each text input
# modifying the appropiate key of the dictionary
return lambda instance,value : self.change_paramvalue(key,value,isfloat)
def change_paramvalue(self,param_key,value,isfloat=True):
#Change the value for a key
param_dict=self.semileaf_dict
options=param_dict['options']
#value always comes as a string
if isfloat:
try:
value=float(value)
except:
pass
options[param_key]=value
def clear(self):
self.paramsholder.clear_widgets()
| StarcoderdataPython |
11237459 | <reponame>ICRC-BME/epycom
# -*- coding: utf-8 -*-
# Copyright (c) St. Anne's University Hospital in Brno. International Clinical
# Research Center, Biomedical Engineering. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# Std imports
# Third pary imports
import pandas as pd
# Local imports
def match_detections(gs_df, dd_df, bn, freq_name=None,
sec_unit=None, sec_margin=1):
"""
Matches gold standard detections with detector detections.
Parameters
----------
gs_df: pandas.DataFrame
Gold standard detections
dd_df: pandas.DataFrame
Detector detections
bn: list
Names of event start stop [start_name, stop_name]
freq_name: str
Name of frequency column
sec_unit: int
Number representing one second of signal - this can
significantly imporove the speed of this function
sec_margin: int
Margin for creating subsets of compared data - should be set according
to the legnth of compared events (1s for HFO should be enough)
Returns
-------
match_df: pandas.DataFrame
Dataframe with matched indeces (pandas DataFrame)
"""
match_df = pd.DataFrame(columns=('gs_index', 'dd_index'))
match_df_idx = 0
for row_gs in gs_df.iterrows():
matched_idcs = []
gs = [row_gs[1][bn[0]], row_gs[1][bn[1]]]
if sec_unit: # We can create subset - significant speed improvement
for row_dd in dd_df[(dd_df[bn[0]] < gs[0]
+ sec_unit * sec_margin) &
(dd_df[bn[0]] > gs[0]
- sec_unit * sec_margin)].iterrows():
dd = [row_dd[1][bn[0]], row_dd[1][bn[1]]]
if check_detection_overlap(gs, dd):
matched_idcs.append(row_dd[0])
else:
for row_dd in dd_df.iterrows():
dd = [row_dd[1][bn[0]], row_dd[1][bn[1]]]
if check_detection_overlap(gs, dd):
matched_idcs.append(row_dd[0])
if len(matched_idcs) == 0:
match_df.loc[match_df_idx] = [row_gs[0], None]
elif len(matched_idcs) == 1:
match_df.loc[match_df_idx] = [row_gs[0], matched_idcs[0]]
else:
# In rare event of multiple overlaps get the closest frequency
if freq_name:
dd_idx = (
abs(dd_df.loc[matched_idcs, freq_name]
- row_gs[1][freq_name])).idxmin()
match_df.loc[match_df_idx] = [row_gs[0], dd_idx]
# Closest event start - less precision than frequency
else:
dd_idx = (
abs(dd_df.loc[matched_idcs, bn[0]]
- row_gs[1][bn[0]])).idxmin()
match_df.loc[match_df_idx] = [row_gs[0], dd_idx]
match_df_idx += 1
return match_df
def check_detection_overlap(gs, dd):
"""
Evaluates if two detections overlap
Paramters
---------
gs: list
Gold standard detection [start,stop]
dd: list
Detector detection [start,stop]
Returns
-------
overlap: bool
Whether two events overlap.
"""
overlap = False
# dd stop in gs + (dd inside gs)
if (dd[1] >= gs[0]) and (dd[1] <= gs[1]):
overlap = True
# dd start in gs + (dd inside gs)
if (dd[0] >= gs[0]) and (dd[0] <= gs[1]):
overlap = True
# gs inside dd
if (dd[0] <= gs[0]) and (dd[1] >= gs[1]):
overlap = True
return overlap
| StarcoderdataPython |
3253339 | # * -- utf-8 -- * # python3
# Author: Tang Time:2018/4/17
import math
for i in range(100000):
x = int(math.sqrt(i+100))
y = int(math.sqrt(i+268))
if (x*x == i+100) and (y*y ==i+268):
print(i)
'''简述:一个整数,它加上100和加上268后都是一个完全平方数 提问:请问该数是多少?''' | StarcoderdataPython |
4917335 | <reponame>dhruvilgandhi/DSA-Together-HacktoberFest
#https://practice.geeksforgeeks.org/problems/find-pair-given-difference1559/1#
# Approach :
# Using Two Pointer techq
# Sort the array before applying two pointer approach
class Solution:
def findPair(self, arr, L,N):
arr.sort()
i,j = 0,1
flag = 0
size = len(arr)
while( i < size and j < size):
if(i != j and arr[j]-arr[i] == N):
flag = 1
break
elif(arr[j] - arr[i] < N):
j +=1
else:
i +=1
if(flag == 1):
return True
else:
return False
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t = int(input())
for _ in range(t):
L,N = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
solObj = Solution()
if(solObj.findPair(arr,L, N)):
print(1)
else:
print(-1)
# } Driver Code Ends | StarcoderdataPython |
194056 | <filename>examples/legacy_examples/dagster_examples/gcp_data_platform/simple_pipeline.py
import datetime
import os
from dagster_gcp.bigquery.resources import bigquery_resource
from dagster_gcp.dataproc.resources import DataprocResource
from google.cloud.bigquery.job import LoadJobConfig, QueryJobConfig
from dagster import InputDefinition, ModeDefinition, Nothing, pipeline, solid
PROJECT_ID = os.getenv('GCP_PROJECT_ID')
DEPLOY_BUCKET_PREFIX = os.getenv('GCP_DEPLOY_BUCKET_PREFIX')
INPUT_BUCKET = os.getenv('GCP_INPUT_BUCKET')
OUTPUT_BUCKET = os.getenv('GCP_OUTPUT_BUCKET')
REGION = 'us-west1'
LATEST_JAR_HASH = '214f4bff2eccb4e9c08578d96bd329409b7111c8'
DATAPROC_CLUSTER_CONFIG = {
'projectId': PROJECT_ID,
'clusterName': 'gcp-data-platform',
'region': 'us-west1',
'cluster_config': {
'masterConfig': {'machineTypeUri': 'n1-highmem-4'},
'workerConfig': {'numInstances': 0},
'softwareConfig': {
'properties': {
# Create a single-node cluster
# This needs to be the string "true" when
# serialized, not a boolean true
'dataproc:dataproc.allow.zero.workers': 'true'
}
},
},
}
@solid
def create_dataproc_cluster(_):
DataprocResource(DATAPROC_CLUSTER_CONFIG).create_cluster()
@solid(config_schema={'date': str}, input_defs=[InputDefinition('start', Nothing)])
def data_proc_spark_operator(context):
dt = datetime.datetime.strptime(context.solid_config['date'], "%Y-%m-%d")
cluster_resource = DataprocResource(DATAPROC_CLUSTER_CONFIG)
job_config = {
'job': {
'placement': {'clusterName': 'gcp-data-platform'},
'reference': {'projectId': PROJECT_ID},
'sparkJob': {
'args': [
'--gcs-input-bucket',
INPUT_BUCKET,
'--gcs-output-bucket',
OUTPUT_BUCKET,
'--date',
dt.strftime('%Y-%m-%d'),
],
'mainClass': 'io.dagster.events.EventPipeline',
'jarFileUris': [
'%s/events-assembly-%s.jar' % (DEPLOY_BUCKET_PREFIX, LATEST_JAR_HASH)
],
},
},
'projectId': PROJECT_ID,
'region': REGION,
}
job = cluster_resource.submit_job(job_config)
job_id = job['reference']['jobId']
cluster_resource.wait_for_job(job_id)
@solid(input_defs=[InputDefinition('start', Nothing)])
def delete_dataproc_cluster(_):
DataprocResource(DATAPROC_CLUSTER_CONFIG).delete_cluster()
@solid(
config_schema={'date': str},
input_defs=[InputDefinition('start', Nothing)],
required_resource_keys={'bigquery'},
)
def gcs_to_bigquery(context):
dt = datetime.datetime.strptime(context.solid_config['date'], "%Y-%m-%d")
bq = context.resources.bigquery
destination = '{project_id}.events.events${date}'.format(
project_id=PROJECT_ID, date=dt.strftime('%Y%m%d')
)
load_job_config = LoadJobConfig(
source_format='PARQUET',
create_disposition='CREATE_IF_NEEDED',
write_disposition='WRITE_TRUNCATE',
)
source_uris = [
'gs://{bucket}/{date}/*.parquet'.format(bucket=OUTPUT_BUCKET, date=dt.strftime('%Y/%m/%d'))
]
bq.load_table_from_uri(source_uris, destination, job_config=load_job_config).result()
@solid(input_defs=[InputDefinition('start', Nothing)],)
def explore_visits_by_hour(context):
bq = context.resources.bigquery
query_job_config = QueryJobConfig(
destination='%s.aggregations.explore_visits_per_hour' % PROJECT_ID,
create_disposition='CREATE_IF_NEEDED',
write_disposition='WRITE_TRUNCATE',
)
sql = '''
SELECT FORMAT_DATETIME("%F %H:00:00", DATETIME(TIMESTAMP_SECONDS(CAST(timestamp AS INT64)))) AS ts,
COUNT(1) AS num_visits
FROM events.events
WHERE url = '/explore'
GROUP BY ts
ORDER BY ts ASC
'''
bq.query(sql, job_config=query_job_config)
@pipeline(mode_defs=[ModeDefinition(resource_defs={'bigquery': bigquery_resource})])
def gcp_data_platform():
dataproc_job = delete_dataproc_cluster(data_proc_spark_operator(create_dataproc_cluster()))
events_in_bq = gcs_to_bigquery(dataproc_job)
explore_visits_by_hour(events_in_bq)
| StarcoderdataPython |
11218783 | <gh_stars>1-10
import logging
try:
import json
except ImportError:
import simplejson as json
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from nipapwww.lib.base import BaseController, render
from pynipap import Tag, VRF, Prefix, Pool, NipapError
log = logging.getLogger(__name__)
class XhrController(BaseController):
""" Interface to a few of the NIPAP API functions.
"""
@classmethod
def extract_prefix_attr(cls, req):
""" Extract prefix attributes from arbitary dict.
"""
# TODO: add more?
attr = {}
if 'id' in request.params:
attr['id'] = int(request.params['id'])
if 'prefix' in request.params:
attr['prefix'] = request.params['prefix']
if 'pool' in request.params:
attr['pool'] = { 'id': int(request.params['pool']) }
if 'node' in request.params:
attr['node'] = request.params['node']
if 'type' in request.params:
attr['type'] = request.params['type']
if 'country' in request.params:
attr['country'] = request.params['country']
if 'indent' in request.params:
attr['indent'] = request.params['indent']
return attr
@classmethod
def extract_pool_attr(cls, req):
""" Extract pool attributes from arbitary dict.
"""
attr = {}
if 'id' in request.params:
attr['id'] = int(request.params['id'])
if 'name' in request.params:
attr['name'] = request.params['name']
if 'description' in request.params:
attr['description'] = request.params['description']
if 'default_type' in request.params:
attr['default_type'] = request.params['default_type']
if 'ipv4_default_prefix_length' in request.params:
attr['ipv4_default_prefix_length'] = int(request.params['ipv4_default_prefix_length'])
if 'ipv6_default_prefix_length' in request.params:
attr['ipv6_default_prefix_length'] = int(request.params['ipv6_default_prefix_length'])
return attr
def list_vrf(self):
""" List VRFs and return JSON encoded result.
"""
try:
vrfs = VRF.list()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(vrfs, cls=NipapJSONEncoder)
def smart_search_vrf(self):
""" Perform a smart VRF search.
The "smart" search function tries extract a query from
a text string. This query is then passed to the search_vrf
function, which performs the search.
"""
search_options = {}
extra_query = None
if 'query_id' in request.params:
search_options['query_id'] = request.params['query_id']
if 'max_result' in request.params:
search_options['max_result'] = request.params['max_result']
if 'offset' in request.params:
search_options['offset'] = request.params['offset']
if 'vrf_id' in request.params:
extra_query = {
'val1': 'id',
'operator': 'equals',
'val2': request.params['vrf_id']
}
try:
result = VRF.smart_search(request.params['query_string'],
search_options, extra_query
)
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(result, cls=NipapJSONEncoder)
def add_vrf(self):
""" Add a new VRF to NIPAP and return its data.
"""
v = VRF()
if 'rt' in request.params:
if request.params['rt'].strip() != '':
v.rt = request.params['rt'].strip()
if 'name' in request.params:
if request.params['name'].strip() != '':
v.name = request.params['name'].strip()
if 'description' in request.params:
v.description = request.params['description']
if 'tags' in request.params:
v.tags = json.loads(request.params['tags'])
try:
v.save()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(v, cls=NipapJSONEncoder)
def edit_vrf(self, id):
""" Edit a VRF.
"""
try:
v = VRF.get(int(id))
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
if 'rt' in request.params:
if request.params['rt'].strip() != '':
v.rt = request.params['rt'].strip()
else:
v.rt = None
if 'name' in request.params:
if request.params['name'].strip() != '':
v.name = request.params['name'].strip()
else:
v.name = None
if 'description' in request.params:
v.description = request.params['description']
if 'tags' in request.params:
v.tags = json.loads(request.params['tags'])
try:
v.save()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(v, cls=NipapJSONEncoder)
def remove_vrf(self):
""" Remove a VRF.
"""
try:
vrf = VRF.get(int(request.params['id']))
vrf.remove()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(vrf, cls=NipapJSONEncoder)
def list_pool(self):
""" List pools and return JSON encoded result.
"""
# fetch attributes from request.params
attr = XhrController.extract_pool_attr(request.params)
try:
pools = Pool.list(attr)
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(pools, cls=NipapJSONEncoder)
def smart_search_pool(self):
""" Perform a smart pool search.
The "smart" search function tries extract a query from
a text string. This query is then passed to the search_pool
function, which performs the search.
"""
search_options = {}
if 'query_id' in request.params:
search_options['query_id'] = request.params['query_id']
if 'max_result' in request.params:
search_options['max_result'] = request.params['max_result']
if 'offset' in request.params:
search_options['offset'] = request.params['offset']
try:
result = Pool.smart_search(request.params['query_string'],
search_options
)
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(result, cls=NipapJSONEncoder)
def add_pool(self):
""" Add a pool.
"""
# extract attributes
p = Pool()
p.name = request.params.get('name')
p.description = request.params.get('description')
p.default_type = request.params.get('default_type')
if 'ipv4_default_prefix_length' in request.params:
if request.params['ipv4_default_prefix_length'].strip() != '':
p.ipv4_default_prefix_length = request.params['ipv4_default_prefix_length']
if 'ipv6_default_prefix_length' in request.params:
if request.params['ipv6_default_prefix_length'].strip() != '':
p.ipv6_default_prefix_length = request.params['ipv6_default_prefix_length']
if 'tags' in request.params:
p.tags = json.loads(request.params['tags'])
try:
p.save()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(p, cls=NipapJSONEncoder)
def edit_pool(self, id):
""" Edit a pool.
"""
# extract attributes
p = Pool.get(int(id))
if 'name' in request.params:
p.name = request.params.get('name')
if 'description' in request.params:
p.description = request.params.get('description')
if 'default_type' in request.params:
p.default_type = request.params.get('default_type')
if 'ipv4_default_prefix_length' in request.params:
if request.params['ipv4_default_prefix_length'].strip() != '':
p.ipv4_default_prefix_length = request.params['ipv4_default_prefix_length']
else:
p.ipv4_default_prefix_length = None
if 'ipv6_default_prefix_length' in request.params:
if request.params['ipv6_default_prefix_length'].strip() != '':
p.ipv6_default_prefix_length = request.params['ipv6_default_prefix_length']
else:
p.ipv6_default_prefix_length = None
if 'tags' in request.params:
p.tags = json.loads(request.params['tags'])
try:
p.save()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(p, cls=NipapJSONEncoder)
def remove_pool(self):
""" Remove a pool.
"""
try:
pool = Pool.get(int(request.params['id']))
pool.remove()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(pool, cls=NipapJSONEncoder)
def list_prefix(self):
""" List prefixes and return JSON encoded result.
"""
# fetch attributes from request.params
attr = XhrController.extract_prefix_attr(request.params)
try:
prefixes = Prefix.list(attr)
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(prefixes, cls=NipapJSONEncoder)
def search_prefix(self):
""" Search prefixes. Does not yet incorporate all the functions of the
search_prefix API function due to difficulties with transferring
a complete 'dict-to-sql' encoded data structure.
Instead, a list of prefix attributes can be given which will be
matched with the 'equals' operator if notheing else is specified. If
multiple attributes are given, they will be combined with the 'and'
operator. Currently, it is not possible to specify different
operators for different attributes.
"""
# extract operator
if 'operator' in request.params:
operator = request.params['operator']
else:
operator = 'equals'
# fetch attributes from request.params
attr = XhrController.extract_prefix_attr(request.params)
# build query dict
n = 0
q = {}
for key, val in attr.items():
if n == 0:
q = {
'operator': operator,
'val1': key,
'val2': val
}
else:
q = {
'operator': 'and',
'val1': {
'operator': operator,
'val1': key,
'val2': val
},
'val2': q
}
n += 1
# extract search options
search_opts = {}
if 'children_depth' in request.params:
search_opts['children_depth'] = request.params['children_depth']
if 'parents_depth' in request.params:
search_opts['parents_depth'] = request.params['parents_depth']
if 'include_neighbors' in request.params:
search_opts['include_neighbors'] = request.params['include_neighbors']
if 'max_result' in request.params:
search_opts['max_result'] = request.params['max_result']
if 'offset' in request.params:
search_opts['offset'] = request.params['offset']
try:
result = Prefix.search(q, search_opts)
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(result, cls=NipapJSONEncoder)
def smart_search_prefix(self):
""" Perform a smart search.
The smart search function tries extract a query from
a text string. This query is then passed to the search_prefix
function, which performs the search.
"""
search_options = {}
extra_query = None
vrf_filter = None
if 'query_id' in request.params:
search_options['query_id'] = request.params['query_id']
if 'include_all_parents' in request.params:
if request.params['include_all_parents'] == 'true':
search_options['include_all_parents'] = True
else:
search_options['include_all_parents'] = False
if 'include_all_children' in request.params:
if request.params['include_all_children'] == 'true':
search_options['include_all_children'] = True
else:
search_options['include_all_children'] = False
if 'parents_depth' in request.params:
search_options['parents_depth'] = request.params['parents_depth']
if 'children_depth' in request.params:
search_options['children_depth'] = request.params['children_depth']
if 'include_neighbors' in request.params:
if request.params['include_neighbors'] == 'true':
search_options['include_neighbors'] = True
else:
search_options['include_neighbors'] = False
if 'max_result' in request.params:
search_options['max_result'] = request.params['max_result']
if 'offset' in request.params:
search_options['offset'] = request.params['offset']
if 'parent_prefix' in request.params:
search_options['parent_prefix'] = request.params['parent_prefix']
if 'vrf_filter[]' in request.params:
vrf_filter_parts = []
# Fetch VRF IDs from search query and build extra query dict for
# smart_search_prefix.
vrfs = request.params.getall('vrf_filter[]')
if len(vrfs) > 0:
vrf = vrfs[0]
vrf_filter = {
'operator': 'equals',
'val1': 'vrf_id',
'val2': vrf if vrf != 'null' else None
}
for vrf in vrfs[1:]:
vrf_filter = {
'operator': 'or',
'val1': vrf_filter,
'val2': {
'operator': 'equals',
'val1': 'vrf_id',
'val2': vrf if vrf != 'null' else None
}
}
if vrf_filter:
extra_query = vrf_filter
if 'indent' in request.params:
if extra_query:
extra_query = {
'operator': 'and',
'val1': extra_query,
'val2': {
'operator': 'equals',
'val1': 'indent',
'val2': request.params['indent']
}
}
else:
extra_query = {
'operator': 'equals',
'val1': 'indent',
'val2': request.params['indent']
}
try:
result = Prefix.smart_search(request.params['query_string'],
search_options, extra_query)
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(result, cls=NipapJSONEncoder)
def add_prefix(self):
""" Add prefix according to the specification.
The following keys can be used:
vrf ID of VRF to place the prefix in
prefix the prefix to add if already known
family address family (4 or 6)
description A short description
comment Longer comment
node Hostname of node
type Type of prefix; reservation, assignment, host
status Status of prefix; assigned, reserved, quarantine
pool ID of pool
country Country where the prefix is used
order_id Order identifier
customer_id Customer identifier
vlan VLAN ID
alarm_priority Alarm priority of prefix
monitor If the prefix should be monitored or not
from-prefix A prefix the prefix is to be allocated from
from-pool A pool (ID) the prefix is to be allocated from
prefix_length Prefix length of allocated prefix
"""
p = Prefix()
# Sanitize input parameters
if 'vrf' in request.params:
try:
if request.params['vrf'] is None or len(request.params['vrf']) == 0:
p.vrf = None
else:
p.vrf = VRF.get(int(request.params['vrf']))
except ValueError:
return json.dumps({'error': 1, 'message': "Invalid VRF ID '%s'" % request.params['vrf']})
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
if 'description' in request.params:
if request.params['description'].strip() != '':
p.description = request.params['description'].strip()
if 'comment' in request.params:
if request.params['comment'].strip() != '':
p.comment = request.params['comment'].strip()
if 'node' in request.params:
if request.params['node'].strip() != '':
p.node = request.params['node'].strip()
if 'status' in request.params:
p.status = request.params['status'].strip()
if 'type' in request.params:
p.type = request.params['type'].strip()
if 'pool' in request.params:
if request.params['pool'].strip() != '':
try:
p.pool = Pool.get(int(request.params['pool']))
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
if 'country' in request.params:
if request.params['country'].strip() != '':
p.country = request.params['country'].strip()
if 'order_id' in request.params:
if request.params['order_id'].strip() != '':
p.order_id = request.params['order_id'].strip()
if 'customer_id' in request.params:
if request.params['customer_id'].strip() != '':
p.customer_id = request.params['customer_id'].strip()
if 'alarm_priority' in request.params:
p.alarm_priority = request.params['alarm_priority'].strip()
if 'monitor' in request.params:
if request.params['monitor'] == 'true':
p.monitor = True
else:
p.monitor = False
if 'vlan' in request.params:
if request.params['vlan'].strip() != '':
p.vlan = request.params['vlan']
if 'tags' in request.params:
p.tags = json.loads(request.params['tags'])
# arguments
args = {}
if 'from_prefix[]' in request.params:
args['from-prefix'] = request.params.getall('from_prefix[]')
if 'from_pool' in request.params:
try:
args['from-pool'] = Pool.get(int(request.params['from_pool']))
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
if 'family' in request.params:
args['family'] = request.params['family']
if 'prefix_length' in request.params:
args['prefix_length'] = request.params['prefix_length']
# manual allocation?
if args == {}:
if 'prefix' in request.params:
p.prefix = request.params['prefix']
try:
p.save(args)
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(p, cls=NipapJSONEncoder)
def edit_prefix(self, id):
""" Edit a prefix.
"""
try:
p = Prefix.get(int(id))
# extract attributes
if 'prefix' in request.params:
p.prefix = request.params['prefix']
if 'type' in request.params:
p.type = request.params['type'].strip()
if 'description' in request.params:
if request.params['description'].strip() == '':
p.description = None
else:
p.description = request.params['description'].strip()
if 'comment' in request.params:
if request.params['comment'].strip() == '':
p.comment = None
else:
p.comment = request.params['comment'].strip()
if 'node' in request.params:
if request.params['node'].strip() == '':
p.node = None
else:
p.node = request.params['node'].strip()
if 'status' in request.params:
p.status = request.params['status'].strip()
if 'pool' in request.params:
if request.params['pool'].strip() == '':
p.pool = None
else:
try:
p.pool = Pool.get(int(request.params['pool']))
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
if 'alarm_priority' in request.params:
p.alarm_priority = request.params['alarm_priority'].strip()
if 'monitor' in request.params:
if request.params['monitor'] == 'true':
p.monitor = True
else:
p.monitor = False
if 'country' in request.params:
if request.params['country'].strip() == '':
p.country = None
else:
p.country = request.params['country'].strip()
if 'order_id' in request.params:
if request.params['order_id'].strip() == '':
p.order_id = None
else:
p.order_id = request.params['order_id'].strip()
if 'customer_id' in request.params:
if request.params['customer_id'].strip() == '':
p.customer_id = None
else:
p.customer_id = request.params['customer_id'].strip()
if 'vrf' in request.params:
try:
if request.params['vrf'] is None or len(request.params['vrf']) == 0:
p.vrf = None
else:
p.vrf = VRF.get(int(request.params['vrf']))
except ValueError:
return json.dumps({'error': 1, 'message': "Invalid VRF ID '%s'" % request.params['vrf']})
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
if 'vlan' in request.params:
if request.params['vlan'].strip() != '':
p.vlan = request.params['vlan']
if 'tags' in request.params:
p.tags = json.loads(request.params['tags'])
p.save()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(p, cls=NipapJSONEncoder)
def remove_prefix(self):
""" Remove a prefix.
"""
try:
p = Prefix.get(int(request.params['id']))
p.remove()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(p, cls=NipapJSONEncoder)
def add_current_vrf(self):
""" Add VRF to filter list session variable
"""
vrf_id = request.params.get('vrf_id')
if vrf_id is not None:
if vrf_id == 'null':
vrf = VRF()
else:
vrf = VRF.get(int(vrf_id))
session['current_vrfs'][vrf_id] = { 'id': vrf.id, 'rt': vrf.rt,
'name': vrf.name, 'description': vrf.description }
session.save()
return json.dumps(session.get('current_vrfs', {}))
def del_current_vrf(self):
""" Remove VRF to filter list session variable
"""
vrf_id = request.params.get('vrf_id')
if vrf_id in session['current_vrfs']:
del session['current_vrfs'][vrf_id]
session.save()
return json.dumps(session.get('current_vrfs', {}))
def get_current_vrfs(self):
""" Return VRF filter list from session variable
"""
return json.dumps(session.get('current_vrfs', {}))
def list_tags(self):
""" List Tags and return JSON encoded result.
"""
try:
tags = Tags.list()
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(tags, cls=NipapJSONEncoder)
class NipapJSONEncoder(json.JSONEncoder):
""" A class used to encode NIPAP objects to JSON.
"""
def default(self, obj):
if isinstance(obj, Tag):
return {
'name': obj.name
}
elif isinstance(obj, VRF):
return {
'id': obj.id,
'rt': obj.rt,
'name': obj.name,
'description': obj.description,
'tags': obj.tags
}
elif isinstance(obj, Pool):
if obj.vrf is None:
vrf_id = None
vrf_rt = None
else:
vrf_id = obj.vrf.id
vrf_rt = obj.vrf.rt
return {
'id': obj.id,
'name': obj.name,
'vrf_rt': vrf_rt,
'vrf_id': vrf_id,
'description': obj.description,
'default_type': obj.default_type,
'ipv4_default_prefix_length': obj.ipv4_default_prefix_length,
'ipv6_default_prefix_length': obj.ipv6_default_prefix_length,
'tags': obj.tags
}
elif isinstance(obj, Prefix):
if obj.pool is None:
pool = None
else:
pool = obj.pool.id
vrf_id = obj.vrf.id
vrf_rt = obj.vrf.rt
return {
'id': obj.id,
'family': obj.family,
'vrf_rt': vrf_rt,
'vrf_id': vrf_id,
'prefix': obj.prefix,
'display_prefix': obj.display_prefix,
'description': obj.description,
'comment': obj.comment,
'inherited_tags': obj.inherited_tags,
'tags': obj.tags,
'node': obj.node,
'pool': pool,
'type': obj.type,
'indent': obj.indent,
'country': obj.country,
'order_id': obj.order_id,
'customer_id': obj.customer_id,
'authoritative_source': obj.authoritative_source,
'monitor': obj.monitor,
'alarm_priority': obj.alarm_priority,
'display': obj.display,
'match': obj.match,
'children': obj.children,
'vlan': obj.vlan
}
else:
return json.JSONEncoder.default(self, obj)
| StarcoderdataPython |
6480158 | # hello world code for driving robot
from modules.default_config import motion
motion.can.iface = 'can0'
@_core.init_task
def _():
_e.r.conf_set('send_status_interval', 10)
_e.r.accel(400)
| StarcoderdataPython |
8069630 | <filename>ghostdr/ghost/recipes/test/149_masterArc_test.py
#!python
import os
import glob
import shutil
import re
import numpy as np
import pytest
import itertools
import astrodata
from gempy.utils import logutils
from recipe_system.reduction.coreReduce import Reduce
from recipe_system.utils.reduce_utils import normalize_ucals
from recipe_system.mappers.primitiveMapper import PrimitiveMapper
from recipe_system.mappers.recipeMapper import RecipeMapper
# from ..test import get_or_create_tmpdir
import ghostdr
@pytest.mark.fullreduction
class TestMasterArc(object):
"""
Class for testing GHOST arc frame reduction.
"""
# Test needs to be run separately for the Before and After arcs so
# both can have the correct slit viewer frame passed to them
ARM_RES_COMBOS = list(itertools.product(
['red', 'blue', ],
['std', 'high'],
['Before', 'After']
))
@pytest.fixture(scope='class', params=ARM_RES_COMBOS)
def do_master_arc(self, get_or_create_tmpdir, request):
"""
Perform overscan subtraction on raw bias frame.
.. note::
Fixture.
"""
arm, res, epoch = request.param
rawfilename = 'arc{}*{}*{}[0-9].fits'.format(epoch, res, arm)
# Copy the raw data file into here
tmpsubdir, cal_service = get_or_create_tmpdir
# Find all the relevant files
# rawfiles = glob.glob(os.path.join(os.path.dirname(
# os.path.abspath(__file__)),
# 'testdata',
# rawfilename))
# for f in rawfiles:
# shutil.copy(f, os.path.join(tmpsubdir.dirname, tmpsubdir.basename))
rawfiles = glob.glob(os.path.join(tmpsubdir.dirname, tmpsubdir.basename,
rawfilename))
# Do the master bias generation
reduce = Reduce()
reduce.drpkg = 'ghostdr'
reduce.files = rawfiles
reduce.mode = ['test', ]
reduce.recipename = 'recipeArcCreateMaster'
# reduce.mode = ['sq', ]
# reduce.recipename = 'makeProcessedBias'
reduce.logfile = os.path.join(tmpsubdir.dirname, tmpsubdir.basename,
'reduce_masterarc_{}_{}.log'.format(
res, arm))
reduce.logmode = 'quiet'
reduce.suffix = '_{}_{}_testMasterArc'.format(res, arm)
logutils.config(file_name=reduce.logfile, mode=reduce.logmode)
# import pdb; pdb.set_trace()
calibs = {
'processed_bias': glob.glob(os.path.join(
'calibrations',
'processed_bias',
'bias*{}*.fits'.format(arm)))[0],
'processed_dark': glob.glob(os.path.join(
'calibrations',
'processed_dark',
'dark*{}*.fits'.format(arm)))[0],
'processed_flat': glob.glob(os.path.join(
'calibrations',
'processed_flat',
'flat*{}*{}*.fits'.format(res, arm)))[0],
'processed_slitflat': glob.glob(os.path.join(
'calibrations',
'processed_slitflat',
'flat*{}*slitflat*.fits'.format(res)))[0],
'processed_slit': glob.glob(os.path.join(
'calibrations',
'processed_slit',
'arc{}*{}*_slit.fits'.format(epoch, res)))[0],
}
reduce.ucals = normalize_ucals(reduce.files, [
'{}:{}'.format(k, v) for k, v in calibs.items()
])
# import pdb;
# pdb.set_trace()
reduce.runr()
corrfilename = '*' + reduce.suffix + '.fits'
corrfilename = os.path.join(tmpsubdir.dirname, tmpsubdir.basename,
glob.glob(corrfilename)[0])
corrfile = os.path.join(tmpsubdir.dirname, tmpsubdir.basename,
corrfilename)
# Return filenames of raw, subtracted files
yield rawfiles, corrfile, calibs
# Execute teardown code
pass
def test_arc_bias_done(self, do_master_arc):
"""
Check that bias subtraction was actually performed.
"""
rawfiles, corrfile, calibs = do_master_arc
corrarc = astrodata.open(corrfile)
assert corrarc.phu.get('BIASCORR'), "No record of bias " \
"correction having been " \
"performed on {} " \
"(PHU keyword BIASCORR " \
"missing)".format(corrfile)
bias_used = corrarc.phu.get('BIASIM')
assert bias_used == calibs[
'processed_bias'
].split(os.sep)[-1], "Incorrect bias frame " \
"recorded in processed " \
"flat " \
"({})".format(bias_used)
def test_arc_dark_done(self, do_master_arc):
"""
Check that dark subtraction was actually performed.
"""
rawfiles, corrfile, calibs = do_master_arc
corrarc = astrodata.open(corrfile)
assert corrarc.phu.get('DARKCORR'), "No record of dark " \
"correction having been " \
"performed on {} " \
"(PHU keyword DARKCORR " \
"missing)".format(corrfile)
dark_used = corrarc.phu.get('DARKIM')
assert dark_used == calibs[
'processed_dark'
].split(os.sep)[-1], "Incorrect dark frame " \
"recorded in processed " \
"arc " \
"({})".format(dark_used)
# FIXME: Still requires the following tests:
# - Has profile been extracted successfully?
# - Has the wavelength been fitted properly?
# However, need to work out where the divide-by-zero errors are coming from
# in polyfit before meaningful tests can be made
@pytest.mark.fullreduction
@pytest.mark.parametrize('arm,res,epoch', TestMasterArc.ARM_RES_COMBOS)
def test_arc_missing_pixelmodel(arm, res, epoch, get_or_create_tmpdir):
"""
Check for the correct behaviour/error handling if PIXELMODEL extn. missing.
"""
rawfilename = 'arc{}*{}*{}[0-9].fits'.format(epoch, res, arm)
# Copy the raw data file into here
tmpsubdir, cal_service = get_or_create_tmpdir
# Find all the relevant files
# rawfiles = glob.glob(os.path.join(os.path.dirname(
# os.path.abspath(__file__)),
# 'testdata',
# rawfilename))
# for f in rawfiles:
# shutil.copy(f, os.path.join(tmpsubdir.dirname, tmpsubdir.basename))
rawfiles = glob.glob(os.path.join(tmpsubdir.dirname, tmpsubdir.basename,
rawfilename))
rawfiles_ad = [astrodata.open(_) for _ in rawfiles]
calibs = {
'processed_bias': glob.glob(os.path.join(
'calibrations',
'processed_bias',
'bias*{}*.fits'.format(arm)))[0],
'processed_dark': glob.glob(os.path.join(
'calibrations',
'processed_dark',
'dark*{}*.fits'.format(arm)))[0],
'processed_flat': glob.glob(os.path.join(
'calibrations',
'processed_flat',
'flat*{}*{}*.fits'.format(res, arm)))[0],
'processed_slitflat': glob.glob(os.path.join(
'calibrations',
'processed_slitflat',
'flat*{}*slitflat*.fits'.format(res)))[0],
'processed_slit': glob.glob(os.path.join(
'calibrations',
'processed_slit',
'arc{}*{}*_slit.fits'.format(epoch, res)))[0],
}
flat = astrodata.open(calibs['processed_flat'])
del flat[0].PIXELMODEL
flatname = 'flat_{}_{}_nopixmod.fits'.format(arm, res)
flat.write(filename=flatname, overwrite=True)
calibs['processed_flat'] = flatname
# import pdb;
# pdb.set_trace()
pm = PrimitiveMapper(rawfiles_ad, mode='test', drpkg='ghostdr',
recipename='recipeArcCreateMaster',
usercals=normalize_ucals(rawfiles, ['{}:{}'.format(k, v) for k,v in calibs.items()])
# usercals=calibs,
)
rm = RecipeMapper(rawfiles_ad, mode='test', drpkg='ghostdr',
recipename='recipeArcCreateMaster',
# usercals=calibs,
)
p = pm.get_applicable_primitives()
recipe = rm.get_applicable_recipe()
with pytest.raises(AttributeError) as e_pixmod:
recipe(p)
# import pdb; pdb.set_trace()
assert 'PIXELMODEL' in e_pixmod.value.__str__(), "The assertion error raised " \
"in this " \
"test doesn't seem to be " \
"about the " \
"missing PIXELMODEL " \
"extension, as expected."
# Teardown code
os.remove(flatname)
| StarcoderdataPython |
68886 | <gh_stars>0
from django.test import TestCase
from django.test.client import Client
from google_analytics.utils import COOKIE_NAME
from urlparse import parse_qs
class GoogleAnalyticsTestCase(TestCase):
def SetUp(self):
pass
def test_cookies_set_properly(self):
client = Client()
response = client.get(
'/google-analytics/?p=%2Fhome&r=test.com')
cookie_1 = str(response.client.cookies.get(COOKIE_NAME))
response = client.get(
'/google-analytics/?p=%2Fblog&utmdebug=True&r=test.com')
cookie_2 = str(response.client.cookies.get(COOKIE_NAME))
self.assertEqual(cookie_1[:62], cookie_2[:62])
def test_ga_url(self):
client = Client()
response = client.get(
'/google-analytics/?p=%2Fhome&utmdebug=True&r=test.com')
ga_url1 = response.get('X-GA-MOBILE-URL')
response = client.get(
'/google-analytics/?p=%2Fblog&utmdebug=True&r=test.com')
ga_url2 = response.get('X-GA-MOBILE-URL')
self.assertEqual(
parse_qs(ga_url1).get('cid'),
parse_qs(ga_url2).get('cid'))
self.assertEqual(parse_qs(ga_url1).get('t'), ['pageview'])
self.assertEqual(parse_qs(ga_url1).get('dr'), ['test.com'])
self.assertEqual(parse_qs(ga_url1).get('dp'), ['/home'])
self.assertEqual(parse_qs(ga_url2).get('dp'), ['/blog'])
self.assertEqual(parse_qs(ga_url1).get('tid'), ['ua-test-id'])
| StarcoderdataPython |
105416 |
def reverse(x):
"""
:type x: int
:rtype: int
"""
if x < 0:
x = str(x)[:0:-1]
x = int("-" + x)
else:
x = str(x)[::-1]
x = int(x)
if x > 2**31 - 1 or x < -2**31:
return 0
return x
if __name__ == '__main__':
x = 1534236469
y = reverse(x)
print y | StarcoderdataPython |
1942957 |
## Quantile regression
#
# This example page shows how to use ``statsmodels``' ``QuantReg`` class to replicate parts of the analysis published in
#
# * <NAME> and <NAME>. "Quantile Regressioin". Journal of Economic Perspectives, Volume 15, Number 4, Fall 2001, Pages 143–156
#
# We are interested in the relationship between income and expenditures on food for a sample of working class Belgian households in 1857 (the Engel data).
#
# ## Setup
#
# We first need to load some modules and to retrieve the data. Conveniently, the Engel dataset is shipped with ``statsmodels``.
from __future__ import print_function
import patsy
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
from statsmodels.regression.quantile_regression import QuantReg
data = sm.datasets.engel.load_pandas().data
data.head()
# ## Least Absolute Deviation
#
# The LAD model is a special case of quantile regression where q=0.5
mod = smf.quantreg('foodexp ~ income', data)
res = mod.fit(q=.5)
print(res.summary())
# ## Visualizing the results
#
# We estimate the quantile regression model for many quantiles between .05 and .95, and compare best fit line from each of these models to Ordinary Least Squares results.
# ### Prepare data for plotting
#
# For convenience, we place the quantile regression results in a Pandas DataFrame, and the OLS results in a dictionary.
quantiles = np.arange(.05, .96, .1)
def fit_model(q):
res = mod.fit(q=q)
return [q, res.params['Intercept'], res.params['income']] + res.conf_int().loc['income'].tolist()
models = [fit_model(x) for x in quantiles]
models = pd.DataFrame(models, columns=['q', 'a', 'b','lb','ub'])
ols = smf.ols('foodexp ~ income', data).fit()
ols_ci = ols.conf_int().loc['income'].tolist()
ols = dict(a = ols.params['Intercept'],
b = ols.params['income'],
lb = ols_ci[0],
ub = ols_ci[1])
print(models)
print(ols)
# ### First plot
#
# This plot compares best fit lines for 10 quantile regression models to the least squares fit. As Koenker and Hallock (2001) point out, we see that:
#
# 1. Food expenditure increases with income
# 2. The *dispersion* of food expenditure increases with income
# 3. The least squares estimates fit low income observations quite poorly (i.e. the OLS line passes over most low income households)
x = np.arange(data.income.min(), data.income.max(), 50)
get_y = lambda a, b: a + b * x
for i in range(models.shape[0]):
y = get_y(models.a[i], models.b[i])
plt.plot(x, y, linestyle='dotted', color='grey')
y = get_y(ols['a'], ols['b'])
plt.plot(x, y, color='red', label='OLS')
plt.scatter(data.income, data.foodexp, alpha=.2)
plt.xlim((240, 3000))
plt.ylim((240, 2000))
plt.legend()
plt.xlabel('Income')
plt.ylabel('Food expenditure')
plt.show()
# ### Second plot
#
# The dotted black lines form 95% point-wise confidence band around 10 quantile regression estimates (solid black line). The red lines represent OLS regression results along with their 95% confindence interval.
#
# In most cases, the quantile regression point estimates lie outside the OLS confidence interval, which suggests that the effect of income on food expenditure may not be constant across the distribution.
from matplotlib import rc
rc('text', usetex=True)
n = models.shape[0]
p1 = plt.plot(models.q, models.b, color='black', label='Quantile Reg.')
p2 = plt.plot(models.q, models.ub, linestyle='dotted', color='black')
p3 = plt.plot(models.q, models.lb, linestyle='dotted', color='black')
p4 = plt.plot(models.q, [ols['b']] * n, color='red', label='OLS')
p5 = plt.plot(models.q, [ols['lb']] * n, linestyle='dotted', color='red')
p6 = plt.plot(models.q, [ols['ub']] * n, linestyle='dotted', color='red')
plt.ylabel(r'\beta_\mbox{income}')
plt.xlabel('Quantiles of the conditional food expenditure distribution')
plt.legend()
plt.show()
| StarcoderdataPython |
5029790 | <reponame>kristiewirth/dst<gh_stars>0
import os
from collections import Counter
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import progressbar
import seaborn as sns
class Eda:
"""
Exploratory data analysis (EDA)
"""
def separate_cols_by_type(self, df):
"""
Split the DataFrame into two groups by type
Parameters
--------
df: DataFrame
Returns
--------
numerical_vals: DataFrame
categorical_vals: DataFrame
"""
numerical_vals = df[
[
col
for col in df.select_dtypes(
exclude=["object", "bool", "datetime"]
).columns
# ID columns values aren't particularly important to examine
if "_id" not in str(col)
]
]
categorical_vals = df[
[
col
for col in df.select_dtypes(include=["object", "bool"]).columns
if "_id" not in str(col)
and str(col) != "date"
and "timestamp" not in str(col)
]
]
return numerical_vals, categorical_vals
def check_for_mistyped_cols(self, numerical_vals, categorical_vals):
"""
Check for columns coded incorrectly
Parameters
--------
numerical_vals: list
categorical_vals: list
Returns
--------
mistyped_cols: list
"""
mistyped_cols = []
for col in numerical_vals.columns:
if numerical_vals[col].nunique() <= 20:
print("Coded as numerical, is this actually an object / bool?\n")
print(col)
print(numerical_vals[col].unique())
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
mistyped_cols.append(col)
for col in categorical_vals.columns:
if "_id" in col:
continue
# Booleans can be recoded as floats but still are good as booleans
elif categorical_vals[col].dtypes == bool:
continue
try:
# Test two random values
float(categorical_vals[col][0])
float(categorical_vals[col][5])
print("Coded as categorical, is this actually an int / float?\n")
print(col)
print(categorical_vals[col].unique()[:10])
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
mistyped_cols.append(col)
except Exception:
pass
return mistyped_cols
def find_cols_to_exclude(self, df):
"""
Returns columns that may not be helpful for model building.
Exclusion criteria:
- Possible PII (address, name, username, date, etc. in col name)
- Large proportion of nulls
- Only 1 value in entire col
- Dates
- Low variance in col values
- Large number of categorical values
Parameters
--------
df: DataFrame
Returns
--------
lst: list
"""
lst = []
for col in df.columns:
if (
"address" in str(col)
or "first_name" in str(col)
or "last_name" in str(col)
or "username" in str(col)
or "_id" in str(col)
or "date" in str(col)
or "time" in str(col)
):
lst.append({col: "Considering excluding because potential PII column."})
elif df[col].isnull().sum() / float(df.shape[0]) >= 0.5:
lst.append(
{
col: "Considering excluding because {}% of column is null.".format(
round(
(df[col].isnull().sum() / float(df.shape[0]) * 100.0), 2
)
)
}
)
elif len(df[col].unique()) <= 1:
lst.append(
{
col: "Considering excluding because column includes only one value."
}
)
elif df[col].dtype == "datetime64[ns]":
lst.append(
{col: "Considering excluding because column is a timestamp."}
)
elif df[col].dtype not in ["object", "bool"]:
if df[col].var() < 0.00001:
lst.append(
{
col: "Considering excluding because column variance is low ({})".format(
round(df[col].var(), 2)
)
}
)
elif df[col].dtype in ["object", "bool"]:
if len(df[col].unique()) > 500:
lst.append(
{
col: "Considering excluding because object column has large number of unique values ({})".format(
len(df[col].unique())
)
}
)
[print(x) for x in lst]
return lst
def sample_unique_vals(self, df):
"""
Examine a few unique vals in each column
Parameters
--------
df: DataFrame
"""
for col in df:
print(col)
try:
print(df[col].unique()[:20])
print(df[col].nunique())
except Exception:
pass
print("\n------------------------------------\n")
def find_correlated_features(self, df):
"""
Find & sort correlated features
Parameters
--------
df: DataFrame
Returns
--------
s: Series
"""
if df.empty:
return pd.DataFrame()
c = df.corr().abs()
s = c.unstack()
s = s[s <= 0.99999]
s = s.sort_values(ascending=False)
s_df = s.reset_index()
s_df.columns = ["feature_1", "feature_2", "corr"]
return s_df
def check_unique_by_identifier_col(self, df, identifier_col):
"""
Check if there are duplicates by entity (e.g. user, item).
Parameters
--------
df: DataFrame
Returns
--------
dup_rows: DataFrame
"""
try:
dup_rows = pd.concat(
x for col, x in df.groupby(identifier_col) if len(x) > 1
).sort_values(identifier_col)
except Exception:
return "No duplicate rows found."
return dup_rows
def violin_plots_by_col(self, df, path="../images/", group_by_var=None):
"""
Makes a violin plot for each numerical column.
Parameters
--------
df: DataFrame
path: str
group_by_var: str
Variable to group violin plots by
"""
numerical_vals, _ = self.separate_cols_by_type(df)
# Need to fill zeros to get accurate percentile numbers
numerical_vals.fillna(0, inplace=True)
if numerical_vals.empty:
return "No numerical columns to graph."
if not os.path.exists(path):
os.makedirs(path)
iter_bar = progressbar.ProgressBar()
for col in iter_bar(numerical_vals):
# Filter out some extreme outliers for cleaner plot
filtered_df = df[
(df[col] <= df[col].quantile(0.99))
& (df[col] >= df[col].quantile(0.01))
]
fig = plt.figure(figsize=(9, 9))
ax = fig.add_subplot(111)
ax.set_title(col)
if group_by_var:
sns.violinplot(x=group_by_var, y=col, data=filtered_df, ax=ax)
else:
sns.violinplot(
x=col,
data=filtered_df,
ax=ax,
)
text = "75th Percentile: {}\nMedian: {}\n25th Percentile: {}".format(
round(np.percentile(numerical_vals[col], 75), 2),
round(np.median(numerical_vals[col]), 2),
round(np.percentile(numerical_vals[col], 25), 2),
)
# Place a text box in upper left in axes coords
props = dict(boxstyle="round", facecolor="white", alpha=0.5)
ax.text(
0.05,
0.95,
text,
transform=ax.transAxes,
fontsize=14,
verticalalignment="top",
bbox=props,
)
plt.tight_layout()
if group_by_var:
plt.savefig(f"{path}violinplot_{col}_by_{group_by_var}.png")
else:
plt.savefig(f"{path}violinplot_{col}.png")
def bar_graphs_by_col(self, df, path="../images/", group_by_var=None):
"""
Makes a bar graph for each categorical column.
Parameters
--------
df: DataFrame
path: str
group_by_var: str
Variable to group bar graphs by
"""
_, categorical_vals = self.separate_cols_by_type(df)
if categorical_vals.empty:
return "No categorical columns to graph."
if not os.path.exists(path):
os.makedirs(path)
iter_bar = progressbar.ProgressBar()
for col in iter_bar(categorical_vals):
if col == group_by_var:
continue
num_unique_vals = len(df[col].unique())
try:
if num_unique_vals == 1:
continue
# More values than this doesn't display well, just show the top values
if group_by_var:
# Group bys are hard to read unless this is smaller
num_groups = len(df[group_by_var].unique())
most_vals_allowed = round(50 / num_groups)
if most_vals_allowed < 5:
most_vals_allowed = 5
else:
most_vals_allowed = 50
if num_unique_vals > most_vals_allowed:
adjust_vals = df[
df[col].isin(
[
x[0]
for x in Counter(df[col]).most_common(most_vals_allowed)
]
)
]
else:
adjust_vals = df.copy()
fig = plt.figure(figsize=(9, 9))
ax = fig.add_subplot(111)
ax.set_title(col)
if group_by_var:
# Change to proportions by group instead of straight counts (misleading by sample size)
grouped_df = df.groupby([group_by_var, col]).count()
grouped_df_pcts = grouped_df.groupby(level=0).apply(
lambda x: x / float(x.sum())
)
grouped_df_pcts = grouped_df_pcts.reset_index()
grouped_df_pcts.columns = [group_by_var, col, "proportion"]
grouped_df_pcts.sort_values(
by="proportion", ascending=True, inplace=True
)
pivot_df = pd.pivot_table(
grouped_df_pcts,
values="proportion",
index=col,
columns=group_by_var,
).reset_index()
# Sort pivot table by most common cols
sorter = list(
adjust_vals.groupby([col])
.count()
.iloc[:, 1]
.sort_values(ascending=True)
.index
)
sorterIndex = dict(zip(sorter, range(len(sorter))))
pivot_df["rank"] = pivot_df[col].map(sorterIndex)
pivot_df.sort_values(by="rank", ascending=True, inplace=True)
pivot_df.drop("rank", axis=1, inplace=True)
pivot_df.plot(
x=col,
kind="barh",
ylabel=f"proportion_{col}_within_{group_by_var}",
ax=ax,
)
plt.tight_layout()
plt.savefig(
f"{path}bargraph_proportion_{col}_within_{group_by_var}.png"
)
else:
grouped_df = (
adjust_vals.groupby([col]).count().iloc[:, 1]
/ adjust_vals.shape[0]
)
grouped_df = grouped_df.reset_index()
grouped_df.columns = [col, "proportion"]
grouped_df.sort_values(
by="proportion", ascending=True, inplace=True
)
grouped_df.plot(
x=col, kind="barh", legend=None, ylabel="proportion", ax=ax
)
plt.tight_layout()
plt.savefig(f"{path}bargraph_{col}.png")
except Exception:
continue
| StarcoderdataPython |
1992986 | <gh_stars>0
def compute_fine(actual_date, expected_date):
fine = 0
if actual_date[2] <= expected_date[2] and actual_date[1] <= expected_date[1] and actual_date[0] <= expected_date[0]:
# Actual date is on or before expected date
fine = 0
elif actual_date[0] > expected_date[0] and actual_date[1] == expected_date[1] and actual_date[2] == expected_date[2]:
fine = 15 * (actual_date[0] - expected_date[0])
elif actual_date[1] > expected_date[1] and actual_date[2] == expected_date[2]:
fine = 500 * (actual_date[1] - expected_date[1])
elif actual_date[2] > expected_date[2]:
fine = 10000
return fine
if __name__ == "__main__":
# Read date in list format from stdin
actual_date = list(map(int, input().strip().split()))
# Read another date in list format from stdin
expected_date = list(map(int, input().strip().split()))
# Compute fine
print("Fine = ", compute_fine(actual_date, expected_date))
| StarcoderdataPython |
11371570 | <filename>fastaProcessing/fastaAlnCut.py<gh_stars>0
#!/usr/bin/env python
'''
1. fasta file (assume already aligned)
2. start (1-based)
3. end
'''
from sys import argv, exit
from Bio import SeqIO
from os import system
try:
fname = argv[1]
start = int(argv[2])
end = int(argv[3])
except:
exit(__doc__)
f = open(fname, 'r')
records = SeqIO.parse(f, 'fasta')
for record in records:
seqName = record.description
seqShortName = record.id
sequence = record.seq
frag = sequence[start-1:end]
print("%s_%s_%s\t%s"%(seqName, start, end, frag))
f.close()
| StarcoderdataPython |
5092783 | # Character field ID when accessed: 103000003
# ObjectID: 0
# ParentID: 103000003
| StarcoderdataPython |
168918 | from cStringIO import StringIO
from ceph_deploy.hosts import remotes
class TestObjectGrep(object):
def setup(self):
self.file_object = StringIO('foo\n')
self.file_object.seek(0)
def test_finds_term(self):
assert remotes.object_grep('foo', self.file_object)
def test_does_not_find_anything(self):
assert remotes.object_grep('bar', self.file_object) is False
| StarcoderdataPython |
48355 | import datetime
from django.test import TestCase
from ..utils import get_fiscal_year, Holiday
import logging
logger = logging.getLogger(__name__)
__author__ = 'lberrocal'
class TestUtils(TestCase):
def test_get_fiscal_year(self):
cdates = [[datetime.date(2015, 10, 1), 'AF16'],
[datetime.date(2015, 9, 30), 'AF15'],
[datetime.date(2016, 1, 5), 'AF16'],]
for cdate in cdates:
fy = get_fiscal_year(cdate[0])
self.assertEqual(cdate[1], fy)
def test_get_fiscal_year_datetime(self):
cdates = [[datetime.datetime(2015, 10, 1, 16, 0), 'AF16'],
[datetime.datetime(2015, 9, 30, 2, 45), 'AF15'],
[datetime.datetime(2016, 1, 5, 3, 45), 'AF16'],]
for cdate in cdates:
fy = get_fiscal_year(cdate[0])
self.assertEqual(cdate[1], fy)
class TestHolidays(TestCase):
def test_is_holiday(self):
holiday = datetime.date(2015,12,25)
holiday_manager = Holiday()
self.assertTrue(holiday_manager.is_holiday(holiday))
non_holiday = datetime.date(2015,12,24)
self.assertFalse(holiday_manager.is_holiday(non_holiday))
def test_working_days_between(self):
holiday_manager = Holiday()
start_date = datetime.date(2016, 1,1)
end_date = datetime.date(2016,1,31)
self.assertEqual(19, holiday_manager.working_days_between(start_date, end_date))
| StarcoderdataPython |
3460556 | <reponame>teodorpatras/crate-bench
import os
from crate import client
from bench import importers, downloader
FIXTURES_URL = "https://www.vbb.de/media/download/2029"
IMPORT_MAPPING = {
'agency.txt': importers.AgenciesImporter,
'calendar_dates.txt': importers.CalendarDatesImporter,
'calendar.txt': importers.CalendarImporter,
'frequencies.txt': importers.FrequenciesImporter,
'routes.txt': importers.RoutesImporter,
'shapes.txt': importers.ShapesImporter,
'stop_times.txt': importers.StopTimesImporter,
'stops.txt': importers.StopsImporter,
'transfers.txt': importers.TransfersImporter,
'trips.txt': importers.TripsImporter
}
def fetch_fixtures():
print("\n↓ Preparing benchmark! Downloading fixtures...")
directory = os.path.join(os.getcwd(), 'fixtures')
downloader.fetch_data(FIXTURES_URL, directory)
print("✓ Done! Fixtures can be found under '{}'!\n".format(directory))
return directory
def import_data(directory):
connection = client.connect('localhost:4200')
sec = 0
for filename in os.listdir(directory):
if filename in IMPORT_MAPPING:
importer = IMPORT_MAPPING[filename](connection.cursor())
sec += importer.import_file(os.path.join(directory, filename))
return round(sec, 2)
if __name__ == '__main__':
directory = fetch_fixtures()
print("================ CRATEDB BULK INSERT BENCHMARK ======================\n")
sec = import_data(directory)
print("\n\n================ AWWW YES! DONE IN {} SECONDS! (⌐■_■) ===============\n".format(sec))
| StarcoderdataPython |
3286742 | <filename>mqttassistant/app.py
import asyncio
import signal
from . import mqtt
from . import web
from .config import Config
from .dispatch import Signal
from .log import get_logger
from .warn import configure_warnings
configure_warnings()
class Application:
def __init__(self, **kwargs):
self.logger = get_logger('App', level=kwargs.get('log_level', 'INFO'))
self.running = asyncio.Future()
# Config
self.config = Config.parse_config_path(path=kwargs['config_path'])
# Signals
self.mqtt_topic_signal = Signal()
# Mqtt client
self.mqtt = mqtt.Mqtt(topic_signal=self.mqtt_topic_signal, **kwargs)
# Web server
self.web = web.Server(app_config=self.config, mqtt_topic_signal=self.mqtt_topic_signal, **kwargs)
def start(self):
self.logger.info('started')
self.loop = asyncio.get_event_loop()
self.loop.add_signal_handler(signal.SIGINT, lambda: asyncio.create_task(self.stop()))
self.loop.add_signal_handler(signal.SIGTERM, lambda: asyncio.create_task(self.stop()))
self.loop.create_task(self.run())
self.loop.run_until_complete(self.running)
async def run(self):
# Mqtt client
self.mqtt_task = self.mqtt.run()
self.loop.create_task(self.mqtt_task)
# Web server
self.web_task = self.web.run()
self.loop.create_task(self.web_task)
async def stop(self):
self.logger.info('stopping')
await self.web.stop()
await self.mqtt.stop()
self.running.set_result(False)
self.logger.info('stopped')
| StarcoderdataPython |
1912628 | <reponame>davewood/do-portal
import os
from flask import request, current_app, g
from app import db
from app.core import ApiResponse, ApiPagedResponse
from app.models import Sample, Permission
from app.api.decorators import permission_required
from app.tasks import analysis
from app.utils import get_hashes
from . import cp
@cp.route('/samples', methods=['GET'])
def get_samples():
"""Return a paginated list of samples
**Example request**:
.. sourcecode:: http
GET /api/1.0/samples?page=1 HTTP/1.1
Host: cp.cert.europa.eu
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.0 200 OK
Content-Type: application/json
Link: <.../api/1.0/samples?page=1&per_page=20>; rel="First",
<.../api/1.0/samples?page=0&per_page=20>; rel="Last"
{
"count": 2,
"items": [
{
"created": "2016-03-21T16:09:47",
"ctph": "49152:77qzLl6EKvwkdB7qzLl6EKvwkTY40GfAHw7qzLl6EKv...",
"filename": "stux.zip",
"id": 2,
"sha256": "1eedab2b09a4bf6c87b273305c096fa2f597ff9e4bdd39bc..."
},
{
"created": "2016-03-20T16:58:09",
"ctph": "49152:77qzLl6EKvwkdB7qzLl6EKvwkTY40GfAHw7qzLl6EKv...",
"filename": "stux.zip",
"id": 1,
"sha256": "1eedab2b09a4bf6c87b273305c096fa2f597ff9e4bdd39bc45..."
}
],
"page": 1
}
:reqheader Accept: Content type(s) accepted by the client
:resheader Content-Type: this depends on `Accept` header or request
:resheader Link: Describe relationship with other resources
:>json array items: Samples list
:>jsonarr integer id: Sample unique ID
:>jsonarr string created: Time of upload
:>jsonarr string sha256: SHA256 of file
:>jsonarr string ctph: CTPH (a.k.a. fuzzy hash) of file
:>jsonarr string filename: Filename (as provided by the client)
:>json integer page: Current page number
:>json integer count: Total number of items
:status 200: Files found
:status 404: Resource not found
"""
return ApiPagedResponse(Sample.query.filter_by(user_id=g.user.id))
@cp.route('/samples/<string:sha256>', methods=['GET'])
def get_sample(sha256):
"""Return samples identified by `sha256`
**Example request**:
.. sourcecode:: http
GET /api/1.0/samples/1eedab2b09a4bf6c87b273305c096fa2f597f... HTTP/1.1
Host: cp.cert.europa.eu
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.0 200 OK
Content-Type: application/json
{
"created": "2016-03-21T16:09:47",
"ctph": "49152:77qzLl6EKvwkdB7qzLl6EKvwk:azp6EwdMzp6EwTVfKVzp6Ew...",
"filename": "stux.zip",
"id": 2,
"sha256": "1eedab2b09a4bf6c87b273305c096fa2f597ff9e4bdd39bc4594d..."
}
:param sha256: SHA-256 of file
:reqheader Accept: Content type(s) accepted by the client
:resheader Content-Type: this depends on `Accept` header or request
:>jsonarr integer id: Sample unique ID
:>jsonarr string created: Time of upload
:>jsonarr string sha256: SHA256 of file
:>jsonarr string ctph: CTPH (a.k.a. fuzzy hash) of file
:>jsonarr string filename: Filename (as provided by the client)
:status 200: Returns sample details object
:status 404: Resource not found
"""
i = Sample.query.filter_by(sha256=sha256, user_id=g.user.id).first_or_404()
return ApiResponse(i)
@cp.route('/samples', methods=['POST', 'PUT'])
@permission_required(Permission.SUBMITSAMPLE)
def add_cp_sample():
"""Upload untrusted files, E.i. malware samples, files for analysis.
After upload MD5, SHA1, SHA256, SHA512 and CTPH hashes are calculated.
**Example request**:
.. sourcecode:: http
POST /api/1.0/samples HTTP/1.1
Host: cp.cert.europa.eu
Accept: application/json
Content-Type: multipart/form-data; boundary=----FormBoundaryrflTTZA0oE
------FormBoundaryrflTTZA0oE
Content-Disposition: form-data; name="files[0]"; filename="stux.zip"
Content-Type: application/zip
------FormBoundaryrflTTZA0oE--
**Example response**:
.. sourcecode:: http
HTTP/1.0 201 CREATED
Content-Type: application/json
{
"files": [
{
"created": "2016-03-21T16:09:47",
"ctph": "49152:77qzLl6EKvwkdB7qzLl6EKvwkTY40GfAHw7qzLl6EKvwk...",
"filename": "stux.zip",
"id": 2,
"sha256": "1eedab2b09a4bf6c87b273305c096fa2f597ff9e4bdd39bc4..."
}
],
"message": "Files uploaded"
}
:reqheader Accept: Content type(s) accepted by the client
:reqheader Content-Type: multipart/form-data required
:resheader Content-Type: this depends on `Accept` header or request
:form files: Files to be uploaded
:>json array files: List of files saved to disk
:>jsonarr integer id: Sample unique ID
:>jsonarr string created: Time of upload
:>jsonarr string sha256: SHA256 of file
:>jsonarr string ctph: CTPH (a.k.a. fuzzy hash) of file
:>jsonarr string filename: Filename (as provided by the client)
:>json string message: Status message
:statuscode 201: Files successfully saved
"""
uploaded_samples = []
for idx, file_ in request.files.items():
buf = file_.stream.read()
hashes = get_hashes(buf)
hash_path = os.path.join(
current_app.config['APP_UPLOADS_SAMPLES'],
hashes.sha256
)
if not os.path.isfile(hash_path):
file_.stream.seek(0)
file_.save(hash_path)
s = Sample(user_id=g.user.id, filename=file_.filename, md5=hashes.md5,
sha1=hashes.sha1, sha256=hashes.sha256,
sha512=hashes.sha512, ctph=hashes.ctph)
db.session.add(s)
try:
db.session.commit()
analysis.preprocess(s)
except Exception as e:
db.session.rollback()
db.session.flush()
current_app.log.error(e.args[0])
uploaded_samples.append(s.serialize())
return ApiResponse({
'message': 'Files uploaded',
'files': uploaded_samples
}, 201)
| StarcoderdataPython |
8011746 | <reponame>neerbek/taboo-selective
# -*- coding: utf-8 -*-
"""
Created on October 3, 2017
@author: neerbek
Trains a RNN flat model on input list of trees and embeddings
"""
import sys
from numpy.random import RandomState # type: ignore
import numpy as np
import ai_util
import jan_ai_util
import rnn_model.rnn
import rnn_model.learn
import rnn_model.FlatTrainer
import confusion_matrix
import kmeans_cluster_util as kutil
# import importlib
# importlib.reload(jan_ai_util)
# os.chdir("../../taboo-core")
inputfile = "output/kmeans_embeddingsC1.txt"
inputdevfile = "output/kmeans_embeddings2C1.txt"
extradata = None
runOnly = False
trainParam = rnn_model.FlatTrainer.TrainParam()
trainParam.retain_probability = 0.9
trainParam.batchSize = 500
# randomSeed = 7485
randomSeed = None
hiddenLayerSize = 150
numberOfHiddenLayers = 2
nEpochs = 5 * 128
trainReportFrequency = 32 * 72
validationFrequency = 64 * 72
inputmodel = None
filePrefix = "save"
learnRate = 0.5
momentum = 0.0
featureDropCount = 0
dataAugmentCount = 0
dataAugmentFactor = None
timers = jan_ai_util.Timers()
def syntax():
print("""syntax: kmeans_cluster_cmd3.py
-inputfile <filename> | -inputdevfile <filename> | -extradata <file> |-retain_probability <float> |
-batchSize <int> | -randomSeed <int> | -hiddenLayerSize <int> | -numberOfHiddenLayers <int> |
-nEpochs <int> | -learnRate <float> | -momentum <float> | -L1param <float> | -L2param <float> |
-dataAugmentCount <int> | -dataAugmentFactor <float> | -trainReportFrequency <int> |
-validationFrequency <int> | -inputmodel <filename> | filePrefix <string> | -runOnly
-h | --help | -?
-inputfile is a list of final sentence embeddings in the format of run_model_verbose.py
-inputdevfile is a list of final sentence embeddings in the format of run_model_verbose.py
-extradata is a file with node embeddigs for sentences in inputfile. In the format of run_model_verbose.py. Exact match on sentences are used to select which node values to use.
-inputmodel is an optioal previous saved set of parameters for the NN model which will be loaded
-retain_probability the probability of a neuron NOT being dropped in dropout
-batchSize the number of embeddings trained in a minibatch
-randomSeed initialize the random number generator
-hiddenLayerSize number of neurons in the hidden layer(s)
-numberOfHiddenLayers number of hidden layers
-nEpochs number of complete loops of the training data to do
-learnRate - learnrate for gradient (w/o momentum) learner
-momentum - momentum for gradient (with momentum) learner
-L1param - weight of L1 regularization
-L2param - weight of L1 regularization
-dataAugmentCount - number of times to increase data by add a noisy version
-dataAugmentFactor - multiplicative factor for noise (default uniform 0..1 distributed)
-featureDropCount - number of random features to drop (set to 0)
-trainReportFrequency - number of minibatches to do before outputting progress on training set
-validationFrequency - number of minibatches to do before outputting progress on validation set
-filePrefix is a prefix added to all saved model parameters in this run
-runOnly do not train only validates
""")
sys.exit()
arglist = sys.argv
# arglist = "train_flat_feature_dropout.py -retain_probability 0.9 -hiddenLayerSize 150 -numberOfHiddenLayers 3 -filePrefix save -learnRate 0.01 -momentum 0 -trainReportFrequency 450 -validationFrequency 900 -nEpochs 400 -randomSeed 37624".split(" ")
argn = len(arglist)
i = 1
if argn == 1:
syntax()
print("Parsing args")
while i < argn:
setting = arglist[i]
arg = None
if i < argn - 1:
arg = arglist[i + 1]
next_i = i + 2 # assume option with argument (increment by 2)
if setting == '-inputfile':
inputfile = arg
elif setting == '-inputdevfile':
inputdevfile = arg
elif setting == '-extradata':
extradata = arg
elif setting == '-retain_probability':
trainParam.retain_probability = float(arg)
elif setting == '-randomSeed':
randomSeed = int(arg)
elif setting == '-batchSize':
trainParam.batchSize = int(arg)
elif setting == '-hiddenLayerSize':
hiddenLayerSize = int(arg)
elif setting == '-numberOfHiddenLayers':
numberOfHiddenLayers = int(arg)
elif setting == '-nEpochs':
nEpochs = int(arg)
elif setting == '-learnRate':
learnRate = float(arg)
elif setting == '-momentum':
momentum = float(arg)
elif setting == '-trainReportFrequency':
trainReportFrequency = ai_util.eval_expr(arg)
elif setting == '-validationFrequency':
validationFrequency = ai_util.eval_expr(arg)
elif setting == '-inputmodel':
inputmodel = arg
elif setting == '-filePrefix':
filePrefix = arg
elif setting == '-featureDropCount':
featureDropCount = int(arg)
elif setting == '-L1param':
trainParam.L1param = float(arg)
elif setting == '-L2param':
trainParam.L2param = float(arg)
elif setting == '-dataAugmentCount':
dataAugmentCount = int(arg)
elif setting == '-dataAugmentFactor':
dataAugmentFactor = float(arg)
else:
# expected option with no argument
if setting == '-help':
syntax()
elif setting == '-?':
syntax()
elif setting == '-h':
syntax()
elif setting == '-runOnly':
runOnly = True
else:
msg = "unknown option: " + setting
print(msg)
syntax()
raise Exception(msg)
next_i = i + 1
i = next_i
lines = confusion_matrix.read_embeddings(inputfile, max_line_count=-1)
if extradata != None:
lines = confusion_matrix.read_embeddings(extradata, max_line_count=-1, originalLines=lines)
print("number of input train lines {}".format(len(lines)))
a1 = confusion_matrix.get_embedding_matrix(lines, normalize=True)
lines2 = confusion_matrix.read_embeddings(inputdevfile, max_line_count=-1)
a2 = confusion_matrix.get_embedding_matrix(lines2, normalize=True)
if randomSeed is None:
rng = RandomState()
randomSeed = rng.randint(10000000)
print("Using randomSeed: {}".format(randomSeed))
rng = RandomState(randomSeed)
print(len(lines), len(lines2))
kutil.get_base_accuracy(lines, "train acc (orig model on embeddings)").report()
if featureDropCount > 0:
perm = rng.permutation(a1.shape[1])
featureDropArray = perm[:featureDropCount]
for f in featureDropArray:
a1[:, f] = 0
a2[:, f] = 0
print("featureDropArray", featureDropArray)
# print(a1[10])
trainParam.X = jan_ai_util.addBiasColumn(a1) # add 1 bias column, not really needed, but ...
trainParam.valX = jan_ai_util.addBiasColumn(a2) # add 1 bias column, not really needed, but ...
if dataAugmentCount > 0:
tmpX = trainParam.X
tmpValX = trainParam.valX
for i in range(dataAugmentCount):
tmpX = np.concatenate((tmpX, jan_ai_util.addNoise(trainParam.X, rng, noiseFactor=dataAugmentFactor)), axis=0)
tmpValX = np.concatenate((tmpValX, jan_ai_util.addNoise(trainParam.valX, rng, noiseFactor=dataAugmentFactor)), axis=0)
trainParam.X = tmpX
trainParam.valX = tmpValX
# format y to 2 class "softmax"
trainParam.Y = jan_ai_util.lines2multiclassification(lines, classes=[0, 4])
trainParam.valY = jan_ai_util.lines2multiclassification(lines2, classes=[0, 4])
if dataAugmentCount > 0:
tmpY = trainParam.Y
tmpValY = trainParam.valY
for i in range(dataAugmentCount):
tmpY = np.concatenate((tmpY, trainParam.Y), axis=0)
tmpValY = np.concatenate((tmpValY, trainParam.valY), axis=0)
trainParam.Y = tmpY
trainParam.valY = tmpValY
trainParam.learner = rnn_model.learn.GradientDecentWithMomentumLearner(lr=learnRate, mc=momentum)
inputSize = trainParam.X.shape[1]
def buildModel(isDropoutEnabled, rng=RandomState(randomSeed)):
model = rnn_model.FlatTrainer.RNNContainer(nIn=inputSize, isDropoutEnabled=isDropoutEnabled, rng=rng)
for i in range(numberOfHiddenLayers):
dropout = rnn_model.FlatTrainer.DropoutLayer(model, trainParam.retain_probability, rnn_model.FlatTrainer.ReluLayer(nOut=hiddenLayerSize))
model.addLayer(dropout)
model.addLayer(rnn_model.FlatTrainer.RegressionLayer(nOut=2))
return model
model = buildModel(True)
if inputmodel != None:
model.load(inputmodel)
validationModel = buildModel(False)
# actual training
timers.traintimer.begin()
rnn_model.FlatTrainer.train(trainParam, model, validationModel, n_epochs=nEpochs, trainReportFrequency=trainReportFrequency, validationFrequency=validationFrequency, file_prefix=filePrefix, rng=rng, runOnly=runOnly)
# done
timers.endAndReport()
| StarcoderdataPython |
4924613 | <reponame>zuru/MappedConvolutions
import torch
import torch.nn as nn
import math
import _mapped_convolution_ext._weighted_mapped_avg_pooling as weighted_mapped_avg_pool
import _mapped_convolution_ext._mapped_avg_pooling as mapped_avg_pool
import _mapped_convolution_ext._resample as resample
from .layer_utils import *
class MappedAvgPoolFunction(torch.autograd.Function):
@staticmethod
def forward(self,
input,
sample_map,
kernel_size,
interp,
interp_weights=None):
if interp_weights is not None:
pooled_output = weighted_mapped_avg_pool.weighted_mapped_avg_pool(
input, sample_map, interp_weights, kernel_size, interp)
else:
pooled_output = mapped_avg_pool.mapped_avg_pool(
input, sample_map, kernel_size, interp)
self.save_for_backward(torch.tensor([input.shape[2], input.shape[3]]),
sample_map, torch.tensor(kernel_size),
torch.tensor(interp), interp_weights)
return pooled_output
@staticmethod
def backward(self, grad_output):
input_shape, \
sample_map, \
kernel_size, \
interp, \
interp_weights = self.saved_tensors
if interp_weights is not None:
grad_input = weighted_mapped_avg_pool.weighted_mapped_avg_unpool(
grad_output, sample_map, interp_weights, input_shape[0],
input_shape[1], kernel_size, interp)
else:
grad_input = mapped_avg_pool.mapped_avg_unpool(
grad_output, sample_map, input_shape[0], input_shape[1],
kernel_size, interp)
return grad_input, None, None, None, None
class MappedAvgPool(nn.Module):
def __init__(self, kernel_size, interpolation='bilinear'):
super(MappedAvgPool, self).__init__()
self.kernel_size = kernel_size
if interpolation == 'nearest':
self.interp = 0
elif interpolation == 'bilinear':
self.interp = 1
elif interpolation == 'bispherical':
self.interp = 2
else:
assert False, 'Unsupported interpolation type'
def forward(self, x, sample_map, interp_weights=None):
check_args(x, sample_map, interp_weights, None, self.kernel_size)
return MappedAvgPoolFunction.apply(x, sample_map, self.kernel_size,
self.interp, interp_weights)
class MappedAvgUnpoolFunction(torch.autograd.Function):
@staticmethod
def forward(self,
input,
oh,
ow,
sample_map,
kernel_size,
interp,
interp_weights=None):
if interp_weights is not None:
pooled_output = weighted_mapped_avg_pool.weighted_mapped_avg_unpool(
input, sample_map, oh, ow, interp_weights, kernel_size, interp)
else:
pooled_output = mapped_avg_pool.mapped_avg_unpool(
input, sample_map, oh, ow, kernel_size, interp)
self.save_for_backward(torch.tensor([input.shape[2], input.shape[3]]),
sample_map, torch.tensor(kernel_size),
torch.tensor(interp), interp_weights)
return pooled_output
@staticmethod
def backward(self, grad_output):
input_shape, \
sample_map, \
kernel_size, \
interp, \
interp_weights = self.saved_tensors
if interp_weights is not None:
grad_input = weighted_mapped_avg_pool.weighted_mapped_avg_pool(
grad_output, sample_map, interp_weights, kernel_size, interp)
else:
grad_input = mapped_avg_pool.mapped_avg_pool(
grad_output, sample_map, kernel_size, interp)
return grad_input, None, None, None, None, None, None, None
class MappedAvgUnpool(nn.Module):
def __init__(self, kernel_size, interpolation='bilinear'):
super(MappedAvgUnpool, self).__init__()
self.kernel_size = kernel_size
if interpolation == 'nearest':
self.interp = 0
elif interpolation == 'bilinear':
self.interp = 1
elif interpolation == 'bispherical':
self.interp = 2
else:
assert False, 'Unsupported interpolation type'
def forward(self, x, oh, ow, sample_map, interp_weights=None):
'''
x: batch x channels x input_height x input_width
oh: scalar output height
ow: scalar output width
sample_map: input_height x input_width x kernel_size x 2 (x, y)
interp_weights: [OPTIONAL] input_height x input_width x kernel_size x num_interp_points x 2 (x, y)
'''
check_args(x, sample_map, interp_weights, None, self.kernel_size)
check_input_map_shape(x, sample_map)
return MappedAvgUnpoolFunction.apply(x, oh, ow, sample_map,
self.kernel_size, self.interp,
interp_weights)
| StarcoderdataPython |
9771030 | from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from django.contrib.auth import login, logout
from django.contrib.auth.hashers import check_password
from apps.goods.models import GoodsType
from apps.user.models import User
class AdminLoginView(View):
"""后台登录接口"""
def post(self, request):
"""管理界面登录接口"""
# 初始化返回结果
response = {
'code': 1,
'data': [],
'msg': ''
}
# 获取数据
username = request.POST.get('username')
password = request.POST.get('password')
# 逻辑处理
if not all([username, password]):
response['msg'] = '数据不完整'
return JsonResponse(response)
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
user = None
if user is not None:
pwd = <PASSWORD>
if check_password(password, pwd):
if user.is_superuser:
login(request, user)
response['code'] = 0
response['msg'] = '登录成功'
response['data'] = []
# 判断是否需要记住用户名
return JsonResponse(response)
else:
response['msg'] = '不是超级管理员'
return JsonResponse(response)
# 记录用户的登录状态
else:
response['msg'] = '密码不正确'
return JsonResponse(response)
else:
response['msg'] = '用户不存在'
return JsonResponse(response)
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super(AdminLoginView, self).dispatch(*args, **kwargs)
| StarcoderdataPython |
3205005 | """Tic Tac Toe."""
from game import Game
import sys
class TicTacToe(Game):
"""Tic Tac Toe game class."""
def __init__(self):
"""Construct new tictactoe game instance."""
self.board = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
self.player = 'X'
self.winner = None
def reset(self):
"""Reset board between games."""
self.board = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
self.player = 'X'
self.winner = None
def get_open_moves(self):
"""Returns list of available moves given current states and next states."""
actions = []
states = []
for i, val in enumerate(self.board):
if val == '-':
actions.append(i)
self.board[i] = self.player
states.append(self.get_state(self.board))
self.board[i] = '-'
return states, actions
def get_state(self, board):
"""Returns board state as String."""
return ''.join(board)
def is_win(self):
"""Check the board for win condition.
Possible outputs are X, O, Draw, None.
"""
# Check win condition
row_1 = self.board[0] + self.board[1] + self.board[2]
row_2 = self.board[3] + self.board[4] + self.board[5]
row_3 = self.board[6] + self.board[7] + self.board[8]
col_1 = self.board[0] + self.board[3] + self.board[6]
col_2 = self.board[1] + self.board[4] + self.board[7]
col_3 = self.board[2] + self.board[5] + self.board[8]
diag_1 = self.board[0] + self.board[4] + self.board[8]
diag_2 = self.board[2] + self.board[4] + self.board[6]
triples = [row_1, row_2, row_3, col_1, col_2, col_3, diag_1, diag_2]
for triple in triples:
if (triple == 'OOO'):
return 'O'
elif (triple == 'XXX'):
return 'X'
# Check draw condition
if '-' not in self.board:
return 'Draw'
return None
def is_valid_move(self, position):
"""Check that potential move is in a valid position.
Valid means inbounds and not occupied.
"""
if position >= 0 and position < len(self.board):
return self.board[position] == '-'
else:
return False
def make_move(self, position):
"""Makes move by setting position to player value.
Also toggles player and returns is_win result.
"""
self.board[position] = self.player
self.player = 'O' if self.player == 'X' else 'X'
return self.is_win()
def read_input(self):
"""Define game specific read in function from command line."""
return int(sys.stdin.readline()[:-1])
def print_board(self):
print('{} {} {}\n{} {} {}\n{} {} {}'.format(self.board[0], self.board[1], self.board[2],
self.board[3], self.board[4], self.board[5],
self.board[6], self.board[7], self.board[8]))
print('=====')
def print_instructions(self):
print('===============\n'
'How to play:\n'
'Possible moves are [0,9) corresponding to these spaces on the board:\n\n'
'0 | 1 | 2\n'
'3 | 4 | 5\n'
'6 | 7 | 8\n')
| StarcoderdataPython |
11283611 | <filename>download.py
import argparse
import asyncio
import hashlib
from urllib.parse import urlsplit
import aiohttp
chunk_size = 1_024 # Set to 1 KB chunks
async def download_url(url, destination):
print(f'Downloading {url}')
file_hash = hashlib.sha256()
with open(destination, 'wb') as file:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
# define async generator for getting bytes
async def get_bytes():
while True:
chunk = await response.content.read(chunk_size)
if not chunk:
return
yield chunk
# handle the download
async for chunk in get_bytes():
file_hash.update(chunk)
file.write(chunk)
print(f'Downloaded {destination}, sha256: {file_hash.hexdigest()}')
def main():
# get the URL from the command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument('url', metavar='URL', help='The URL to download')
arguments = parser.parse_args()
# get the filename from the URL
url_parts = urlsplit(arguments.url)
file_name = url_parts.path[url_parts.path.rfind('/') + 1:]
# start the download async
loop = asyncio.get_event_loop()
loop.run_until_complete(download_url(arguments.url, file_name))
if __name__ == '__main__':
main()
| StarcoderdataPython |
357429 | <reponame>vitekcode/premise
from pathlib import Path
import numpy as np
import pandas as pd
import wurst
import yaml
from schema import And, Optional, Or, Schema, Use
from .ecoinvent_modification import (
LIST_IMAGE_REGIONS,
LIST_REMIND_REGIONS,
SUPPORTED_EI_VERSIONS,
)
from .transformation import *
from .utils import eidb_label
def find_iam_efficiency_change(
variable: Union[str, list], location: str, custom_data
) -> float:
"""
Return the relative change in efficiency for `variable` in `location`
relative to 2020.
:param variable: IAM variable name
:param location: IAM region
:return: relative efficiency change (e.g., 1.05)
"""
for c in custom_data.values():
if "efficiency" in c:
if variable in c["efficiency"].variables.values:
scaling_factor = (
c["efficiency"]
.sel(region=location, variables=variable)
.values.item(0)
)
if scaling_factor in (np.nan, np.inf):
scaling_factor = 1
return scaling_factor
def check_inventories(custom_scenario, data, model, pathway, custom_data):
for i, scenario in enumerate(custom_scenario):
with open(scenario["config"], "r") as stream:
config_file = yaml.safe_load(stream)
df = pd.read_excel(scenario["scenario data"])
for k, v in config_file["production pathways"].items():
name = v["ecoinvent alias"]["name"]
ref = v["ecoinvent alias"]["reference product"]
if (
len(
[
a
for a in data
if (name, ref) == (a["name"], a["reference product"])
]
)
== 0
) and not v["ecoinvent alias"].get("exists in ecoinvent"):
raise ValueError(
f"The inventories provided do not contain the activity: {name, ref}"
)
for i, a in enumerate(data):
a["custom scenario dataset"] = True
if (name, ref) == (a["name"], a["reference product"]):
data[i] = flag_activities_to_adjust(
a, df, model, pathway, v, custom_data
)
return data
def flag_activities_to_adjust(a, df, model, pathway, v, custom_data):
regions = (
df.loc[
(df["model"] == model) & (df["pathway"] == pathway),
"region",
]
.unique()
.tolist()
)
if "except regions" in v:
regions = [r for r in regions if r not in v["except regions"]]
# add potential technosphere or biosphere filters
if "efficiency" in v:
a["adjust efficiency"] = True
a["regions"] = regions
for eff in v["efficiency"]:
if "includes" in eff:
for flow_type in ["technosphere", "biosphere"]:
if flow_type in eff["includes"]:
items_to_include = eff["includes"][flow_type]
if f"{flow_type} filters" in a:
a[f"{flow_type} filters"].append(
[
items_to_include,
{
r: find_iam_efficiency_change(
eff["variable"],
r,
custom_data,
)
for r in regions
},
]
)
else:
a[f"{flow_type} filters"] = [
[
items_to_include,
{
r: find_iam_efficiency_change(
eff["variable"],
r,
custom_data,
)
for r in regions
},
]
]
else:
a[f"technosphere filters"] = [
[
None,
{
r: find_iam_efficiency_change(
eff["variable"],
r,
custom_data,
)
for r in regions
},
],
]
a[f"biosphere filters"] = [
[
None,
{
r: find_iam_efficiency_change(
eff["variable"],
r,
custom_data,
)
for r in regions
},
],
]
if "replaces" in v:
a["replaces"] = v["replaces"]
if "replaces in" in v:
a["replaces in"] = v["replaces in"]
if "replacement ratio" in v:
a["replacement ratio"] = v["replacement ratio"]
return a
def detect_ei_activities_to_adjust(custom_scenario, data, model, pathway, custom_data):
"""
Flag activities native to ecoinvent that will their efficiency to be adjusted.
"""
for i, scenario in enumerate(custom_scenario):
with open(scenario["config"], "r") as stream:
config_file = yaml.safe_load(stream)
df = pd.read_excel(scenario["scenario data"])
for k, v in config_file["production pathways"].items():
if "exists in ecoinvent" in v["ecoinvent alias"]:
if v["ecoinvent alias"]["exists in ecoinvent"]:
if "efficiency" in v:
name = v["ecoinvent alias"]["name"]
ref = v["ecoinvent alias"]["reference product"]
for ds in ws.get_many(
data,
ws.equals("name", name),
ws.equals("reference product", ref),
):
ds = flag_activities_to_adjust(
ds, df, model, pathway, v, custom_data
)
return data
def check_custom_scenario_dictionary(custom_scenario, need_for_inventories):
dict_schema = Schema(
[
{
"inventories": And(
str,
Use(str),
lambda f: Path(f).exists() and Path(f).suffix == ".xlsx"
if need_for_inventories
else True,
),
"scenario data": And(
Use(str), lambda f: Path(f).exists() and Path(f).suffix == ".xlsx"
),
"config": And(
Use(str), lambda f: Path(f).exists() and Path(f).suffix == ".yaml"
),
Optional("ecoinvent version"): And(
Use(str), lambda v: v in SUPPORTED_EI_VERSIONS
),
}
]
)
dict_schema.validate(custom_scenario)
if (
sum(s == y for s in custom_scenario for y in custom_scenario)
/ len(custom_scenario)
> 1
):
raise ValueError("Two or more entries in `custom_scenario` are similar.")
def check_config_file(custom_scenario):
for i, scenario in enumerate(custom_scenario):
with open(scenario["config"], "r") as stream:
config_file = yaml.safe_load(stream)
file_schema = Schema(
{
"production pathways": {
str: {
"production volume": {
"variable": str,
},
"ecoinvent alias": {
"name": str,
"reference product": str,
Optional("exists in ecoinvent"): bool,
},
Optional("efficiency"): [
{
"variable": str,
Optional("reference year"): And(
Use(int), lambda n: 2005 <= n <= 2100
),
Optional("includes"): {
Optional("technosphere"): list,
Optional("biosphere"): list,
},
}
],
Optional("except regions"): And(
list,
Use(list),
lambda s: all(
i in LIST_REMIND_REGIONS + LIST_IMAGE_REGIONS for i in s
),
),
Optional("replaces"): [{"name": str, "reference product": str}],
Optional("replaces in"): [
{"name": str, "reference product": str}
],
Optional("replacement ratio"): float,
},
},
Optional("markets"): [
{
"name": str,
"reference product": str,
"unit": str,
"includes": [{"name": str, "reference product": str}],
Optional("except regions"): And(
list,
Use(list),
lambda s: all(
i in LIST_REMIND_REGIONS + LIST_IMAGE_REGIONS for i in s
),
),
Optional("replaces"): [{"name": str, "reference product": str}],
Optional("replaces in"): [
{"name": str, "reference product": str}
],
Optional("replacement ratio"): float,
}
],
}
)
file_schema.validate(config_file)
if "markets" in config_file:
# check that providers composing the market
# are listed
for market in config_file["markets"]:
market_providers = [
(a["name"], a["reference product"]) for a in market["includes"]
]
listed_providers = [
(
a["ecoinvent alias"]["name"],
a["ecoinvent alias"]["reference product"],
)
for a in config_file["production pathways"].values()
]
if any([i not in listed_providers for i in market_providers]):
raise ValueError(
"One of more providers listed under `markets/includes` is/are not listed "
"under `production pathways`."
)
needs_imported_inventories = [False for _ in custom_scenario]
for i, scenario in enumerate(custom_scenario):
with open(scenario["config"], "r") as stream:
config_file = yaml.safe_load(stream)
if len(list(config_file["production pathways"].keys())) != sum(
get_recursively(config_file["production pathways"], "exists in ecoinvent")
):
needs_imported_inventories[i] = True
return sum(needs_imported_inventories)
def check_scenario_data_file(custom_scenario, iam_scenarios):
for i, scenario in enumerate(custom_scenario):
with open(scenario["config"], "r") as stream:
config_file = yaml.safe_load(stream)
df = pd.read_excel(scenario["scenario data"])
mandatory_fields = ["model", "pathway", "region", "variables", "unit"]
if not all(v in df.columns for v in mandatory_fields):
raise ValueError(
f"One or several mandatory column are missing "
f"in the scenario data file no. {i + 1}. Mandatory columns: {mandatory_fields}."
)
years_cols = [c for c in df.columns if isinstance(c, int)]
if any(y for y in years_cols if y < 2005 or y > 2100):
raise ValueError(
f"One or several of the years provided in the scenario data file no. {i + 1} are "
"out of boundaries (2005 - 2100)."
)
if len(pd.isnull(df).sum()[pd.isnull(df).sum() > 0]) > 0:
raise ValueError(
f"The following columns in the scenario data file no. {i + 1}"
f"contains empty cells.\n{pd.isnull(df).sum()[pd.isnull(df).sum() > 0]}."
)
if any(
m not in [s["model"] for s in iam_scenarios] for m in df["model"].unique()
):
raise ValueError(
f"One or several model name(s) in the scenario data file no. {i + 1} "
"is/are not found in the list of scenarios to create."
)
if any(
m not in df["model"].unique() for m in [s["model"] for s in iam_scenarios]
):
raise ValueError(
f"One or several model name(s) in the list of scenarios to create "
f"is/are not found in the scenario data file no. {i + 1}. "
)
if any(
m not in [s["pathway"] for s in iam_scenarios]
for m in df["pathway"].unique()
):
raise ValueError(
f"One or several pathway name(s) in the scenario data file no. {i + 1} "
"is/are not found in the list of scenarios to create."
)
if any(
m not in df["pathway"].unique()
for m in [s["pathway"] for s in iam_scenarios]
):
raise ValueError(
f"One or several pathway name(s) in the list of scenarios to create "
f"is/are not found in the scenario data file no. {i + 1}."
)
d_regions = {"remind": LIST_REMIND_REGIONS, "image": LIST_IMAGE_REGIONS}
for irow, r in df.iterrows():
if r["region"] not in d_regions[r["model"]]:
raise ValueError(
f"Region {r['region']} indicated "
f"in row {irow} is not valid for model {r['model'].upper()}."
)
if not all(
v in get_recursively(config_file, "variable")
for v in df["variables"].unique()
):
raise ValueError(
f"One or several variable names in the scenario data file no. {i + 1} "
"cannot be found in the configuration file."
)
if not all(
v in df["variables"].unique()
for v in get_recursively(config_file, "variable")
):
raise ValueError(
f"One or several variable names in the configuration file {i + 1} "
"cannot be found in the scenario data file."
)
try:
np.array_equal(df.iloc[:, 5:], df.iloc[:, 5:].astype(float))
except ValueError as e:
raise TypeError(
f"All values provided in the time series must be numerical "
f"in the scenario data file no. {i + 1}."
) from e
return custom_scenario
def get_recursively(search_dict, field):
"""Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided.
"""
fields_found = []
for key, value in search_dict.items():
if key == field:
fields_found.append(value)
elif isinstance(value, dict):
results = get_recursively(value, field)
for result in results:
fields_found.append(result)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = get_recursively(item, field)
for another_result in more_results:
fields_found.append(another_result)
return fields_found
def check_custom_scenario(custom_scenario: dict, iam_scenarios: list) -> dict:
"""
Check that all required keys and values are found to add a custom scenario.
:param custom_scenario: scenario dictionary
:return: scenario dictionary
"""
# Validate yaml config file
need_for_ext_inventories = check_config_file(custom_scenario)
# Validate `custom_scenario` dictionary
check_custom_scenario_dictionary(custom_scenario, need_for_ext_inventories)
# Validate scenario data
check_scenario_data_file(custom_scenario, iam_scenarios)
return custom_scenario
class Custom(BaseTransformation):
def __init__(
self,
database: List[dict],
iam_data: IAMDataCollection,
custom_scenario: dict,
custom_data: dict,
model: str,
pathway: str,
year: int,
version: str,
):
super().__init__(database, iam_data, model, pathway, year)
self.custom_scenario = custom_scenario
self.custom_data = custom_data
def adjust_efficiency(self, dataset: dict) -> dict:
"""
Adjust the input-to-output efficiency of a dataset and return it back.
:param dataset: dataset to be adjusted
:return: adjusted dataset
"""
if "adjust efficiency" in dataset:
for eff_type in ["technosphere", "biosphere"]:
if f"{eff_type} filters" in dataset:
for x in dataset[f"{eff_type} filters"]:
scaling_factor = 1 / x[1][dataset["location"]]
filters = x[0]
if eff_type == "technosphere":
for exc in ws.technosphere(
dataset,
*[ws.contains("name", x) for x in filters]
if filters is not None
else [],
):
wurst.rescale_exchange(exc, scaling_factor)
else:
for exc in ws.biosphere(
dataset,
*[ws.contains("name", x) for x in filters]
if filters is not None
else [],
):
wurst.rescale_exchange(exc, scaling_factor)
return dataset
def regionalize_imported_inventories(self) -> None:
"""
Produce IAM region-specific version fo the dataset.
"""
acts_to_regionalize = [
ds for ds in self.database if "custom scenario dataset" in ds
]
for ds in acts_to_regionalize:
del ds["custom scenario dataset"]
new_acts = self.fetch_proxies(
name=ds["name"],
ref_prod=ds["reference product"],
relink=True,
regions=ds.get("regions", self.regions),
)
# adjust efficiency
new_acts = {k: self.adjust_efficiency(v) for k, v in new_acts.items()}
self.database.extend(new_acts.values())
if "replaces" in ds:
self.relink_to_new_datasets(
replaces=ds["replaces"],
replaces_in=ds.get("replaces in", None),
new_name=ds["name"],
new_ref=ds["reference product"],
ratio=ds.get("replacement ratio", 1),
regions=ds.get("regions", self.regions),
)
def get_market_dictionary_structure(self, market: dict, region: str) -> dict:
"""
Return a dictionary for market creation. To be further filled with exchanges.
:param market: YAML configuration file
:param region: region to create the dataset for.
:return: dictionary
"""
return {
"name": market["name"],
"reference product": market["reference product"],
"unit": market["unit"],
"location": region,
"database": eidb_label(self.model, self.scenario, self.year),
"code": str(uuid.uuid4().hex),
"exchanges": [
{
"name": market["name"],
"product": market["reference product"],
"unit": market["unit"],
"location": region,
"type": "production",
"amount": 1,
}
],
}
def fill_in_world_market(self, market: dict, regions: list, i: int) -> dict:
world_market = self.get_market_dictionary_structure(market, "World")
new_excs = []
for region in regions:
supply_share = np.clip(
(
self.custom_data[i]["production volume"]
.sel(region=region, year=self.year)
.sum(dim="variables")
/ self.custom_data[i]["production volume"]
.sel(year=self.year)
.sum(dim=["variables", "region"])
).values.item(0),
0,
1,
)
new_excs.append(
{
"name": market["name"],
"product": market["reference product"],
"unit": market["unit"],
"location": region,
"type": "technosphere",
"amount": supply_share,
}
)
world_market["exchanges"].extend(new_excs)
return world_market
def check_existence_of_market_suppliers(self):
# Loop through custom scenarios
for i, c in enumerate(self.custom_scenario):
# Open corresponding config file
with open(c["config"], "r") as stream:
config_file = yaml.safe_load(stream)
# Check if information on market creation is provided
if "markets" in config_file:
for market in config_file["markets"]:
# Loop through the technologies that should compose the market
for dataset_to_include in market["includes"]:
# try to see if we find a provider with that region
suppliers = list(
ws.get_many(
self.database,
ws.equals("name", dataset_to_include["name"]),
ws.equals(
"reference product",
dataset_to_include["reference product"],
),
ws.either(
*[
ws.equals("location", loc)
for loc in self.regions
]
),
)
)
if len(suppliers) == 0:
print(f"Regionalize dataset {dataset_to_include['name']}.")
ds = list(
ws.get_many(
self.database,
ws.equals("name", dataset_to_include["name"]),
ws.equals(
"reference product",
dataset_to_include["reference product"],
),
)
)[0]
ds["custom scenario dataset"] = True
self.regionalize_imported_inventories()
def create_custom_markets(self) -> None:
"""
Create new custom markets, and create a `World` market
if no data is provided for it.
"""
self.check_existence_of_market_suppliers()
# Loop through custom scenarios
for i, c in enumerate(self.custom_scenario):
# Open corresponding config file
with open(c["config"], "r") as stream:
config_file = yaml.safe_load(stream)
# Check if information on market creation is provided
if "markets" in config_file:
print("Create custom markets.")
for market in config_file["markets"]:
# Check if there are regions we should not
# create a market for
if "except regions" in market:
regions = [
r for r in self.regions if r not in market["except regions"]
]
else:
regions = self.regions
# Loop through regions
for region in regions:
# Create market dictionary
new_market = self.get_market_dictionary_structure(
market, region
)
new_excs = []
# Loop through the technologies that should compose the market
for dataset_to_include in market["includes"]:
# try to see if we find a provider with that region
try:
act = ws.get_one(
self.database,
ws.equals("name", dataset_to_include["name"]),
ws.equals(
"reference product",
dataset_to_include["reference product"],
),
ws.equals("location", region),
)
for a, b in config_file["production pathways"].items():
if (
b["ecoinvent alias"]["name"] == act["name"]
and b["ecoinvent alias"]["reference product"]
== act["reference product"]
):
var = b["production volume"]["variable"]
# supply share = production volume of that technology in this region
# over production volume of all technologies in this region
try:
supply_share = np.clip(
(
self.custom_data[i][
"production volume"
].sel(
region=region,
year=self.year,
variables=var,
)
/ self.custom_data[i]["production volume"]
.sel(region=region, year=self.year)
.sum(dim="variables")
).values.item(0),
0,
1,
)
except KeyError:
continue
if supply_share > 0:
new_excs.append(
{
"name": act["name"],
"product": act["reference product"],
"unit": act["unit"],
"location": act["location"],
"type": "technosphere",
"amount": supply_share,
}
)
# if we do not find a supplier, it can be correct if it was
# listed in `except regions`. In any case, we jump to the next technology.
except ws.NoResults:
continue
if len(new_excs) > 0:
total = 0
for exc in new_excs:
total += exc["amount"]
for exc in new_excs:
exc["amount"] /= total
new_market["exchanges"].extend(new_excs)
self.database.append(new_market)
else:
regions.remove(region)
# if so far, a market for `World` has not been created
# we need to create one then
if "World" not in regions:
world_market = self.fill_in_world_market(market, regions, i)
self.database.append(world_market)
# if the new markets are meant to replace for other
# providers in the database
if "replaces" in market:
self.relink_to_new_datasets(
replaces=market["replaces"],
replaces_in=market.get("replaces in", None),
new_name=market["name"],
new_ref=market["reference product"],
ratio=market.get("replacement ratio", 1),
regions=regions,
)
def relink_to_new_datasets(
self,
replaces: list,
replaces_in: list,
new_name: str,
new_ref: str,
ratio,
regions: list,
) -> None:
"""
Replaces exchanges that match `old_name` and `old_ref` with exchanges that
have `new_name` and `new_ref`. The new exchange is from an IAM region, and so, if the
region is not part of `regions`, we use `World` instead.
:param old_name: `name` of the exchange to replace
:param old_ref: `product` of the exchange to replace
:param new_name: `name`of the new provider
:param new_ref: `product` of the new provider
:param regions: list of IAM regions the new provider can originate from
"""
print("Relink to new markets.")
if replaces_in:
datasets = [
ds
for ds in self.database
if any(
k["name"].lower() in ds["name"].lower()
and k["reference product"].lower()
in ds["reference product"].lower()
for k in replaces_in
)
]
else:
datasets = self.database
for ds in datasets:
for exc in ds["exchanges"]:
if (
any(
k["name"].lower() in exc["name"].lower()
and k["reference product"].lower() in exc.get("product").lower()
for k in replaces
)
and exc["type"] == "technosphere"
):
if ds["location"] in self.regions:
if ds["location"] not in regions:
new_loc = "World"
else:
new_loc = ds["location"]
else:
new_loc = self.ecoinvent_to_iam_loc[ds["location"]]
exc["name"] = new_name
exc["product"] = new_ref
exc["location"] = new_loc
exc["amount"] *= ratio
if "input" in exc:
del exc["input"]
| StarcoderdataPython |
3532458 | <gh_stars>1-10
"""
A circular racetrack has N runners on it, all running at distinct
constant speeds in the same direction. There is only one spot along
the track (say, the starting line) where any runner is allowed to
pass any other runner; if two runners "collide" at any other point
along the circle, then the race is over and everyone stops.
For which N is it possible for N runners to run this way indefinitely?
The original problem asked for N = 10.
This script encodes the problem in the Z3 Theorem Prover.
It only works for up to N = 4, where it successfully finds a set of
possible runners; for a larger number, it thinks for a while, and
eventually says "unknown".
Example solution obtained by Z3 when N = 4:
speed0 = 6,
speed1 = 8,
speed2 = 9,
speed3 = 12
Notes on problem encoding:
We observe that for any two runners at speeds r, s (in laps / hour),
they meet every 1 / |s - r| hours. This means that r / |s - r| (the
distance traveled in laps) must be a positive integer. We can also
drop the absolute value and simply state that there is some integer n
(possibly negative) such that r = (s - r) * n.
This condition, for every pair of speeds, is sufficient to imply the
constraints in the original problem, as long as we additionally state
that all speeds are positive integers (in particular, not zero).
(That they are nonzero rules out n = 0 and also means they must be
distinct, from r = (s - r) * n.)
Proof that there is a solution for all N:
We proceed by induction.
Suppose that there is a solution with runner speeds r_1, r_2, ..., r_N,
and assume WLOG that r_i are all positive integers. Let
R = LCM(r_1, r_2, ..., r_N)
and consider the set of N+1 positive integers
R, R + r_1, R + r_2, ..., R + r_n.
We claim that this set of runner speeds works. First, consider the
pair of speeds (R + r_i) and (R + r_j): their difference is (r_i - r_j).
This divides r_i and r_j by inductive hypothesis, and it divides R
because it divides r_i (since R is the LCM), so it divides (R + r_i)
and (R + r_j). Second, consider the pair of speeds R and (R + r_i).
The difference is r_i, which divides R since it is the LCM,
so it divides R and R + r_i. This completes the inductive step.
Finally, for the base case we take a single runner with speed 1, and
this completes the proof.
"""
import z3
"""
Solve the runner problem for N runners.
"""
def solve_runner_problem(N):
solver = z3.Solver()
# Assign a positive integer speed to each runner.
# This is WLOG since the ratio of any two runners' speeds is rational.
speeds = [z3.Int("speed" + str(i)) for i in range(N)]
for s in speeds:
solver.add(s > 0)
# For any pair of speeds r and s, r / (s - r) is an integer.
for i in range(N):
for j in range(i+1, N):
n_i_j = z3.FreshInt()
solver.add(speeds[i] == (speeds[j] - speeds[i]) * n_i_j)
# Print and then solve the constraints.
print(f"Constraints: {solver.assertions()}")
result = str(solver.check())
print(f"Result: {result}")
if result == 'sat':
print(f"Model: {solver.model()}")
"""
When run from the command line: try with 1, 2, 3, 4, and 5 runners.
"""
for N in range(1, 6):
print(f"========== Number of runners: {N} ==========")
solve_runner_problem(N)
| StarcoderdataPython |
3210119 | from functions import *
##El conjunto a analizar es:
#Conjunto = [2,4,6,9,12,18,27,36,48,60,72]
#Prueba de que no cumple ningun orden
#Conjunto = [0,1,2,3]
#Relación =[(0,0),(0,1),(0,2),(0,3),(1,0),(1,1),(1,2),(1,3),(2,0),(2,2),(3,3)]
#Prueba relacion de equivalencia
#Conjunto =['a','b','c','d']
#Relación =[('a','a'),('a','d'),('d','d'),('d','a'),('b','b'),('b','c'),('c','c'),('c','b')]
#Prueba de Orden parcial
#Conjunto = [2,4,6,9,12,18,27,36,48,60,72]
#Relación = [(2, 2), (4,4), (6,6),(9,9),(12,12), (18,18), (27,27),(36,36), (48,48), (60,60), (72,72), (72,2)]
#tambien es de orden parcial
# Relación = [(2,2),(2,4),(2,6),(2,12),(2,18),(2,36),(2,48),(2,60),(2,72),(4,4),(4,12),(4,36),(4,48),
# (4,60),(4,72),(6,6),(6,12),(6,18),(6,36),(6,48),(6,60),(6,72),(9,9),(9,18),(9,36),(9,72),(12,12),(12,36),
# (12,48),(12,60),(12,72),(18,18),(18,36),(18,72),(27,27),(36,36),(36,72),(48,48),(60,60),(72,72)]
Conjunto = [1,2,3,4,6,12]
Relación = [(1,1),(2,2),(3,3),(4,4),(6,6),(12,12),(1,2),(1,3),(1,4),(1,6),(1,12),(2,3),(2,4),(2,6),(2,12)
,(3,4),(3,6),(3,12),(4,6),(4,12),(6,12)]
comprobar_relaciones(Relación,Conjunto)
## Se imprimen los resultados si la relación es de orden o de equivalencia
## Si la relación es de equivalencia se obtendra las cotas de los elementos AB
#elementosAB = [2,3]
orden_o_equivalencia(Conjunto,Relación)
| StarcoderdataPython |
11204367 | #!/usr/bin/env python
# This example demonstrates the use of 2D text the old way by using a
# vtkTextMapper and a vtkScaledTextActor.
import vtk
# Create a sphere source, mapper, and actor
sphere = vtk.vtkSphereSource()
sphereMapper = vtk.vtkPolyDataMapper()
sphereMapper.SetInputConnection(sphere.GetOutputPort())
sphereActor = vtk.vtkLODActor()
sphereActor.SetMapper(sphereMapper)
# Create a text mapper.
textMapper = vtk.vtkTextMapper()
textMapper.SetInput("This is a sphere")
# Set the text, font, justification, and text properties (bold,
# italics, etc.).
tprop = textMapper.GetTextProperty()
tprop.SetFontSize(18)
tprop.SetFontFamilyToArial()
tprop.SetJustificationToCentered()
tprop.BoldOn()
tprop.ItalicOn()
tprop.ShadowOn()
tprop.SetColor(0, 0, 1)
# Create a scaled text actor. Set the position of the text.
textActor = vtk.vtkScaledTextActor()
textActor.SetMapper(textMapper)
textActor.SetDisplayPosition(90, 50)
# Create the Renderer, RenderWindow, RenderWindowInteractor
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Add the actors to the renderer; set the background and size; zoom
# in; and render.
ren.AddActor2D(textActor)
ren.AddActor(sphereActor)
ren.SetBackground(1, 1, 1)
renWin.SetSize(250, 125)
ren.ResetCamera()
ren.GetActiveCamera().Zoom(1.5)
iren.Initialize()
renWin.Render()
iren.Start()
| StarcoderdataPython |
6697978 | <gh_stars>1-10
import os.path
import gzip
from itertools import izip
folder = 'noEvolve3/'
treatment_postfixes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30, 40, 60, 80, 100]
slrs = [15]
partners = ["Host", "Sym"]
reps = range(10,21)
#reps = range(1001, 1021)
final_update = 3
header = "uid smoi slr rep update host_count sym_count sym_val host_val burst_size uninfected\n"
outputFileName = folder+"munged_peak_moi.dat"
outFile = open(outputFileName, 'w')
outFile.write(header)
for t in treatment_postfixes:
for s in slrs:
for r in reps:
max_so_far = float("-inf")
host_fname = folder +"HostValsSM"+str(t)+"_Seed" + str(r)+"_SLR"+str(s) + ".data"
sym_fname = folder +"SymValsSM" + str(t) + "_Seed" + str(r)+"_SLR"+str(s) + ".data"
lysis_fname = folder +"LysisSM" + str(t) + "_Seed" + str(r) +"_SLR"+str(s) + ".data"
uid = str(t) + "_" + str(r)
host_file = open(host_fname, 'r')
sym_file = open(sym_fname, 'r')
lysis_file = open(lysis_fname, 'r')
with open(host_fname) as host_file, open(sym_fname) as sym_file:
for host_line, sym_line, lysis_line in izip(host_file, sym_file, lysis_file):
if (host_line[0] != "u"):
splitline = host_line.split(',')
symline = sym_line.split(',')
lysisline = lysis_line.split(',')
if (float(splitline[2])>0 and (float(symline[2])/float(splitline[2])) > max_so_far):
max_so_far = (float(symline[2])/float(splitline[2]))
max_line = "{} {} {} {} {} {} {} {} {} {} {}\n".format(uid, t, s, r, splitline[0], splitline[2], symline[2], symline[1], splitline[1], lysisline[1].strip(), splitline[3])
outFile.write(max_line)
host_file.close()
sym_file.close()
lysis_file.close()
outFile.close()
| StarcoderdataPython |
9614180 | """
Clean the data
"""
from paths import *
import os
import emoji
import string
from datetime import datetime
import re
import nltk
from pickle import dump
from multiprocessing import Pool
import random
from my_random import SEED
def clean_a_line(line, eng_words, remove_non_eng_words=False):
"""
Clean a single line.
:param line: The line to clean.
:type line: str.
:param eng_words: A list-like or generator of all the English words.
:param remove_non_eng_words: flag for removing non-english words (True for removing, False otherwise).
:return: The line after cleaning.
"""
def remove_non_eng(text):
return " ".join(w for w in nltk.wordpunct_tokenize(text) if w.lower() in eng_words or not w.isalpha())
def remove_emojis(text):
return emoji.get_emoji_regexp().sub(r'', text)
line = re.sub(r'\(?http\S+\)?', '', remove_emojis(line))
if remove_non_eng_words:
line = remove_non_eng(line)
line = line.strip()
if all([ch in string.punctuation for ch in list(line)]):
line = ''
return line.replace('[removed]', '').replace('[deleted]', '')
def clean_data(params):
"""
Clean the data in the input files, and save in the given output directory.
:param params: Input parameters: input directory path, input filenames (not complete path), output directory, list of English words
:type params: tuple.
:return: None
"""
input_dir, input_files, output_dir, eng_words = params
for filename in input_files:
if filename.endswith('.txt'):
print(filename)
with open(input_dir / filename, mode='r', encoding='utf-8') as fr:
with open(output_dir / filename, mode='w', encoding='utf-8') as fw:
for line in fr.readlines():
clean_line = clean_a_line(line, eng_words)
if clean_line:
fw.write(f'{clean_line}\n')
def sentecize_data(input_dir, output_dir, shuffle=False):
"""
Break text files into sentences and save them to the given output directory.
:param input_dir: Input directory.
:param output_dir: Output directory.
:param shuffle: Whether to shuffle the sentences before saving or not.
:return: None
"""
sentence_ptrn = r"(?<=[A-Za-z][A-Za-z])[.?\n!]+|(?<=[0-9)\}\]])[.?\n!]+"
for i, filename in enumerate(os.listdir(input_dir)):
sentences = []
if filename.endswith('.txt'):
print(f'{i + 1}. {filename}')
with open(input_dir / filename, mode='r', encoding='utf-8') as fr:
for line in fr.readlines():
for sentence in re.split(sentence_ptrn, line):
stripped_sentence = sentence.strip()
if len(stripped_sentence) > 2:
sentences.append(stripped_sentence)
with open(output_dir / filename, mode='w', encoding='utf-8') as fw:
if shuffle:
random.seed(SEED)
random.shuffle(sentences)
for sentence in sentences:
fw.write(f'{sentence}\n')
def tokenize_data(input_dir, output_dir):
"""
Break the sentences in the input files to tokens, and save them to the given output directory.
:param input_dir: Input directory.
:param output_dir: Output directory.
:return: None
"""
for i, filename in enumerate(os.listdir(input_dir)):
if filename.endswith('.txt'):
print(f'{i + 1}. {filename}')
with open(input_dir / filename, mode='r', encoding='utf-8') as fr:
with open(output_dir / filename, mode='w', encoding='utf-8') as fw:
for sentence in fr.readlines():
fw.write(f"{' '.join(nltk.word_tokenize(sentence))}\n")
def posify_data(params):
"""
Convert (tag) tokenized data to POS (part of speach) and save to the given output dir.
"""
input_dir, input_files, output_dir = params
for filename in input_files:
if filename.endswith('.txt'):
print(filename)
with open(output_dir / filename, mode='w', encoding='utf-8') as fw:
fw.writelines('\n'.join([' '.join([pair[1] for pair in nltk.pos_tag(line.split())])
for line in open(input_dir / filename, mode='r', encoding='utf-8').readlines()]))
def chunkify_data(input_dir, output_dir, minimum_tokens_in_sentence=3, chunk_size=2000):
"""
Make chunks of given size.
:param input_dir: Input direcctory of data to chunkify.
:param output_dir: Output directory for saving.
:param minimum_tokens_in_sentence: Minimum tokens in each sentence.
:param chunk_size: Approximate size of each chunk (in number words). Approximate because a sentence won't be cut in
the middle.
:return: None
"""
for i, filename in enumerate(os.listdir(input_dir)):
if filename.endswith('.txt'):
print(f'{i + 1}. {filename}')
country_chunks_lst = [[]] # list of country chunks. each inner list is a chunk of size chunk_size.
current_chunk_size = 0
with open(input_dir / filename, mode='r', encoding='utf-8') as fr:
with open(output_dir / filename.replace('.txt', PKL_LST_EXT), mode='wb') as fw:
lines = fr.readlines()
random.Random(SEED).shuffle(lines)
for tokens_line in lines:
tokens_line_split = tokens_line.split()
if len(tokens_line_split) >= minimum_tokens_in_sentence:
if current_chunk_size >= chunk_size:
country_chunks_lst.append([])
current_chunk_size = 0
country_chunks_lst[-1].append(tokens_line)
current_chunk_size += len(tokens_line_split)
dump(country_chunks_lst, fw, -1)
if __name__ == '__main__':
# ESTIMATED TOTAL TIME: 27 MINUTES
CLEAN = True
SENTECIZE, SHUFFLE = True, True
TOKENIZE = True
CHUNKIFY_TOKENS = True
POSIFY = True
CHUNKIFY_POS = True
estimated_time = round(CLEAN * 7 + SENTECIZE * 0.5 + TOKENIZE * 3 + CHUNKIFY_TOKENS * 0.5 + POSIFY * 11 + CHUNKIFY_POS * 0.5)
ts = datetime.now()
print(ts)
print(f'Estimated time: {estimated_time} minutes')
input_dir = RAW_DATA_DIR
clean_output_dir = CLEAN_DATA_DIR
sentences_output_dir = SENTENCES_DIR
tokens_output_dir = TOKENS_DIR
tokens_chunks_output_dir = TOKEN_CHUNKS_DIR
pos_chunks_output_dir = POS_CHUNKS_DIR
pos_output_dir = POS_DIR
"""
Perform the enabled steps.
Use parallelism to speed things up.
"""
if CLEAN:
# EST: 5 minutes
words = set(nltk.corpus.words.words())
print('Cleaning...')
clean_output_dir.mkdir(exist_ok=True)
raw_files = [f for f in os.listdir(input_dir) if f.endswith('.txt')]
print(f'{len(raw_files)} files...')
pools = 6 # run multiple cores in parallel.
pool = Pool(pools)
file_groups = [(input_dir_, lst_of_files, output_dir, words) for input_dir_, output_dir, lst_of_files in
zip([input_dir] * pools,
[clean_output_dir] * pools,
[raw_files[i: i+(len(raw_files)//(pools-1))]
for i in range(0, len(raw_files), len(raw_files)//(pools-1))])]
assert len(file_groups) <= pools
pool.map(clean_data, file_groups)
print(f'{datetime.now()}\n')
if SENTECIZE:
# Quick
print('Sentecizing...')
sentences_output_dir.mkdir(exist_ok=True)
sentecize_data(clean_output_dir, sentences_output_dir, shuffle=SHUFFLE)
print(f'{datetime.now()}\n')
if TOKENIZE:
# 3 minutes
print('Tokenizing...')
tokens_output_dir.mkdir(exist_ok=True)
tokenize_data(sentences_output_dir, tokens_output_dir)
print(f'{datetime.now()}\n')
if CHUNKIFY_TOKENS:
# Quick
print('Chunkifying tokens...')
tokens_chunks_output_dir.mkdir(exist_ok=True)
chunkify_data(tokens_output_dir, tokens_chunks_output_dir)
print(f'{datetime.now()}\n')
if POSIFY:
# Very slow => On 6 cores it takes 11 minutes.
print('Posifying ', end='')
pos_output_dir.mkdir(exist_ok=True)
tokenized_files = [f for f in os.listdir(tokens_output_dir) if f.endswith('.txt')]
print(f'{len(tokenized_files)} files...')
pools = 6 # run multiple cores in parallel.
pool = Pool(pools)
file_groups = [(input_dir_, lst_of_files, output_dir) for input_dir_, output_dir, lst_of_files in
zip([tokens_output_dir] * pools,
[pos_output_dir] * pools,
[tokenized_files[i: i+(len(tokenized_files)//(pools-1))]
for i in range(0, len(tokenized_files), len(tokenized_files)//(pools-1))])]
assert len(file_groups) <= pools
pool.map(posify_data, file_groups)
print(f'{datetime.now()}\n')
if CHUNKIFY_POS:
# Quick
print('Chunkifying POS...')
pos_chunks_output_dir.mkdir(exist_ok=True)
chunkify_data(pos_output_dir, pos_chunks_output_dir)
print(f'{datetime.now()}\n')
print('')
print(datetime.now() - ts)
| StarcoderdataPython |
9651317 | # encoding: utf-8
"""
Tests of the "software" module
"""
from datetime import date
import json
from fairgraph.software import Software, OperatingSystem, SoftwareCategory, ProgrammingLanguage, License
from fairgraph.core import Person, Organization
from fairgraph.commons import License
try:
import pyxus
have_pyxus = True
except ImportError:
have_pyxus = False
import pytest
class MockInstance(object):
def __init__(self, data):
self.data = data
@pytest.mark.skipif(not have_pyxus, reason="pyxus not available")
class TestSoftware(object):
def test__build_data(self):
input_data = dict(
name="PyNN v0.9.4",
version="0.9.4",
summary="A Python package for simulator-independent specification of neuronal network models",
description="PyNN (pronounced 'pine') is a simulator-independent language for building neuronal network models.",
#identifier=Identifier("RRID:SCR_002715"),
citation=("<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME> (2009) "
"PyNN: a common interface for neuronal network simulators. "
"Front. Neuroinform. 2:11 doi:10.3389/neuro.11.011.2008"),
license=License("CeCILL v2"),
release_date=date(2019, 3, 22),
previous_version=None,
contributors=[Person("Davison", "Andrew", "<EMAIL>")],
project=None,
image="https://neuralensemble.org/static/photos/pynn_logo.png",
download_url="https://files.pythonhosted.org/packages/a2/1c/78b5d476900254c2c638a29a343ea12985ea16b12c7aed8cec252215c848/PyNN-0.9.4.tar.gz",
access_url="https://pypi.org/project/PyNN/0.9.4/",
categories=None,
subcategories=None,
operating_system=[OperatingSystem("Linux"), OperatingSystem("MacOS"), OperatingSystem("Windows")],
release_notes="http://neuralensemble.org/docs/PyNN/releases/0.9.4.html",
requirements="neo, lazyarray",
copyright=Organization("The PyNN community"),
components=None,
part_of=None,
funding=[Organization("CNRS"), Organization("Human Brain Project")],
languages=ProgrammingLanguage("Python"),
features=None,
#keywords="simulation, neuroscience",
is_free=True,
homepage="https://neuralensemble.org/PyNN/",
documentation="http://neuralensemble.org/docs/PyNN/",
help="https://groups.google.com/forum/#!forum/neuralensemble"
)
software_release = Software(**input_data)
kg_data = software_release._build_data(client=None)
assert kg_data == {
'name': input_data["name"],
'version': input_data["version"],
'headline': input_data["summary"],
'description': input_data["description"],
'citation': input_data["citation"],
'license': {'@id': input_data["license"].iri, 'label': input_data["license"].label},
'dateCreated': '2019-03-22',
#'copyrightYear': input_data["release_date"].year,
'author': {'@id': None, '@type': ['nsg:Person', 'prov:Agent']},
#'image': {'@id': input_data["image"]},
#'distribution': {
# 'downloadURL': {"@id": input_data["download_url"]},
# 'accessURL': {"@id": input_data["access_url"]}
#},
'operatingSystem': [
{'@id': os.iri, 'label': os.label}
for os in input_data["operating_system"]
],
'releaseNotes': {'@id': input_data["release_notes"]},
'softwareRequirements': input_data["requirements"],
'copyrightHolder': {'@id': None, '@type': ['nsg:Organization']},
'funder': [{'@id': None, '@type': ['nsg:Organization']}, {'@id': None, '@type': ['nsg:Organization']}],
#'programmingLanguage': [{'@id': input_data["languages"].iri, 'label': input_data["languages"].label}],
#'keywords': input_data["keywords"],
'isAccessibleForFree': input_data["is_free"],
'url': {'@id': input_data["homepage"]},
'documentation': {'@id': input_data["documentation"]},
'softwareHelp': {'@id': input_data["help"]}
}
def test_from_instance(self):
instance_data = json.loads("""{
"@context": [
"https://nexus-int.humanbrainproject.org/v0/contexts/neurosciencegraph/core/data/v0.1.0",
{
"dbpedia": "http://dbpedia.org/resource/",
"wd": "http://www.wikidata.org/entity/",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"label": "rdfs:label",
"schema": "http://schema.org/",
"hbpsc": "https://schema.hbp.eu/softwarecatalog/"
},
"https://nexus-int.humanbrainproject.org/v0/contexts/nexus/core/resource/v0.3.0"
],
"@id": "https://nexus-int.humanbrainproject.org/v0/data/softwarecatalog/software/software/v0.1.1/beb9546e-c801-4159-ab3f-5678a5f75f33",
"@type": [
"hbpsc:Software",
"nsg:Entity"
],
"providerId": "doi:10.5281/zenodo.1400175",
"applicationCategory": [
{
"@id": "https://www.wikidata.org/wiki/Q166142",
"label": "application"
}
],
"applicationSubCategory": [
{
"@id": "https://www.wikidata.org/wiki/Q184148",
"label": "plug-in"
}
],
"citation": "<NAME> et al. (2018). NEST 2.16.0. Zenodo. 10.5281/zenodo.1400175",
"code": {
"@id": "https://github.com/nest/nest-simulator"
},
"copyrightYear": 2018,
"dateCreated": "2018-08-21",
"description": "NEST is a highly scalable simulator for networks of point or few-compartment spiking neuron models. It includes multiple synaptic plasticity models, gap junctions, and the capacity to define complex network structure.",
"device": [
{
"@id": "https://www.wikidata.org/wiki/Q5082128",
"label": "mobile device"
}
],
"documentation": {
"@id": "http://www.nest-simulator.org/documentation/"
},
"encodingFormat": [
{
"@id": "https://www.wikidata.org/wiki/Q28865",
"label": "Python"
}
],
"headline": "NEST is a highly scalable simulator for networks of point or few-compartment spiking neuron models. It includes multiple synaptic plasticity models, gap junctions, and the capacity to define complex network structure.",
"identifier": [
{
"propertyID": "doi",
"value": "10.5281/zenodo.1400175"
},
{
"@id": "https://doi.org/10.5281/zenodo.1400175"
}
],
"image": {
"@id": "http://www.nest-simulator.org/wp-content/uploads/nest-simulated-www-320.png"
},
"isAccessibleForFree": true,
"programmingLanguage": [
{
"@id": "https://www.wikidata.org/wiki/Q28865",
"label": "Python"
}
],
"license": {
"@id": "https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html",
"label": "GNU General Public License 2 or later (http://www.nest-simulator.org/license/)"
},
"name": "NEST v2.16.0",
"operatingSystem": [
{
"@id": "http://dbpedia.org/resource/Linux",
"label": "Linux"
}
],
"releaseNotes": {
"@id": "https://github.com/nest/nest-simulator/releases/tag/v2.16.0"
},
"screenshot": {
"@id": "http://www.nest-simulator.org/wp-content/uploads/nest-simulated-www-320.png"
},
"softwareHelp": {
"@id": "http://www.nest-simulator.org/community/"
},
"softwareRequirements": "libreadline, gsl, ...",
"url": {
"@id": "http://www.nest-simulator.org/"
},
"version": "2.16.0"
}
""")
instance = MockInstance(instance_data)
software_release = Software.from_kg_instance(instance, client=None, use_cache=False)
assert software_release.name == instance_data["name"]
assert software_release.operating_system == OperatingSystem("Linux")
| StarcoderdataPython |
95179 | <filename>lenstronomywrapper/Sampler/launch_script.py
from lenstronomywrapper.Sampler.run import run
import sys
import os
from time import time
#job_index = int(sys.argv[1])
job_index = 1
# the name of the folder containing paramdictionary files
chain_ID = 'B1422'
# where to generate output files
#out_path = '/scratch/abenson/'
out_path = os.getenv('HOME') + '/data/sims/'
# wherever you put the launch folder containing the
# paramdictionary files
#paramdictionary_folder_path = '/scratch/abenson/'
paramdictionary_folder_path = os.getenv('HOME') + '/data/'
print(job_index)
t0 = time()
# launch and forget
test_mode = True
run(job_index, chain_ID, out_path,
paramdictionary_folder_path, test_mode=test_mode)
tend = time()
print('time ellapsed: ', tend - t0)
| StarcoderdataPython |
394577 | <gh_stars>10-100
#!/usr/bin/env python
array = [
{
'fips': '01',
'abbr': 'AL',
'name': 'Alabama',
},
{
'fips': '02',
'abbr': 'AK',
'name': 'Alaska',
},
{
'fips': '04',
'abbr': 'AZ',
'name': 'Arizona',
},
{
'fips': '05',
'abbr': 'AR',
'name': 'Arkansas',
},
{
'fips': '06',
'abbr': 'CA',
'name': 'California',
},
{
'fips': '08',
'abbr': 'CO',
'name': 'Colorado',
},
{
'fips': '09',
'abbr': 'CT',
'name': 'Connecticut',
'votesby': 'town',
},
{
'fips': '10',
'abbr': 'DE',
'name': 'Delaware',
},
{
'fips': '11',
'abbr': 'DC',
'name': 'District of Columbia',
},
{
'fips': '12',
'abbr': 'FL',
'name': 'Florida',
},
{
'fips': '13',
'abbr': 'GA',
'name': 'Georgia',
},
{
'fips': '15',
'abbr': 'HI',
'name': 'Hawaii',
},
{
'fips': '16',
'abbr': 'ID',
'name': 'Idaho',
},
{
'fips': '17',
'abbr': 'IL',
'name': 'Illinois',
},
{
'fips': '18',
'abbr': 'IN',
'name': 'Indiana',
},
{
'fips': '19',
'abbr': 'IA',
'name': 'Iowa',
},
{
'fips': '20',
'abbr': 'KS',
'name': 'Kansas',
'votesby': 'district',
},
{
'fips': '21',
'abbr': 'KY',
'name': 'Kentucky',
},
{
'fips': '22',
'abbr': 'LA',
'name': 'Louisiana',
},
{
'fips': '23',
'abbr': 'ME',
'name': 'Maine',
},
{
'fips': '24',
'abbr': 'MD',
'name': 'Maryland',
},
{
'fips': '25',
'abbr': 'MA',
'name': 'Massachusetts',
'votesby': 'town',
},
{
'fips': '26',
'abbr': 'MI',
'name': 'Michigan',
},
{
'fips': '27',
'abbr': 'MN',
'name': 'Minnesota',
},
{
'fips': '28',
'abbr': 'MS',
'name': 'Mississippi',
},
{
'fips': '29',
'abbr': 'MO',
'name': 'Missouri',
},
{
'fips': '30',
'abbr': 'MT',
'name': 'Montana',
},
{
'fips': '31',
'abbr': 'NE',
'name': 'Nebraska',
},
{
'fips': '32',
'abbr': 'NV',
'name': 'Nevada',
},
{
'fips': '33',
'abbr': 'NH',
'name': 'New Hampshire',
'votesby': 'town',
},
{
'fips': '34',
'abbr': 'NJ',
'name': 'New Jersey',
},
{
'fips': '35',
'abbr': 'NM',
'name': 'New Mexico',
},
{
'fips': '36',
'abbr': 'NY',
'name': 'New York',
},
{
'fips': '37',
'abbr': 'NC',
'name': 'North Carolina',
},
{
'fips': '38',
'abbr': 'ND',
'name': 'North Dakota',
},
{
'fips': '39',
'abbr': 'OH',
'name': 'Ohio',
},
{
'fips': '40',
'abbr': 'OK',
'name': 'Oklahoma',
},
{
'fips': '41',
'abbr': 'OR',
'name': 'Oregon',
},
{
'fips': '42',
'abbr': 'PA',
'name': 'Pennsylvania',
},
{
'fips': '44',
'abbr': 'RI',
'name': 'Rhode Island',
},
{
'fips': '45',
'abbr': 'SC',
'name': 'South Carolina',
},
{
'fips': '46',
'abbr': 'SD',
'name': 'South Dakota',
},
{
'fips': '47',
'abbr': 'TN',
'name': 'Tennessee',
},
{
'fips': '48',
'abbr': 'TX',
'name': 'Texas',
},
{
'fips': '49',
'abbr': 'UT',
'name': 'Utah',
},
{
'fips': '50',
'abbr': 'VT',
'name': 'Vermont',
'votesby': 'town',
},
{
'fips': '51',
'abbr': 'VA',
'name': 'Virginia',
},
{
'fips': '53',
'abbr': 'WA',
'name': 'Washington',
},
{
'fips': '54',
'abbr': 'WV',
'name': 'West Virginia',
},
{
'fips': '55',
'abbr': 'WI',
'name': 'Wisconsin',
},
{
'fips': '56',
'abbr': 'WY',
'name': 'Wyoming',
},
{
'fips': '72',
'abbr': 'PR',
'name': '<NAME>',
},
]
byAbbr = {}
for state in array:
byAbbr[ state['abbr'] ] = state
byName = {}
for state in array:
byName[ state['name'] ] = state
| StarcoderdataPython |
4854629 | import os
from torch.utils.data import Dataset
from PIL import Image
class SuperviselyPersonDataset(Dataset):
def __init__(self, imgdir, segdir, transform=None):
self.img_dir = imgdir
self.img_files = sorted(os.listdir(imgdir))
self.seg_dir = segdir
self.seg_files = sorted(os.listdir(segdir))
assert len(self.img_files) == len(self.seg_files)
self.transform = transform
def __len__(self):
return len(self.img_files)
def __getitem__(self, idx):
with Image.open(
os.path.join(self.img_dir, self.img_files[idx])
) as img, Image.open(os.path.join(self.seg_dir, self.seg_files[idx])) as seg:
img = img.convert("RGB")
seg = seg.convert("L")
if self.transform is not None:
img, seg = self.transform(img, seg)
return img, seg
| StarcoderdataPython |
8053988 | import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
import sys
from torch.autograd import Variable
import math
def flip(x, dim):
xsize = x.size()
dim = x.dim() + dim if dim < 0 else dim
x = x.contiguous()
x = x.view(-1, *xsize[dim:])
x = x.view(x.size(0), x.size(1), -1)[
:,
getattr(
torch.arange(x.size(1) - 1, -1, -1), ("cpu", "cuda")[x.is_cuda]
)().long(),
:,
]
return x.view(xsize)
def sinc(band, t_right):
y_right = torch.sin(2 * math.pi * band * t_right) / (2 * math.pi * band * t_right)
y_left = flip(y_right, 0)
y = torch.cat([y_left, Variable(torch.ones(1)).cuda(), y_right])
return y
class SincConv_fast(nn.Module):
"""Sinc-based convolution
Parameters
----------
in_channels : `int`
Number of input channels. Must be 1.
out_channels : `int`
Number of filters.
kernel_size : `int`
Filter length.
sample_rate : `int`, optional
Sample rate. Defaults to 16000.
Usage
-----
See `torch.nn.Conv1d`
Reference
---------
<NAME>, <NAME>,
"Speaker Recognition from raw waveform with SincNet".
https://arxiv.org/abs/1808.00158
"""
@staticmethod
def to_mel(hz):
return 2595 * np.log10(1 + hz / 700)
@staticmethod
def to_hz(mel):
return 700 * (10 ** (mel / 2595) - 1)
def __init__(
self,
out_channels,
kernel_size,
sample_rate=16000,
in_channels=1,
stride=1,
padding=0,
dilation=1,
bias=False,
groups=1,
min_low_hz=50,
min_band_hz=50,
):
super(SincConv_fast, self).__init__()
if in_channels != 1:
# msg = (f'SincConv only support one input channel '
# f'(here, in_channels = {in_channels:d}).')
msg = (
"SincConv only support one input channel (here, in_channels = {%i})"
% (in_channels)
)
raise ValueError(msg)
self.out_channels = out_channels
self.kernel_size = kernel_size
# Forcing the filters to be odd (i.e, perfectly symmetrics)
if kernel_size % 2 == 0:
self.kernel_size = self.kernel_size + 1
self.stride = stride
self.padding = padding
self.dilation = dilation
if bias:
raise ValueError("SincConv does not support bias.")
if groups > 1:
raise ValueError("SincConv does not support groups.")
self.sample_rate = sample_rate
self.min_low_hz = min_low_hz
self.min_band_hz = min_band_hz
# initialize filterbanks such that they are equally spaced in Mel scale
low_hz = 30
high_hz = self.sample_rate / 2 - (self.min_low_hz + self.min_band_hz)
mel = np.linspace(
self.to_mel(low_hz), self.to_mel(high_hz), self.out_channels + 1
)
hz = self.to_hz(mel)
# filter lower frequency (out_channels, 1)
self.low_hz_ = nn.Parameter(torch.Tensor(hz[:-1]).view(-1, 1))
# filter frequency band (out_channels, 1)
self.band_hz_ = nn.Parameter(torch.Tensor(np.diff(hz)).view(-1, 1))
# Hamming window
# self.window_ = torch.hamming_window(self.kernel_size)
n_lin = torch.linspace(
0, (self.kernel_size / 2) - 1, steps=int((self.kernel_size / 2))
) # computing only half of the window
self.window_ = 0.54 - 0.46 * torch.cos(2 * math.pi * n_lin / self.kernel_size)
# (1, kernel_size/2)
n = (self.kernel_size - 1) / 2.0
self.n_ = (
2 * math.pi * torch.arange(-n, 0).view(1, -1) / self.sample_rate
) # Due to symmetry, I only need half of the time axes
def forward(self, waveforms):
"""
Parameters
----------
waveforms : `torch.Tensor` (batch_size, 1, n_samples)
Batch of waveforms.
Returns
-------
features : `torch.Tensor` (batch_size, out_channels, n_samples_out)
Batch of sinc filters activations.
"""
self.n_ = self.n_.to(waveforms.device)
self.window_ = self.window_.to(waveforms.device)
low = self.min_low_hz + torch.abs(self.low_hz_)
high = torch.clamp(
low + self.min_band_hz + torch.abs(self.band_hz_),
self.min_low_hz,
self.sample_rate / 2,
)
band = (high - low)[:, 0]
f_times_t_low = torch.matmul(low, self.n_)
f_times_t_high = torch.matmul(high, self.n_)
band_pass_left = (
(torch.sin(f_times_t_high) - torch.sin(f_times_t_low)) / (self.n_ / 2)
) * self.window_ # Equivalent of Eq.4 of the reference paper (SPEAKER RECOGNITION FROM RAW WAVEFORM WITH SINCNET). I just have expanded the sinc and simplified the terms. This way I avoid several useless computations.
band_pass_center = 2 * band.view(-1, 1)
band_pass_right = torch.flip(band_pass_left, dims=[1])
band_pass = torch.cat(
[band_pass_left, band_pass_center, band_pass_right], dim=1
)
band_pass = band_pass / (2 * band[:, None])
self.filters = (band_pass).view(self.out_channels, 1, self.kernel_size)
return F.conv1d(
waveforms,
self.filters,
stride=self.stride,
padding=self.padding,
dilation=self.dilation,
bias=None,
groups=1,
)
class sinc_conv(nn.Module):
def __init__(self, N_filt, Filt_dim, fs):
super(sinc_conv, self).__init__()
# Mel Initialization of the filterbanks
low_freq_mel = 80
high_freq_mel = 2595 * np.log10(1 + (fs / 2) / 700) # Convert Hz to Mel
mel_points = np.linspace(
low_freq_mel, high_freq_mel, N_filt
) # Equally spaced in Mel scale
f_cos = 700 * (10 ** (mel_points / 2595) - 1) # Convert Mel to Hz
b1 = np.roll(f_cos, 1)
b2 = np.roll(f_cos, -1)
b1[0] = 30
b2[-1] = (fs / 2) - 100
self.freq_scale = fs * 1.0
self.filt_b1 = nn.Parameter(torch.from_numpy(b1 / self.freq_scale))
self.filt_band = nn.Parameter(torch.from_numpy((b2 - b1) / self.freq_scale))
self.N_filt = N_filt
self.Filt_dim = Filt_dim
self.fs = fs
def forward(self, x):
filters = Variable(torch.zeros((self.N_filt, self.Filt_dim))).cuda()
N = self.Filt_dim
t_right = Variable(
torch.linspace(1, (N - 1) / 2, steps=int((N - 1) / 2)) / self.fs
).cuda()
min_freq = 50.0
min_band = 50.0
filt_beg_freq = torch.abs(self.filt_b1) + min_freq / self.freq_scale
filt_end_freq = filt_beg_freq + (
torch.abs(self.filt_band) + min_band / self.freq_scale
)
n = torch.linspace(0, N, steps=N)
# Filter window (hamming)
window = 0.54 - 0.46 * torch.cos(2 * math.pi * n / N)
window = Variable(window.float().cuda())
for i in range(self.N_filt):
low_pass1 = (
2
* filt_beg_freq[i].float()
* sinc(filt_beg_freq[i].float() * self.freq_scale, t_right)
)
low_pass2 = (
2
* filt_end_freq[i].float()
* sinc(filt_end_freq[i].float() * self.freq_scale, t_right)
)
band_pass = low_pass2 - low_pass1
band_pass = band_pass / torch.max(band_pass)
filters[i, :] = band_pass.cuda() * window
out = F.conv1d(x, filters.view(self.N_filt, 1, self.Filt_dim))
return out
def act_fun(act_type):
if act_type == "relu":
return nn.ReLU()
if act_type == "tanh":
return nn.Tanh()
if act_type == "sigmoid":
return nn.Sigmoid()
if act_type == "leaky_relu":
return nn.LeakyReLU(0.2)
if act_type == "elu":
return nn.ELU()
if act_type == "softmax":
return nn.LogSoftmax(dim=1)
if act_type == "linear":
return nn.LeakyReLU(1) # initializzed like this, but not used in forward!
class LayerNorm(nn.Module):
def __init__(self, features, eps=1e-6):
super(LayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(features))
self.beta = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.gamma * (x - mean) / (std + self.eps) + self.beta
class MLP(nn.Module):
def __init__(self, options):
super(MLP, self).__init__()
self.input_dim = int(options["input_dim"])
self.fc_lay = options["fc_lay"]
self.fc_drop = options["fc_drop"]
self.fc_use_batchnorm = options["fc_use_batchnorm"]
self.fc_use_laynorm = options["fc_use_laynorm"]
self.fc_use_laynorm_inp = options["fc_use_laynorm_inp"]
self.fc_use_batchnorm_inp = options["fc_use_batchnorm_inp"]
self.fc_act = options["fc_act"]
self.wx = nn.ModuleList([])
self.bn = nn.ModuleList([])
self.ln = nn.ModuleList([])
self.act = nn.ModuleList([])
self.drop = nn.ModuleList([])
# input layer normalization
if self.fc_use_laynorm_inp:
self.ln0 = LayerNorm(self.input_dim)
# input batch normalization
if self.fc_use_batchnorm_inp:
self.bn0 = nn.BatchNorm1d([self.input_dim], momentum=0.05)
self.N_fc_lay = len(self.fc_lay)
current_input = self.input_dim
# Initialization of hidden layers
for i in range(self.N_fc_lay):
# dropout
self.drop.append(nn.Dropout(p=self.fc_drop[i]))
# activation
self.act.append(act_fun(self.fc_act[i]))
add_bias = True
# layer norm initialization
self.ln.append(LayerNorm(self.fc_lay[i]))
self.bn.append(nn.BatchNorm1d(self.fc_lay[i], momentum=0.05))
if self.fc_use_laynorm[i] or self.fc_use_batchnorm[i]:
add_bias = False
# Linear operations
self.wx.append(nn.Linear(current_input, self.fc_lay[i], bias=add_bias))
# weight initialization
self.wx[i].weight = torch.nn.Parameter(
torch.Tensor(self.fc_lay[i], current_input).uniform_(
-np.sqrt(0.01 / (current_input + self.fc_lay[i])),
np.sqrt(0.01 / (current_input + self.fc_lay[i])),
)
)
self.wx[i].bias = torch.nn.Parameter(torch.zeros(self.fc_lay[i]))
current_input = self.fc_lay[i]
def forward(self, x):
# Applying Layer/Batch Norm
if bool(self.fc_use_laynorm_inp):
x = self.ln0((x))
if bool(self.fc_use_batchnorm_inp):
x = self.bn0((x))
for i in range(self.N_fc_lay):
if self.fc_act[i] != "linear":
if self.fc_use_laynorm[i]:
x = self.drop[i](self.act[i](self.ln[i](self.wx[i](x))))
if self.fc_use_batchnorm[i]:
x = self.drop[i](self.act[i](self.bn[i](self.wx[i](x))))
if (
self.fc_use_batchnorm[i] == False
and self.fc_use_laynorm[i] == False
):
x = self.drop[i](self.act[i](self.wx[i](x)))
else:
if self.fc_use_laynorm[i]:
x = self.drop[i](self.ln[i](self.wx[i](x)))
if self.fc_use_batchnorm[i]:
x = self.drop[i](self.bn[i](self.wx[i](x)))
if (
self.fc_use_batchnorm[i] == False
and self.fc_use_laynorm[i] == False
):
x = self.drop[i](self.wx[i](x))
return x
class SincNet(nn.Module):
def __init__(
self,
cnn_N_filt,
cnn_len_filt,
cnn_max_pool_len,
cnn_act,
cnn_drop,
cnn_use_laynorm,
cnn_use_batchnorm,
cnn_use_laynorm_inp,
cnn_use_batchnorm_inp,
input_dim,
fs,
):
super(SincNet, self).__init__()
self.cnn_N_filt = cnn_N_filt
self.cnn_len_filt = cnn_len_filt
self.cnn_max_pool_len = cnn_max_pool_len
self.cnn_act = cnn_act
self.cnn_drop = cnn_drop
self.cnn_use_laynorm = cnn_use_laynorm
self.cnn_use_batchnorm = cnn_use_batchnorm
self.cnn_use_laynorm_inp = cnn_use_laynorm_inp
self.cnn_use_batchnorm_inp = cnn_use_batchnorm_inp
self.input_dim = int(input_dim)
self.fs = fs
self.N_cnn_lay = len(self.cnn_N_filt)
self.conv = nn.ModuleList([])
self.bn = nn.ModuleList([])
self.ln = nn.ModuleList([])
self.act = nn.ModuleList([])
self.drop = nn.ModuleList([])
if self.cnn_use_laynorm_inp:
self.ln0 = LayerNorm(self.input_dim)
if self.cnn_use_batchnorm_inp:
self.bn0 = nn.BatchNorm1d([self.input_dim], momentum=0.05)
current_input = self.input_dim
for i in range(self.N_cnn_lay):
N_filt = int(self.cnn_N_filt[i])
len_filt = int(self.cnn_len_filt[i])
# dropout
self.drop.append(nn.Dropout(p=self.cnn_drop[i]))
# activation
self.act.append(act_fun(self.cnn_act[i]))
# layer norm initialization
self.ln.append(
LayerNorm(
[
N_filt,
int(
(current_input - self.cnn_len_filt[i] + 1)
/ self.cnn_max_pool_len[i]
),
]
)
)
self.bn.append(
nn.BatchNorm1d(
N_filt,
int(
(current_input - self.cnn_len_filt[i] + 1)
/ self.cnn_max_pool_len[i]
),
momentum=0.05,
)
)
if i == 0:
self.conv.append(
SincConv_fast(self.cnn_N_filt[0], self.cnn_len_filt[0], self.fs)
)
else:
self.conv.append(
nn.Conv1d(
self.cnn_N_filt[i - 1], self.cnn_N_filt[i], self.cnn_len_filt[i]
)
)
current_input = int(
(current_input - self.cnn_len_filt[i] + 1) / self.cnn_max_pool_len[i]
)
self.out_dim = current_input * N_filt
def forward(self, x):
batch = x.shape[0]
seq_len = x.shape[1]
if bool(self.cnn_use_laynorm_inp):
x = self.ln0((x))
if bool(self.cnn_use_batchnorm_inp):
x = self.bn0((x))
x = x.view(batch, 1, seq_len)
for i in range(self.N_cnn_lay):
if self.cnn_use_laynorm[i]:
if i == 0:
x = self.drop[i](
self.act[i](
self.ln[i](
F.max_pool1d(
torch.abs(self.conv[i](x)), self.cnn_max_pool_len[i]
)
)
)
)
else:
x = self.drop[i](
self.act[i](
self.ln[i](
F.max_pool1d(self.conv[i](x), self.cnn_max_pool_len[i])
)
)
)
if self.cnn_use_batchnorm[i]:
x = self.drop[i](
self.act[i](
self.bn[i](
F.max_pool1d(self.conv[i](x), self.cnn_max_pool_len[i])
)
)
)
if self.cnn_use_batchnorm[i] == False and self.cnn_use_laynorm[i] == False:
x = self.drop[i](
self.act[i](F.max_pool1d(self.conv[i](x), self.cnn_max_pool_len[i]))
)
x = x.view(batch, -1)
return x
| StarcoderdataPython |
3598801 | <filename>util/tFunctions.py
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from collections import Counter
from typing import List
from azure.quantum.optimization import Term
def tOrder ( terms0 : Term ) -> int :
if len ( terms0.ids ) == 0 :
return ( 0 )
return ( Counter ( terms0.ids ).most_common ( 1 )[ 0 ][ 1 ] )
def tGreaterThan ( term0 : Term , term1 : Term ) -> bool :
if tOrder ( term0 ) > tOrder ( term1 ) :
return ( True )
return ( False )
def tSimplify ( terms0 : List [ Term ] ) -> List [ Term ] :
terms = []
for term in terms0 :
combined = False
inserted = False
term.ids.sort()
for t in terms :
if t.ids == term.ids :
t.c += term.c
combined = True
break
if not combined :
for i in range ( len ( terms ) ) :
if tGreaterThan ( term , terms [ i ] ) :
terms.insert ( i , term )
inserted = True
break
if not inserted :
terms.append ( term )
ret = []
for t in terms :
if t.c != 0 :
ret.append ( t )
return ( ret )
def tAdd ( terms0 : List [ Term ] , terms1 : List [ Term ] ) -> List [ Term ] :
return tSimplify ( terms0 + terms1 )
def tSubtract ( terms0 : List [ Term ] , terms1 : List [ Term ] ) -> List [ Term ] :
terms = []
for term0 in terms0 :
terms.append( Term ( c = term0.c , indices = term0.ids ) )
for term1 in terms1 :
terms.append ( Term ( c = -1 * term1.c , indices = term1.ids ) )
return tSimplify ( terms )
def tMultiply ( terms0 : List [ Term ] , terms1 : List [ Term ] ) -> List [ Term ] :
terms = []
for term0 in terms0 :
for term1 in terms1 :
terms.append ( Term ( c = term0.c * term1.c , indices = term0.ids + term1.ids ) )
return tSimplify ( terms )
def tSquare ( terms0 : List [ Term ] ) -> List [ Term ] :
return ( tMultiply ( terms0 , terms0 ) )
| StarcoderdataPython |
3406536 | <reponame>egor5q/zombiedef
# -*- coding: utf-8 -*-
import os
import telebot
import time
import telebot
import random
import info
import threading
from emoji import emojize
from telebot import types
from pymongo import MongoClient
token = os.environ['TELEGRAM_TOKEN']
bot = telebot.TeleBot(token)
client=MongoClient(os.environ['database'])
db=client.survivals
users=db.users
symbollist=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я', ' ']
@bot.message_handler()
def allmessages(m):
start=0
if users.find_one({'id':m.from_user.id})==None:
users.insert_one(createuser(m.from_user.id,m.from_user.first_name,m.from_user.username))
start=1
user=users.find_one({'id':m.from_user.id})
if start==1:
bot.send_message(m.chat.id, 'Здраствуй, выживший! Назови своё имя.')
users.update_one({'id':user['id']},{'$push':{'effects':'setname'}})
else:
if 'setname' in user['effects']:
no=0
for ids in m.text:
if ids not in symbollist:
no=1
if no==0:
users.update_one({'id':user['id']},{'$set':{'heroname':m.text}})
bot.send_message(m.chat.id, 'Добро пожаловать в отряд, '+m.text+'! Чтобы противостоять армиям зомби, тебе '+
'понадобится оружие. На, держи!')
bot.send_message(m.chat.id, 'Получено: *пистолет*')
users.update_one({'id':user['id']},{'$push':{'inventory':'pistol'}})
time.sleep(2)
bot.send_message(m.chat.id, 'Со всей нашей командой ты можешь познакомиться здесь: @неизветно. Ладно, хватит '+
'слов - зомби наступают! Пошли, будешь помогать обороняться.')#@Survivalschat. ')
t=threading.Timer(2,defcamp,args=[user])
t.start()
def defcamp(user):
pass
def createuser(id,name,username):
return {'id':{
'name':name,
'heroname':None,
'id':id,
'username':username,
'effects':[],
'inventory':[]
}
if True:
print('7777')
bot.polling(none_stop=True,timeout=600)
| StarcoderdataPython |
1774171 | <gh_stars>1-10
from gym.envs.registration import register
register(
id='Drawenv-v0',
entry_point='draw_gym.draw_env:DrawEnv',
max_episode_steps=10,
reward_threshold=0.0,
) | StarcoderdataPython |
3410060 | <reponame>WitnessNR/Updated_WiNR
from numba import njit
import numpy as np
import matplotlib.pyplot as plt
from solve import *
# from tensorflow.contrib.keras.api.keras.models import Sequential
# from tensorflow.contrib.keras.api.keras.layers import Dense, Dropout, Activation, Flatten, GlobalAveragePooling2D, Lambda
# from tensorflow.contrib.keras.api.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, InputLayer, BatchNormalization, Reshape
# from tensorflow.contrib.keras.api.keras.models import load_model
# from tensorflow.contrib.keras.api.keras import backend as K
# from tensorflow.contrib.keras.api.keras.datasets import mnist, cifar10
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, GlobalAveragePooling2D, Lambda
from tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, InputLayer, BatchNormalization, Reshape
from tensorflow.keras.models import load_model
from tensorflow.keras.datasets import mnist, cifar10
import tensorflow as tf
from utils import generate_data_myself
import time
from activations import sigmoid_linear_bounds
from pgd_attack import *
linear_bounds = None
import random
def fn(correct, predicted):
return tf.nn.softmax_cross_entropy_with_logits(labels=correct,
logits=predicted)
class CNNModel:
def __init__(self, model, inp_shape = (28,28,1)):
print('-----------', inp_shape, '---------')
temp_weights = [layer.get_weights() for layer in model.layers]
self.weights = []
self.biases = []
self.shapes = []
self.pads = []
self.strides = []
self.model = model
cur_shape = inp_shape
self.shapes.append(cur_shape)
for layer in model.layers:
print(cur_shape)
weights = layer.get_weights()
if type(layer) == Conv2D:
print('conv')
if len(weights) == 1:
W = weights[0].astype(np.float32)
b = np.zeros(W.shape[-1], dtype=np.float32)
else:
W, b = weights
W = W.astype(np.float32)
b = b.astype(np.float32)
padding = layer.get_config()['padding']
stride = layer.get_config()['strides']
pad = (0,0,0,0) #p_hl, p_hr, p_wl, p_wr
if padding == 'same':
desired_h = int(np.ceil(cur_shape[0]/stride[0]))
desired_w = int(np.ceil(cur_shape[0]/stride[1]))
total_padding_h = stride[0]*(desired_h-1)+W.shape[0]-cur_shape[0]
total_padding_w = stride[1]*(desired_w-1)+W.shape[1]-cur_shape[1]
pad = (int(np.floor(total_padding_h/2)),int(np.ceil(total_padding_h/2)),int(np.floor(total_padding_w/2)),int(np.ceil(total_padding_w/2)))
cur_shape = (int((cur_shape[0]+pad[0]+pad[1]-W.shape[0])/stride[0])+1, int((cur_shape[1]+pad[2]+pad[3]-W.shape[1])/stride[1])+1, W.shape[-1])
self.strides.append(stride)
self.pads.append(pad)
self.shapes.append(cur_shape)
self.weights.append(W)
self.biases.append(b)
elif type(layer) == GlobalAveragePooling2D:
print('global avg pool')
b = np.zeros(cur_shape[-1], dtype=np.float32)
W = np.zeros((cur_shape[0],cur_shape[1],cur_shape[2],cur_shape[2]), dtype=np.float32)
for f in range(W.shape[2]):
W[:,:,f,f] = 1/(cur_shape[0]*cur_shape[1])
pad = (0,0,0,0)
stride = ((1,1))
cur_shape = (1,1,cur_shape[2])
self.strides.append(stride)
self.pads.append(pad)
self.shapes.append(cur_shape)
self.weights.append(W)
self.biases.append(b)
elif type(layer) == AveragePooling2D:
print('avg pool')
b = np.zeros(cur_shape[-1], dtype=np.float32)
pool_size = layer.get_config()['pool_size']
stride = layer.get_config()['strides']
W = np.zeros((pool_size[0],pool_size[1],cur_shape[2],cur_shape[2]), dtype=np.float32)
for f in range(W.shape[2]):
W[:,:,f,f] = 1/(pool_size[0]*pool_size[1])
pad = (0,0,0,0) #p_hl, p_hr, p_wl, p_wr
if padding == 'same':
desired_h = int(np.ceil(cur_shape[0]/stride[0]))
desired_w = int(np.ceil(cur_shape[0]/stride[1]))
total_padding_h = stride[0]*(desired_h-1)+pool_size[0]-cur_shape[0]
total_padding_w = stride[1]*(desired_w-1)+pool_size[1]-cur_shape[1]
pad = (int(np.floor(total_padding_h/2)),int(np.ceil(total_padding_h/2)),int(np.floor(total_padding_w/2)),int(np.ceil(total_padding_w/2)))
cur_shape = (int((cur_shape[0]+pad[0]+pad[1]-pool_size[0])/stride[0])+1, int((cur_shape[1]+pad[2]+pad[3]-pool_size[1])/stride[1])+1, cur_shape[2])
self.strides.append(stride)
self.pads.append(pad)
self.shapes.append(cur_shape)
self.weights.append(W)
self.biases.append(b)
elif type(layer) == Activation:
print('activation')
elif type(layer) == Lambda:
print('lambda')
elif type(layer) == InputLayer:
print('input')
elif type(layer) == BatchNormalization:
print('batch normalization')
gamma, beta, mean, std = weights
std = np.sqrt(std+0.001) #Avoids zero division
a = gamma/std
b = -gamma*mean/std+beta
self.weights[-1] = a*self.weights[-1]
self.biases[-1] = a*self.biases[-1]+b
elif type(layer) == Dense:
print('FC')
W, b = weights
b = b.astype(np.float32)
W = W.reshape(list(cur_shape)+[W.shape[-1]]).astype(np.float32)
cur_shape = (1,1,W.shape[-1])
self.strides.append((1,1))
self.pads.append((0,0,0,0))
self.shapes.append(cur_shape)
self.weights.append(W)
self.biases.append(b)
elif type(layer) == Dropout:
print('dropout')
elif type(layer) == MaxPooling2D:
print('pool')
pool_size = layer.get_config()['pool_size']
stride = layer.get_config()['strides']
pad = (0,0,0,0) #p_hl, p_hr, p_wl, p_wr
if padding == 'same':
desired_h = int(np.ceil(cur_shape[0]/stride[0]))
desired_w = int(np.ceil(cur_shape[0]/stride[1]))
total_padding_h = stride[0]*(desired_h-1)+pool_size[0]-cur_shape[0]
total_padding_w = stride[1]*(desired_w-1)+pool_size[1]-cur_shape[1]
pad = (int(np.floor(total_padding_h/2)),int(np.ceil(total_padding_h/2)),int(np.floor(total_padding_w/2)),int(np.ceil(total_padding_w/2)))
cur_shape = (int((cur_shape[0]+pad[0]+pad[1]-pool_size[0])/stride[0])+1, int((cur_shape[1]+pad[2]+pad[3]-pool_size[1])/stride[1])+1, cur_shape[2])
self.strides.append(stride)
self.pads.append(pad)
self.shapes.append(cur_shape)
self.weights.append(np.full(pool_size+(1,1),np.nan,dtype=np.float32))
self.biases.append(np.full(1,np.nan,dtype=np.float32))
elif type(layer) == Flatten:
print('flatten')
elif type(layer) == Reshape:
print('reshape')
else:
print(str(type(layer)))
raise ValueError('Invalid Layer Type')
print(cur_shape)
for i in range(len(self.weights)):
self.weights[i] = np.ascontiguousarray(self.weights[i].transpose((3,0,1,2)).astype(np.float32))
self.biases[i] = np.ascontiguousarray(self.biases[i].astype(np.float32))
def predict(self, data):
return self.model(data)
@njit
def conv(W, x, pad, stride):
p_hl, p_hr, p_wl, p_wr = pad
s_h, s_w = stride
y = np.zeros((int((x.shape[0]-W.shape[1]+p_hl+p_hr)/s_h)+1, int((x.shape[1]-W.shape[2]+p_wl+p_wr)/s_w)+1, W.shape[0]), dtype=np.float32)
for a in range(y.shape[0]):
for b in range(y.shape[1]):
for c in range(y.shape[2]):
for i in range(W.shape[1]):
for j in range(W.shape[2]):
for k in range(W.shape[3]):
if 0<=s_h*a+i-p_hl<x.shape[0] and 0<=s_w*b+j-p_wl<x.shape[1]:
y[a,b,c] += W[c,i,j,k]*x[s_h*a+i-p_hl,s_w*b+j-p_wl,k]
return y
@njit
def pool(pool_size, x0, pad, stride):
p_hl, p_hr, p_wl, p_wr = pad
s_h, s_w = stride
y0 = np.zeros((int((x0.shape[0]+p_hl+p_hr-pool_size[0])/s_h)+1, int((x0.shape[1]+p_wl+p_wr-pool_size[1])/s_w)+1, x0.shape[2]), dtype=np.float32)
for x in range(y0.shape[0]):
for y in range(y0.shape[1]):
for r in range(y0.shape[2]):
cropped = LB[s_h*x-p_hl:pool_size[0]+s_h*x-p_hl, s_w*y-p_wl:pool_size[1]+s_w*y-p_wl,r]
y0[x,y,r] = cropped.max()
return y0
@njit
def conv_bound(W, b, pad, stride, x0, eps, p_n):
y0 = conv(W, x0, pad, stride)
UB = np.zeros(y0.shape, dtype=np.float32)
LB = np.zeros(y0.shape, dtype=np.float32)
for k in range(W.shape[0]):
if p_n == 105: # p == "i", q = 1
dualnorm = np.sum(np.abs(W[k,:,:,:]))
elif p_n == 1: # p = 1, q = i
dualnorm = np.max(np.abs(W[k,:,:,:]))
elif p_n == 2: # p = 2, q = 2
dualnorm = np.sqrt(np.sum(W[k,:,:,:]**2))
mid = y0[:,:,k]+b[k]
UB[:,:,k] = mid+eps*dualnorm
LB[:,:,k] = mid-eps*dualnorm
return LB, UB
@njit
def conv_full(A, x, pad, stride):
p_hl, p_hr, p_wl, p_wr = pad
s_h, s_w = stride
y = np.zeros((A.shape[0], A.shape[1], A.shape[2]), dtype=np.float32)
for a in range(y.shape[0]):
for b in range(y.shape[1]):
for c in range(y.shape[2]):
for i in range(A.shape[3]):
for j in range(A.shape[4]):
for k in range(A.shape[5]):
if 0<=s_h*a+i-p_hl<x.shape[0] and 0<=s_w*b+j-p_wl<x.shape[1]:
y[a,b,c] += A[a,b,c,i,j,k]*x[s_h*a+i-p_hl,s_w*b+j-p_wl,k]
return y
@njit
def conv_bound_full(A, B, pad, stride, x0, eps, p_n):
y0 = conv_full(A, x0, pad, stride)
UB = np.zeros(y0.shape, dtype=np.float32)
LB = np.zeros(y0.shape, dtype=np.float32)
for a in range(y0.shape[0]):
for b in range(y0.shape[1]):
for c in range(y0.shape[2]):
if p_n == 105: # p == "i", q = 1
dualnorm = np.sum(np.abs(A[a,b,c,:,:,:]))
elif p_n == 1: # p = 1, q = i
dualnorm = np.max(np.abs(A[a,b,c,:,:,:]))
elif p_n == 2: # p = 2, q = 2
dualnorm = np.sqrt(np.sum(A[a,b,c,:,:,:]**2))
mid = y0[a,b,c]+B[a,b,c]
UB[a,b,c] = mid+eps*dualnorm
LB[a,b,c] = mid-eps*dualnorm
return LB, UB
@njit
def upper_bound_conv(A, B, pad, stride, W, b, inner_pad, inner_stride, inner_shape, LB, UB):
A_new = np.zeros((A.shape[0], A.shape[1], A.shape[2], inner_stride[0]*(A.shape[3]-1)+W.shape[1], inner_stride[1]*(A.shape[4]-1)+W.shape[2], W.shape[3]), dtype=np.float32)
B_new = np.zeros(B.shape, dtype=np.float32)
A_plus = np.maximum(A, 0)
A_minus = np.minimum(A, 0)
alpha_u, alpha_l, beta_u, beta_l = linear_bounds(LB, UB)
assert A.shape[5] == W.shape[0]
for x in range(A_new.shape[0]):
for y in range(A_new.shape[1]):
for t in range(A_new.shape[3]):
for u in range(A_new.shape[4]):
if 0<=t+stride[0]*inner_stride[0]*x-inner_stride[0]*pad[0]-inner_pad[0]<inner_shape[0] and 0<=u+stride[1]*inner_stride[1]*y-inner_stride[1]*pad[2]-inner_pad[2]<inner_shape[1]:
for p in range(A.shape[3]):
for q in range(A.shape[4]):
if 0<=t-inner_stride[0]*p<W.shape[1] and 0<=u-inner_stride[1]*q<W.shape[2] and 0<=p+stride[0]*x-pad[0]<alpha_u.shape[0] and 0<=q+stride[1]*y-pad[2]<alpha_u.shape[1]:
for z in range(A_new.shape[2]):
for v in range(A_new.shape[5]):
for r in range(W.shape[0]):
A_new[x,y,z,t,u,v] += W[r,t-inner_stride[0]*p,u-inner_stride[1]*q,v]*alpha_u[p+stride[0]*x-pad[0],q+stride[1]*y-pad[2],r]*A_plus[x,y,z,p,q,r]
A_new[x,y,z,t,u,v] += W[r,t-inner_stride[0]*p,u-inner_stride[1]*q,v]*alpha_l[p+stride[0]*x-pad[0],q+stride[1]*y-pad[2],r]*A_minus[x,y,z,p,q,r]
B_new = conv_full(A_plus,alpha_u*b+beta_u,pad,stride) + conv_full(A_minus,alpha_l*b+beta_l,pad,stride)+B
return A_new, B_new
@njit
def lower_bound_conv(A, B, pad, stride, W, b, inner_pad, inner_stride, inner_shape, LB, UB):
A_new = np.zeros((A.shape[0], A.shape[1], A.shape[2], inner_stride[0]*(A.shape[3]-1)+W.shape[1], inner_stride[1]*(A.shape[4]-1)+W.shape[2], W.shape[3]), dtype=np.float32)
B_new = np.zeros(B.shape, dtype=np.float32)
A_plus = np.maximum(A, 0)
A_minus = np.minimum(A, 0)
alpha_u, alpha_l, beta_u, beta_l = linear_bounds(LB, UB)
assert A.shape[5] == W.shape[0]
for x in range(A_new.shape[0]):
for y in range(A_new.shape[1]):
for t in range(A_new.shape[3]):
for u in range(A_new.shape[4]):
if 0<=t+stride[0]*inner_stride[0]*x-inner_stride[0]*pad[0]-inner_pad[0]<inner_shape[0] and 0<=u+stride[1]*inner_stride[1]*y-inner_stride[1]*pad[2]-inner_pad[2]<inner_shape[1]:
for p in range(A.shape[3]):
for q in range(A.shape[4]):
if 0<=t-inner_stride[0]*p<W.shape[1] and 0<=u-inner_stride[1]*q<W.shape[2] and 0<=p+stride[0]*x-pad[0]<alpha_u.shape[0] and 0<=q+stride[1]*y-pad[2]<alpha_u.shape[1]:
for z in range(A_new.shape[2]):
for v in range(A_new.shape[5]):
for r in range(W.shape[0]):
A_new[x,y,z,t,u,v] += W[r,t-inner_stride[0]*p,u-inner_stride[1]*q,v]*alpha_l[p+stride[0]*x-pad[0],q+stride[1]*y-pad[2],r]*A_plus[x,y,z,p,q,r]
A_new[x,y,z,t,u,v] += W[r,t-inner_stride[0]*p,u-inner_stride[1]*q,v]*alpha_u[p+stride[0]*x-pad[0],q+stride[1]*y-pad[2],r]*A_minus[x,y,z,p,q,r]
B_new = conv_full(A_plus,alpha_l*b+beta_l,pad,stride) + conv_full(A_minus,alpha_u*b+beta_u,pad,stride)+B
return A_new, B_new
@njit
def pool_linear_bounds(LB, UB, pad, stride, pool_size):
p_hl, p_hr, p_wl, p_wr = pad
s_h, s_w = stride
alpha_u = np.zeros((pool_size[0], pool_size[1], int((UB.shape[0]+p_hl+p_hr-pool_size[0])/s_h)+1, int((UB.shape[1]+p_wl+p_wr-pool_size[1])/s_w)+1, UB.shape[2]), dtype=np.float32)
beta_u = np.zeros((int((UB.shape[0]+p_hl+p_hr-pool_size[0])/s_h)+1, int((UB.shape[1]+p_wl+p_wr-pool_size[1])/s_w)+1, UB.shape[2]), dtype=np.float32)
alpha_l = np.zeros((pool_size[0], pool_size[1], int((LB.shape[0]+p_hl+p_hr-pool_size[0])/s_h)+1, int((LB.shape[1]+p_wl+p_wr-pool_size[1])/s_w)+1, LB.shape[2]), dtype=np.float32)
beta_l = np.zeros((int((LB.shape[0]+p_hl+p_hr-pool_size[0])/s_h)+1, int((LB.shape[1]+p_wl+p_wr-pool_size[1])/s_w)+1, LB.shape[2]), dtype=np.float32)
for x in range(alpha_u.shape[2]):
for y in range(alpha_u.shape[3]):
for r in range(alpha_u.shape[4]):
cropped_LB = LB[s_h*x-p_hl:pool_size[0]+s_h*x-p_hl, s_w*y-p_wl:pool_size[1]+s_w*y-p_wl,r]
cropped_UB = UB[s_h*x-p_hl:pool_size[0]+s_h*x-p_hl, s_w*y-p_wl:pool_size[1]+s_w*y-p_wl,r]
max_LB = cropped_LB.max()
idx = np.where(cropped_UB>=max_LB)
u_s = np.zeros(len(idx[0]), dtype=np.float32)
l_s = np.zeros(len(idx[0]), dtype=np.float32)
gamma = np.inf
for i in range(len(idx[0])):
l_s[i] = cropped_LB[idx[0][i],idx[1][i]]
u_s[i] = cropped_UB[idx[0][i],idx[1][i]]
if l_s[i] == u_s[i]:
gamma = l_s[i]
if gamma == np.inf:
gamma = (np.sum(u_s/(u_s-l_s))-1)/np.sum(1/(u_s-l_s))
if gamma < np.max(l_s):
gamma = np.max(l_s)
elif gamma > np.min(u_s):
gamma = np.min(u_s)
weights = ((u_s-gamma)/(u_s-l_s)).astype(np.float32)
else:
weights = np.zeros(len(idx[0]), dtype=np.float32)
w_partial_sum = 0
num_equal = 0
for i in range(len(idx[0])):
if l_s[i] != u_s[i]:
weights[i] = (u_s[i]-gamma)/(u_s[i]-l_s[i])
w_partial_sum += weights[i]
else:
num_equal += 1
gap = (1-w_partial_sum)/num_equal
if gap < 0.0:
gap = 0.0
elif gap > 1.0:
gap = 1.0
for i in range(len(idx[0])):
if l_s[i] == u_s[i]:
weights[i] = gap
for i in range(len(idx[0])):
t = idx[0][i]
u = idx[1][i]
alpha_u[t,u,x,y,r] = weights[i]
alpha_l[t,u,x,y,r] = weights[i]
beta_u[x,y,r] = gamma-np.dot(weights, l_s)
growth_rate = np.sum(weights)
if growth_rate <= 1:
beta_l[x,y,r] = np.min(l_s)*(1-growth_rate)
else:
beta_l[x,y,r] = np.max(u_s)*(1-growth_rate)
return alpha_u, alpha_l, beta_u, beta_l
@njit
def upper_bound_pool(A, B, pad, stride, pool_size, inner_pad, inner_stride, inner_shape, LB, UB):
A_new = np.zeros((A.shape[0], A.shape[1], A.shape[2], inner_stride[0]*(A.shape[3]-1)+pool_size[0], inner_stride[1]*(A.shape[4]-1)+pool_size[1], A.shape[5]), dtype=np.float32)
B_new = np.zeros(B.shape, dtype=np.float32)
A_plus = np.maximum(A, 0)
A_minus = np.minimum(A, 0)
alpha_u, alpha_l, beta_u, beta_l = pool_linear_bounds(LB, UB, inner_pad, inner_stride, pool_size)
for x in range(A_new.shape[0]):
for y in range(A_new.shape[1]):
for t in range(A_new.shape[3]):
for u in range(A_new.shape[4]):
inner_index_x = t+stride[0]*inner_stride[0]*x-inner_stride[0]*pad[0]-inner_pad[0]
inner_index_y = u+stride[1]*inner_stride[1]*y-inner_stride[1]*pad[2]-inner_pad[2]
if 0<=inner_index_x<inner_shape[0] and 0<=inner_index_y<inner_shape[1]:
for p in range(A.shape[3]):
for q in range(A.shape[4]):
if 0<=t-inner_stride[0]*p<alpha_u.shape[0] and 0<=u-inner_stride[1]*q<alpha_u.shape[1] and 0<=p+stride[0]*x-pad[0]<alpha_u.shape[2] and 0<=q+stride[1]*y-pad[2]<alpha_u.shape[3]:
A_new[x,y,:,t,u,:] += A_plus[x,y,:,p,q,:]*alpha_u[t-inner_stride[0]*p,u-inner_stride[1]*q,p+stride[0]*x-pad[0],q+stride[1]*y-pad[2],:]
A_new[x,y,:,t,u,:] += A_minus[x,y,:,p,q,:]*alpha_l[t-inner_stride[0]*p,u-inner_stride[1]*q,p+stride[0]*x-pad[0],q+stride[1]*y-pad[2],:]
B_new = conv_full(A_plus,beta_u,pad,stride) + conv_full(A_minus,beta_l,pad,stride)+B
return A_new, B_new
@njit
def lower_bound_pool(A, B, pad, stride, pool_size, inner_pad, inner_stride, inner_shape, LB, UB):
A_new = np.zeros((A.shape[0], A.shape[1], A.shape[2], inner_stride[0]*(A.shape[3]-1)+pool_size[0], inner_stride[1]*(A.shape[4]-1)+pool_size[1], A.shape[5]), dtype=np.float32)
B_new = np.zeros(B.shape, dtype=np.float32)
A_plus = np.maximum(A, 0)
A_minus = np.minimum(A, 0)
alpha_u, alpha_l, beta_u, beta_l = pool_linear_bounds(LB, UB, inner_pad, inner_stride, pool_size)
for x in range(A_new.shape[0]):
for y in range(A_new.shape[1]):
for t in range(A_new.shape[3]):
for u in range(A_new.shape[4]):
inner_index_x = t+stride[0]*inner_stride[0]*x-inner_stride[0]*pad[0]-inner_pad[0]
inner_index_y = u+stride[1]*inner_stride[1]*y-inner_stride[1]*pad[2]-inner_pad[2]
if 0<=inner_index_x<inner_shape[0] and 0<=inner_index_y<inner_shape[1]:
for p in range(A.shape[3]):
for q in range(A.shape[4]):
if 0<=t-inner_stride[0]*p<alpha_u.shape[0] and 0<=u-inner_stride[1]*q<alpha_u.shape[1] and 0<=p+stride[0]*x-pad[0]<alpha_u.shape[2] and 0<=q+stride[1]*y-pad[2]<alpha_u.shape[3]:
A_new[x,y,:,t,u,:] += A_plus[x,y,:,p,q,:]*alpha_l[t-inner_stride[0]*p,u-inner_stride[1]*q,p+stride[0]*x-pad[0],q+stride[1]*y-pad[2],:]
A_new[x,y,:,t,u,:] += A_minus[x,y,:,p,q,:]*alpha_u[t-inner_stride[0]*p,u-inner_stride[1]*q,p+stride[0]*x-pad[0],q+stride[1]*y-pad[2],:]
B_new = conv_full(A_plus,beta_l,pad,stride) + conv_full(A_minus,beta_u,pad,stride)+B
return A_new, B_new
@njit
def compute_bounds(weights, biases, out_shape, nlayer, x0, eps, p_n, strides, pads, LBs, UBs):
pad = (0,0,0,0)
stride = (1,1)
modified_LBs = LBs + (np.ones(out_shape, dtype=np.float32),)
modified_UBs = UBs + (np.ones(out_shape, dtype=np.float32),)
for i in range(nlayer-1, -1, -1):
if not np.isnan(weights[i]).any(): #Conv
if i == nlayer-1:
A_u = weights[i].reshape((1, 1, weights[i].shape[0], weights[i].shape[1], weights[i].shape[2], weights[i].shape[3]))*np.ones((out_shape[0], out_shape[1], weights[i].shape[0], weights[i].shape[1], weights[i].shape[2], weights[i].shape[3]), dtype=np.float32)
B_u = biases[i]*np.ones((out_shape[0], out_shape[1], out_shape[2]), dtype=np.float32)
A_l = A_u.copy()
B_l = B_u.copy()
else:
A_u, B_u = upper_bound_conv(A_u, B_u, pad, stride, weights[i], biases[i], pads[i], strides[i], modified_UBs[i].shape, modified_LBs[i+1], modified_UBs[i+1])
A_l, B_l = lower_bound_conv(A_l, B_l, pad, stride, weights[i], biases[i], pads[i], strides[i], modified_LBs[i].shape, modified_LBs[i+1], modified_UBs[i+1])
else: #Pool
if i == nlayer-1:
A_u = np.eye(out_shape[2]).astype(np.float32).reshape((1,1,out_shape[2],1,1,out_shape[2]))*np.ones((out_shape[0], out_shape[1], out_shape[2], 1,1,out_shape[2]), dtype=np.float32)
B_u = np.zeros(out_shape, dtype=np.float32)
A_l = A_u.copy()
B_l = B_u.copy()
A_u, B_u = upper_bound_pool(A_u, B_u, pad, stride, weights[i].shape[1:], pads[i], strides[i], modified_UBs[i].shape, np.maximum(modified_LBs[i],0), np.maximum(modified_UBs[i],0))
A_l, B_l = lower_bound_pool(A_l, B_l, pad, stride, weights[i].shape[1:], pads[i], strides[i], modified_LBs[i].shape, np.maximum(modified_LBs[i],0), np.maximum(modified_UBs[i],0))
pad = (strides[i][0]*pad[0]+pads[i][0], strides[i][0]*pad[1]+pads[i][1], strides[i][1]*pad[2]+pads[i][2], strides[i][1]*pad[3]+pads[i][3])
stride = (strides[i][0]*stride[0], strides[i][1]*stride[1])
LUB, UUB = conv_bound_full(A_u, B_u, pad, stride, x0, eps, p_n)
LLB, ULB = conv_bound_full(A_l, B_l, pad, stride, x0, eps, p_n)
return LLB, ULB, LUB, UUB, A_u, A_l, B_u, B_l, pad, stride
def find_output_bounds(weights, biases, shapes, pads, strides, x0, eps, p_n):
LB, UB = conv_bound(weights[0], biases[0], pads[0], strides[0], x0, eps, p_n)
LBs = [x0-eps, LB]
UBs = [x0+eps, UB]
for i in range(2,len(weights)+1):
LB, _, _, UB, A_u, A_l, B_u, B_l, pad, stride = compute_bounds(tuple(weights), tuple(biases), shapes[i], i, x0, eps, p_n, tuple(strides), tuple(pads), tuple(LBs), tuple(UBs))
UBs.append(UB)
LBs.append(LB)
return LBs[-1], UBs[-1], A_u, A_l, B_u, B_l, pad, stride
def warmup(model, x, eps_0, p_n, fn):
print('Warming up...')
weights = model.weights[:-1]
biases = model.biases[:-1]
shapes = model.shapes[:-1]
W, b, s = model.weights[-1], model.biases[-1], model.shapes[-1]
last_weight = np.ascontiguousarray((W[0,:,:,:]).reshape([1]+list(W.shape[1:])),dtype=np.float32)
weights.append(last_weight)
biases.append(np.asarray([b[0]]))
shapes.append((1,1,1))
fn(weights, biases, shapes, model.pads, model.strides, x, eps_0, p_n)
ts = time.time()
timestr = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H%M%S')
#Prints to log file
def printlog(s):
print(s, file=open("logs/cnn_bounds_full_core_with_LP"+timestr+".txt", "a"))
def run(file_name, n_samples, eps_0, p_n, q_n, activation = 'sigmoid', cifar=False, fashion_mnist=False, gtsrb=False):
np.random.seed(1215)
#tf.set_random_seed(1215)
random.seed(1215)
keras_model = load_model(file_name, custom_objects={'fn':fn, 'tf':tf})
if cifar:
model = CNNModel(keras_model, inp_shape = (32,32,3))
elif gtsrb:
print('gtsrb')
model = CNNModel(keras_model, inp_shape = (48,48,3))
else:
model = CNNModel(keras_model)
print('--------abstracted model-----------')
global linear_bounds
linear_bounds = sigmoid_linear_bounds
upper_bound_conv.recompile()
lower_bound_conv.recompile()
compute_bounds.recompile()
dataset = ''
if cifar:
dataset = 'cifar10'
inputs, targets, true_labels, true_ids = generate_data_myself('cifar10', model.model, samples=n_samples, start=0)
elif gtsrb:
dataset = 'gtsrb'
inputs, targets, true_labels, true_ids = generate_data_myself('gtsrb', model.model, samples=n_samples, start=0)
elif fashion_mnist:
dataset = 'fashion_mnist'
inputs, targets, true_labels, true_ids = generate_data_myself('fashion_mnist', model.model, samples=n_samples, start=0)
else:
dataset = 'mnist'
inputs, targets, true_labels, true_ids = generate_data_myself('mnist', model.model, samples=n_samples, start=0)
print('----------generated data---------')
#eps_0 = 0.020
printlog('===========================================')
printlog("model name = {}".format(file_name))
printlog("eps = {:.5f}".format(eps_0))
time_limit = 2000
DeepCert_robust_number = 0
PGD_falsified_number = 0
PGD_DeepCert_unknown_number = 0
DeepCert_robust_img_id = []
PGD_time = 0
DeepCert_time = 0
total_images = 0
'''
printlog("----------------PGD+DeepCert----------------")
for i in range(len(inputs)):
total_images += 1
printlog("----------------image id = {}----------------".format(i))
predict_label = np.argmax(true_labels[i])
printlog("image predict label = {}".format(predict_label))
printlog("----------------PGD----------------")
PGD_start_time = time.time()
# generate adversarial example using PGD
PGD_flag = False
predict_label_for_attack = predict_label.astype("float32")
image = tf.constant(inputs[i])
image = tf.expand_dims(image, axis=0)
attack_kwargs = {"eps": eps_0, "alpha": eps_0/1000, "num_iter": 48, "restarts": 48}
attack = PgdRandomRestart(model=keras_model, **attack_kwargs)
attack_inputs = (image, tf.constant(predict_label_for_attack))
adv_example = attack(*attack_inputs, time_limit=20, predict_label=predict_label)
# judge whether the adv_example is true adversarial example
adv_example_label = keras_model.predict(adv_example)
adv_example_label = np.argmax(adv_example_label)
if adv_example_label != predict_label:
original_image = image.numpy()
adv_example = adv_example.numpy()
norm_fn = lambda x: np.max(np.abs(x),axis=(1,2,3))
norm_diff = norm_fn(adv_example-original_image)
printlog("PGD norm_diff(adv_example-original_example) = {}".format(norm_diff))
PGD_flag = True
PGD_falsified_number += 1
#falsified_number += 1
printlog("PGD adv_example_label = {}".format(adv_example_label))
printlog("PGD attack succeed!")
else:
printlog("PGD attack failed!")
PGD_time += (time.time() - PGD_start_time)
if PGD_flag:
continue
printlog('----------------DeepCert----------------')
DeepCert_start_time = time.time()
DeepCert_flag = True
for j in range(i*9,i*9+9):
target_label = targets[j]
printlog("target label = {}".format(target_label))
weights = model.weights[:-1]
biases = model.biases[:-1]
shapes = model.shapes[:-1]
W, b, s = model.weights[-1], model.biases[-1], model.shapes[-1]
last_weight = (W[predict_label,:,:,:]-W[target_label,:,:,:]).reshape([1]+list(W.shape[1:]))
weights.append(last_weight)
biases.append(np.asarray([b[predict_label]-b[target_label]]))
shapes.append((1,1,1))
LB, UB, A_u, A_l, B_u, B_l, pad, stride = find_output_bounds(weights, biases, shapes, model.pads, model.strides, inputs[i].astype(np.float32), eps_0, p_n)
printlog("DeepCert: {:.6s} <= f_c - f_t <= {:.6s}".format(str(np.squeeze(LB)),str(np.squeeze(UB))))
if LB <= 0:
DeepCert_flag = False
break
if DeepCert_flag:
DeepCert_robust_number += 1
DeepCert_robust_img_id.append(i)
printlog("DeepCert: robust")
elif PGD_flag:
pass
else:
PGD_DeepCert_unknown_number += 1
printlog("DeepCert: unknown")
DeepCert_time += (time.time()-DeepCert_start_time)
printlog("PGD - falsified: {}".format(PGD_flag))
printlog("DeepCert - robust: {}, unknown: {}".format((DeepCert_flag and not(PGD_flag)), not(DeepCert_flag)))
if (PGD_time+DeepCert_time)>=time_limit:
printlog("[L1] PGD_DeepCert_total_time = {}, reach time limit!".format(PGD_time+DeepCert_time))
break
PGD_DeepCert_total_time = (PGD_time+DeepCert_time)
PGD_aver_time = PGD_time / total_images
DeepCert_aver_time = DeepCert_time / total_images
PGD_DeepCert_aver_time = PGD_DeepCert_total_time / total_images
printlog("[L0] method = PGD, average runtime = {:.3f}".format(PGD_aver_time))
printlog("[L0] method = DeepCert, average runtime = {:.3f}".format(DeepCert_aver_time))
printlog("[L0] method = PGD+DeepCert, eps = {}, total images = {}, robust = {}, falsified = {}, unknown = {}, average runtime = {:.3f}".format(eps_0, total_images, DeepCert_robust_number, PGD_falsified_number, PGD_DeepCert_unknown_number, PGD_DeepCert_aver_time))
'''
warmup(model, inputs[0].astype(np.float32), eps_0, p_n, find_output_bounds)
printlog("----------------WiNR----------------")
WiNR_start_time = time.time()
WiNR_robust_number = 0
WiNR_falsified_number = 0
WiNR_unknown_number = 0
verified_number = 0
WiNR_robust_img_id = []
WiNR_falsified_img_id = []
total_images = 0
for i in range(len(inputs)):
total_images += 1
printlog("----------------image id = {}----------------".format(i))
predict_label = np.argmax(true_labels[i])
printlog("image predict label = {}".format(predict_label))
adv_false = []
has_adv_false = False
WiNR_robust_flag = True
WiNR_falsified_flag = False
for j in range(i*9,i*9+9):
target_label = targets[j]
printlog("target label = {}".format(target_label))
weights = model.weights[:-1]
biases = model.biases[:-1]
shapes = model.shapes[:-1]
W, b, s = model.weights[-1], model.biases[-1], model.shapes[-1]
last_weight = (W[predict_label,:,:,:]-W[target_label,:,:,:]).reshape([1]+list(W.shape[1:]))
weights.append(last_weight)
biases.append(np.asarray([b[predict_label]-b[target_label]]))
shapes.append((1,1,1))
LB, UB, A_u, A_l, B_u, B_l, pad, stride = find_output_bounds(weights, biases, shapes, model.pads, model.strides, inputs[i].astype(np.float32), eps_0, p_n)
# solving
lp_model = new_model()
lp_model, x = creat_var(lp_model, inputs[i], eps_0)
shape = inputs[i].shape
adv_image, min_val = get_solution_value(lp_model, x, shape, A_u, A_l, B_u, B_l, pad, stride, p_n, eps_0)
printlog("WiNR min_val={:.5f}".format(min_val))
if min_val > 0:
continue
WiNR_robust_flag = False
# label of potential counterexample
a = adv_image[np.newaxis,:,:,:]
aa = a.astype(np.float32)
adv_label = np.argmax(np.squeeze(keras_model.predict(aa)))
if adv_label == predict_label:
adv_false.append((adv_image, target_label))
has_adv_false = True
printlog('this adv_example is false!')
continue
WiNR_diff = (adv_image-inputs[i]).reshape(-1)
WiNR_diff = np.absolute(WiNR_diff)
WiNR_diff = np.max(WiNR_diff)
printlog("WiNR diff(adv_example-original_example) = {}".format(WiNR_diff))
WiNR_falsified_flag = True
break
if WiNR_robust_flag:
WiNR_robust_number += 1
WiNR_robust_img_id.append(i)
printlog("WiNR: robust")
elif WiNR_falsified_flag:
printlog("WiNR: falsified")
WiNR_falsified_number += 1
WiNR_falsified_img_id.append(i)
else:
printlog("WiNR: unknown")
WiNR_unknown_number += 1
printlog("WiNR - robust: {}, falsified: {}, unknown: {}".format(WiNR_robust_flag, WiNR_falsified_flag, (not(WiNR_robust_flag) and not(WiNR_falsified_flag))))
end_time = (time.time()-WiNR_start_time)
verified_number += 1
if end_time >= time_limit:
printlog("verifying time : {} sec, reach time limit {} sec.".format(end_time, time_limit))
break
WiNR_total_time = (time.time()-WiNR_start_time)
printlog("WiNR time: {:.5f}".format(WiNR_total_time))
WiNR_aver_time = WiNR_total_time / total_images
printlog("[L0] method = WiNR, eps = {}, total images = {}, verified number = {}, robust = {}, falsified = {}, unknown = {}, average runtime = {:.3f}".format(eps_0, total_images, verified_number, WiNR_robust_number, WiNR_falsified_number, WiNR_unknown_number, WiNR_aver_time))
printlog("[L0] DeepCert robust images id: {}".format(DeepCert_robust_img_id))
printlog("[L0] WiNR robust images id: {}".format(WiNR_robust_img_id))
'''
printlog("----------------PGD+WiNR----------------")
PGD_before_WiNR_falsified_number = 0
WiNR_after_PGD_robust_number = 0
WiNR_after_PGD_falsified_number = 0
WiNR_after_PGD_unknown_number = 0
PGD_before_WiNR_time = 0
WiNR_after_PGD_time = 0
PGD_before_WiNR_falsified_img_id = []
WiNR_after_PGD_falsified_img_id = []
total_images = 0
for i in range(len(inputs)):
total_images += 1
printlog("----------------image id = {}----------------".format(i))
predict_label = np.argmax(true_labels[i])
printlog("image predict label = {}".format(predict_label))
printlog("----------------PGD(+WiNR)----------------")
PGD_before_WiNR_start_time = time.time()
# generate adversarial example using PGD
PGD_before_WiNR_flag = False
predict_label_for_attack = predict_label.astype("float32")
image = tf.constant(inputs[i])
image = tf.expand_dims(image, axis=0)
attack_kwargs = {"eps": eps_0, "alpha": eps_0/1000, "num_iter": 48, "restarts": 48}
attack = PgdRandomRestart(model=keras_model, **attack_kwargs)
attack_inputs = (image, tf.constant(predict_label_for_attack))
adv_example = attack(*attack_inputs, time_limit=20, predict_label=predict_label)
# judge whether the adv_example is true adversarial example
adv_example_label = keras_model.predict(adv_example)
adv_example_label = np.argmax(adv_example_label)
if adv_example_label != predict_label:
original_image = image.numpy()
adv_example = adv_example.numpy()
norm_fn = lambda x: np.max(np.abs(x),axis=(1,2,3))
norm_diff = norm_fn(adv_example-original_image)
printlog("PGD(+WiNR) norm_diff(adv_example-original_example) = {}".format(norm_diff))
PGD_before_WiNR_flag = True
PGD_before_WiNR_falsified_number += 1
PGD_before_WiNR_falsified_img_id.append(i)
printlog("PGD(+WiNR) adv_example_label = {}".format(adv_example_label))
printlog("PGD(+WiNR) attack succeed!")
else:
printlog("PGD(+WiNR) attack failed!")
PGD_before_WiNR_time += (time.time() - PGD_before_WiNR_start_time)
if PGD_before_WiNR_flag:
continue
printlog('----------------WiNR(+PGD)----------------')
WiNR_after_PGD_start_time = time.time()
adv_false = []
has_adv_false = False
WiNR_after_PGD_robust_flag = True
WiNR_after_PGD_falsified_flag = False
for j in range(i*9,i*9+9):
target_label = targets[j]
printlog("target label = {}".format(target_label))
weights = model.weights[:-1]
biases = model.biases[:-1]
shapes = model.shapes[:-1]
W, b, s = model.weights[-1], model.biases[-1], model.shapes[-1]
last_weight = (W[predict_label,:,:,:]-W[target_label,:,:,:]).reshape([1]+list(W.shape[1:]))
weights.append(last_weight)
biases.append(np.asarray([b[predict_label]-b[target_label]]))
shapes.append((1,1,1))
LB, UB, A_u, A_l, B_u, B_l, pad, stride = find_output_bounds(weights, biases, shapes, model.pads, model.strides, inputs[i].astype(np.float32), eps_0, p_n)
# solving
lp_model = new_model()
lp_model, x = creat_var(lp_model, inputs[i], eps_0)
shape = inputs[i].shape
adv_image, min_val = get_solution_value(lp_model, x, shape, A_u, A_l, B_u, B_l, pad, stride, p_n, eps_0)
printlog("WiNR(+PGD) min_val={:.5f}".format(min_val))
if min_val > 0:
continue
WiNR_after_PGD_robust_flag = False
# label of potential counterexample
a = adv_image[np.newaxis,:,:,:]
aa = a.astype(np.float32)
adv_label = np.argmax(np.squeeze(keras_model.predict(aa)))
if adv_label == predict_label:
adv_false.append((adv_image, target_label))
has_adv_false = True
print('this adv_example is false!')
continue
WiNR_diff = (adv_image-inputs[i]).reshape(-1)
WiNR_diff = np.absolute(WiNR_diff)
WiNR_diff = np.max(WiNR_diff)
printlog("WiNR(+PGD) diff(adv_example-original_example) = {}".format(WiNR_diff))
WiNR_after_PGD_falsified_flag = True
break
if WiNR_after_PGD_robust_flag:
WiNR_after_PGD_robust_number += 1
printlog("WiNR(+PGD): robust")
elif WiNR_after_PGD_falsified_flag:
WiNR_after_PGD_falsified_number += 1
WiNR_after_PGD_falsified_img_id.append(i)
printlog("WiNR(+PGD): falsified")
else:
printlog("WiNR(+PGD): unknown")
WiNR_after_PGD_unknown_number += 1
WiNR_after_PGD_time += (time.time()-WiNR_after_PGD_start_time)
printlog("PGD(+WiNR) - falsified: {}".format(PGD_before_WiNR_flag))
printlog("WiNR(+PGD) - robust: {}, falsified: {}, unknown: {}".format(WiNR_after_PGD_robust_flag, WiNR_after_PGD_falsified_flag, (not(WiNR_after_PGD_robust_flag) and not(WiNR_after_PGD_falsified_flag))))
if (PGD_before_WiNR_time + WiNR_after_PGD_time) >= time_limit:
printlog("PGD + WiNR total time : {} sec, reach time limit!".format(PGD_before_WiNR_time + WiNR_after_PGD_time))
break
PGD_before_WiNR_aver_time = PGD_before_WiNR_time / total_images
WiNR_after_PGD_aver_time = WiNR_after_PGD_time / total_images
PGD_WiNR_total_time = PGD_before_WiNR_time + WiNR_after_PGD_time
PGD_WiNR_total_aver_time = PGD_WiNR_total_time / total_images
printlog("[L0] method = PGD(+WiNR), average runtime = {:.3f}".format(PGD_before_WiNR_aver_time))
printlog("[L0] method = WiNR(+PGD), average runtime = {:.3f}".format(WiNR_after_PGD_aver_time))
printlog("[L0] method = PGD+WiNR, eps = {}, total images = {}, robust = {}, falsified = {}, unknown = {}, average runtime = {:.3f}".format(eps_0, total_images, WiNR_after_PGD_robust_number, (PGD_before_WiNR_falsified_number+WiNR_after_PGD_falsified_number), WiNR_after_PGD_unknown_number, PGD_WiNR_total_aver_time))
printlog("[L0] PGD(+WiNR) falsified images id: {}".format(len(PGD_before_WiNR_falsified_img_id)))
printlog("[L0] WiNR(+PGD) falsified images: {}".format(len(WiNR_after_PGD_falsified_img_id)))
printlog("[L0] WiNR falsified images: {}".format(len(WiNR_falsified_img_id)))
printlog("[L0] PGD(+WiNR) falsified images id: {}".format(PGD_before_WiNR_falsified_img_id))
printlog("[L0] WiNR(+PGD) falsified images id: {}".format(WiNR_after_PGD_falsified_img_id))
printlog("[L0] WiNR falsified images id: {}".format(WiNR_falsified_img_id))
'''
printlog("----------------WiNR+PGD(aimed at false positives)----------------")
WiNR_with_PGD_start_time = time.time()
PGD_falsified_falsepositive_number = 0
WiNR_with_PGD_robust_number = 0
WiNR_with_PGD_falsified_number = 0
WiNR_with_PGD_unknown_number = 0
PGD_falsified_falsepositive_time = 0
PGD_falsified_falsepositive_img_id = []
WiNR_after_PGD_falsified_falsepositive_img_id = []
total_images = 0
for i in range(len(inputs)):
total_images += 1
printlog("----------------image id = {}----------------".format(i))
predict_label = np.argmax(true_labels[i])
printlog("image predict label = {}".format(predict_label))
printlog('----------------WiNR(+PGD[aimed at false positive])----------------')
adv_false = []
has_adv_false = False
WiNR_with_PGD_robust_flag = True
WiNR_with_PGD_falsified_flag = False
for j in range(i*9,i*9+9):
target_label = targets[j]
printlog("target label = {}".format(target_label))
weights = model.weights[:-1]
biases = model.biases[:-1]
shapes = model.shapes[:-1]
W, b, s = model.weights[-1], model.biases[-1], model.shapes[-1]
last_weight = (W[predict_label,:,:,:]-W[target_label,:,:,:]).reshape([1]+list(W.shape[1:]))
weights.append(last_weight)
biases.append(np.asarray([b[predict_label]-b[target_label]]))
shapes.append((1,1,1))
LB, UB, A_u, A_l, B_u, B_l, pad, stride = find_output_bounds(weights, biases, shapes, model.pads, model.strides, inputs[i].astype(np.float32), eps_0, p_n)
# solving
lp_model = new_model()
lp_model, x = creat_var(lp_model, inputs[i], eps_0)
shape = inputs[i].shape
adv_image, min_val = get_solution_value(lp_model, x, shape, A_u, A_l, B_u, B_l, pad, stride, p_n, eps_0)
printlog("WiNR(+PGD[aimed at falsepositive]) min_val={:.5f}".format(min_val))
if min_val > 0:
continue
WiNR_with_PGD_robust_flag = False
# label of potential counterexample
a = adv_image[np.newaxis,:,:,:]
aa = a.astype(np.float32)
adv_label = np.argmax(np.squeeze(keras_model.predict(aa)))
# adv_image is false positive
if adv_label == predict_label:
printlog("----------------PGD(aimed at false positive)----------------")
PGD_falsified_falsepositive_start_time = time.time()
# generate adversarial example using PGD
predict_label_for_attack = predict_label.astype("float32")
original_image = tf.constant(inputs[i])
original_image = tf.expand_dims(original_image, axis=0)
image = adv_image.astype(np.float32)
image = tf.constant(image)
image = tf.expand_dims(image, axis=0)
attack_kwargs = {"eps": eps_0, "alpha": eps_0/2000, "num_iter": 48, "restarts": 48}
attack = PgdRandomRestart(model=keras_model, **attack_kwargs)
attack_inputs = (image, tf.constant(predict_label_for_attack))
adv_example = attack(*attack_inputs, time_limit=20, predict_label=predict_label, false_positive=True, original_images=original_image)
# judge whether the adv_example is true adversarial example
adv_example_label = keras_model.predict(adv_example)
adv_example_label = np.argmax(adv_example_label)
if adv_example_label != predict_label:
original_image = original_image.numpy()
adv_example = adv_example.numpy()
norm_fn = lambda x: np.max(np.abs(x),axis=(1,2,3))
norm_diff = norm_fn(adv_example-original_image)
printlog("PGD(aimed at falsepositive) norm_diff(adv_example-original_example) = {}".format(norm_diff))
PGD_falsified_falsepositive_number += 1
PGD_falsified_falsepositive_img_id.append(i)
printlog("PGD(aimed at falsepositive) adv_example_label = {}".format(adv_example_label))
printlog("PGD(aimed at falsepositive) attack succeed!")
PGD_falsified_falsepositive_time += (time.time() - PGD_falsified_falsepositive_start_time)
WiNR_with_PGD_falsified_flag = True
break
else:
PGD_falsified_falsepositive_time += (time.time() - PGD_falsified_falsepositive_start_time)
printlog("PGD(aimed at falsepositive) attack failed!")
print('this adv_example is false!')
continue
WiNR_diff = (adv_image-inputs[i]).reshape(-1)
WiNR_diff = np.absolute(WiNR_diff)
WiNR_diff = np.max(WiNR_diff)
printlog("WiNR(+PGD[aimed at falsepositive]) diff(adv_example-original_example) = {}".format(WiNR_diff))
WiNR_after_PGD_falsified_falsepositive_img_id.append(i)
WiNR_with_PGD_falsified_flag = True
break
if WiNR_with_PGD_robust_flag:
WiNR_with_PGD_robust_number += 1
printlog("WiNR(+PGD[aimed at falsepositive]): robust")
elif WiNR_with_PGD_falsified_flag:
WiNR_with_PGD_falsified_number += 1
printlog("WiNR(+PGD[aimed at falsepositive]): falsified")
else:
printlog("WiNR(+PGD[aimed at falsepositive]): unknown")
WiNR_with_PGD_unknown_number += 1
end_time = (time.time()-WiNR_with_PGD_start_time)
if end_time >= time_limit:
printlog("WiNR(+PGD[aimed at falsepositive]) total time : {} sec, reach time limit!".format(end_time))
break
WiNR_with_PGD_time = (time.time()-WiNR_with_PGD_start_time)
printlog("WiNR with PGD time: {:.5f}".format(WiNR_with_PGD_time))
WiNR_with_PGD_aver_time = WiNR_with_PGD_time / total_images
printlog("[L0] method = PGD(aimed at falsepositive), total runtime = {}".format(PGD_falsified_falsepositive_time))
printlog("[L0] method = WiNR+PGD(aimed at falsepositive), eps = {}, total images = {}, robust = {}, falsified = {}, unknown = {}, average runtime = {:.3f}".format(eps_0, total_images, WiNR_with_PGD_robust_number, WiNR_with_PGD_falsified_number, WiNR_with_PGD_unknown_number, WiNR_with_PGD_aver_time))
printlog("[L0] PGD[aimed at falsepositive] falsified images id: {}".format(len(PGD_falsified_falsepositive_img_id)))
printlog("[L0] WiNR(+PGD[aimed at falsepositive]) falsified images: {}".format(len(WiNR_after_PGD_falsified_falsepositive_img_id)))
printlog("[L0] WiNR falsified images: {}".format(len(WiNR_falsified_img_id)))
printlog("[L0] PGD[aimed at falsepositive] falsified images id: {}".format(PGD_falsified_falsepositive_img_id))
printlog("[L0] WiNR(+PGD[aimed at falsepositive]) falsified images id: {}".format(WiNR_after_PGD_falsified_falsepositive_img_id))
printlog("[L0] WiNR falsified images id: {}".format(WiNR_falsified_img_id))
print('------------------')
print('------------------')
# return PGD+DeepCert, WiNR, PGD+WiNR
#return eps_0, len(inputs), DeepCert_robust_number, PGD_falsified_number, PGD_DeepCert_unknown_number, PGD_aver_time, DeepCert_aver_time, PGD_DeepCert_aver_time, WiNR_robust_number, WiNR_falsified_number, WiNR_unknown_number, WiNR_aver_time, WiNR_after_PGD_robust_number, (PGD_before_WiNR_falsified_number+WiNR_after_PGD_falsified_number), WiNR_after_PGD_unknown_number, PGD_before_WiNR_aver_time, WiNR_after_PGD_aver_time, PGD_WiNR_total_aver_time
# return WiNR, PGD+WiNR
# return eps_0, len(inputs), WiNR_robust_number, WiNR_falsified_number, WiNR_unknown_number, WiNR_aver_time, WiNR_after_PGD_robust_number, (PGD_before_WiNR_falsified_number+WiNR_after_PGD_falsified_number), WiNR_after_PGD_unknown_number, PGD_before_WiNR_aver_time, WiNR_after_PGD_aver_time, PGD_WiNR_total_aver_time
# return WiNR, WiNR+PGD[aimed at false positive]
return eps_0, len(inputs), WiNR_robust_number, WiNR_falsified_number, WiNR_unknown_number, WiNR_aver_time, WiNR_with_PGD_robust_number, WiNR_with_PGD_falsified_number, WiNR_with_PGD_unknown_number, WiNR_with_PGD_aver_time
# for i in range(len(inputs)):
# print('image: ', i, file=f)
# print('image: ', i)
# predict_label = np.argmax(true_labels[i])
# print('predict_label:', predict_label)
# print('predict_label:', predict_label, file=f)
# adv_false = []
# has_adv_false = False
# flag = True
# for j in range(i*9,i*9+9):
# target_label = targets[j]
# print('target_label:', target_label)
# print('target_label:', target_label, file=f)
# weights = model.weights[:-1]
# biases = model.biases[:-1]
# shapes = model.shapes[:-1]
# W, b, s = model.weights[-1], model.biases[-1], model.shapes[-1]
# last_weight = (W[predict_label,:,:,:]-W[target_label,:,:,:]).reshape([1]+list(W.shape[1:]))
# weights.append(last_weight)
# biases.append(np.asarray([b[predict_label]-b[target_label]]))
# shapes.append((1,1,1))
# LB, UB, A_u, A_l, B_u, B_l, pad, stride = find_output_bounds(weights, biases, shapes, model.pads, model.strides, inputs[i].astype(np.float32), eps_0, p_n)
# # solving
# lp_model = new_model()
# lp_model, x = creat_var(lp_model, inputs[i], eps_0)
# shape = inputs[i].shape
# adv_image, min_val = get_solution_value(lp_model, x, shape, A_u, A_l, B_u, B_l, pad, stride, p_n, eps_0)
# if min_val > 0:
# continue
# # label of potential counterexample
# a = adv_image[np.newaxis,:,:,:]
# print(a.dtype)
# aa = a.astype(np.float32)
# adv_label = np.argmax(np.squeeze(keras_model.predict(aa)))
# print('adv_label: ', adv_label)
# print('adv_label: ', adv_label, file=f)
# if adv_label == predict_label:
# adv_false.append((adv_image, target_label))
# has_adv_false = True
# print('this adv_example is false!', file=f)
# continue
# flag = False
# fashion_mnist_labels_names = ['T-shirt or top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# cifar10_labels_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
# # save adv images
# print('adv_image.shape:', adv_image.shape)
# print(adv_image)
# print(adv_image, file=f)
# save_adv_image = np.clip(adv_image * 255, 0, 255)
# if cifar:
# save_adv_image = save_adv_image.astype(np.int32)
# plt.imshow(save_adv_image)
# adv_label_str = cifar10_labels_names[adv_label]
# elif gtsrb:
# save_adv_image = save_adv_image.astype(np.int32)
# plt.imshow(save_adv_image)
# adv_label_str = str(adv_label)
# elif fashion_mnist:
# plt.imshow(save_adv_image, cmap='gray')
# adv_label_str = fashion_mnist_labels_names[adv_label]
# else:
# plt.imshow(save_adv_image, cmap='gray')
# adv_label_str = str(adv_label)
# print(save_adv_image)
# print(save_adv_image, file=f)
# print('adv_label_str.shape:', type(adv_label_str))
# save_path = 'adv_examples/'+ dataset + '_'+str(eps_0)+'_adv_image_'+str(i)+'_adv_label_'+adv_label_str +'.png'
# plt.savefig(save_path)
# print(inputs[i].astype(np.float32))
# original_image = np.clip(inputs[i].astype(np.float32)*255,0,255)
# if cifar:
# original_image = original_image.astype(np.int32)
# plt.imshow(original_image)
# predict_label_str = cifar10_labels_names[predict_label]
# elif gtsrb:
# original_image = original_image.astype(np.int32)
# plt.imshow(original_image)
# predict_label_str = str(predict_label)
# elif fashion_mnist:
# plt.imshow(original_image, cmap='gray')
# predict_label_str = fashion_mnist_labels_names[predict_label]
# else:
# plt.imshow(original_image, cmap='gray')
# predict_label_str = str(predict_label)
# print(original_image, file=f)
# save_path = 'adv_examples/'+ dataset +'_'+str(eps_0)+'_original_image_'+str(i)+'_predict_label_'+predict_label_str+'.png'
# plt.savefig(save_path)
# break
# if not flag:
# unrobust_number += 1
# print('this figure is not robust in eps_0', file=f)
# print("[L1] method = WiNR-{}, model = {}, image no = {}, true_label = {}, target_label = {}, adv_label = {}, robustness = {:.5f}".format(activation, file_name, i+1, predict_label, target_label, adv_label,eps_0), file=f)
# else:
# if has_adv_false:
# has_adv_false_number += 1
# else:
# robust_number += 1
# print("figure {} is robust in {}.".format(i, eps_0), file=f)
# print('---------------------------------', file=f)
# print("robust: {}, unrobust: {}, has_adv_false: {}".format((flag and (not has_adv_false)), (not flag), has_adv_false), file=f)
# time_sum = time.time() - start_time
# if time_sum >= limit_time:
# print('time_sum:',time_sum, file=f)
# break
# first_sort_time = (time.time()-start_time)
# print("[L0] method = WiNR-{}, model = {}, eps = {}, total images = {}, robust = {}, unrobust = {}, has_adv_false = {}, total runtime = {:.2f}".format(activation,file_name,eps_0, len(inputs), robust_number, unrobust_number, has_adv_false_number, first_sort_time), file=f)
# results.append((eps_0, robust_number, unrobust_number, has_adv_false_number, first_sort_time))
# print('eps_0 robust_number unrobust_number has_adv_false_number total_runtime', file=f)
# for i in range(len(results)):
# print(results[i][0], '\t', results[i][1], '\t\t', results[i][2], '\t\t', results[i][3], '\t\t', results[i][4], file=f)
# f.close()
# print('------------------')
# print('------------------')
# return results
| StarcoderdataPython |
3380640 | <reponame>ViviHong200709/EduCDM
# coding: utf-8
# 2021/6/19 @ tongshiwei
from EduCDM.IRR import MIRT
import logging
from longling.lib.structure import AttrDict
from longling import set_logging_info
from EduCDM.IRR import pair_etl as etl, point_etl as vt_etl, extract_item
set_logging_info()
params = AttrDict(
batch_size=256,
n_neg=10,
n_imp=10,
logger=logging.getLogger(),
hyper_params={"user_num": 4164}
)
item_knowledge = extract_item("../../data/a0910/item.csv", 123, params)
train_data, train_df = etl("../../data/a0910/train.csv", item_knowledge, params)
valid_data, _ = vt_etl("../../data/a0910/valid.csv", item_knowledge, params)
test_data, _ = vt_etl("../../data/a0910/test.csv", item_knowledge, params)
cdm = MIRT(
4163 + 1,
17746 + 1,
123
)
cdm.train(
train_data,
valid_data,
epoch=2,
)
cdm.save("IRR-MIRT.params")
cdm.load("IRR-MIRT.params")
print(cdm.eval(test_data))
| StarcoderdataPython |
11332860 | #
# Copyright (c) 2017 Orange.
#
# 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.
#
"""Datasource for configuration options"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from collections import OrderedDict
import datetime
import os
import six
from oslo_concurrency import lockutils
from oslo_config import cfg
from oslo_config import types
from oslo_log import log as logging
import oslo_messaging as messaging
from congress.cfg_validator import parsing
from congress.cfg_validator import utils
from congress.datasources import constants
from congress.datasources import datasource_driver
from congress.dse2 import dse_node as dse
LOG = logging.getLogger(__name__)
FILE = u'file'
VALUE = u'binding'
OPTION = u'option'
OPTION_INFO = u'option_info'
INT_TYPE = u'int_type'
FLOAT_TYPE = u'float_type'
STR_TYPE = u'string_type'
LIST_TYPE = u'list_type'
RANGE_TYPE = u'range_type'
URI_TYPE = u'uri_type'
IPADDR_TYPE = u'ipaddr_type'
SERVICE = u'service'
HOST = u'host'
MODULE = u'module'
TEMPLATE = u'template'
TEMPLATE_NS = u'template_ns'
NAMESPACE = u'namespace'
class ValidatorDriver(datasource_driver.PollingDataSourceDriver):
"""Driver for the Configuration validation datasource"""
# pylint: disable=too-many-instance-attributes
DS_NAME = u'config'
def __init__(self, name=None, args=None):
super(ValidatorDriver, self).__init__(self.DS_NAME, args)
# { template_hash -> {name, namespaces} }
self.known_templates = {}
# { namespace_hash -> namespace_name }
self.known_namespaces = {}
# set(config_hash)
self.known_configs = set()
# { template_hash -> (conf_hash, conf)[] }
self.templates_awaited_by_config = {}
self.agent_api = ValidatorAgentClient()
self.rule_added = False
if hasattr(self, 'add_rpc_endpoint'):
self.add_rpc_endpoint(ValidatorDriverEndpoints(self))
self._init_end_start_poll()
# pylint: disable=no-self-use
def get_context(self):
"""context for RPC. To define"""
return {}
@staticmethod
def get_datasource_info():
"""Gives back a standardized description of the datasource"""
result = {}
result['id'] = 'config'
result['description'] = (
'Datasource driver that allows OS configs retrieval.')
result['config'] = {
'poll_time': constants.OPTIONAL,
'lazy_tables': constants.OPTIONAL}
return result
@classmethod
def get_schema(cls):
sch = {
# option value
VALUE: [
{'name': 'option_id', 'desc': 'The represented option'},
{'name': 'file_id',
'desc': 'The file containing the assignement'},
{'name': 'val', 'desc': 'Actual value'}],
OPTION: [
{'name': 'id', 'desc': 'Id'},
{'name': 'namespace', 'desc': ''},
{'name': 'group', 'desc': ''},
{'name': 'name', 'desc': ''}, ],
# options metadata, omitted : dest
OPTION_INFO: [
{'name': 'option_id', 'desc': 'Option id'},
{'name': 'type', 'desc': ''},
{'name': 'default', 'desc': ''},
{'name': 'deprecated', 'desc': ''},
{'name': 'deprecated_reason', 'desc': ''},
{'name': 'mutable', 'desc': ''},
{'name': 'positional', 'desc': ''},
{'name': 'required', 'desc': ''},
{'name': 'sample_default', 'desc': ''},
{'name': 'secret', 'desc': ''},
{'name': 'help', 'desc': ''}],
HOST: [
{'name': 'id', 'desc': 'Id'},
{'name': 'name', 'desc': 'Arbitraty host name'}],
FILE: [
{'name': 'id', 'desc': 'Id'},
{'name': 'host_id', 'desc': 'File\'s host'},
{'name': 'template',
'desc': 'Template specifying the content of the file'},
{'name': 'name', 'desc': ''}],
MODULE: [
{'name': 'id', 'desc': 'Id'},
{'name': 'base_dir', 'desc': ''},
{'name': 'module', 'desc': ''}],
SERVICE: [
{'name': 'service', 'desc': ''},
{'name': 'host', 'desc': ''},
{'name': 'version', 'desc': ''}],
TEMPLATE: [
{'name': 'id', 'desc': ''},
{'name': 'name', 'desc': ''}, ],
TEMPLATE_NS: [
{'name': 'template', 'desc': 'hash'},
{'name': 'namespace', 'desc': 'hash'}],
NAMESPACE: [
{'name': 'id', 'desc': ''},
{'name': 'name', 'desc': ''}],
INT_TYPE: [
{'name': 'option_id', 'desc': ''},
{'name': 'min', 'desc': ''},
{'name': 'max', 'desc': ''},
{'name': 'choices', 'desc': ''}, ],
FLOAT_TYPE: [
{'name': 'option_id', 'desc': ''},
{'name': 'min', 'desc': ''},
{'name': 'max', 'desc': ''}, ],
STR_TYPE: [
{'name': 'option_id', 'desc': ''},
{'name': 'regex', 'desc': ''},
{'name': 'max_length', 'desc': ''},
{'name': 'quotes', 'desc': ''},
{'name': 'ignore_case', 'desc': ''},
{'name': 'choices', 'desc': ''}, ],
LIST_TYPE: [
{'name': 'option_id', 'desc': ''},
{'name': 'item_type', 'desc': ''},
{'name': 'bounds', 'desc': ''}, ],
IPADDR_TYPE: [
{'name': 'option_id', 'desc': ''},
{'name': 'version', 'desc': ''}, ],
URI_TYPE: [
{'name': 'option_id', 'desc': ''},
{'name': 'max_length', 'desc': ''},
{'name': 'schemes', 'desc': ''}, ],
RANGE_TYPE: [
{'name': 'option_id', 'desc': ''},
{'name': 'min', 'desc': ''},
{'name': 'max', 'desc': ''}, ],
}
return sch
def poll(self):
LOG.info("%s:: polling", self.name)
# Initialize published state to a sensible empty state.
# Avoids races with queries.
if self.number_of_updates == 0:
for tablename in set(self.get_schema()):
self.state[tablename] = set()
self.publish(tablename, self.state[tablename],
use_snapshot=False)
self.agent_api.publish_templates_hashes(self.get_context())
self.agent_api.publish_configs_hashes(self.get_context())
self.last_updated_time = datetime.datetime.now()
self.number_of_updates += 1
def process_config_hashes(self, hashes, host):
"""Handles a list of config files hashes and their retrieval.
If the driver can process the parsing and translation of the config,
it registers the configs to the driver.
:param hashes: A list of config files hashes
:param host: Name of the node hosting theses config files
"""
LOG.debug('Received configs list from %s' % host)
for cfg_hash in set(hashes) - self.known_configs:
config = self.agent_api.get_config(self.get_context(),
cfg_hash, host)
if self.process_config(cfg_hash, config, host):
self.known_configs.add(cfg_hash)
LOG.debug('Config %s from %s registered' % (cfg_hash, host))
@lockutils.synchronized('validator_process_template_hashes')
def process_template_hashes(self, hashes, host):
"""Handles a list of template hashes and their retrieval.
Uses lock to avoid multiple sending of the same data.
:param hashes: A list of templates hashes
:param host: Name of the node hosting theses config files
"""
LOG.debug('Process template hashes from %s' % host)
for t_h in set(hashes) - set(self.known_templates):
LOG.debug('Treating template hash %s' % t_h)
template = self.agent_api.get_template(self.get_context(), t_h,
host)
ns_hashes = template['namespaces']
for ns_hash in set(ns_hashes) - set(self.known_namespaces):
namespace = self.agent_api.get_namespace(
self.get_context(), ns_hash, host)
self.known_namespaces[ns_hash] = namespace
self.known_templates[t_h] = template
for (c_h, config) in self.templates_awaited_by_config.pop(t_h, []):
if self.process_config(c_h, config, host):
self.known_configs.add(c_h)
LOG.debug('Config %s from %s registered (late)' %
(c_h, host))
return True
def translate_service(self, host_id, service, version):
"""Translates a service infos to SERVICE table.
:param host_id: Host ID, should reference HOST.ID
:param service: A service name
:param version: A version name, can be None
"""
if not host_id or not service:
return
service_row = tuple(
map(utils.cfg_value_to_congress, (service, host_id, version)))
self.state[SERVICE].add(service_row)
def translate_host(self, host_id, host_name):
"""Translates a host infos to HOST table.
:param host_id: Host ID
:param host_name: A host name
"""
if not host_id:
return
host_row = tuple(
map(utils.cfg_value_to_congress, (host_id, host_name)))
self.state[HOST].add(host_row)
def translate_file(self, file_id, host_id, template_id, file_name):
"""Translates a file infos to FILE table.
:param file_id: File ID
:param host_id: Host ID, should reference HOST.ID
:param template_id: Template ID, should reference TEMPLATE.ID
"""
if not file_id or not host_id:
return
file_row = tuple(
map(utils.cfg_value_to_congress,
(file_id, host_id, template_id, file_name)))
self.state[FILE].add(file_row)
def translate_template_namespace(self, template_id, name, ns_ids):
"""Translates a template infos and its namespaces infos.
Modifies tables : TEMPLATE, NAMESPACE and TEMPLATE_NS
:param template_id: Template ID
:param name: A template name
:param ns_ids: List of namespace IDs, defining this template, should
reference NAMESPACE.ID
"""
if not template_id:
return
template_row = tuple(
map(utils.cfg_value_to_congress, (template_id, name)))
self.state[TEMPLATE].add(template_row)
for ns_h, ns_name in six.iteritems(ns_ids):
if not ns_h:
continue
namespace_row = tuple(map(utils.cfg_value_to_congress,
(ns_h, ns_name)))
self.state[NAMESPACE].add(namespace_row)
tpl_ns_row = tuple(
map(utils.cfg_value_to_congress, (template_id, ns_h)))
self.state[TEMPLATE_NS].add(tpl_ns_row)
# pylint: disable=protected-access,too-many-branches
def translate_type(self, opt_id, cfg_type):
"""Translates a type to the appropriate type table.
:param opt_id: Option ID, should reference OPTION.ID
:param cfg_type: An oslo ConfigType for the referenced option
"""
if not opt_id:
return
if isinstance(cfg_type, types.String):
tablename = STR_TYPE
# oslo.config 5.2 begins to use a different representation of
# choices (OrderedDict). We first convert back to simple list to
# have consistent output regardless of oslo.config version
if isinstance(cfg_type.choices, OrderedDict):
choices = list(map(lambda item: item[0],
cfg_type.choices.items()))
else:
choices = cfg_type.choices
row = (cfg_type.regex, cfg_type.max_length, cfg_type.quotes,
cfg_type.ignore_case, choices)
elif isinstance(cfg_type, types.Integer):
tablename = INT_TYPE
# oslo.config 5.2 begins to use a different representation of
# choices (OrderedDict). We first convert back to simple list to
# have consistent output regardless of oslo.config version
if isinstance(cfg_type.choices, OrderedDict):
choices = list(map(lambda item: item[0],
cfg_type.choices.items()))
else:
choices = cfg_type.choices
row = (cfg_type.min, cfg_type.max, choices)
elif isinstance(cfg_type, types.Float):
tablename = FLOAT_TYPE
row = (cfg_type.min, cfg_type.max)
elif isinstance(cfg_type, types.List):
tablename = LIST_TYPE
row = (type(cfg_type.item_type).__name__, cfg_type.bounds)
elif isinstance(cfg_type, types.IPAddress):
tablename = IPADDR_TYPE
if cfg_type.version_checker == cfg_type._check_ipv4:
version = 4
elif cfg_type.version_checker == cfg_type._check_ipv6:
version = 6
else:
version = None
row = (version,)
elif isinstance(cfg_type, types.URI):
tablename = URI_TYPE
row = (cfg_type.max_length, cfg_type.schemes)
elif isinstance(cfg_type, types.Range):
tablename = RANGE_TYPE
row = (cfg_type.min, cfg_type.max)
else:
return
row = (opt_id,) + row
if isinstance(cfg_type, types.List):
self.translate_type(opt_id, cfg_type.item_type)
self.state[tablename].add(
tuple(map(utils.cfg_value_to_congress, row)))
def translate_value(self, file_id, option_id, value):
"""Translates a value to the VALUE table.
If value is a list, a table entry is added for every list item.
If value is a dict, a table entry is added for every key-value.
:param file_id: File ID, should reference FILE.ID
:param option_id: Option ID, should reference OPTION.ID
:param value: A value, can be None
"""
if not file_id:
return
if not option_id:
return
if isinstance(value, list):
for v_item in value:
value_row = tuple(
map(utils.cfg_value_to_congress,
(option_id, file_id, v_item)))
self.state[VALUE].add(value_row)
elif isinstance(value, dict):
for v_key, v_item in six.iteritems(value):
value_row = tuple(
map(utils.cfg_value_to_congress,
(option_id, file_id, '%s:%s' % (v_key, v_item))))
self.state[VALUE].add(value_row)
else:
value_row = tuple(
map(utils.cfg_value_to_congress,
(option_id, file_id, value)))
self.state[VALUE].add(value_row)
def translate_option(self, option, group_name):
"""Translates an option metadata to datasource tables.
Modifies tables : OPTION, OPTION_INFO
:param option: An IdentifiedOpt object
:param group_name: Associated section name
"""
if option is None:
return
if not group_name:
return
option_row = tuple(map(utils.cfg_value_to_congress, (
option.id_, option.ns_id, group_name, option.name)))
self.state[OPTION].add(option_row)
option_info_row = tuple(
map(utils.cfg_value_to_congress, (
option.id_,
type(option.type).__name__,
option.default,
option.deprecated_for_removal,
option.deprecated_reason,
option.mutable,
option.positional,
option.required,
option.sample_default,
option.secret,
option.help)))
self.state[OPTION_INFO].add(option_info_row)
def translate_conf(self, conf, file_id):
"""Translates a config manager to the datasource state.
:param conf: A config manager ConfigOpts, containing the parsed values
and the options metadata to read them
:param file_id: Id of the file, which contains the parsed values
"""
cfg_ns = conf._namespace
def _do_translation(option, group_name='DEFAULT'):
option = option['opt']
self.translate_option(option, group_name)
try:
value = option._get_from_namespace(cfg_ns, group_name)
if hasattr(cfg, 'LocationInfo'):
value = value[0]
except KeyError:
# No value parsed for this option
return
self.translate_type(option.id_, option.type)
try:
value = parsing.parse_value(option.type, value)
except (ValueError, TypeError):
LOG.warning('Value for option %s is not valid : %s' % (
option.name, value))
self.translate_value(file_id, option.id_, value)
for _, option in six.iteritems(conf._opts):
_do_translation(option)
for group_name, identified_group in six.iteritems(conf._groups):
for _, option in six.iteritems(identified_group._opts):
_do_translation(option, group_name)
def process_config(self, file_hash, config, host):
"""Manages all translations related to a config file.
Publish tables to PE.
:param file_hash: Hash of the configuration file
:param config: object representing the configuration
:param host: Remote host name
:return: True if config was processed
"""
try:
LOG.debug("process_config hash=%s" % file_hash)
template_hash = config['template']
template = self.known_templates.get(template_hash, None)
if template is None:
waiting = (
self.templates_awaited_by_config.get(template_hash, []))
waiting.append((file_hash, config))
self.templates_awaited_by_config[template_hash] = waiting
LOG.debug('Template %s not yet registered' % template_hash)
return False
host_id = utils.compute_hash(host)
namespaces = [self.known_namespaces.get(h, None).get('data', None)
for h in template['namespaces']]
conf = parsing.construct_conf_manager(namespaces)
parsing.add_parsed_conf(conf, config['data'])
for tablename in set(self.get_schema()) - set(self.state):
self.state[tablename] = set()
self.publish(tablename, self.state[tablename],
use_snapshot=False)
self.translate_conf(conf, file_hash)
self.translate_host(host_id, host)
self.translate_service(
host_id, config['service'], config['version'])
file_name = os.path.basename(config['path'])
self.translate_file(file_hash, host_id, template_hash, file_name)
ns_hashes = {h: self.known_namespaces[h]['name']
for h in template['namespaces']}
self.translate_template_namespace(template_hash, template['name'],
ns_hashes)
for tablename in self.state:
self.publish(tablename, self.state[tablename],
use_snapshot=True)
return True
except KeyError:
LOG.error('Config %s from %s NOT registered'
% (file_hash, host))
return False
class ValidatorAgentClient(object):
"""RPC Proxy to access the agent from the datasource."""
def __init__(self, topic=utils.AGENT_TOPIC):
transport = messaging.get_transport(cfg.CONF)
target = messaging.Target(exchange=dse.DseNode.EXCHANGE,
topic=topic,
version=dse.DseNode.RPC_VERSION)
self.client = messaging.RPCClient(transport, target)
def publish_configs_hashes(self, context):
"""Asks for config hashes"""
cctx = self.client.prepare(fanout=True)
return cctx.cast(context, 'publish_configs_hashes')
def publish_templates_hashes(self, context):
"""Asks for template hashes"""
cctx = self.client.prepare(fanout=True)
return cctx.cast(context, 'publish_templates_hashes')
# block calling thread
def get_namespace(self, context, ns_hash, server):
"""Retrieves an explicit namespace from a server given a hash. """
cctx = self.client.prepare(server=server)
return cctx.call(context, 'get_namespace', ns_hash=ns_hash)
# block calling thread
def get_template(self, context, tpl_hash, server):
"""Retrieves an explicit template from a server given a hash"""
cctx = self.client.prepare(server=server)
return cctx.call(context, 'get_template', tpl_hash=tpl_hash)
# block calling thread
def get_config(self, context, cfg_hash, server):
"""Retrieves a config from a server given a hash"""
cctx = self.client.prepare(server=server)
return cctx.call(context, 'get_config', cfg_hash=cfg_hash)
class ValidatorDriverEndpoints(object):
"""RPC endpoint on the datasource driver for use by the agents"""
def __init__(self, driver):
self.driver = driver
# pylint: disable=unused-argument
def process_templates_hashes(self, context, **kwargs):
"""Process the template hashes received from a server"""
LOG.debug(
'Received template hashes from host %s' % kwargs.get('host', ''))
self.driver.process_template_hashes(**kwargs)
# pylint: disable=unused-argument
def process_configs_hashes(self, context, **kwargs):
"""Process the config hashes received from a server"""
LOG.debug(
'Received config hashes from host %s' % kwargs.get('host', ''))
self.driver.process_config_hashes(**kwargs)
| StarcoderdataPython |
11381287 | <filename>pdb_profiling/viewer.py
# @Created Date: 2020-10-21 09:09:05 pm
# @Filename: viewer.py
# @Email: <EMAIL>
# @Author: <NAME>
# @Last Modified: 2020-10-21 09:09:10 pm
# @Copyright (c) 2020 MinghuiGroup, Soochow University
from pandas import isna, DataFrame
from pdb_profiling.utils import expand_interval
from pdb_profiling.processors.pdbe.record import PDB
class NGL(object):
@staticmethod
def get_related_auth_res(res_df, struct_asym_id, res_num_set):
if len(res_num_set) > 0:
subset = res_df[res_df.struct_asym_id.eq(struct_asym_id) & res_df.residue_number.isin(res_num_set)]
return ('('+subset.author_residue_number.astype(str)+'^'+subset.author_insertion_code+subset.multiple_conformers.apply(lambda x: ' and %' if isna(x) else ' and %A')+')')
else:
subset = res_df[res_df.struct_asym_id.eq(struct_asym_id)]
assert len(subset) == 1
return ('('+subset.author_residue_number.astype(str)+'^'+subset.author_insertion_code+subset.multiple_conformers.apply(lambda x: ' and %' if isna(x) else ' and %A')+')').iloc[0]
@staticmethod
def get_type(x):
if x in (
'polypeptide(L)',
'polypeptide(D)'):
return 'protein'
elif x in (
'polydeoxyribonucleotide',
'polyribonucleotide',
'polydeoxyribonucleotide/polyribonucleotide hybrid'):
return 'nucleic'
else:
return 'ligand'
@classmethod
def interface_sele_str_unit(cls, res_df, record, suffix):
mol_type = cls.get_type(record[f'molecule_type{suffix}'])
if mol_type != 'ligand':
res = cls.get_related_auth_res(res_df, record[f'struct_asym_id{suffix}'], frozenset(expand_interval(record[f'interface_range{suffix}'])))
sres = cls.get_related_auth_res(res_df, record[f'struct_asym_id{suffix}'], frozenset(expand_interval(record[f'surface_range{suffix}'])))
res = ' or '.join(res)
sres = ' or '.join(sres)
return mol_type, f' and ({res})', f' and ({sres})'
else:
res = cls.get_related_auth_res(res_df, record[f'struct_asym_id{suffix}'], frozenset())
sres = cls.get_related_auth_res(res_df, record[f'struct_asym_id{suffix}'], frozenset())
return mol_type, f' and {res}', f' and {sres}'
@classmethod
def get_interface_sele_str(cls, record):
res_df = PDB(record['pdb_id']).fetch_from_pdbe_api('api/pdb/entry/residue_listing/', PDB.to_dataframe).result()
type_1, i_str_1, s_str_1 = cls.interface_sele_str_unit(res_df, record, '_1')
type_2, i_str_2, s_str_2 = cls.interface_sele_str_unit(res_df, record, '_2')
chain_id_1 = record['chain_id_1']
chain_id_2 = record['chain_id_2']
return ((f'{type_1} and :{chain_id_1}'+i_str_1, f'{type_2} and :{chain_id_2}'+i_str_2),
(f'{type_1} and :{chain_id_1}'+s_str_1, f'{type_2} and :{chain_id_2}'+s_str_2))
@classmethod
def get_interface_view(cls, view, record, **kwargs):
(i1, i2), (s1, s2) = cls.get_interface_sele_str(record)
view.add_spacefill(selection=s1, opacity=kwargs.get('surface_opacity_1', 0.05), color=kwargs.get('surface_color_1', 'white'))
view.add_spacefill(selection=s2, opacity=kwargs.get('surface_opacity_2', 0.05), color=kwargs.get('surface_color_2', 'white'))
view.add_spacefill(selection=i1, opacity=kwargs.get('interface_opacity_1', 0.5), color=kwargs.get('interface_color_1', 'green'))
view.add_spacefill(selection=i2, opacity=kwargs.get('interface_opacity_2', 0.5), color=kwargs.get('interface_color_2', 'red'))
view.background = kwargs.get('background', '#F3F3F3')
view._set_size(*kwargs.get('size', ('50%', '50%')))
return view
| StarcoderdataPython |
1698160 | <reponame>cmsong111/NJ_code
a= int(input())
print('%X'% a)
| StarcoderdataPython |
3386126 | <gh_stars>1-10
import tensorflow as tf
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.models import Model
train_loss_tracker = tf.keras.metrics.Mean()
val_loss_tracker = tf.keras.metrics.Mean()
train_acc_tracker = tf.keras.metrics.SparseCategoricalAccuracy()
val_acc_tracker = tf.keras.metrics.SparseCategoricalAccuracy()
class CustomModel(tf.keras.Model):
"""
Inherited from `tf.keras.Model`.
Custom training step, test step, metrics.
self.compiled_loss is SparseCategoricalCrossentropy.
metrics include {train loss, val loss, train acc, val acc}
"""
def train_step(self, data):
x, y = data['img'], data['label']
with tf.GradientTape() as tape:
y_pred = self(x, training=True) # Forward pass
# Compute our own loss
loss = self.compiled_loss(y, y_pred)
# Compute gradients
trainable_vars = self.trainable_variables
gradients = tape.gradient(loss, trainable_vars)
# Update weights
self.optimizer.apply_gradients(zip(gradients, trainable_vars))
# Compute our own metrics
train_loss_tracker.update_state(loss)
train_acc_tracker.update_state(y, y_pred)
return {"loss": train_loss_tracker.result(),
"acc": train_acc_tracker.result()}
def test_step(self, data):
x, y = data['img'], data['label']
# Compute predictions
y_pred = self(x, training=False)
# Updates the metrics tracking the loss
loss = self.compiled_loss(y, y_pred)
# Update the metrics.
val_loss_tracker.update_state(loss)
val_acc_tracker.update_state(y, y_pred)
return {"loss": val_loss_tracker.result(),
"acc": val_acc_tracker.result()}
@property
def metrics(self):
return [train_loss_tracker, val_loss_tracker,
train_acc_tracker, val_acc_tracker]
def model_fn(is_training=True, **params):
"""
Create base model with MobileNetV2 + Dense layer (n class).
Wrap up with CustomModel process.
Args:
is_training (bool): if it is going to be trained or not
params: keyword arguments (parameters dictionary)
"""
baseModel = MobileNetV2(
include_top=False, weights='imagenet',
input_shape=(224, 224, 3), pooling="avg")
fc = tf.keras.layers.Dense(
params['n_class'], activation="softmax",
name="softmax_layer")(baseModel.output)
model = CustomModel(inputs=baseModel.input, outputs=fc)
# If it is not training mode
if not is_training:
model.trainable = False
return model
| StarcoderdataPython |
11391149 | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/00b_inference.export.ipynb (unless otherwise specified).
__all__ = ['get_information']
# Cell
from fastai.vision.all import *
# Cell
def _gen_dict(tfm):
"Grabs the `attrdict` and transform name from `tfm`"
tfm_dict = attrdict(tfm, *tfm.store_attrs.split(','))
if 'partial' in tfm.name:
tfm_name = tfm.name[1].split(' --')[0]
else:
tfm_name = tfm.name.split(' --')[0]
return tfm_dict, tfm_name
# Cell
def _make_tfm_dict(tfms, type_tfm=False):
"Extracts transform params from `tfms`"
tfm_dicts = {}
for tfm in tfms:
if hasattr(tfm, 'store_attrs') and not isinstance(tfm, AffineCoordTfm):
if type_tfm or tfm.split_idx is not 0:
tfm_dict,name = _gen_dict(tfm)
tfm_dict = to_list(tfm_dict)
tfm_dicts[name] = tfm_dict
return tfm_dicts
# Cell
@typedispatch
def _extract_tfm_dicts(dl:TfmdDL):
"Extracts all transform params from `dl`"
type_tfm,use_images = True,False
attrs = ['tfms','after_item','after_batch']
tfm_dicts = {}
for attr in attrs:
tfm_dicts[attr] = _make_tfm_dict(getattr(dl, attr), type_tfm)
if attr == 'tfms':
if getattr(dl,attr)[0][1].name == 'PILBase.create':
use_images=True
if attr == 'after_item': tfm_dicts[attr]['ToTensor'] = {'is_image':use_images}
type_tfm = False
return tfm_dicts
# Cell
def get_information(dls): return _extract_tfm_dicts(dls[0])
# Cell
from fastai.tabular.all import *
# Cell
@typedispatch
def _extract_tfm_dicts(dl:TabDataLoader):
"Extracts all transform params from `dl`"
types = 'normalize,fill_missing,categorify'
if hasattr(dl, 'categorize'): types += ',categorize'
if hasattr(dl, 'regression_setup'): types += ',regression_setup'
tfms = {}
name2idx = {name:n for n,name in enumerate(dl.dataset) if name in dl.cat_names or name in dl.cont_names}
idx2name = {v:k for k,v in name2idx.items()}
cat_idxs = {name2idx[name]:name for name in dl.cat_names}
cont_idxs = {name2idx[name]:name for name in dl.cont_names}
names = {'cats':cat_idxs, 'conts':cont_idxs}
tfms['encoder'] = names
for t in types.split(','):
tfm = getattr(dl, t)
tfms[t] = to_list(attrdict(tfm, *tfm.store_attrs.split(',')))
categorize = dl.procs.categorify.classes.copy()
for i,c in enumerate(categorize):
categorize[c] = {a:b for a,b in enumerate(categorize[c])}
categorize[c] = {v: k for k, v in categorize[c].items()}
categorize[c].pop('#na#')
categorize[c][np.nan] = 0
tfms['categorify']['classes'] = categorize
new_dict = {}
for k,v in tfms.items():
if k == 'fill_missing':
k = 'FillMissing'
new_dict.update({k:v})
else:
new_dict.update({k.capitalize():v})
return new_dict
# Cell
@patch
def to_fastinference(x:Learner, data_fname='data', model_fname='model', path=Path('.')):
"Export data for `fastinference_onnx` or `_pytorch` to use"
if not isinstance(path,Path): path = Path(path)
dicts = get_information(x.dls)
with open(path/f'{data_fname}.pkl', 'wb') as handle:
pickle.dump(dicts, handle, protocol=pickle.HIGHEST_PROTOCOL)
torch.save(x.model, path/f'{model_fname}.pkl')
| StarcoderdataPython |
9635805 | <gh_stars>1-10
import numpy as np
def init_pop(n_pop, n_var, xl, xu):
"""
Initialize a population with uniform distribution
parameter
----------
n_pop: int
population size
n_var: int
number of decision variables
xl, xu: float
lower and upper boundary of decision variables
return
----------
2D-Array
a matrix showing the population where each row is an individual
"""
X = np.random.uniform(xl, xu, (n_pop, n_var))
return X
def eval_pop(X, problem, problem_name):
"""
Evaluate a population with the given objectives
parameter
-----------
X: 2D-Array
population matrix where each row is an individual
problem: method
objective function which returns fitness values of a input individual
return
-----------
2D-Array
fitness value matrix where each row is the fitness values of an individual
"""
# F = []]
benchmark_name = ''.join(i for i in problem_name if not i.isdigit())
if (benchmark_name == "dtlz" or benchmark_name == "DTLZ"):
F = problem(X)
elif (benchmark_name == "uf" or benchmark_name == "UF"):
F = []
for x in X:
F.append(problem(x))
return np.array(F) | StarcoderdataPython |
3318163 | <gh_stars>1-10
def output_gpx(points, output_filename):
"""
Output a GPX file with latitude and longitude from the points DataFrame.
"""
from xml.dom.minidom import getDOMImplementation
def append_trkpt(pt, trkseg, doc):
trkpt = doc.createElement('trkpt')
trkpt.setAttribute('lat', '%.8f' % (pt['lat']))
trkpt.setAttribute('lon', '%.8f' % (pt['lon']))
trkseg.appendChild(trkpt)
doc = getDOMImplementation().createDocument(None, 'gpx', None)
trk = doc.createElement('trk')
doc.documentElement.appendChild(trk)
trkseg = doc.createElement('trkseg')
trk.appendChild(trkseg)
points.apply(append_trkpt, axis=1, trkseg=trkseg, doc=doc)
with open(output_filename, 'w') as fh:
doc.writexml(fh, indent=' ')
def main():
points = get_data(sys.argv[1])
print('Unfiltered distance: %0.2f' % (distance(points),))
smoothed_points = smooth(points)
print('Filtered distance: %0.2f' % (distance(smoothed_points),))
output_gpx(smoothed_points, 'out.gpx')
if __name__ == '__main__':
main() | StarcoderdataPython |
8088916 | <reponame>alviproject/alvi
def create_node(pipe, id, parent_id, value):
pipe.send('create_node', (id, ), dict(
id=id,
parent_id=parent_id,
value=value,
))
def update_node(pipe, id, value):
pipe.send('update_node', (id, ), dict(
id=id,
value=value,
))
def remove_node(pipe, id):
pipe.send('remove_node', (id, ), dict(
id=id,
))
| StarcoderdataPython |
11382161 | <gh_stars>10-100
import unittest
import ctypes as ct
from ctree.c.nodes import *
class TestSymbols(unittest.TestCase):
def _check(self, actual, expected):
self.assertEqual(actual.codegen(), expected)
def test_symbolref(self):
ref = SymbolRef("foo")
self._check(ref, "foo")
def test_init_local(self):
ref = SymbolRef("foo", _local=True)
self._check(ref, "__local foo")
def test_init_const(self):
ref = SymbolRef("foo", _const=True)
self._check(ref, "const foo")
def test_set_local(self):
ref = SymbolRef("foo")
ref.set_local()
self._check(ref, "__local foo")
def test_set_const(self):
ref = SymbolRef("foo")
ref.set_const()
self._check(ref, "const foo")
def test_set_global(self):
ref = SymbolRef("foo")
ref.set_global()
self._check(ref, "__global foo")
def test_unique(self):
ref1 = SymbolRef.unique("foo", ct.c_int())
ref2 = SymbolRef.unique("foo", ct.c_int())
self.assertNotEqual(ref1.codegen(), ref2.codegen())
def test_copy(self):
ref1 = SymbolRef("foo")
ref2 = ref1.copy()
self._check(ref1, ref2.codegen(()))
def test_copy_without_declare(self):
ref1 = SymbolRef("foo", ct.c_int())
ref2 = ref1.copy()
self._check(ref2, "foo")
def test_copy_with_declare(self):
ref1 = SymbolRef("foo", ct.c_float())
ref2 = ref1.copy(declare=True)
self._check(ref2, "float foo")
| StarcoderdataPython |
8192514 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from . import utilities, tables
class GetInstanceTypeResult:
"""
A collection of values returned by getInstanceType.
"""
def __init__(__self__, addons=None, class_=None, disk=None, id=None, label=None, memory=None, network_out=None, price=None, transfer=None, vcpus=None):
if addons and not isinstance(addons, dict):
raise TypeError("Expected argument 'addons' to be a dict")
__self__.addons = addons
if class_ and not isinstance(class_, str):
raise TypeError("Expected argument 'class_' to be a str")
__self__.class_ = class_
if disk and not isinstance(disk, float):
raise TypeError("Expected argument 'disk' to be a float")
__self__.disk = disk
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
__self__.id = id
if label and not isinstance(label, str):
raise TypeError("Expected argument 'label' to be a str")
__self__.label = label
if memory and not isinstance(memory, float):
raise TypeError("Expected argument 'memory' to be a float")
__self__.memory = memory
if network_out and not isinstance(network_out, float):
raise TypeError("Expected argument 'network_out' to be a float")
__self__.network_out = network_out
if price and not isinstance(price, dict):
raise TypeError("Expected argument 'price' to be a dict")
__self__.price = price
if transfer and not isinstance(transfer, float):
raise TypeError("Expected argument 'transfer' to be a float")
__self__.transfer = transfer
if vcpus and not isinstance(vcpus, float):
raise TypeError("Expected argument 'vcpus' to be a float")
__self__.vcpus = vcpus
class AwaitableGetInstanceTypeResult(GetInstanceTypeResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetInstanceTypeResult(
addons=self.addons,
class_=self.class_,
disk=self.disk,
id=self.id,
label=self.label,
memory=self.memory,
network_out=self.network_out,
price=self.price,
transfer=self.transfer,
vcpus=self.vcpus)
def get_instance_type(id=None,label=None,opts=None):
"""
Provides information about a Linode instance type
## Attributes
The Linode Instance Type resource exports the following attributes:
* `id` - The ID representing the Linode Type
* `label` - The Linode Type's label is for display purposes only
* `class` - The class of the Linode Type
* `disk` - The Disk size, in MB, of the Linode Type
* `price.0.hourly` - Cost (in US dollars) per hour.
* `price.0.monthly` - Cost (in US dollars) per month.
* `addons.0.backups.0.price.0.hourly` - The cost (in US dollars) per hour to add Backups service.
* `addons.0.backups.0.price.0.monthly` - The cost (in US dollars) per month to add Backups service.
:param str id: Label used to identify instance type
> This content is derived from https://github.com/terraform-providers/terraform-provider-linode/blob/master/website/docs/d/instance_type.html.markdown.
"""
__args__ = dict()
__args__['id'] = id
__args__['label'] = label
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = utilities.get_version()
__ret__ = pulumi.runtime.invoke('linode:index/getInstanceType:getInstanceType', __args__, opts=opts).value
return AwaitableGetInstanceTypeResult(
addons=__ret__.get('addons'),
class_=__ret__.get('class'),
disk=__ret__.get('disk'),
id=__ret__.get('id'),
label=__ret__.get('label'),
memory=__ret__.get('memory'),
network_out=__ret__.get('networkOut'),
price=__ret__.get('price'),
transfer=__ret__.get('transfer'),
vcpus=__ret__.get('vcpus'))
| StarcoderdataPython |
164152 | <gh_stars>0
import machine, network, ubinascii, ujson, urequests
WiFi = network.WLAN(network.STA_IF)
mac = ubinascii.hexlify(network.WLAN().config("mac"),":").decode()
print("MAC address: " + mac)
def connect():
import network, utime
WiFi = network.WLAN(network.STA_IF)
if not WiFi.isconnected():
print ("Connecting ..")
WiFi.active(True)
WiFi.connect("Tufts_Wireless","")
i=0
while i < 25 and not WiFi.isconnected():
utime.sleep_ms(200)
i=i+1
if WiFi.isconnected():
print ("Connection succeeded")
else:
print ("Connection failed")
else:
print ("Network Settings:", WiFi.ifconfig())
connect()
print ("WiFi: ",WiFi.isconnected())
# Info
Tag = "test"
Type = "STRING"
Value = "0.000000"
urlBase = "https://api.systemlinkcloud.com/nitag/v2/tags/"
urlTag = urlBase + Tag
urlValue = urlBase + Tag + "/values/current"
headers = {"Content-Type":"application/json","Accept":"application/json","x-ni-api-key":"<KEY>"}
propName={"type":Type,"path":Tag}
propValue = {"value":{"type":Type,"value":Value}}
# PUT
print(urequests.put(urlTag,headers=headers,json=propName).text)
print(urequests.put(urlValue,headers=headers,json=propValue).text)
# Info
Tag = "test"
Type = "STRING"
Value = "0.000000"
urlBase = "https://api.systemlinkcloud.com/nitag/v2/tags/"
urlTag = urlBase + Tag
urlValue = urlBase + Tag + "/values/current"
headers = {"Content-Type":"application/json","Accept":"application/json","x-ni-api-key":"<KEY>"}
propName={"type":Type,"path":Tag}
propValue = {"value":{"type":Type,"value":Value}}
## GET
value = urequests.get(urlValue,headers=headers).text
data = ujson.loads(value)
result = data.get("value").get("value")
print ("value = ",result)
| StarcoderdataPython |
244390 | # -*- coding: utf-8 -*-
import re
# All of the variables available in a PKGBUILD
PB_VARIABLES = [
# String variables
'pkgver', 'pkgrel', 'pkgdesc', 'url', 'epoch', 'pkgbase',
# Bash Array variables
'pkgname', 'license', 'source', 'groups', 'arch', 'depends',
'makedepends', 'checkdepends', 'optdepends', 'options', 'backup',
'provides', 'replaces', 'conflicts', ]
PB_SEARCH = {
# Mostly single line variables
# Note, most of these won't get anything if they are part of an 'if'
# statement in the PKGBUILD.
'pkgver': re.compile(r'^\s*pkgver=([^ \n]+)', re.M | re.S),
'pkgrel': re.compile(r'^\s*pkgrel=([^ \n]+)', re.M | re.S),
'epoch': re.compile(r'^\s*epoch=([^ \n]+)', re.M | re.S),
'url': re.compile(r'^\s*url=([^ \n]+)', re.M | re.S),
'pkgdesc': re.compile(r'^\s*pkgdesc=([^\n]+)', re.M | re.S),
'pkgbase': re.compile(r'^\s*pkgbase=([^ \n]+)', re.M | re.S),
# Array vareable finding and parsing. Possibly multi-line
'pkgname': re.compile(r'^\s*pkgname=\(?([^\)\n]+)[)\n]', re.M | re.S),
'license': re.compile(r'^\s*license=\(([^\)]+)\)', re.M | re.S),
'depends': re.compile(r'^\s*depends=\(([^\)]+)\)', re.M | re.S),
'makedepends': re.compile(r'^\s*makedepends=\(([^\)]+)\)', re.M | re.S),
'checkdepends': re.compile(r'^\s*checkdepends=\(([^\)]+)\)', re.M | re.S),
'optdepends': re.compile(r'^\s*optdepends=\(([^\)]+)\)', re.M | re.S),
'source': re.compile(r'^\s*source=\(([^\)]+)\)', re.M | re.S),
'groups': re.compile(r'^\s*groups=\(([^\)]+)\)', re.M | re.S),
'arch': re.compile(r'^\s*arch=\(([^\)]+)\)', re.M | re.S),
'options': re.compile(r'^\s*options=\(([^\)]+)\)', re.M | re.S),
'backup': re.compile(r'^\s*backup=\(([^\)]+)\)', re.M | re.S),
'provides': re.compile(r'^\s*provides=\(([^\)]+)\)', re.M | re.S),
'replaces': re.compile(r'^\s*replaces=\(([^\)]+)\)', re.M | re.S),
'conflicts': re.compile(r'^\s*conflicts=\(([^\)]+)\)', re.M | re.S), }
PRINTER_CATEGORIES = {
1: 'None',
2: 'daemons',
3: 'devel',
4: 'editors',
5: 'emulators',
6: 'games',
7: 'gnome',
8: 'i18n',
9: 'kde',
10: 'lib',
11: 'modules',
12: 'multimedia',
13: 'network',
14: 'office',
15: 'science',
16: 'system',
17: 'X11',
18: 'xfce',
19: 'kernels', }
PRINTER_FORMAT_STRINGS = {
'a': 'LastModified',
'c': 'CategoryID',
'd': 'Description',
'i': 'ID',
'l': 'License',
'm': 'Maintainer',
'n': 'Name',
'o': 'NumVotes',
'p': 'URLPath',
's': 'FirstSubmitted',
't': 'OutOfDate',
'u': 'URL',
'v': 'Version',
'%': '%', }
PRINTER_INFO_FORMAT_STRINGS = {
'p': 'AUR Page', # Replaces URLPath
'S': 'Submitted',
'A': 'Last Modified', # Times in nice format
'T': 'OutOfDate', }
PRINTER_INFO_INFO_FORMAT_STRINGS = { # Added stuff for full info stuff
'C': 'Conflicts With',
'D': 'Depends On',
'M': 'Makedepends',
'O': 'Optional Deps',
'P': 'Provides',
'R': 'Replaces', }
REPO_LOCAL_VARIABLES = [
'NAME',
'VERSION',
'BASE',
'DESC',
'URL',
'ARCH',
'BUILDDATE',
'INSTALLDATE',
'PACKAGER',
'SIZE',
'DEPENDS',
'LICENSE',
'VALIDATION',
'REPLACES',
'OPTDEPENDS',
'CONFLICTS',
'PROVIDES', ]
REPO_SYNC_VARIABLES = [
'FILENAME',
'NAME',
'BASE',
'VERSION',
'DESC',
'CSIZE',
'ISIZE',
'URL',
'LICENSE',
'ARCH',
'BUILDDATE',
'PACKAGER',
'REPLACES',
# In the desc file
'DEPENDS',
'CONFLICTS',
'PROVIDES',
'OPTDEPENDS',
'MAKEDEPENDS', ]
| StarcoderdataPython |
9719582 | <reponame>marstr/azure-cli-dev-tools
# -----------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -----------------------------------------------------------------------------
import re
from knack.log import get_logger
from knack.util import CLIError
from azdev.utilities import (
display, heading, subheading, cmd, require_azure_cli)
logger = get_logger(__name__)
TOTAL = 'ALL'
DEFAULT_THRESHOLD = 10
# TODO: Treat everything as bubble instead of specific modules
# explicit thresholds that deviate from the default
THRESHOLDS = {
'network': 30,
'vm': 30,
'batch': 30,
'storage': 50,
TOTAL: 300
}
def check_load_time(runs=3):
require_azure_cli()
heading('Module Load Performance')
regex = r"[^']*'([^']*)'[\D]*([\d\.]*)"
results = {TOTAL: []}
# Time the module loading X times
for i in range(0, runs + 1):
lines = cmd('az -h --debug', show_stderr=True).result
if i == 0:
# Ignore the first run since it can be longer due to *.pyc file compilation
continue
try:
lines = lines.decode().splitlines()
except AttributeError:
lines = lines.splitlines()
total_time = 0
for line in lines:
if line.startswith('DEBUG: Loaded module'):
matches = re.match(regex, line)
mod = matches.group(1)
val = float(matches.group(2)) * 1000
total_time = total_time + val
if mod in results:
results[mod].append(val)
else:
results[mod] = [val]
results[TOTAL].append(total_time)
passed_mods = {}
failed_mods = {}
mods = sorted(results.keys())
bubble_found = False
for mod in mods:
val = results[mod]
mean_val = mean(val)
stdev_val = pstdev(val)
threshold = THRESHOLDS.get(mod) or DEFAULT_THRESHOLD
statistics = {
'average': mean_val,
'stdev': stdev_val,
'threshold': threshold,
'values': val
}
if mean_val > threshold:
if not bubble_found and mean_val < 30:
# This temporary measure allows one floating performance
# failure up to 30 ms. See issue #6224 and #6218.
bubble_found = True
passed_mods[mod] = statistics
else:
failed_mods[mod] = statistics
else:
passed_mods[mod] = statistics
subheading('Results')
if failed_mods:
display('== PASSED MODULES ==')
display_table(passed_mods)
display('\nFAILED MODULES')
display_table(failed_mods)
raise CLIError("""
FAILED: Some modules failed. If values are close to the threshold, rerun. If values
are large, check that you do not have top-level imports like azure.mgmt or msrestazure
in any modified files.
""")
display('== PASSED MODULES ==')
display_table(passed_mods)
display('\nPASSED: Average load time all modules: {} ms'.format(
int(passed_mods[TOTAL]['average'])))
def mean(data):
"""Return the sample arithmetic mean of data."""
n = len(data)
if n < 1:
raise ValueError('len < 1')
return sum(data) / float(n)
def sq_deviation(data):
"""Return sum of square deviations of sequence data."""
c = mean(data)
return sum((x - c) ** 2 for x in data)
def pstdev(data):
"""Calculates the population standard deviation."""
n = len(data)
if n < 2:
raise ValueError('len < 2')
ss = sq_deviation(data)
return (ss / n) ** 0.5
def display_table(data):
display('{:<20} {:>12} {:>12} {:>12} {:>25}'.format('Module', 'Average', 'Threshold', 'Stdev', 'Values'))
for key, val in data.items():
display('{:<20} {:>12.0f} {:>12.0f} {:>12.0f} {:>25}'.format(
key, val['average'], val['threshold'], val['stdev'], str(val['values'])))
| StarcoderdataPython |
4974001 | import hashlib
import json
from time import time
from uuid import uuid4
from urllib.parse import urlparse
import requests
class Blockchain(object):
def __init__(self):
# Initiates the blockchain
self.chain = []
self.current_transactions = []
# Creating a genesis block
self.new_block(previous_hash=1, proof=100)
# Unique nodes
self.nodes = set()
def new_block(self, proof, previous_hash=None):
'''
Adds new block to the chain
:param proof: <int> The proof provided by Proof of Work algorithm
:param previous_hash: (Optional) <str> Hash of previous block
:return: <dict> New block
'''
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.chain[-1]),
}
# Resetting the current list of transactions
self.current_transactions = []
self.chain.append(block)
return block
def new_transaction(self, sender, recipient, amount):
'''
Creates a new transaction to move to the newly mined block
:param sender: <str> Address of the sender
:param recipient: <str> Address of the recipient
:param amount: <int> Amount transfered
:return: <int> Index of the block that will hold this transaction (New block)
'''
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount,
})
return self.last_block['index'] + 1
@staticmethod
def hash(block):
'''
Adds hashing to the newly added block (SHA-256 hashing alogrithm)
:param block: <dict> Newly created block to which hashing needs to be added
:return: <str>
'''
# Sorting keys to prevent inconsistent hashing
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
@property
def last_block(self):
# Returns the last block in the chain
return self.chain[-1]
def proof_of_work(self, last_proof):
'''
Proof of Work Algorithm to check the validity of provided solution by miner to mine new block
- Find a number p' such that hash(pp') contains leading numbers as 2711, where p is the previous p'
- p is the previous proof and p' is the new proof
:param last_proof: <int>
:return: <int>
'''
proof = 0
while self.valid_proof(last_proof, proof) is False:
proof += 1
return proof
@staticmethod
def valid_proof(last_proof, proof):
'''
Validates the proof: Does hash(last_proof,proof) contains leading digits as 2711 or not?
:param last_proof: <int> Previous proof
:param proof: <int> Current Proof
:return: <bool> True if correct, Fasle if algorithm isn't satisfied
'''
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == '2711'
def register_node(self, address):
"""
Add a new node to the list of nodes
:param address: <str> Address of node. Eg. 'http://192.168.0.5:5000'
:return: None
"""
parsed_url = urlparse(address)
self.nodes.add(parsed_url.netloc)
def valid_chain(self, chain):
"""
Determine if a given blockchain is valid
:param chain: <list> A blockchain
:return: <bool> True if valid, False if not
"""
last_block = chain[0]
current_index = 1
while current_index < len(chain):
block = chain[current_index]
print(f'{last_block}')
print(f'{block}')
print("\n-----------\n")
# Check that the hash of the block is correct
if block['previous_hash'] != self.hash(last_block):
return False
# Check that the Proof of Work is correct
if not self.valid_proof(last_block['proof'], block['proof']):
return False
last_block = block
current_index += 1
return True
def resolve_conflicts(self):
"""
This is the Consensus Algorithm, it resolves conflicts
by replacing the user's chain with the longest one in the network.
:return: <bool> True if our chain was replaced, False if not
"""
neighbours = self.nodes
new_chain = None
# We're only looking for chains longer than the main
max_length = len(self.chain)
# Grab and verify the chains from all the nodes in the network
for node in neighbours:
response = requests.get(f'http://{node}/chain')
if response.status_code == 200:
length = response.json()['length']
chain = response.json()['chain']
# Check if the length is longer and the chain is valid
if length > max_length and self.valid_chain(chain):
max_length = length
new_chain = chain
# Replace main chain if new valid longer chain is discovered
if new_chain:
self.chain = new_chain
return True
return False
| StarcoderdataPython |
6658877 | """
Comparing optimizers
=====================
Comparison of optimizers on various problems.
"""
import functools
import pickle
import numpy as np
from scipy import optimize
from joblib import Memory
from cost_functions import mk_quad, mk_gauss, rosenbrock,\
rosenbrock_prime, rosenbrock_hessian, LoggingFunction, \
CountingFunction
def my_partial(function, **kwargs):
f = functools.partial(function, **kwargs)
functools.update_wrapper(f, function)
return f
methods = {
'Nelder-mead': my_partial(optimize.fmin,
ftol=1e-12, maxiter=5e3,
xtol=1e-7, maxfun=1e6),
'Powell': my_partial(optimize.fmin_powell,
ftol=1e-9, maxiter=5e3,
maxfun=1e7),
'BFGS': my_partial(optimize.fmin_bfgs,
gtol=1e-9, maxiter=5e3),
'Newton': my_partial(optimize.fmin_ncg,
avextol=1e-7, maxiter=5e3),
'Conjugate gradient': my_partial(optimize.fmin_cg,
gtol=1e-7, maxiter=5e3),
'L-BFGS': my_partial(optimize.fmin_l_bfgs_b,
approx_grad=1, factr=10.0,
pgtol=1e-8, maxfun=1e7),
"L-BFGS w f'": my_partial(optimize.fmin_l_bfgs_b,
factr=10.0,
pgtol=1e-8, maxfun=1e7),
}
###############################################################################
def bencher(cost_name, ndim, method_name, x0):
cost_function = mk_costs(ndim)[0][cost_name][0]
method = methods[method_name]
f = LoggingFunction(cost_function)
method(f, x0)
this_costs = np.array(f.all_f_i)
return this_costs
# Bench with gradients
def bencher_gradient(cost_name, ndim, method_name, x0):
cost_function, cost_function_prime, hessian = mk_costs(ndim)[0][cost_name]
method = methods[method_name]
f_prime = CountingFunction(cost_function_prime)
f = LoggingFunction(cost_function, counter=f_prime.counter)
method(f, x0, f_prime)
this_costs = np.array(f.all_f_i)
return this_costs, np.array(f.counts)
# Bench with the hessian
def bencher_hessian(cost_name, ndim, method_name, x0):
cost_function, cost_function_prime, hessian = mk_costs(ndim)[0][cost_name]
method = methods[method_name]
f_prime = CountingFunction(cost_function_prime)
hessian = CountingFunction(hessian, counter=f_prime.counter)
f = LoggingFunction(cost_function, counter=f_prime.counter)
method(f, x0, f_prime, fhess=hessian)
this_costs = np.array(f.all_f_i)
return this_costs, np.array(f.counts)
def mk_costs(ndim=2):
costs = {
'Well-conditioned quadratic': mk_quad(.7, ndim=ndim),
'Ill-conditioned quadratic': mk_quad(.02, ndim=ndim),
'Well-conditioned Gaussian': mk_gauss(.7, ndim=ndim),
'Ill-conditioned Gaussian': mk_gauss(.02, ndim=ndim),
'Rosenbrock ': (rosenbrock, rosenbrock_prime, rosenbrock_hessian),
}
rng = np.random.RandomState(0)
starting_points = 4*rng.rand(20, ndim) - 2
if ndim > 100:
starting_points = starting_points[:10]
return costs, starting_points
###############################################################################
# Compare methods without gradient
mem = Memory('.', verbose=3)
if 1:
gradient_less_benchs = dict()
for ndim in (2, 8, 32, 128):
this_dim_benchs = dict()
costs, starting_points = mk_costs(ndim)
for cost_name, cost_function in costs.iteritems():
# We don't need the derivative or the hessian
cost_function = cost_function[0]
function_bench = dict()
for x0 in starting_points:
all_bench = list()
# Bench gradient-less
for method_name, method in methods.iteritems():
if method_name in ('Newton', "L-BFGS w f'"):
continue
this_bench = function_bench.get(method_name, list())
this_costs = mem.cache(bencher)(cost_name, ndim,
method_name, x0)
if np.all(this_costs > .25*ndim**2*1e-9):
convergence = 2*len(this_costs)
else:
convergence = np.where(
np.diff(this_costs > .25*ndim**2*1e-9)
)[0].max() + 1
this_bench.append(convergence)
all_bench.append(convergence)
function_bench[method_name] = this_bench
# Bench with gradients
for method_name, method in methods.iteritems():
if method_name in ('Newton', 'Powell', 'Nelder-mead',
"L-BFGS"):
continue
this_method_name = method_name
if method_name.endswith(" w f'"):
this_method_name = method_name[:-4]
this_method_name = this_method_name + "\nw f'"
this_bench = function_bench.get(this_method_name, list())
this_costs, this_counts = mem.cache(bencher_gradient)(
cost_name, ndim, method_name, x0)
if np.all(this_costs > .25*ndim**2*1e-9):
convergence = 2*this_counts.max()
else:
convergence = np.where(
np.diff(this_costs > .25*ndim**2*1e-9)
)[0].max() + 1
convergence = this_counts[convergence]
this_bench.append(convergence)
all_bench.append(convergence)
function_bench[this_method_name] = this_bench
# Bench Newton with Hessian
method_name = 'Newton'
this_bench = function_bench.get(method_name, list())
this_costs = mem.cache(bencher_hessian)(cost_name, ndim,
method_name, x0)
if np.all(this_costs > .25*ndim**2*1e-9):
convergence = 2*len(this_costs)
else:
convergence = np.where(
np.diff(this_costs > .25*ndim**2*1e-9)
)[0].max() + 1
this_bench.append(convergence)
all_bench.append(convergence)
function_bench[method_name + '\nw Hessian '] = this_bench
# Normalize across methods
x0_mean = np.mean(all_bench)
for method_name in function_bench:
function_bench[method_name][-1] /= x0_mean
this_dim_benchs[cost_name] = function_bench
gradient_less_benchs[ndim] = this_dim_benchs
print 80*'_'
print 'Done cost %s, ndim %s' % (cost_name, ndim)
print 80*'_'
pickle.dump(gradient_less_benchs, file('compare_optimizers.pkl', 'w'))
| StarcoderdataPython |
11278559 | <reponame>raufer/pytheater
from pytheater.actor import Actor
class AnonymousActor(Actor):
async def receive(self, message, sender=None):
return message
| StarcoderdataPython |
3231783 | '''
Created on Nov 12, 2016
@author: jeanl
'''
import FlightDB as fDB
from Midterm_Graph import *
DBAddress = './Database/Graph.db'
AirAddress = './Database/AirportData.csv'
FlyAddress = './Database/FlightData.csv'
folder_name = './Database'
# Make a Database
database = fDB.FlightDB(folder_name)
GraphAddress = 'C:\Users\jeanl\workspace\CEE505 Midterm\src\Database'
# Try finding routes
g = Midterm_Graph(GraphAddress)
g.findPaths('MIA','SEA')
#print "Shortest Path"
#print g.findShortestPath('LGA', 'SFO')
print "Longest Path"
print g.findLongestPath('MIA','SEA')
| StarcoderdataPython |
9692336 | <gh_stars>1000+
import collections
import os
import six
import yaml
from copy import deepcopy
from geodata.address_formatting.formatter import AddressFormatter
from geodata.configs.utils import recursive_merge, DoesNotExist
from geodata.encoding import safe_encode
this_dir = os.path.realpath(os.path.dirname(__file__))
OSM_BOUNDARIES_DIR = os.path.join(this_dir, os.pardir, os.pardir, os.pardir,
'resources', 'boundaries', 'osm')
class OSMAddressComponents(object):
'''
Keeps a map of OSM keys and values to the standard components
of an address like city, state, etc. used for address formatting.
When we reverse geocode a point, it will fall into a number of
polygons, and we simply need to assign the names of said polygons
to an address field.
'''
ADMIN_LEVEL = 'admin_level'
# These keys override country-level
global_keys_override = {
'place': {
'island': AddressFormatter.ISLAND,
'islet': AddressFormatter.ISLAND,
'municipality': AddressFormatter.CITY,
'city': AddressFormatter.CITY,
'town': AddressFormatter.CITY,
'township': AddressFormatter.CITY,
'village': AddressFormatter.CITY,
'hamlet': AddressFormatter.CITY,
'suburb': AddressFormatter.SUBURB,
'quarter': AddressFormatter.SUBURB,
'neighbourhood': AddressFormatter.SUBURB
},
'border_type': {
'city': AddressFormatter.CITY
}
}
# These keys are fallback in case we haven't added a country or there is no admin_level=
global_keys = {
'place': {
'country': AddressFormatter.COUNTRY,
'state': AddressFormatter.STATE,
'region': AddressFormatter.STATE,
'province': AddressFormatter.STATE,
'county': AddressFormatter.STATE_DISTRICT,
},
'gnis:class': {
'populated place': AddressFormatter.CITY,
}
}
def __init__(self, boundaries_dir=OSM_BOUNDARIES_DIR):
self.config = {}
self.use_admin_center = {}
for filename in os.listdir(boundaries_dir):
if not filename.endswith('.yaml'):
continue
country_code = filename.rsplit('.yaml', 1)[0]
data = yaml.load(open(os.path.join(boundaries_dir, filename)))
for prop, values in six.iteritems(data):
if not hasattr(values, 'items'):
# non-dict key
continue
for k, v in values.iteritems():
if isinstance(v, six.string_types) and v not in AddressFormatter.address_formatter_fields:
raise ValueError(u'Invalid value in {} for prop={}, key={}: {}'.format(filename, prop, k, v))
if prop == 'overrides':
self.use_admin_center.update({(r['type'], safe_encode(r['id'])): r.get('probability', 1.0) for r in values.get('use_admin_center', [])})
containing_overrides = values.get('contained_by', {})
if not containing_overrides:
continue
for id_type, vals in six.iteritems(containing_overrides):
for element_id in vals:
override_config = vals[element_id]
config = deepcopy(data)
config.pop('overrides')
recursive_merge(config, override_config)
vals[element_id] = config
self.config[country_code] = data
def component(self, country, prop, value):
component = self.global_keys_override.get(prop, {}).get(value, None)
if component is not None:
return component
component = self.config.get(country, {}).get(prop, {}).get(value, None)
if component is not None:
return component
return self.global_keys.get(prop, {}).get(value, None)
def component_from_properties(self, country, properties, containing=(), global_keys=True):
country_config = self.config.get(country, {})
config = country_config
overrides = country_config.get('overrides')
if overrides:
id_overrides = overrides.get('id', {})
element_type = properties.get('type')
element_id = properties.get('id')
override_value = id_overrides.get(element_type, {})
element_id = six.binary_type(element_id or '')
if element_id in override_value:
return override_value[element_id]
contained_by_overrides = overrides.get('contained_by')
if contained_by_overrides and containing:
# Note, containing should be passed in from smallest to largest
for containing_type, containing_id in containing:
override_config = contained_by_overrides.get(containing_type, {}).get(six.binary_type(containing_id or ''), None)
if override_config:
config = override_config
break
values = [(k.lower(), v.lower()) for k, v in six.iteritems(properties) if isinstance(v, six.string_types)]
global_overrides_last = config.get('global_overrides_last', False)
# place=city, place=suburb, etc. override per-country boundaries
if not global_overrides_last:
for k, v in values:
containing_component = self.global_keys_override.get(k, {}).get(v, DoesNotExist)
if containing_component is not DoesNotExist:
return containing_component
if k != self.ADMIN_LEVEL and k in config:
containing_component = config.get(k, {}).get(v, DoesNotExist)
if containing_component is not DoesNotExist:
return containing_component
# admin_level tags are mapped per country
for k, v in values:
containing_component = config.get(k, {}).get(v, DoesNotExist)
if containing_component is not DoesNotExist:
return containing_component
# other place keys like place=state, etc. serve as a backup
# when no admin_level tags are available
for k, v in values:
containing_component = self.global_keys.get(k, {}).get(v, DoesNotExist)
if containing_component is not DoesNotExist:
return containing_component
if global_overrides_last:
for k, v in values:
containing_component = self.global_keys_override.get(k, {}).get(v, DoesNotExist)
if containing_component is not DoesNotExist:
return containing_component
return None
osm_address_components = OSMAddressComponents()
| StarcoderdataPython |
9778361 | import __main__
from threading import Thread
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
from gi.repository import GObject
try:
DBusGMainLoop(set_as_default=True)
GObject.threads_init()
dbus.mainloop.glib.threads_init()
dbus_loop = DBusGMainLoop()
DBUS_BUS = dbus.SystemBus(mainloop=dbus_loop)
MAINLOOP = GLib.MainLoop()
DBUS_THREAD = Thread(target=MAINLOOP.run, daemon=True)
DBUS_THREAD.start()
except:
print("Error Loading DBus, functionality will be reduced!")
| StarcoderdataPython |
286051 | #Shipping Accounts App
#Define list of users
users = ['eramom', 'footea', 'davisv', 'papinukt', 'allenj', 'eliasro']
print("Welcome to the Shipping Accounts Program.")
#Get user input
username = input("\nHello, what is your username: ").lower().strip()
#User is in list....
if username in users:
#print a price summary
print("\nHello " + username + ". Welcome back to your account.")
print("Current shipping prices are as follows:")
print("\nShipping orders 0 to 100: \t\t$5.10 each")
print("Shipping orders 100 to 500: \t\t$5.00 each")
print("Shipping orders 500 to 1000 \t\t$4.95 each")
print("Shipping orders over 1000: \t\t$4.80 each")
#Determine price based on how many items are shipped
quantity = int(input("\nHow many items would you like to ship: "))
if quantity < 100:
cost = 5.10
elif quantity < 500:
cost = 5.00
elif quantity < 1000:
cost = 4.95
else:
cost = 4.80
#Display final cost
bill = quantity*cost
bill = round(bill, 2)
print("To ship " + str(quantity) + " items it will cost you $" +str(bill) + " at $" + str(cost) + " per item.")
#Place order
choice = input("\nWould you like to place this order (y/n): ").lower()
if choice.startswith('y'):
print("OKAY. Shipping your " + str(quantity) + " items.")
else:
print("OKAY, no order is being placed at this time.")
#The user is not in the list
else:
print("Sorry, you do not have an account with us. Goodbye...") | StarcoderdataPython |
8171230 | <filename>all.py
# all.py made for the DSS project.
# Written by A.E.A.E, To be committed on Github
# Imports
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# Importing our dataset
digits = load_digits()
# Allocating x,y to our data,target (respectively)
x = digits.data
y = digits.target
# Creating our training/test sets.
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, stratify=y, random_state=0)
# Classifying the LogisticRegression % fitting to train
classifier1 = LogisticRegression(C=0.01, multi_class="auto", random_state=0)
classifier2 = KNeighborsClassifier(n_neighbors=2, metric='minkowski', p=2)
classifier3 = DecisionTreeClassifier(max_depth=14, random_state=0)
classifier1.fit(x_train, y_train)
classifier2.fit(x_train, y_train)
classifier3.fit(x_train, y_train)
# Running Predictions
print("Running Predictions with classifiers:\n")
pred = classifier1.predict(x_test[0].reshape(1, -1))
print("(Testing LogisticRegression: predicted: ", pred[0], ", Actual result: ", y_test[0])
pred = classifier2.predict(x_test[0].reshape(1, -1))
print("Testing K-NN: predicted: ", pred[0], ", Actual result: ", y_test[0])
pred = classifier3.predict(x_test[0].reshape(1, -1))
print("Testing DecisionTree: predicted: ", pred[0], ", Actual result: ", y_test[0])
print("========================")
# Checking Accuracy
print("Checking Accuracy with classifiers\n")
acc1 = classifier1.score(x_train, y_train)
print("[LogisticReg] Model Accuracy(train):", acc1*100)
acc2 = classifier1.score(x_test, y_test)
print("[LogisticReg] Model Accuracy(test):", acc2*100)
print("========================")
acc1 = classifier2.score(x_train, y_train)
print("[K-NN] Model Accuracy(train):", acc1*100)
acc2 = classifier2.score(x_test, y_test)
print("[K-NN] Model Accuracy(test):", acc2*100)
print("========================")
acc1 = classifier3.score(x_train, y_train)
print("[DecisionTree] Model Accuracy(train):", acc1*100)
acc2 = classifier3.score(x_test, y_test)
print("[DecisionTree] Model Accuracy(test):", acc2*100)
test_accuracy = []
ctest = np.arange(0.1, 5, 0.1)
for c in ctest:
clf = LogisticRegression(solver='liblinear', C=c, multi_class="auto", random_state=0)
clf.fit(x,y)
test_accuracy.append(clf.score(x_test, y_test))
plt.plot(ctest, test_accuracy, label='Accuracy of the test set')
plt.ylabel('Accuracy')
plt.legend()
plt.show() | StarcoderdataPython |
5044605 | nombre = 'Soto'
lugar = 'San Telmo'
hora = '3 de la mañana'
comida = 'mondiola'
# los %s sereemplazan con las cadenas del final, en el orden en que aparecen.
print('Hola, %s, te invito a una fiesta en %s, mañana a las %s. Traé %s.' % (nombre, lugar, hora, comida))
| StarcoderdataPython |
5073587 | <filename>team7/notmain.py<gh_stars>1-10
import webbrowser
webbrowser.open("https://www.youtube.com/watch?v=z8ZqFlw6hYg")
while True:
print("ValueError: ctypes objects containing pointers cannot be pickled")
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.