content
stringlengths 0
894k
| type
stringclasses 2
values |
---|---|
import torch
import torch.nn as nn
import torch.nn.functional as F
class GraphAttentionLayer(nn.Module):
"""
Simple GAT layer, similar to https://arxiv.org/abs/1710.10903
"""
def __init__(self, in_features, out_features, dropout, alpha, concat=True, drop_enc=False):
super(GraphAttentionLayer, self).__init__()
self.dropout = dropout
self.in_features = in_features
self.out_features = out_features
self.alpha = alpha
self.concat = concat
self.drop_enc = drop_enc
# dimension of W is (d, d')
self.W = nn.Parameter(torch.zeros(size=(in_features, out_features)))
nn.init.xavier_uniform_(self.W.data, gain=1.414)
self.a = nn.Parameter(torch.zeros(size=(2*out_features, 1)))
nn.init.xavier_uniform_(self.a.data, gain=1.414)
self.leakyrelu = nn.LeakyReLU(self.alpha)
def forward(self, input, adj, serv_emb):
"""
input is initialized doctor embedding, dim = (N, d)
adj is the list of services done by each doctor, dim = (N,)
serv_emb is the embedding matrix of all services, dim = (K, d)
h_prime is the new doctor embedding, dim = (N, d)
"""
N, d = input.size()
num_svc = serv_emb.size()[0]
h_doc = torch.mm(input, self.W)
h_svc = torch.mm(serv_emb, self.W)
a_input = torch.cat((h_doc.repeat(1, num_svc).view(N * num_svc, -1),
h_svc.repeat(N, 1)), dim=1).view(N, -1, 2 * self.out_features)
e = self.leakyrelu(torch.matmul(a_input, self.a).squeeze(2))
zero_vec = -9e15 * torch.ones_like(e)
attention = torch.where(adj > 0, e, zero_vec)
attention = F.softmax(attention, dim=1)
if self.drop_enc:
attention = F.dropout(attention, self.dropout, training=self.training)
h_prime = torch.matmul(attention, h_svc)
if self.concat:
return F.elu(h_prime)
else:
return h_prime
|
python
|
from FrameLibDocs.utils import read_json, write_json
from FrameLibDocs.variables import help_dir, current_version
def main():
template_dir = help_dir / "templates"
internal_dir = help_dir / "internal_tabs"
external_dir = current_version / "FrameLib" / "externals"
master_template = help_dir / "help_template.maxhelp"
templates = [x for x in template_dir.rglob("fl.*.maxhelp")]
for t in templates:
try:
template = read_json(t)
tabs = read_json(internal_dir / t.name)
except FileNotFoundError:
print(f'Ignoring {t.stem} wthout internal tabs')
else:
tabs_boxes = tabs["patcher"]["boxes"]
for box in tabs_boxes:
template["patcher"]["boxes"].append(box)
write_json(template_dir / t.name, template)
if __name__ == "__main__":
main()
|
python
|
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
import inspect
import multiprocessing
from typing import Tuple, Callable, Union, List, Type, Optional
import numpy as np
import tensorflow as tf
from absl import flags
import objax
from examples.fixmatch.libml.augment import ctaugment
from examples.fixmatch.libml.augment.core import get_tf_augment
from examples.fixmatch.libml.data import core
FLAGS = flags.FLAGS
flags.DEFINE_string(
'augment', 'CTA(sm,sm,sm)',
'Dataset augmentation method:\n'
' Augmentation primitives:\n'
' x = identity\n'
' m = mirror\n'
' s = shift\n'
' sc = shift+cutout\n'
' sm = shift+mirror\n'
' smc = shift+mirror+cutout\n'
'Augmentations:\n'
' (primitive,primitive,primitive) = Default augmentation (primitives for labeled, 1st unlabeled, 2nd unlabeled)\n'
' CTA(primitive,primitive,primitive,depth=int,th=float,decay=float) = CTAugment\n')
class AugmentPool:
NAME = ''
def __init__(self, labeled: core.DataSet, unlabeled: core.DataSet, nclass: int, batch: int, uratio: int,
tfops: Tuple[Callable, Callable, Callable], predict: Callable):
x = labeled.map(tfops[0], FLAGS.para_augment).batch(batch).nchw().one_hot(nclass)
u = unlabeled.map(lambda d: dict(image=tf.stack([tfops[1](d)['image'], tfops[2](d)['image']]),
index=d['index'], label=d['label']),
FLAGS.para_augment)
u = u.batch(batch * uratio).map(lambda d: dict(image=tf.transpose(d['image'], [0, 1, 4, 2, 3]),
index=d['index'], label=d['label']))
train = x.zip((x.data, u.data)).map(lambda x, u: dict(xindex=x['index'], x=x['image'], label=x['label'],
uindex=u['index'], u=u['image'], secret_label=u['label']))
self.train = core.Numpyfier(train.prefetch(16))
self.predict = predict
def __iter__(self):
return iter(self.train)
class AugmentPoolCTA(AugmentPool):
NAME = 'CTA'
def __init__(self, labeled: core.DataSet, unlabeled: core.DataSet, nclass: int, batch: int, uratio: int,
tfops: Tuple[Callable, Callable, Callable], predict: Callable,
depth: Union[int, str] = 2,
th: Union[float, str] = 0.8,
decay: Union[float, str] = 0.99):
super().__init__(labeled, unlabeled, nclass, batch, uratio, tfops, predict)
self.pool = multiprocessing.Pool(FLAGS.para_augment)
self.cta = ctaugment.CTAugment(int(depth), float(th), float(decay))
self.queue = []
@staticmethod
def numpy_apply_policies(x, u, cta: ctaugment.CTAugment):
x = objax.util.image.nhwc(x)
u = objax.util.image.nhwc(u)
nchw = objax.util.image.nchw
policy_list = [cta.policy(probe=True) for _ in range(x.shape[0])]
cutout_policy = lambda probe: cta.policy(probe=probe) + [ctaugment.OP('cutout', (1,))]
u_strong = np.stack([ctaugment.apply(u[i, 1], cutout_policy(False)) for i in range(u.shape[0])])
return dict(policy=policy_list,
probe=nchw(np.stack([ctaugment.apply(x[i], policy) for i, policy in enumerate(policy_list)])),
u=nchw(np.stack([u[:, 0], u_strong], axis=1)))
def __iter__(self):
for data in self.train:
self.queue.append((dict(xindex=data['xindex'], uindex=data['uindex'], x=data['x'],
label=data['label'], secret_label=data['secret_label']),
self.pool.apply_async(self.numpy_apply_policies, (data['x'], data['u'], self.cta))))
if len(self.queue) > 2 * FLAGS.para_augment:
d, pd = self.queue.pop(0)
d.update(pd.get())
probe = self.predict(d['probe'])
w1 = 1 - 0.5 * np.abs(probe - d['label']).sum(1)
for p in range(w1.shape[0]):
self.cta.update_rates(d['policy'][p], w1[p])
yield d
def get_augment(train: core.DataSet, extra: Optional[List[Type[AugmentPool]]] = None):
pool, a = FLAGS.augment.split('(')
a = a[:-1].split(',')
a, kwargs = a[:3], {k: v for k, v in (x.split('=') for x in a[3:])}
kwargs['tfops'] = tuple(get_tf_augment(ai, size=train.image_shape[0]) for ai in a)
for x in list(globals().values()) + (extra or []):
if inspect.isclass(x) and issubclass(x, AugmentPool):
if x.NAME == pool:
pool = x
return functools.partial(pool, **kwargs)
|
python
|
from mini_gplus.models import Media
def get_media(object_name):
return Media.objects.get(id=object_name)
def create_media(object_name):
media = Media()
media.id = object_name
# have to force save for some reason...
# https://github.com/MongoEngine/mongoengine/issues/1246
media.save(force_insert=True)
return media
|
python
|
# -*- coding: utf-8 -*-
"""Particle system Constraints objects
MIT License
Copyright (c) 2020 Mauro Lopez
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
SOFT
"""
class Constraint(object):
"""base particles constraint abstraction
"""
def solve(self):
"""this method will be called for the dynamic system to solve the costraints
between particles, this should be override by each Constraint instance
"""
raise NotImplementedError
class ParticleLink(Constraint):
"""connect two particles together in order to preserve the fixed distance between them
"""
def __init__(self, particleA, particleB, damping=.9):
self._particleA = particleA
self._particleB = particleB
self._damping = float(damping)
self._restLenght = self.getdistance()
def setDamping(self, damping):
"""how much the linked particule folow without delay
Args:
damping (float): value between 0-1
"""
if damping <=0:
damping = 0
self._damping = float(damping)
def setRestLenght(self, lenght):
"""set fixed distance between the particles
Args:
lenght (float): distance between the particles
"""
self._restLenght = float(lenght)
def getRestLeght(self):
"""get fixed distance between particles
Returns:
float
"""
return self._restLenght
def getdistance(self):
"""get current distance between particles
Returns:
float
"""
relativePos = self._particleB.getPosition() - self._particleA.getPosition()
return relativePos.magnitude()
def solve(self):
"""move particules preserving the rest distance, if the particles are
more far away then the rest distnce it will pull them closer, and vice versa
"""
if self._particleA.isPinned() and self._particleB.isPinned():
return
relativePos = self._particleB.getPosition() - self._particleA.getPosition()
distance = relativePos.magnitude()
direction = relativePos.normalize()
difference = abs(distance - self._restLenght)
if distance == self._restLenght:
direction *=0
elif (distance > self._restLenght):
direction *= -1
offset = .05
if self._particleA.isPinned() or self._particleB.isPinned():
offset = 1.0
movement = direction * difference * self._damping
if not self._particleA.isPinned():
self._particleA.addPosition(-movement*offset)
if not self._particleB.isPinned():
self._particleB.addPosition(movement*offset)
class ParticleSpring(Constraint):
"""connect two particles together in order to preserve the fixed distance between them
preserving the force created after get the fixed distance (streetch or compress force)
and aplying that force to the second paricule making it bounce
"""
def __init__(self, particleA, particleB, springStiffnes=.1, springDamping=.8):
self._particleA = particleA
self._particleB = particleB
self._springStiffnes = float(springStiffnes)
self._springDamping = float(springDamping)
self._restLenght = self.getdistance()
def setRestLenght(self, lenght):
"""set fixed distance between particles
Returns:
float
"""
self._restLenght = float(lenght)
def setStiffnes(self, stiffness):
"""set froce preservation value
Returns:
float
"""
self._springStiffnes = float(stiffness)
def getRestLeght(self):
"""get fixed distance between particles
Returns:
float
"""
return self._restLenght
def getdistance(self):
"""get current distance between particles
Returns:
float
"""
relativePos = self._particleB.getPosition() - self._particleA.getPosition()
return relativePos.magnitude()
def solve(self):
"""move particules preserving the rest distance, if the particles are
more far away then the rest distnce it will pull them closer, and vice versa
then apply the bounce force to the second particule
"""
if self._particleA.isPinned() and self._particleB.isPinned():
return
if self.getRestLeght() == 0:
self._particleB.setPosition(self._particleA.getPosition())
return
springVector = self._particleB.getPosition() - self._particleA.getPosition() # Vector Between The Two Masses
r = springVector.magnitude() # Distance Between The Two Masses
tension = r - self.getRestLeght() # curren lenght vs rest lenght
if tension <= 0: #avoid sqash repulsion
return
# The Spring Force Is Added To The Force
direction = (springVector / r) # unit vector for representing just the directional vector between the masses
force = -direction * tension * self._springStiffnes
#force += -(self.mass1.vel - self.mass2.vel) * self.frictionConstant # The Friction Force Is Added To The force
#self._particleA.addPosition(force) # Force Is Applied To mass1
self._particleB.addPosition(force*self._springDamping)
class ParticlesRope(Constraint):
"""link several particules to create a rope
"""
def __init__(self, particles, iterations=20, damping=.9):
self._particles = particles
self._iterations = iterations
self._damping = damping
self._links = list()
self.setup()
def setup(self):
"""create a link constrain between each particles
"""
self.link = list()
for i, particle in enumerate(self._particles[:-1]):
self._links.append(ParticleLink(particle,self._particles[i+1], self._damping))
def solve(self):
"""solve each link contraints through several iterations to reduce
particle position error on each iteration
"""
for i in range(self._iterations):
for link in self._links:
link.solve()
def setRigidity(self, dampingList):
for link, stiff in zip(self._links, dampingList):
if stiff>1:
stiff = 1
elif stiff<.01:
stiff = .01
link.setDamping(stiff)
|
python
|
from django.db import models
from django.contrib.auth.models import User
"""Dzien pracy - od zeskanowania kodu do ponownego zeskanowania
"""
class WorkDay(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
started = models.DateTimeField(auto_now_add=True)
finished = models.DateTimeField(null=True)
class Meta:
app_label = 'api'
|
python
|
import sys
import unittest
class SC2EnvTests(unittest.TestCase):
def test_sc2env_four_towers_hra(self):
sys.argv = ['',
'--task', 'abp.examples.sc2env.four_towers.hra',
'--folder', 'test/tasks/sc2env_four_towers_hra']
from abp.trainer.task_runner import main
main()
def test_sc2env_four_towers_multi_unit_hra(self):
sys.argv = ['',
'--task', 'abp.examples.sc2env.four_towers_multi_unit.hra',
'--folder', 'test/tasks/sc2env_four_towers_multi_unit_hra']
from abp.trainer.task_runner import main
main()
|
python
|
# Regression test based on detection of carbuncle phenomenon (Odd-Even decoupling)
# MHD Riemann solvers
#
# Modules
import logging
import scripts.utils.athena as athena
import sys
import os
from shutil import move
sys.path.insert(0, '../../vis/python')
import athena_read # noqa
athena_read.check_nan_flag = True
logger = logging.getLogger('athena' + __name__[7:]) # set logger name based on module
_fluxes = ['hlle', 'roe', 'llf', 'lhlld', 'hlld']
_exec = os.path.join('bin', 'athena')
# Prepare Athena++
def prepare(**kwargs):
logger.debug('Running test ' + __name__)
global _fluxes
for i in athena.global_config_args:
tmp = i.split('=')
if tmp[0] == '--flux' and len(tmp) == 2:
_fluxes = [tmp[1]]
for flux in _fluxes:
athena.configure('b',
prob='quirk',
coord='cartesian',
flux=flux, **kwargs)
# to save time, reuse compiled .o files for all executables created in this test:
athena.make(clean_first=False)
move(_exec, _exec + '_' + flux)
os.system('cp -r obj obj_' + flux)
os.system('rm -rf obj')
# Run Athena++
def run(**kwargs):
for flux in _fluxes:
move(_exec + '_' + flux, _exec)
os.system('mv obj_' + flux + ' obj')
athena.run('hydro/athinput.quirk',
arguments=[])
return 'skip_lcov'
# Analyze outputs
def analyze():
# read data from error file
filename = 'bin/carbuncle-diff.dat'
all_data = athena_read.error_dat(filename)
all_data = all_data.reshape(len(_fluxes)) # , -1, all_data.shape[-1])
analyze_status = True
max_ratio = 0.05
for i, flux in enumerate(_fluxes):
data = all_data[i]
flux_str = 'With flux "{0:}": '.format(flux)
if data > max_ratio and flux not in ['hlld', 'roe']:
logger.warning(flux_str + "difference in post-shock P/rho^gamma "
+ f"in even/odd rows is too large: {data}")
analyze_status = False
return analyze_status
|
python
|
"""
******** INFO ********
Created by Konrad Wybraniec
[email protected]
**********************
"""
from mainwindow import MrRoot
if __name__ == '__main__':
root = MrRoot()
root.configure()
root.mainloop()
# this is testing comment.
|
python
|
#
# Copyright (C) 2021 Vaticle
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import os
import subprocess
import unittest
from time import sleep
from unittest import TestCase
from typedb.client import *
SCHEMA = SessionType.SCHEMA
WRITE = TransactionType.WRITE
READ = TransactionType.READ
class TestClusterFailover(TestCase):
def setUp(self):
root_ca_path = os.environ["ROOT_CA"]
credential = TypeDBCredential("admin", "password", root_ca_path)
with TypeDB.cluster_client(["127.0.0.1:11729", "127.0.0.1:21729", "127.0.0.1:31729"], credential) as client:
if client.databases().contains("typedb"):
client.databases().get("typedb").delete()
client.databases().create("typedb")
def get_primary_replica(self, database_manager: ClusterDatabaseManager):
retry_num = 0
while retry_num < 10:
print("Discovering replicas for database 'typedb'...")
db = database_manager.get("typedb")
print("Discovered " + str([str(replica) for replica in db.replicas()]))
if db.primary_replica():
return db.primary_replica()
else:
retry_num += 1
print("There is no primary replica yet. Retrying in 2s...")
sleep(2)
return self.get_primary_replica(database_manager)
assert False, "Retry limit exceeded while seeking a primary replica."
def test_put_entity_type_to_crashed_primary_replica(self):
root_ca_path = os.environ["ROOT_CA"]
credential = TypeDBCredential("admin", "password", root_ca_path)
with TypeDB.cluster_client(["127.0.0.1:11729", "127.0.0.1:21729", "127.0.0.1:31729"], credential) as client:
assert client.databases().contains("typedb")
primary_replica = self.get_primary_replica(client.databases())
print("Performing operations against the primary replica " + str(primary_replica))
with client.session("typedb", SCHEMA) as session, session.transaction(WRITE) as tx:
tx.concepts().put_entity_type("person")
print("Put the entity type 'person'.")
tx.commit()
with client.session("typedb", SCHEMA) as session, session.transaction(READ) as tx:
person = tx.concepts().get_entity_type("person")
print("Retrieved entity type with label '%s' from primary replica." % person.get_label())
assert person.get_label().name() == "person"
iteration = 0
while iteration < 10:
iteration += 1
primary_replica = self.get_primary_replica(client.databases())
print("Stopping primary replica (test %d/10)..." % iteration)
port = primary_replica.address()[10:15]
lsof = subprocess.check_output(["lsof", "-i", ":%s" % port])
primary_replica_server_pid = [conn.split()[1] for conn in lsof.decode("utf-8").split("\n") if "LISTEN" in conn][0]
print("Primary replica is hosted by server with PID %s" % primary_replica_server_pid)
subprocess.check_call(["kill", "-9", primary_replica_server_pid])
print("Primary replica stopped successfully.")
sleep(5) # TODO: This ensures the server is actually shut down, but it's odd that it needs to be so long
with client.session("typedb", SCHEMA) as session, session.transaction(READ) as tx:
person = tx.concepts().get_entity_type("person")
print("Retrieved entity type with label '%s' from new primary replica." % person.get_label())
assert person.get_label().name() == "person"
idx = str(primary_replica.address())[10]
subprocess.Popen(["./%s/typedb" % idx, "cluster", "--data", "server/data", "--address", "127.0.0.1:%s1729:%s1730:%s1731" % (idx, idx, idx), "--peer", "127.0.0.1:11729:11730:11731", "--peer", "127.0.0.1:21729:21730:21731", "--peer", "127.0.0.1:31729:31730:31731", "--encryption-enabled=true"])
lsof = None
live_check_iteration = 0
while not lsof and live_check_iteration < 60:
live_check_iteration += 1
try:
lsof = subprocess.check_output(["lsof", "-i", ":%s" % port])
except subprocess.CalledProcessError:
pass
if __name__ == "__main__":
unittest.main(verbosity=2)
|
python
|
#!/usr/bin/env python
# coding: utf-8
#
# <a href="https://colab.research.google.com/github/aviadr1/learn-advanced-python/blob/master/content/14_pandas/edm_us_adult_census_income/questions.ipynb" target="_blank">
# <img src="https://colab.research.google.com/assets/colab-badge.svg"
# title="Open this file in Google Colab" alt="Colab"/>
# </a>
#
# # get the data
# run the following two cells below to get the data for this exercise,
# then followup by reading the questions and writing your own code to answer them.
# In[1]:
get_ipython().system('pip install requests')
# In[2]:
import requests
url = "http://mlr.cs.umass.edu/ml/machine-learning-databases/adult/adult.data"
request = requests.get(url)
request.raise_for_status()
with open('adult.csv', 'w') as f:
f.write(request.text)
### now the data is available in the file adult.csv.
### read the questions below
# import pandas as pd
# pd.read_csv('adult.csv')
# # income for adults from the 1994 census
# This dataset was extracted done by Barry Becker from the 1994 Census database.
# source: http://mlr.cs.umass.edu/ml/datasets/Adult
#
# Listing of attributes:
#
# * age: continuous.
# * workclass: Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked.
# * fnlwgt: continuous.
# * education: Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-6th, Preschool.
# * education-num: continuous.
# * marital-status: Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse.
# * occupation: Tech-support, Craft-repair, Other-service, Sales, Exec-managerial, Prof-specialty, Handlers-cleaners, Machine-op-inspct, Adm-clerical, Farming-fishing, Transport-moving, Priv-house-serv, Protective-serv, Armed-Forces.
# * relationship: Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried.
# * race: White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other, Black.
# * sex: Female, Male.
# * capital-gain: continuous.
# * capital-loss: continuous.
# * hours-per-week: continuous.
# * native-country: United-States, Cambodia, England, Puerto-Rico, Canada, Germany, Outlying-US(Guam-USVI-etc), India, Japan, Greece, South, China, Cuba, Iran, Honduras, Philippines, Italy, Poland, Jamaica, Vietnam, Mexico, Portugal, Ireland, France, Dominican-Republic, Laos, Ecuador, Taiwan, Haiti, Columbia, Hungary, Guatemala, Nicaragua, Scotland, Thailand, Yugoslavia, El-Salvador, Trinadad&Tobago, Peru, Hong, Holand-Netherlands.
# * income: >50K, <=50K.
#
# ## 1. load the data
# 1. extract the column names from the description and read the csv while supplying the columns names
# - rename columns with a hyphen `-` to use underscores `_` insead. example: `capital-gain --> capital_gain`
# - look at the head()
# 2. look at info, dtype, check for nan values
# 3. what are the value counts of the categorical variables: workclass, education, marital_status, occupation, relationship, race, sex, native_country, income?
# - do you notice the extra space ' ' at the beginning of each value?
# - remove the extra space
# 4. turn 'sex' and 'income' into 0/1 fields
# - replace the categorical 'sex' column with a numerical 'female' column with value 1 for females and 0 for males
# - replace the categorical 'income' column with a numerical 'over50k' column with value 1 for '>50k' and 0 for '<50K'
# 5. use `.describe()` function to get descriptive statistics for most columns
# - make sure that 'sex' and 'over50k' are now numerical fields
# ## 2. explore capital gains / losses
# ### capital_gain
# 1. plot the histogram for capital gains
# - verbally describe what you see
# 2. for people who have `capital_gain > 0`
# - plot the histogram for capital gains
# 3. how many people have capital gains over 25000?
# - use `value_counts()` to look at all the values of capital_gain over 25000.
# - what's weird about the data?
# 4. could the people who had capital_gain==25124 be related?
# 5. does capital_gain over 50k mean income is over 50k?
#
# ### capital_loss
# 1. plot the histogram of capital_loss
# 2. for people who have `capital_loss > 0`
# - plot the histogram for capital_loss
# 3. how many people had both `capital_gain>0` and `capital_loss>0` ?
# 4. who can afford to lose money on capital investments?
# - what percent of people overall had over 50K income?
# - what percent of people with 0 capital_loss? with capital_loss>0?
#
# ### combining and binning
# 1. create a new `capital_change` column that equals `capital_gain - capital_loss`
# 2. use the `qcut` function to quantize/bin/cut `capital_change` into a new columns called `capital_change_bin` with 10 bins of equal proportions.
# 1. do not bin `capital_change==0` values as there are too many of them
# 2. to simplify using this column later, use the left side of the interval created as the label
# 3. label rows with `capital_change==0` as having `capital_change_bin=0`
# 4. make sure you have no null values for `capital_change_bin`
# 3. how many people have a non-zero capital_change?
# - lets call this 'has_capital_change'
# - plot 'has_capital_change' over 'over50k'
# - what do you learn from this diagram
# 4. plot `capital_change` by `over50k`
# - what do you learn from this diagram
# 4. plot `over50k` by `capital_change_bin`
# - what can you learn from this diagram?
#
# ## education
# 1. what is the mean education_num by education?
# - sort the education categories by the mean_values. does it make sense
# - check out other descriptive statistics to see if anything falls out of place
# - turn education into a categorical ordered type
# - plot education VS education_num
# - what have we learned?
# 1. plot the distribution for `education`
# 2. plot over50k by education
# - what can we learn?
# 3. plot hours_per_week by education
# 1. what can we learn from this plot?
# 2. now use the hue="over50k" of seaborn to see hours_per_week by education/over50k.
# - learn anything else?
# 4. plot education_num by occupation
# - sort by mean education_num
# 4. plot education_num by workclass
# - sort by mean education_num
# 5. create a crosstab or a pivot_table of education VS occupation.
# - normalize it by the education rows
# (each row X shows the conditional probability of having occupation Y by education level X)
# - create a heatmap that shows which occpupations are most likely for each education level
# - verbally describe what you've learned
# 6. create a crosstab or a pivot_table of education VS workclass.
# - normalize it by the education rows
# (each row X shows the conditional probability of having workclass Y by education level X)
# - create a heatmap that shows which workclass is most likely for each education level
# - verbally describe what you've learned
# - re-run this analysis without the private sector
# 7. plot "race" vs "education_num
# 8. plot "relationship" vs "education_num
# ## occupation / workclass
# 1. how many levels of occupation?
# 2. how many levels of worklass?
# 3. how many combinations? potential? actual?
# 4. plot `over50k` by `occupation`
# - sort by mean `over50k`
# - compare this to `over50k` by `education`. which variable more strongly predicts income?
# - compare this to `education_num` by `occupation`. are the highest paying jobs correlated with highest earning education?
# 5. plot `over50k` by `workclass`
# 6. look at combinations of occupation / workclass
# 1. what are the top combinations in terms of earning over50k (mean)? how many people in that category?
# 2. how many of these combinations have more than 100 people?
# 3. show a heatmap of the mean over50k of occupation-vs-worklass for combinations with more than 100 people.
# center the heatmap at the populations mean over50k for increased effect.
# what conclusions can you draw?
# 7. create a numerical encoding for occupation / workclass pairs
# - create a new column called "occ_class" that combines the string of the occupation and workclass
# - use the library [category_encoders](http://contrib.scikit-learn.org/categorical-encoding/), here's an [intro](https://towardsdatascience.com/smarter-ways-to-encode-categorical-data-for-machine-learning-part-1-of-3-6dca2f71b159) how to do it
# - use the weight of evidence encoder `ce.woe.WOEEncoder` here's an [article](https://towardsdatascience.com/all-about-categorical-variable-encoding-305f3361fd02#targetText=Weight%20of%20Evidence%20Encoding,-Weight%20of%20Evidence&targetText=Weight%20of%20evidence%20(WOE)%20is%20a%20measure%20of%20how%20much,P(Bads)%20%3D%201.) explaining it
# - add the encoded occ_class as a new column called `occ_class_woe` to your dataframe
#
# ## correlations
# 1. which features are most important, which correlate?
# - compute the correction matrix of features with themselves
# 2. draw a clustermap or heatmap of this correlation
# - center the cluster at 0
# - annotate the plot with the correlation values
# 3. look at the strongest correlations and draw some conclusions.
#
# ## TODO:
# 1. look at `relationship` and `marriage_status`. how meaningful are they? should we encode them?
# 2. look at `native_country`. how does immigration effect other variables? should we build further categories based on continent or on 1st/2nd/3rd world countries? should we add an `is_immigrant` boolean column?
# 3. we've done the analysis treating each row of the data as a person, when **in fact** each row represents a large group of people, with the variable `fnlwgt` counting how many people are in the group. redo some of the analysis with weighted averages
# 4. look further at age. should we cut this continous variable into age groups like 18-25, 25-40 etc ?
# - combine age/relationship to see if relationship effects can be explained away by age
# 4. `education_num` seems to be a label encoding of `education`. I think some degrees are not properly captured with that encoding, like `assoc-voc`. it would be interesting to to recode it with woe against `over50k` and see if anything changes.
# 5. data quality questions:
# - why are women under-represented in this data
# - why are there no hispanic/latin category in race?
# 6. compare to other interesting analysis:
# - Predicting Earning Potential using the Adult Dataset https://rpubs.com/H_Zhu/235617
# - related notebook on kaggle https://www.kaggle.com/uciml/adult-census-income
#
# In[ ]:
#
# ```{toctree}
# :hidden:
# :titlesonly:
#
#
# solution
# ```
#
|
python
|
#!/usr/bin/env python
"""
_AcquireFiles_
MySQL implementation of Subscription.GetCompletedFiles
"""
__all__ = []
from WMCore.WMBS.MySQL.Subscriptions.GetAvailableFiles import GetAvailableFiles
class GetCompletedFiles(GetAvailableFiles):
sql = """SELECT wmsfc.fileid, wl.site_name FROM wmbs_sub_files_complete wmsfc
INNER JOIN wmbs_file_location wfl ON wfl.fileid = wmsfc.fileid
INNER JOIN wmbs_location_pnns wlpnn ON wlpnn.pnn = wfl.pnn
INNER JOIN wmbs_location wl ON wl.id = wlpnn.location
WHERE wmsfc.subscription = :subscription
"""
def execute(self, subscription=None, conn=None, transaction=False):
results = self.dbi.processData(self.sql, {"subscription": subscription},
conn=conn, transaction=transaction)
return self.formatDict(results)
|
python
|
# Generated by Django 4.0.2 on 2022-03-01 16:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Library', '0002_book_image'),
]
operations = [
migrations.AlterField(
model_name='book',
name='Image',
field=models.ImageField(default='default.jpg', upload_to='book_images'),
),
]
|
python
|
#!/usr/bin/python3
import copy
import itertools as it
import os
import unittest
import unittest.mock as mock
import plato_pylib.plato.parse_tbint_files as parseTbint
import plato_pylib.plato.private.tbint_test_data as tData
import plato_fit_integrals.core.coeffs_to_tables as tCode
class TestIntegralHolder(unittest.TestCase):
def setUp(self):
self.atomPairNames = [("Mg","Mg")]
self.integDicts = [ {k.lower():v for k,v in tData.loadTestBdtFileAExpectedVals_format4().items()} ]
self.testObjA = tCode.IntegralsHolder(self.atomPairNames, self.integDicts)
self.expGetPairPot = copy.deepcopy(self.integDicts[0]["pairpot"][0])
self.expGetPairPot.integrals[:,1] = [6.224678330, -0.010034643, -0.000000300]
self.expGetHopPpPi = copy.deepcopy(self.integDicts[0]["hopping"][-1])
hopCorrVals = [-0.02, -0.023, -0.000045]
for idx in range(len(self.expGetHopPpPi.integrals)):
self.expGetHopPpPi.integrals[idx,1] += hopCorrVals[idx]
def testGetterForPairPotInclCorrection_singleFile(self):
atomA, atomB, integStr = "Mg", "Mg", "PAirPOt" #Weird format on integStr since it should be case-insensitive anyway
actIntegObj = self.testObjA.getIntegTable(integStr, atomA, atomB)
self.assertEqual( self.expGetPairPot, actIntegObj )
def testGetterFromIntegTableInfoPairPot_singleFile(self):
mockModFolder = "something"
atomA, atomB, integStr = "Mg", "Mg", "PAirPOt"
integInfoTable = tCode.IntegralTableInfo(mockModFolder, integStr, atomA, atomB)
actIntegObj = self.testObjA.getIntegTableFromInfoObj(integInfoTable)
self.assertEqual( self.expGetPairPot, actIntegObj )
def testSetterForPairPot_singleFile(self):
atomA, atomB, integStr = "Mg", "Mg", "Pairpot"
testSetTable = copy.deepcopy(self.integDicts[0]["pairpot"][0])
testSetTable.integrals[:,1] *= -1
#We want the pair-potential to be unchanged internally, only the correction
#So if the internal PP repr is unchanged AND PP+corr(result of the getter) is what it was set
#to then the setter has worked correctly
self.testObjA.setIntegTable(testSetTable, integStr, atomA, atomB)
actTablePP = self.testObjA.integDicts[0]["pairpot"][0]
expTablePP = self.integDicts[0]["pairpot"][0]
actFullPPTable = self.testObjA.getIntegTable(integStr, atomA, atomB)
self.assertEqual(expTablePP, actTablePP)
self.assertEqual(testSetTable, self.testObjA.getIntegTable(integStr, atomA, atomB) )
def testGetterForHopInts_singleFile(self):
atomA, atomB, integStr = "Mg", "Mg", "hopping"
shellA, shellB, axAngMom = 1,1,2 #pp pi
actIntegObj = self.testObjA.getIntegTable(integStr, atomA, atomB, shellA, shellB, axAngMom)
self.assertEqual( self.expGetHopPpPi , actIntegObj)
def testGetterFromIntegTableInfoHopInts_singleFile(self):
atomA, atomB, integStr = "Mg", "Mg", "hopping"
shellA, shellB, axAngMom = 1,1,2 #pp pi
mockFolder = "something"
integInfoTable = tCode.IntegralTableInfo(mockFolder, integStr, atomA, atomB, shellA, shellB, axAngMom)
actIntegObj = self.testObjA.getIntegTableFromInfoObj(integInfoTable)
self.assertEqual( self.expGetHopPpPi, actIntegObj )
def testSetterForHopInts_singleFile(self):
atomA, atomB, integStr = "Mg", "Mg", "hopping"
shellA, shellB, axAngMom = 1,1,2 #pp pi
testSetTable = copy.deepcopy(self.integDicts[0]["hopping"][-1])
testSetTable.integrals[:,1] *= -1
#Same logic as pair-pot test. Make sure the hopping integrals unchanged; only the correction integrals should be altered
self.testObjA.setIntegTable(testSetTable, integStr, atomA, atomB, shellA, shellB, axAngMom)
actHopTableNoCorrs = self.testObjA.integDicts[0]["hopping"][-1]
expTableHopNoCorrs = self.integDicts[0]["hopping"][-1]
actTableInclCorrs = self.testObjA.getIntegTable(integStr,atomA,atomB,shellA,shellB,axAngMom)
self.assertEqual(expTableHopNoCorrs, actHopTableNoCorrs) #Making sure we dont modify the hopping integral table(just the corr table)
self.assertEqual( testSetTable, actTableInclCorrs ) #Making sure setter/getter consistent
def testSetterForHopIntsFromIntegInfo_singleFile(self):
mockModFolder = "something"
atomA, atomB, integStr = "Mg", "Mg", "hopping"
shellA, shellB, axAngMom = 1,1,2 #pp pi
testSetTable = copy.deepcopy(self.integDicts[0]["hopping"][-1])
testIntegInfo = tCode.IntegralTableInfo(mockModFolder, integStr, atomA, atomB, shellA, shellB, axAngMom)
testSetTable.integrals[:,1] *= -1
#Same logic as pair-pot test. Make sure the hopping integrals unchanged; only the correction integrals should be altered
self.testObjA.setIntegTableFromInfoObj(testSetTable,testIntegInfo)
actHopTableNoCorrs = self.testObjA.integDicts[0]["hopping"][-1]
expTableHopNoCorrs = self.integDicts[0]["hopping"][-1]
actTableInclCorrs = self.testObjA.getIntegTable(integStr,atomA,atomB,shellA,shellB,axAngMom)
self.assertEqual(expTableHopNoCorrs, actHopTableNoCorrs) #Making sure we dont modify the hopping integral table(just the corr table)
self.assertEqual( testSetTable, actTableInclCorrs ) #Making sure setter/getter consistent
class TestCoeffsTableConverterWriteTables(unittest.TestCase):
def setUp(self):
self.atomPairNames = [("Xa","Xb")]
self.integDicts = [ {k.lower():v for k,v in tData.loadTestBdtFileAExpectedVals_format4().items()} ]
self.integDicts[0]["PairPotCorrection0".lower()][0].integrals[:,1] = 0 #no PP Correction, means it will equal any change i make in total PP
#Write integrals to file
self.outFileA = "Xa_Xb.bdt" #Needs to match the atomPairNames
parseTbint.writeBdtFileFormat4(self.integDicts[0], self.outFileA)
integHolder = tCode.IntegralsHolder(self.atomPairNames, copy.deepcopy(self.integDicts))
integInfo = createIntegTableInfoXaXbPairPot( os.getcwd() )
mockedAnalyticalRepr = mock.Mock()
mockedAnalyticalRepr.evalAtListOfXVals = lambda x: [0 for a in x]
self.testObj = tCode.CoeffsTablesConverter([mockedAnalyticalRepr], [integInfo], integHolder)
def tearDown(self):
os.remove(self.outFileA)
def testCorrectlyWritesPairPot_singleFile(self):
expPPCorr = self.integDicts[0]["pairpot"][0]
expPPCorr.integrals[:,1] *= -1 #Total PP is zero, so the correction must exactly cancel the initial
self.testObj.writeTables() #Will always update before writing them
actualPPCorr = parseTbint.getIntegralsFromBdt(self.outFileA)["PairPotCorrection0"][0]
self.assertEqual(expPPCorr, actualPPCorr)
class TestCoeffsTableConverterPassCoeffs(unittest.TestCase):
def setUp(self):
integHolder = None
integInfoList = [None]
mockedAnalyticalReprs = [mock.Mock() for x in range(3)]
self.nCoeffs = [2,2,1]
for x,nCoeff in it.zip_longest(mockedAnalyticalReprs, self.nCoeffs):
x.nCoeffs=nCoeff
coeffVals = [[0,1],[2,3],[4]]
self.mergedListCoeffs = [0,1,2,3,4]
for x,coeffs in it.zip_longest(mockedAnalyticalReprs,coeffVals):
x.coeffs = coeffs
self.testObj = tCode.CoeffsTablesConverter( mockedAnalyticalReprs, integInfoList, integHolder )
def testGetCoeffs(self):
expCoeffs = self.mergedListCoeffs
actCoeffs = self.testObj.coeffs
[self.assertEqual(exp,act) for exp,act in it.zip_longest(expCoeffs,actCoeffs)]
def testSetCoeffs(self):
expCoeffs = [9,10,11,12,13]
self.testObj.coeffs = expCoeffs
actCoeffs = self.testObj.coeffs
[self.assertEqual(exp,act) for exp,act in it.zip_longest(expCoeffs,actCoeffs)]
def createIntegTableInfoXaXbPairPot(modelFolder):
return tCode.IntegralTableInfo(modelFolder, "pairpot", "Xa", "Xb")
if __name__ == '__main__':
unittest.main()
|
python
|
from unittest import TestCase, mock
from flask import url_for
from app import app
class RootTests(TestCase):
def setUp(self):
self.app = app
self.app.testing = True
self.app_context = self.app.test_request_context()
self.app_context.push()
self.client = self.app.test_client()
def test_root_deve_retornar_hello_world(self):
request = self.client.get(url_for('hello'))
self.assertEqual('Hello World!', request.data.decode())
def test_root_deve_retornar_status_code_200(self):
request = self.client.get(url_for('hello'))
self.assertEqual(200, request.status_code)
|
python
|
from django.apps import AppConfig
class DadfesConfig(AppConfig):
name = "dadfes"
|
python
|
##########################################################
### PYGAME – Graph ###
### 1st Project for Data Structure at NYU Shanghai ###
##########################################################
__author__ = "Jack B. Du (Jiadong Du)"
__copyright__ = "Copyright 2014, the DS 1st Project @NYUSH"
__version__ = "0.0.1"
__email__ = "[email protected]"
__status__ = "Developing"
import time
import random
import pygame
from pygame.locals import *
import sys
import functions
############
## SETUPS ##
############
## initialize pygame
pygame.init()
## setups
SCREEN_WIDTH = 1240
SCREEN_HEIGHT = 768
infoObject = pygame.display.Info()
FULLSCREEN_WIDTH = infoObject.current_w
FULLSCREEN_HEIGHT = infoObject.current_h
CURRENT_SCREEN_WIDTH = SCREEN_WIDTH
CURRENT_SCREEN_HEIGHT = SCREEN_HEIGHT
SCREEN_SIZE = (CURRENT_SCREEN_WIDTH, CURRENT_SCREEN_HEIGHT)
MARGIN_BOTTOM = 30
MARGIN_LEFT = 30
MARGIN_RIGHT = 30
MARGIN_TOP = 30
FONT_SIZE = 20
myfont = pygame.font.SysFont("arial", FONT_SIZE)
paused = False
maxValueList = []
reset = True
# default screen mode
fullscreen = False
# set caption on the bar
pygame.display.set_caption('Jack B. Du\'s Graph')
# create screen
screen = pygame.display.set_mode(SCREEN_SIZE,0,32)
# background setup
background = pygame.Surface(screen.get_size())
background = background.convert()
backgorund_color = (0 ,0 , 0)
background.fill(backgorund_color)
# runtime of f
def timer(f, *p):
begin_time = time.clock()
f(*p)
end_time = time.clock()
return(end_time - begin_time)
def main():
# a list of functions, which support one-list input, two-list input and integer input
functionList = [functions.countEvens,
functions.myMin,
functions.myMax,
functions.median,
functions.secondBiggest,
functions.LIS,
functions.dot,
functions.intersect1,
functions.intersect2,
functions.fib]
# plot the functions
sim(functionList)
def sim(functionList):
global screen, fullscreen, SCREEN_SIZE, CURRENT_SCREEN_WIDTH, CURRENT_SCREEN_HEIGHT, background, paused, maxValueList, reset
mainloop = True
highlightedColor = (255,255,255) # color for highlighted color
# mainloop
while mainloop:
if reset:
textX, textY = 0, -400
manul = 1 # percentage of height
size = 10 # input step size
N = size # initial input size
yPointList = [] # y value for each point
pointList = [] # all the points
color = [] # color for each graph
highlight = 0 # default highlight graph number
maxDict = {} # dict of max value for different algorithms
hide = False # whether or not hide the graphs that are not highlighted
# create different lists of lists for each function
for num in range(len(functionList)):
yPointList.append([])
pointList.append([])
color.append([])
color[num]=(random.randint(1,255),random.randint(1,255),random.randint(1,255))
count = 0 # loop count
highest = 0 # highest point, max y value of all points
highlighted = False # whether in the highlighted mode or not
changed = True # whether changed manually or not
reset = False
if textY < 0:
textY += 20
if not paused:
N += size
for event in pygame.event.get():
# the quit on the system bar
if event.type == QUIT:
mainloop = False
elif event.type == KEYDOWN:
if event.key == K_q: # quit with q/Q key
mainloop = False
elif event.key == K_f: ## press f/F to enter/exit fullscreen mode
fullscreen = not fullscreen
if fullscreen:
CURRENT_SCREEN_WIDTH = FULLSCREEN_WIDTH
CURRENT_SCREEN_HEIGHT = FULLSCREEN_HEIGHT
SCREEN_SIZE = (CURRENT_SCREEN_WIDTH, CURRENT_SCREEN_HEIGHT)
screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN, 32)
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((0, 0, 0))
else:
CURRENT_SCREEN_WIDTH = SCREEN_WIDTH
CURRENT_SCREEN_HEIGHT = SCREEN_HEIGHT
SCREEN_SIZE = (CURRENT_SCREEN_WIDTH, CURRENT_SCREEN_HEIGHT)
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((0, 0, 0))
elif event.key == K_w: # set background white, highlighted black
background.fill((255, 255, 255))
highlightedColor = (0,0,0)
elif event.key == K_b: # set background black, highlighted white
background.fill((0, 0, 0))
highlightedColor = (255,255,255)
elif event.key == K_EQUALS: # scale by 10
changed = True
manul *= 10
elif event.key == K_MINUS: # scale by 1/10
manul /= 10
changed = True
elif event.key == K_d or event.key ==K_0: # press d/0 key to default scale
manul = 1
changed = True
elif event.key == K_h:
hide = not hide
elif event.key == K_SPACE:
paused = not paused
elif event.key == K_r:
reset = True
# press n key to scale by 10n
elif event.key == K_1:
manul = 10
changed = True
elif event.key == K_2:
manul = 20
changed = True
elif event.key == K_3:
manul = 30
changed = True
elif event.key == K_4:
manul = 40
changed = True
elif event.key == K_5:
manul = 50
changed = True
elif event.key == K_6:
manul = 60
changed = True
elif event.key == K_7:
manul = 70
changed = True
elif event.key == K_8:
manul = 80
changed = True
elif event.key == K_9:
manul = 90
changed = True
# highlighting options
elif event.key == K_UP:
changed = False
if highlighted:
currentPos = valueList.index(valueDict[highlight])
if currentPos > 0: # highlight the upper graph
highlight = unsortedValueList.index(valueList[currentPos-1])
else:
highlighted = True # set to highlighted
highlight = unsortedValueList.index(valueList[-1]) # start with the bottom
elif event.key == K_DOWN:
changed = False
if highlighted:
currentPos = valueList.index(valueDict[highlight])
if currentPos < len(functionList)-1: # highlight the lower graph
highlight = unsortedValueList.index(valueList[currentPos+1])
else:
highlighted = True # set to highlighted
highlight = unsortedValueList.index(valueList[0]) # start with the top
elif event.key == K_ESCAPE: # press ESC to escape highlight mode
highlighted = False
screen.blit(background,(0,0))
inputNum = str(int(N/size)) + " (loopCount)"
loopLabel = myfont.render(inputNum, 1, (0,0,255))
screen.blit(loopLabel, (MARGIN_LEFT*2+textX, MARGIN_TOP+textY))
framePointList = [(MARGIN_LEFT,MARGIN_TOP),(MARGIN_LEFT,CURRENT_SCREEN_HEIGHT-MARGIN_BOTTOM),(CURRENT_SCREEN_WIDTH-MARGIN_RIGHT,CURRENT_SCREEN_HEIGHT-MARGIN_BOTTOM)]
pygame.draw.lines(screen, (150,150,150), False, framePointList, 1)
if not paused:
count += 1
valueDict = {}
valueList = []
for function in functionList:
A = [i for i in range (N)]
random.shuffle(A)
try:
time = timer(function, A)
except:
try:
B = [i for i in range (N)]
random.shuffle(B)
time = timer(function, A, B)
except:
time = timer(function, 10*N)
if time>highest:
highest = time
valueDict[functionList.index(function)] = time
valueList.append(time)
yPointList[functionList.index(function)].append(time)
if highlighted and not(changed):
if not paused:
maxValueList = []
for function in functionList:
maxValue = max(yPointList[functionList.index(function)])
maxDict[functionList.index(function)] = maxValue
maxValueList.append(maxValue)
manul = highest/maxValueList[highlight]
for function in functionList:
pointList[functionList.index(function)]=[(MARGIN_LEFT,CURRENT_SCREEN_HEIGHT-MARGIN_BOTTOM)] ## starts from (0,0)
for num in range(count):
posX = (CURRENT_SCREEN_WIDTH - MARGIN_LEFT - MARGIN_RIGHT)/count * (num+1) + MARGIN_LEFT
posY = (CURRENT_SCREEN_HEIGHT - MARGIN_BOTTOM - MARGIN_TOP)*(1-manul*yPointList[functionList.index(function)][num]/highest) + MARGIN_TOP
pointList[functionList.index(function)].append((posX,posY))
if count > 1:
if not hide:
for num in range(len(functionList)):
pygame.draw.lines(screen, color[num], False, pointList[num], 1)
if highlighted:
pygame.draw.lines(screen, highlightedColor, False, pointList[highlight], 2)
if not paused:
unsortedValueList = []
unsortedValueList += valueList
valueList.sort()
valueList.reverse()
for function in functionList:
functionInfo = str(format(valueDict[functionList.index(function)],',.6f')) + " (" + str(function)[10:-16] + ")"
if highlighted and functionList.index(function) == highlight:
functionLabel = myfont.render(functionInfo, 1, highlightedColor)
else:
functionLabel = myfont.render(functionInfo, 1, color[functionList.index(function)])
screen.blit(functionLabel, (MARGIN_LEFT*2+textX, textY+MARGIN_TOP+FONT_SIZE+FONT_SIZE*valueList.index(valueDict[functionList.index(function)])))
percentageInfo = str(int(manul*100)) + '%' + " (scale)"
percentageLabel = myfont.render(percentageInfo, 1, (150,150,150))
screen.blit(percentageLabel, (MARGIN_LEFT*2+textX, textY+MARGIN_TOP+FONT_SIZE+FONT_SIZE*len(valueList)))
pygame.display.update()
pygame.quit()
main()
|
python
|
# -*- coding: utf-8 -*-
"""
DB操作层
只涉及DB操作,最好不涉及业务
"""
from typing import List
from app.exceptions import AuthenticationFailed, ObjNotFound
from app.utils import sha256
from users.models import User, UserPermissionRelation, Permission, Role, UserRoleRelation, RoleMenuRelation, Menu, \
Platform
def authenticate(phone: str, password: str) -> User:
hashed_password = sha256(password)
user: User = User.query.filter(
User.phone == phone, User.password == hashed_password
).first()
if not user:
raise AuthenticationFailed()
return user
def get_user(user_id: int) -> User:
user: User = User.get(user_id)
return user
def get_user_by_phone(phone: str) -> User:
user: User = User.query.filter_by(phone=phone).first()
return user
def get_user_perm_key_list(user_id: int) -> List:
uprs = UserPermissionRelation.query.filter_by(user_id=user_id).all()
perm_id_list = [x.permission_id for x in uprs]
perms = Permission.query.filter(Permission.id.in_(perm_id_list)).all()
return [p.key for p in perms]
def get_role(role_id, raise_exception=False) -> Role:
role: Role = Role.get(role_id)
if not role and raise_exception:
raise ObjNotFound()
return role
def get_user_list() -> List:
users = User.query.filter_by().all()
return users
def delete_role(role_id, raise_exception=False) -> None:
role: Role = Role.get(role_id)
if not role:
if raise_exception:
raise ObjNotFound()
else:
role.delete()
def get_user_roles(user_id):
"""
获取用户角色
"""
urrs = UserRoleRelation.query.filter_by(user_id=user_id).all()
role_id_list = [x.role_id for x in urrs]
roles = []
if role_id_list:
roles = Role.query.filter(Role.id.in_(role_id_list)).all()
return roles
def get_user_menu_by_role_id_list(role_id_list: List):
"""
获取用户菜单权限
"""
rmrs = RoleMenuRelation.query.filter(RoleMenuRelation.role_id.in_(role_id_list)).all()
return rmrs
def get_menu_by_menu_id_list(menu_id_list: List, platform_id: int):
"""
通过菜单ID和平台ID获取菜单列表
"""
menus = Menu.query.filter(
Menu.id.in_(menu_id_list),
Menu.platform_id == platform_id
).all()
return menus
def get_role_relate_by_uid_and_rid(user_id, role_id):
"""
通过用户ID和角色ID获取用户角色关联信息
"""
urr: UserRoleRelation = UserRoleRelation.query.filter_by(
user_id=user_id,
role_id=role_id,
).first()
return urr
def get_role_list():
"""
获取角色列表
"""
roles = Role.query.filter_by().all()
return roles
def get_platform_by_key(platform_key: str, raise_exception=False) -> Platform:
"""
通过平台Key获取平台
"""
platform = Platform.query.filter_by(key=platform_key).first()
if not platform and raise_exception:
raise ObjNotFound()
return platform
|
python
|
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2020 D. Craig Brinck, SE; tamalone1
"""
import unittest
# Run the tests in this module
# Use warnings flag to suppress the PendingDeprecationWarning
# from numpy.matrix
# unittest.main(warnings='ignore')
test_suite = unittest.TestLoader().discover("Testing", pattern='test_*.py')
# `TextTestRunner` does not exit the module. CI will get confused unless we save the result
# and send the proper exit code.
result = unittest.TextTestRunner().run(test_suite)
# Send the proper exit code for Travis-CI to read
if result.wasSuccessful():
exit(0)
else:
exit(1)
|
python
|
import logging
import unittest
from morm.q import Q
LOGGER_NAME = 'morm-test-q-'
log = logging.getLogger(LOGGER_NAME)
class TestMethods(unittest.TestCase):
def test_Q(self):
self.assertEqual(Q('string'), '"string"')
if __name__ == "__main__":
unittest.main(verbosity=2)
|
python
|
"""
Copyright (c) 2016 Jet Propulsion Laboratory,
California Institute of Technology. All rights reserved
"""
import json
from webservice.NexusHandler import NexusHandler, nexus_handler, AVAILABLE_HANDLERS
from webservice.webmodel import NexusResults
@nexus_handler
class HeartbeatHandlerImpl(NexusHandler):
name = "Backend Services Status"
path = "/heartbeat"
description = "Returns health status of Nexus backend services"
params = {}
singleton = True
def __init__(self):
NexusHandler.__init__(self, skipCassandra=True)
def calc(self, computeOptions, **args):
solrOnline = self._tile_service.pingSolr()
# Not sure how to best check cassandra cluster status so just return True for now
cassOnline = True
if solrOnline and cassOnline:
status = {"online": True}
else:
status = {"online": False}
class SimpleResult(object):
def __init__(self, result):
self.result = result
def toJson(self):
return json.dumps(self.result)
return SimpleResult(status)
|
python
|
"""
263. Ugly Number
Easy
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return true if n is an ugly number.
Example 1:
Input: n = 6
Output: true
Explanation: 6 = 2 × 3
Example 2:
Input: n = 1
Output: true
Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
Example 3:
Input: n = 14
Output: false
Explanation: 14 is not ugly since it includes the prime factor 7.
Constraints:
-231 <= n <= 231 - 1
"""
# V0
class Solution(object):
def isUgly(self, n):
# edge case
if n == 0:
return False
if n == 1:
return True
flag = True
while flag:
#print ("n = " + str(n))
if n == 0 or n == 1:
return True
if n % 2 == 0 or n % 3 == 0 or n % 5 == 0:
#print (">>>>")
if n % 2 == 0:
a, b = divmod(n, 2)
flag = True
n = a
elif n % 3 == 0:
a, b = divmod(n, 3)
flag = True
n = a
elif n % 5 == 0:
a, b = divmod(n, 5)
flag = True
n = a
else:
flag = False
return False
# V1
class Solution(object):
# @param {integer} num
# @return {boolean}
def isUgly(self, num):
if num ==0:
return False
while (num%2 ==0 or num%3 ==0 or num%5 ==0):
if num%2 ==0:
num = int(num/2)
if num%3 ==0:
num = int(num/3)
if num%5 ==0:
num = int(num/5)
if num ==1:
return True
else:
return False
# V2
# Time: O(logn) = O(1)
# Space: O(1)
class Solution(object):
# @param {integer} num
# @return {boolean}
def isUgly(self, num):
if num == 0:
return False
for i in [2, 3, 5]:
while num % i == 0:
num /= i
return num == 1
|
python
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'EMG3.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(897, 529)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.widget = QtWidgets.QWidget(self.centralwidget)
self.widget.setGeometry(QtCore.QRect(0, 60, 901, 381))
self.widget.setStyleSheet("background-color: rgb(0, 0, 0);")
self.widget.setObjectName("widget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(60, 10, 801, 41))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.splitter = QtWidgets.QSplitter(self.centralwidget)
self.splitter.setGeometry(QtCore.QRect(0, 450, 891, 31))
self.splitter.setOrientation(QtCore.Qt.Horizontal)
self.splitter.setObjectName("splitter")
self.pushButton = QtWidgets.QPushButton(self.splitter)
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.splitter)
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.splitter)
self.pushButton_3.setObjectName("pushButton_3")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 897, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Real Time \n"
" Identification Emotion EMG-based"))
self.pushButton.setText(_translate("MainWindow", "START"))
self.pushButton_2.setText(_translate("MainWindow", "SAVE"))
self.pushButton_3.setText(_translate("MainWindow", "STOP"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
|
python
|
iterable = [1, 2, 3, 4]
for item in iterable:
print(item)
print('-')
i = 0
while i<len(iterable):
print(iterable[i])
i += 1
# tuple unpacking
print('-')
tupleList = [('a', 1), ('b', 2), ('c', 3)]
for letter, number in tupleList:
print("letter is ", letter)
# need terminating condition and updation in while
i = 1
while i<5:
print(f"i is currently: {i}")
i += 1
# range(start, stop, step) with for
for x in range(10, 20 + 1, 2):
print(x)
# in keyword
print("abc" in "abcdefghijk")
print("xyz" in "abcdefghijk")
|
python
|
# A List it's a collection of grouping of items
item1 = 'bananas'
item2 = 'lego set'
# we can do it shorter -->>
tasks = ['Install Python', 'Learn Python', 'Take a break']
length = len(tasks) # Shows the length of the List
print(length)
# Accessing specific element from List wi the square brackets and position number of element [0] -->first element of List
python = tasks[0]
print(python)
python = tasks[-1]
print(python)
if 'Install Python' in tasks:
print(True)
array = list(range(1, 8)) # Another way to built a function called --> list()
print(array)
r = range(1, 4)
r = list(r)
print(r)
# Accessing all values in a List
colors = ['purple', 'teal', 'magenta', 8.9]
for x in colors:
print(x)
# --------------------------------------------------------------------------------
# While Loop
i = 0
while i < len(colors):
print(colors[i])
i += 1
# --------------------------------------------------------------------------------
# if you want to add 1 item to the list use : --> .append()
motociclete = ['suzuki', 'honda', 'davidson']
masini = ['dacia', 'renault', 'BMW']
masini.append(motociclete)
print(masini)
# --------------------------------------------------------------------------------
# extend() --> add to the end of a list all values passed to extend
# if you want to add more items to the list use : --> .extend()
bloc = ['A1', 'A2', 'B1', 'B2']
casa = ['C1', 'C2']
bloc.extend(casa)
print(bloc)
# --------------------------------------------------------------------------------
# if we want to add item wherever in the list use : --> .insert(index, 'value')
curcubeu = ['purple', 'teal', 'magenta', 8.9]
curcubeu.insert(2, 'Blue')
print(curcubeu)
# insert into a list inside another list
elicopter = ['Croco_2', 'Croco_7', 'Apash_91']
armata = ['Soldat_1', 'Soldat_2', 'Soldat_3', 'soldat_5', 'Soldat_6']
elicopter.append(armata)
print(elicopter)
elicopter[3].append('Soldat_4')
print(elicopter)
# -------------------------------------------------------------------------------
# Remove all elements inside the list with function --> .clear()
elicopter.clear()
print(elicopter)
# -------------------------------------------------------------------------------
# Remove single element from list items use : --> .pop('index')
armata.pop()
print(armata)
# If do not insert index it will remove last item from list
armata.pop(1)
print(armata)
# -------------------------------------------------------------------------------
armata.remove('soldat_5') # Removes a specific value that we give
# : --> .remove('item_name') --> if not found throw error
print(armata)
# -------------------------------------------------------------------------------
# index position to be found regarding element in the list
armata = ['Soldat_1', 'Soldat_2', 'Soldat_2', 'Soldat_3', 'soldat_5', 'Soldat_6']
nume = armata.index('Soldat_1')
print(nume)
nume = armata.index('Soldat_2', 2) # Search 'Soldat_2' after position 2 in List
print(nume)
nume = armata.index('Soldat_2', 2, 5) # Search 'Soldat_2' between position 2 and 5 in List
print(nume)
# ---------------------------------------------------------------------------------
# counting the elements inside the list with .count('item_to_count')
count_1 = armata.count('Soldat_2')
print('We found:', count_1)
# -----------------------------------------------------------------------------------
# reversing the list with .reverse()
print(armata)
armata.reverse()
print(armata)
# -----------------------------------------------------------------------------------
# sorting list with .sort()
armata.sort()
print(armata)
# ------------------------------------------------------------------------------------
# join is a string method / convert list to string --> .join(list)
arma = 'militar '.join(armata)
print(arma)
# --------------------------------------------------------------------------------------
# make new lists from old list using Slices --> list[start:end:step]
armata = ['Soldat_1', 'Soldat_2', 'Soldat_2', 'Soldat_3', 'soldat_5', 'Soldat_6']
print(armata[1:5]) # prints items from list from index 2 to index 4
print(armata[1:5:2]) # prints items from list from index 2 to index 4 | din 2 in 2
# --------------------------------------------------------------------------------------
# swapping values in list
armata[0], armata[1] = armata[1], armata [0]
print(armata)
|
python
|
import torch
from datasets import CubDataset
from models import FineGrainedModel, ResNet18
from torchvision import transforms
from torch.utils.data import DataLoader
train_transforms = transforms.Compose(
[
transforms.Resize((128, 128)),
transforms.ToTensor(),
transforms.Normalize((0.4819, 0.4976, 0.4321),
(0.1878, 0.1864, 0.1992))
]
)
train_ds = CubDataset(transform=train_transforms, trainable=True)
test_ds = CubDataset(transform=train_transforms, trainable=False)
train_dataloader = DataLoader(
train_ds, batch_size=3, shuffle=True, collate_fn=train_ds.collect_fn, drop_last=True)
test_dataloader = DataLoader(
test_ds, batch_size=3, shuffle=False, collate_fn=train_ds.collect_fn)
model = ResNet18()
# model2 = ResNet18()
if torch.cuda.is_available():
model = model.cuda()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
criterion = torch.nn.CrossEntropyLoss()
scheduler = torch.optim.lr_scheduler.StepLR(optimizer,
step_size=30,
gamma=0.1)
if __name__ == "__main__":
EPOCH = 1
for e in range(EPOCH):
# train
model.train()
print("="*10, "Train %d EPOCH" % e, "="*10)
for itr, (img, label) in enumerate(train_dataloader):
if torch.cuda.is_available():
img = img.cuda()
label = label.cuda()
output = model(img)
label = torch.squeeze(label).long()
loss = criterion(output, label)
optimizer.zero_grad()
loss.backward()
optimizer.step()
scheduler.step()
print("step: %03d | train loss:%.3f" % (itr, loss.item()))
print("="*10, "Test %d EPOCH" % e, "="*10)
n_loss = 0.
n_sample = 0
n_right = 0
# model.eval()
# for iter, (img, label) in enumerate(test_dataloader):
# bs = img.shape[0]
# output = model(img)
# ######################
# output = output.topk(1, dim=1)[1].view(bs, 1)
# diff = (output != label)
# diff = diff.sum(1)
# diff = (diff != 0)
# res = diff.sum(0).item()
# n_right += (bs - res)
# ######################
# label = torch.squeeze(label).long()
# loss = criterion(output, label)
# n_sample += bs
# n_loss += loss.item()
# print("step: %03d | Test Loss: %.3f | Acc: %.3f" %
# (iter, n_loss/n_sample, n_right * 1./n_sample))
|
python
|
from gurobipy import *
from prediction.predictor import predict_scores
from utils.progress import inhour
import time
import numpy as np
def sample_users(num_users, num_users_sampled):
return np.random.choice(num_users, num_users_sampled, replace=False)
def sample_items(candidate_items, num_items_sampled):
return np.random.choice(candidate_items, size=num_items_sampled, replace=False)
def sample_keyphrase():
# Critique the most popular keyphrases in the remaining
critiqued_keyphrase = remaining_keyphrases[np.argmax(self.keyphrase_popularity[remaining_keyphrases])]
def get_max_length(df, num_keyphrases, max_iteration):
df_s_f = df[(df['result'] == 'successful') | (df['result'] == 'fail')]
df_s_f.loc[df_s_f['num_existing_keyphrases'] > max_iteration, 'num_existing_keyphrases'] = max_iteration
return df_s_f['num_existing_keyphrases'].mean()
def get_average_length(df, n):
df_s_f = df[(df['result'] == 'successful') | (df['result'] == 'fail')]
iteration = df_s_f[df_s_f['target_rank']==n].groupby('user_id', as_index=False).agg({'iteration':'mean'})['iteration'].to_numpy()
return (np.average(iteration), 1.96*np.std(iteration)/np.sqrt(len(iteration)))
def get_success_num(df, n):
return len(df[(df['result'] == 'successful') & (df['target_rank'] == n)])
def get_fail_num(df, n):
return len(df[(df['result'] == 'fail') & (df['target_rank'] == n)])
def get_success_rate(df, n):
df_s_f = df[(df['result'] == 'successful') | (df['result'] == 'fail')]
df_list_result = df_s_f[df_s_f['target_rank']==n].groupby('user_id', as_index=False)['result'].apply(list).reset_index(name='result')
successful_rate = df_list_result['result'].apply(lambda r: r.count("successful")/len(r)).to_numpy()
return (np.average(successful_rate), 1.96*np.std(successful_rate)/np.sqrt(len(successful_rate)))
def count_occurrence(x):
return x.count("successful")
def add_pop(x, item_pop_index):
return np.where(item_pop_index == x)[0][0]
##################################
# Baseline Methods
##################################
def LPUAC(initial_prediction_u, keyphrase_freq, affected_items, unaffected_items, num_keyphrases, query, test_user, item_latent, reg):
critiqued_vector = np.zeros(keyphrase_freq[0].shape)
for q in query:
critiqued_vector[q] = -keyphrase_freq[test_user][q]
num_critiques = len(query)
num_affected_items = len(affected_items)
num_unaffected_items = len(unaffected_items)
# UAC
lambdas = []
for k in range(num_critiques):
optimal_lambda = 1/(1+num_critiques) # All equals to 1/(K+1)
lambdas.append(optimal_lambda)
critiqued_vector[query[k]] *= optimal_lambda
critique_score = predict_scores(matrix_U=reg.predict(critiqued_vector.reshape(1, -1)),
matrix_V=item_latent)
new_prediction = (1/(1+num_critiques))*initial_prediction_u + critique_score.flatten()
return new_prediction, lambdas
def LPBAC(initial_prediction_u, keyphrase_freq, affected_items, unaffected_items, num_keyphrases, query, test_user, item_latent, reg):
critiqued_vector = np.zeros(keyphrase_freq[0].shape)
for q in query:
critiqued_vector[q] = -keyphrase_freq[test_user][q]
num_critiques = len(query)
num_affected_items = len(affected_items)
num_unaffected_items = len(unaffected_items)
# UAC
lambdas = []
for k in range(num_critiques):
optimal_lambda = 1/(2*num_critiques) # All equals to 1/(2*K)
lambdas.append(optimal_lambda)
critiqued_vector[query[k]] *= optimal_lambda
critique_score = predict_scores(matrix_U=reg.predict(critiqued_vector.reshape(1, -1)),
matrix_V=item_latent)
new_prediction = (1/2)*initial_prediction_u + critique_score.flatten()
return new_prediction, lambdas
##################################
# LP Objectives
##################################
def LP1SimplifiedOptimize(initial_prediction_u, keyphrase_freq, affected_items, unaffected_items, num_keyphrases, query, test_user, item_latent, reg):
critiqued_vector = np.zeros(keyphrase_freq[0].shape)
for q in query:
critiqued_vector[q] = -max(keyphrase_freq[test_user][q],keyphrase_freq[test_user].mean())
num_critiques = len(query)
W2 = reg.coef_
W = item_latent.dot(W2)
num_affected_items = len(affected_items)
num_unaffected_items = len(unaffected_items)
start_time = time.time()
# Model
m = Model("LP1Simplified")
m.setParam('OutputFlag', 0)
# Assignment variables
lambs = []
for k in range(num_critiques):
lambs.append(m.addVar(lb=-1,
ub=1,
vtype=GRB.CONTINUOUS,
name="lamb%d" % query[k]))
m.setObjective(quicksum(initial_prediction_u[affected_item] * num_unaffected_items + quicksum(lambs[k] * critiqued_vector[query[k]] * W[affected_item][query[k]] * num_unaffected_items for k in range(num_critiques)) for affected_item in affected_items) - quicksum(initial_prediction_u[unaffected_item] * num_affected_items + quicksum(lambs[k] * critiqued_vector[query[k]] * W[unaffected_item][query[k]] * num_affected_items for k in range(num_critiques)) for unaffected_item in unaffected_items), GRB.MINIMIZE)
# Optimize
m.optimize()
# print("Elapsed: {}".format(inhour(time.time() - start_time)))
lambdas = []
for k in range(num_critiques):
optimal_lambda = m.getVars()[k].X
lambdas.append(optimal_lambda)
critiqued_vector[query[k]] *= optimal_lambda
critique_score = predict_scores(matrix_U=reg.predict(critiqued_vector.reshape(1, -1)),
matrix_V=item_latent)
new_prediction = initial_prediction_u + critique_score.flatten()
return new_prediction, lambdas
##################################
# LP-Ranking
##################################
def LPRank(initial_prediction_u, keyphrase_freq, affected_items, unaffected_items, num_keyphrases,
query, test_user, item_latent, reg, Z_pre, Z, thetas_pre, lamb = 10, bound_range = 2):
"""
Incremental Approach
"""
critiqued_vector = np.zeros(keyphrase_freq[0].shape)
for q in query:
critiqued_vector[q] = -max(keyphrase_freq[test_user][q],keyphrase_freq[test_user].mean())
num_critiques = len(query)
num_affected_items = len(affected_items)
num_unaffected_items = len(unaffected_items)
# Model
m = Model("LPRank")
m.setParam('OutputFlag', 0) # set to 1 for outputing details
# Assignment variables
thetas = []
us = []
xi_pos = []
xi_neg = []
# weight thetas
for k in range(num_critiques + 1):
thetas.append(m.addVar(lb=-bound_range,
ub=bound_range,
vtype=GRB.CONTINUOUS,
name="theta%d" % k))
thetas = np.array(thetas)
# dummy variable u for absolute theta
for k in range(num_critiques + 1):
us.append(m.addVar(vtype=GRB.CONTINUOUS,
name="u%d" % k))
# slack variables xi
for i in range(num_affected_items):
xi_pos.append(m.addVar(lb = 0,
vtype = GRB.CONTINUOUS,
name = "xi_pos%d" % i ))
for i in range(num_unaffected_items):
xi_neg.append(m.addVar(lb = 0,
vtype = GRB.CONTINUOUS,
name = "xi_neg%d" % i ))
## constraints
# constraints for dummy variable u's
for k in range(num_critiques+1):
m.addConstr(us[k] >= thetas[k] - 1/(num_critiques+1))
m.addConstr(us[k] >= 1/(num_critiques+1) - thetas[k])
# Affected items rank higher
for j in range(num_affected_items):
m.addConstr( thetas_pre.dot(Z_pre.dot(item_latent[affected_items[j]])) - thetas.dot(Z.dot(item_latent[affected_items[j]])) >= 1 - xi_pos[j], name = "pos_constraint%d" % j )
for j in range(num_unaffected_items):
m.addConstr( thetas.dot(Z.dot(item_latent[unaffected_items[j]])) >= thetas_pre.dot(Z_pre.dot(item_latent[unaffected_items[j]])) + 1 - xi_neg[j], name = "neg_constraint%d" % j )
m.setObjective(quicksum(us) + lamb * (quicksum(xi_pos)+quicksum(xi_neg)), GRB.MINIMIZE) # Single regularization
# Optimize
m.optimize()
# Save optimal thetas
thetas = []
for k in range(num_critiques+1):
optimal_theta = m.getVarByName("theta%d" % k).X
thetas.append(optimal_theta)
for k in range(num_critiques):
critiqued_vector[query[k]] *= thetas[k+1]
# Get rating score
critique_score = predict_scores(matrix_U=reg.predict(critiqued_vector.reshape(1, -1)),
matrix_V=item_latent)
new_prediction = thetas[0]*initial_prediction_u + critique_score.flatten()
return new_prediction, thetas
def LPRank2(initial_prediction_u, keyphrase_freq, affected_items, unaffected_items, num_keyphrases,
query, test_user, item_latent, reg, Z_pre, Z, lamb = 10, bound_range = 2):
"""
Non Incremental Approach
"""
critiqued_vector = np.zeros(keyphrase_freq[0].shape)
for q in query:
critiqued_vector[q] = -max(keyphrase_freq[test_user][q],keyphrase_freq[test_user].mean())
num_critiques = len(query)
num_affected_items = len(affected_items)
num_unaffected_items = len(unaffected_items)
# Model
m = Model("LPRank")
m.setParam('OutputFlag', 0) # set to 1 for outputing details
# Assignment variables
thetas = []
us = []
xi_pos = []
xi_neg = []
# weight thetas
for k in range(num_critiques + 1):
thetas.append(m.addVar(lb=-bound_range,
ub=bound_range,
vtype=GRB.CONTINUOUS,
name="theta%d" % k))
thetas = np.array(thetas)
# dummy variable u for absolute theta
for k in range(num_critiques + 1):
us.append(m.addVar(vtype=GRB.CONTINUOUS,
name="u%d" % k))
# slack variables xi
for i in range(num_affected_items):
xi_pos.append(m.addVar(lb = 0,
vtype = GRB.CONTINUOUS,
name = "xi_pos%d" % i ))
for i in range(num_unaffected_items):
xi_neg.append(m.addVar(lb = 0,
vtype = GRB.CONTINUOUS,
name = "xi_neg%d" % i ))
## constraints
# constraints for dummy variable u's
for k in range(num_critiques+1):
m.addConstr(us[k] >= thetas[k] - 1/(num_critiques+1))
m.addConstr(us[k] >= 1/(num_critiques+1) - thetas[k])
# Affected items rank higher
for j in range(num_affected_items):
m.addConstr( initial_prediction_u[affected_items[j]] - thetas.dot(Z.dot(item_latent[affected_items[j]])) >= 1 - xi_pos[j], name = "pos_constraint%d" % j )
# Unaffected items rank lower
for j in range(num_unaffected_items):
m.addConstr( thetas.dot(Z.dot(item_latent[unaffected_items[j]])) >= initial_prediction_u[unaffected_items[j]] + 1 - xi_neg[j], name = "neg_constraint%d" % j )
m.setObjective(quicksum(us) + lamb * (quicksum(xi_pos)+quicksum(xi_neg)), GRB.MINIMIZE) # Single regularization
# Optimize
m.optimize()
# Save optimal thetas
thetas = []
for k in range(num_critiques+1):
optimal_theta = m.getVarByName("theta%d" % k).X
thetas.append(optimal_theta)
for k in range(num_critiques):
critiqued_vector[query[k]] *= thetas[k+1]
# Get rating score
critique_score = predict_scores(matrix_U=reg.predict(critiqued_vector.reshape(1, -1)),
matrix_V=item_latent)
new_prediction = thetas[0]*initial_prediction_u + critique_score.flatten()
return new_prediction, thetas
|
python
|
import json
from rest_framework.fields import MISSING_ERROR_MESSAGE
from rest_framework.relations import *
from django.utils.translation import ugettext_lazy as _
from rest_framework_json_api.exceptions import Conflict
from rest_framework_json_api.utils import Hyperlink, \
get_resource_type_from_queryset, get_resource_type_from_instance, \
get_included_serializers, get_resource_type_from_serializer
class ResourceRelatedField(PrimaryKeyRelatedField):
self_link_view_name = None
related_link_view_name = None
related_link_lookup_field = 'pk'
default_error_messages = {
'required': _('This field is required.'),
'does_not_exist': _('Invalid pk "{pk_value}" - object does not exist.'),
'incorrect_type': _('Incorrect type. Expected resource identifier object, received {data_type}.'),
'incorrect_relation_type': _('Incorrect relation type. Expected {relation_type}, received {received_type}.'),
'missing_type': _('Invalid resource identifier object: missing \'type\' attribute'),
'missing_id': _('Invalid resource identifier object: missing \'id\' attribute'),
'no_match': _('Invalid hyperlink - No URL match.'),
}
def __init__(self, self_link_view_name=None, related_link_view_name=None, **kwargs):
if self_link_view_name is not None:
self.self_link_view_name = self_link_view_name
if related_link_view_name is not None:
self.related_link_view_name = related_link_view_name
self.related_link_lookup_field = kwargs.pop('related_link_lookup_field', self.related_link_lookup_field)
self.related_link_url_kwarg = kwargs.pop('related_link_url_kwarg', self.related_link_lookup_field)
# check for a model class that was passed in for the relation type
model = kwargs.pop('model', None)
if model:
self.model = model
# We include this simply for dependency injection in tests.
# We can't add it as a class attributes or it would expect an
# implicit `self` argument to be passed.
self.reverse = reverse
super(ResourceRelatedField, self).__init__(**kwargs)
def use_pk_only_optimization(self):
# We need the real object to determine its type...
return False
def conflict(self, key, **kwargs):
"""
A helper method that simply raises a validation error.
"""
try:
msg = self.error_messages[key]
except KeyError:
class_name = self.__class__.__name__
msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)
raise AssertionError(msg)
message_string = msg.format(**kwargs)
raise Conflict(message_string)
def get_url(self, name, view_name, kwargs, request):
"""
Given a name, view name and kwargs, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
"""
# Return None if the view name is not supplied
if not view_name:
return None
# Return the hyperlink, or error if incorrectly configured.
try:
url = self.reverse(view_name, kwargs=kwargs, request=request)
except NoReverseMatch:
msg = (
'Could not resolve URL for hyperlinked relationship using '
'view name "%s".'
)
raise ImproperlyConfigured(msg % view_name)
if url is None:
return None
return Hyperlink(url, name)
def get_links(self, obj=None, lookup_field='pk'):
request = self.context.get('request', None)
view = self.context.get('view', None)
return_data = OrderedDict()
kwargs = {lookup_field: getattr(obj, lookup_field) if obj else view.kwargs[lookup_field]}
self_kwargs = kwargs.copy()
self_kwargs.update({'related_field': self.field_name if self.field_name else self.parent.field_name})
self_link = self.get_url('self', self.self_link_view_name, self_kwargs, request)
related_kwargs = {self.related_link_url_kwarg: kwargs[self.related_link_lookup_field]}
related_link = self.get_url('related', self.related_link_view_name, related_kwargs, request)
if self_link:
return_data.update({'self': self_link})
if related_link:
return_data.update({'related': related_link})
return return_data
def to_internal_value(self, data):
if isinstance(data, six.text_type):
try:
data = json.loads(data)
except ValueError:
# show a useful error if they send a `pk` instead of resource object
self.fail('incorrect_type', data_type=type(data).__name__)
if not isinstance(data, dict):
self.fail('incorrect_type', data_type=type(data).__name__)
expected_relation_type = get_resource_type_from_queryset(self.queryset)
if 'type' not in data:
self.fail('missing_type')
if 'id' not in data:
self.fail('missing_id')
if data['type'] != expected_relation_type:
self.conflict('incorrect_relation_type', relation_type=expected_relation_type, received_type=data['type'])
return super(ResourceRelatedField, self).to_internal_value(data['id'])
def to_representation(self, value):
if getattr(self, 'pk_field', None) is not None:
pk = self.pk_field.to_representation(value.pk)
else:
pk = value.pk
# check to see if this resource has a different resource_name when
# included and use that name
resource_type = None
root = getattr(self.parent, 'parent', self.parent)
field_name = self.field_name if self.field_name else self.parent.field_name
if getattr(root, 'included_serializers', None) is not None:
includes = get_included_serializers(root)
if field_name in includes.keys():
resource_type = get_resource_type_from_serializer(includes[field_name])
resource_type = resource_type if resource_type else get_resource_type_from_instance(value)
return OrderedDict([('type', resource_type), ('id', str(pk))])
@property
def choices(self):
queryset = self.get_queryset()
if queryset is None:
# Ensure that field.choices returns something sensible
# even when accessed with a read-only field.
return {}
return OrderedDict([
(
json.dumps(self.to_representation(item)),
self.display_value(item)
)
for item in queryset
])
class SerializerMethodResourceRelatedField(ResourceRelatedField):
def get_attribute(self, instance):
# check for a source fn defined on the serializer instead of the model
if self.source and hasattr(self.parent, self.source):
serializer_method = getattr(self.parent, self.source)
if hasattr(serializer_method, '__call__'):
return serializer_method(instance)
return super(ResourceRelatedField, self).get_attribute(instance)
|
python
|
import kube_vars as globalvars
import kube_factory as factory
import kube_secret
import kube_servicecheck
import kube_pvc
if __name__=="__main__":
# This is the unified interface to accept parameters
# Python model argparse be used to parse the input parameter
# Subparser has been defined in git_handler.py which including what subcmd and related parameters should be used
# IF you want to extenstion more cmd please following this coding pattern
parser=globalvars.get_value('RootCMDParser')
args = parser.parse_args(["-configtype","OutCluster","createsecret","-tenant","demo", "-env","dev", "-envtype","live","-replace","true"])
print(args)
# config and group are global config used to initial gitlab object
config,configtype,context,apiversion = None, None, None , None
if hasattr(args, 'config'):
config=args.config
if hasattr(args, 'configtype'):
configtype=args.configtype
factory.Factory_InitKubeClient(configtype,config,context,apiversion)
args.func(args)
|
python
|
import sys
from PIL import Image, ImageDraw
WRITABLES = [(0, 0, 7, 7), (24, 0, 39, 7), (56, 0, 63, 7)]
imagePath = "schoolgirlsweater_tanukirotate.png"
img = Image.open(imagePath)
draw = ImageDraw.Draw(img)
lengthPass = False
length = 0
while not lengthPass:
msg = input("Enter the messaage to encode (768 characters max):\n")
length = len(msg)
if length > 768:
print("Message is too long, please try again")
else:
lengthPass = True
ascii = [ord(c) for c in msg]
for i in range(768 - length):
ascii = ascii +[0]
it = iter(ascii)
rgb = zip(it, it, it)
counter = 0
writeArea = 0
xy = [0, 0]
for z in rgb:
draw.point(xy, fill = z)
if xy[0] >= (WRITABLES[writeArea])[2]:
xy[0] = (WRITABLES[writeArea])[0]
xy[1] = xy[1] + 1
else:
xy[0] = xy[0] + 1
if xy[1] > (WRITABLES[writeArea])[3] and writeArea + 1 < len(WRITABLES):
writeArea = writeArea + 1
xy[0] = (WRITABLES[writeArea])[0]
xy[1] = (WRITABLES[writeArea])[1]
img.save(imagePath)
img = Image.open(imagePath).convert("RGB")
px = img.load()
counter = 0
writeArea = 0
xy = [0, 0]
decodedString = []
for i in range(256):
#if (px[xy[0], xy[1]]) == (0, 0, 0):
#break
#else:
decodedString.append(px[xy[0], xy[1]])
if xy[0] >= (WRITABLES[writeArea])[2]:
xy[0] = (WRITABLES[writeArea])[0]
xy[1] = xy[1] + 1
else:
xy[0] = xy[0] + 1
if xy[1] > (WRITABLES[writeArea])[3] and writeArea + 1 < len(WRITABLES):
writeArea = writeArea + 1
xy[0] = (WRITABLES[writeArea])[0]
xy[1] = (WRITABLES[writeArea])[1]
decodedString = [i for sub in decodedString for i in sub]
decodedString = ''.join(chr(i) for i in decodedString)
print("Decoded String:")
print (decodedString)
|
python
|
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
import time
import unittest
import common.mqtt_connection as mqtt_connection
import common.mqtt_messages as mqtt_messages
import server.MQTT_callbacks as MQTT_callbacks
import server.storage as server_storage
from main import do_global_config
class TestServerMQTTCallbacks(unittest.TestCase):
def setUpClass() -> None:
do_global_config()
def test_able_to_process_heartbeat(self):
heartbeat = {
"machine_levels": {
"coffee_mg_level": 10,
"milk_mg_level": 10,
"sugar_mg_level": 10,
"water_mg_level": 10
},
"status": "OK",
"id_machine": "UNIT_TEST",
}
MQTT_callbacks.receive_heartbeat(heartbeat)
self.assertTrue("UNIT_TEST" in server_storage.coffee_machines_last_heartbeat)
self.assertTrue("UNIT_TEST" in server_storage.coffee_machines_levels)
def test_able_to_receive_order(self):
order_log = {
"machine_levels": {
"coffee_mg_level": 10,
"milk_mg_level": 10,
"sugar_mg_level": 10,
"water_mg_level": 10
},
"success": "OK",
"machine_id": "UNIT_TEST",
"timestamp": time.time(),
"coffee_name": "good coffee",
}
MQTT_callbacks.receive_order(order_log)
self.assertTrue("UNIT_TEST" in server_storage.coffee_machines_levels)
if __name__ == '__main__':
unittest.main()
|
python
|
import os,copy
import pandas as pd
from collections import OrderedDict
from pypospack.pyposmat.data import PyposmatDataAnalyzer
from pypospack.pyposmat.data import PyposmatDataFile
from pypospack.pyposmat.data import PyposmatConfigurationFile
_fn_config = os.path.join("resources","pyposmat.config.in")
_fn_results_in = os.path.join("resources","pyposmat.results.0.out")
_fn_results_out = os.path.join("resources","pyposmat.results.0a.out")
config = PyposmatConfigurationFile()
config.read(_fn_config)
qoi_targets = config.qoi_targets
print(config.qoi_targets)
print(list(config.qois))
data_in = PyposmatDataFile()
data_in.read(_fn_results_in)
data_out = PyposmatDataFile()
data_out.parameter_names = data_in.parameter_names
data_out.qoi_names = list(config.qois)
data_out.error_names = ['{}.err'.format(q) for q in data_out.qoi_names]
data_out.names = ["sim_id"]\
+data_out.parameter_names\
+data_out.qoi_names\
+data_out.error_names
data_out.types = ["sim_id"]\
+len(data_out.parameter_names)*['param']\
+len(data_out.qoi_names)*['qoi']\
+len(data_out.error_names)*['err']
def calculate_bulk_modulus(c11,c12,c44):
return (c11+2*c12)/3
def calculate_shear_modulus(c11,c12,c44):
return (c11-c12)/2
data_out_lists = []
for i,row in data_in.df.iterrows():
in_row_results = row.to_dict(into=OrderedDict)
out_row_results = OrderedDict()
for k in (["sim_id"]+data_out.parameter_names):
out_row_results[k] = in_row_results[k]
for k in (data_out.qoi_names):
try:
out_row_results[k] = in_row_results[k]
except KeyError as e:
if k == 'Ni_fcc.B':
c11 = in_row_results['Ni_fcc.c11']
c12 = in_row_results['Ni_fcc.c12']
c44 = in_row_results['Ni_fcc.c44']
out_row_results[k] = calculate_bulk_modulus(c11,c12,c44)
elif k == 'Ni_fcc.G':
c11 = in_row_results['Ni_fcc.c11']
c12 = in_row_results['Ni_fcc.c12']
c44 = in_row_results['Ni_fcc.c44']
out_row_results[k] = calculate_bulk_modulus(c11,c12,c44)
else:
raise
for k in (data_out.qoi_names):
out_row_results["{}.err".format(k)] = out_row_results[k] - qoi_targets[k]
data_out_lists.append([out_row_results[k] for k in data_out.names])
data_out.df=pd.DataFrame(data_out_lists,columns=data_out.names)
data_out.write(_fn_results_out)
|
python
|
def slugify(text):
"""
Removes all char from string that can cause problems whe used as a file name.
:param text: text to be modified.
:return: modified text
"""
return "".join(x for x in text if x.isalnum())
|
python
|
# Generated by Django 3.2.4 on 2021-06-21 18:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pvs_suban', '0009_auto_20210621_1753'),
]
operations = [
migrations.AddField(
model_name='address',
name='country',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='countries', to='pvs_suban.country'),
),
migrations.AlterField(
model_name='country',
name='value',
field=models.CharField(blank=True, max_length=256, null=True),
),
]
|
python
|
from PyQt5.QtWidgets import QBoxLayout
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QDialogButtonBox
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QMenu
from PyQt5.QtWidgets import QPushButton
from PyQt5.Qt import pyqtSignal
from PyQt5.Qt import QAction
from PyQt5.QtWidgets import QMessageBox
from PyQt5.Qt import QFontMetrics
from PyQt5.Qt import Qt
from PyQt5.Qt import QUrl
from PyQt5.QtWidgets import QFormLayout
from PyQt5.QtWidgets import QPlainTextEdit
from mc.tools.IconProvider import IconProvider
from mc.tools.EnhancedMenu import Menu, Action
from mc.common.globalvars import gVar
from mc.common import const
from .BookmarkItem import BookmarkItem
class BookmarksFoldersMenu(QMenu):
def __init__(self, parent=None):
'''
@param: parent QWidget
'''
super().__init__(parent)
self._selectedFolder = None # BookmarkItem
self._init()
def selectedFolder(self):
'''
@return: BookmarkItem
'''
return self._selectedFolder
# Q_SIGNALS:
folderSelected = pyqtSignal(BookmarkItem)
# private Q_SLOTS:
def _folderChoosed(self):
act = self.sender()
if not isinstance(act, QAction):
return
folder = act.data()
if not isinstance(folder, BookmarkItem):
return
self.folderSelected.emit(folder)
def _ADD_MENU(self, name):
bookmarks = gVar.app.bookmarks()
item = getattr(bookmarks, name)()
menu = self.addMenu(item.icon(), item.title())
self._createMenu(menu, item)
# private:
def _init(self):
self._ADD_MENU('toolbarFolder')
self._ADD_MENU('menuFolder')
self._ADD_MENU('unsortedFolder')
def _createMenu(self, menu, parent):
'''
@param: menu QMenu
@param: parent BookmarkItem
'''
act = menu.addAction(_('Choose %s') % parent.title())
act.setData(parent)
act.triggered.connect(self._folderChoosed)
menu.addSeparator()
for child in parent.children():
if not child.isFolder(): continue
m = menu.addMenu(child.icon(), child.title())
self._createMenu(m, child)
class BookmarksFoldersButton(QPushButton):
def __init__(self, parent, folder=None):
'''
@param: parent QWidget
@param: folder BookmarkItem
'''
super().__init__(parent)
self._menu = BookmarksFoldersMenu(self) # BookmarksFoldersMenu
self._selectedFolder = None # BookmarkItem
if folder:
self._selectedFolder = folder
else:
self._selectedFolder = gVar.app.bookmarks().lastUsedFolder()
self._init()
self._menu.folderSelected.connect(self.setSelectedFolder)
def selectedFolder(self):
'''
@return: BookmarkItem
'''
return self._selectedFolder
# Q_SIGNALS:
selectedFolderChanged = pyqtSignal(BookmarkItem)
# public Q_SLOTS:
def setSelectedFolder(self, folder):
'''
@param: folder BookmarkItem
'''
assert(folder)
assert(folder.isFolder())
self._selectedFolder = folder
self.setText(folder.title())
self.setIcon(folder.icon())
if self.sender():
self.selectedFolderChanged.emit(folder)
def _init(self):
self.setMenu(self._menu)
self.setSelectedFolder(self._selectedFolder)
class BookmarksTools(object):
@classmethod
def addBookmarkDialog(cls, parent, url, title, folder=None):
'''
@brief: Add Bookmark Dialogs
@param: parent QWidget
@param: url QUrl
@param: title QString
@param: folder BookmarkItem
'''
dialog = QDialog(parent)
layout = QBoxLayout(QBoxLayout.TopToBottom, dialog)
label = QLabel(dialog)
edit = QLineEdit(dialog)
folderButton = BookmarksFoldersButton(dialog, folder)
box = QDialogButtonBox(dialog)
box.addButton(QDialogButtonBox.Ok)
box.addButton(QDialogButtonBox.Cancel)
box.rejected.connect(dialog.reject)
box.accepted.connect(dialog.accept)
layout.addWidget(label)
layout.addWidget(edit)
layout.addWidget(folderButton)
layout.addWidget(box)
label.setText(_('Choose name and location of this bookmark.'))
edit.setText(title)
edit.setCursorPosition(0)
dialog.setWindowIcon(IconProvider.iconForUrl(url))
dialog.setWindowTitle(_('Add New Bookmark'))
size = dialog.size()
size.setWidth(350)
dialog.resize(size)
dialog.exec_()
if dialog.result() == QDialog.Rejected or not edit.text():
del dialog
return False
bookmark = BookmarkItem(BookmarkItem.Url)
bookmark.setTitle(edit.text())
bookmark.setUrl(url)
gVar.app.bookmarks().addBookmark(folderButton.selectedFolder(), bookmark)
del dialog
return True
@classmethod
def bookmarkAllTabsDialog(cls, parent, tabWidget, folder=None):
'''
@param: parent QWidget
@param: tabWidget TabWidget
@param: folder BookmarkItem
'''
assert(tabWidget)
dialog = QDialog(parent)
layout = QBoxLayout(QBoxLayout.TopToBottom, dialog)
label = QLabel(dialog)
folderButton = BookmarksFoldersButton(dialog, folder)
box = QDialogButtonBox(dialog)
box.addButton(QDialogButtonBox.Ok)
box.addButton(QDialogButtonBox.Cancel)
box.rejected.connect(dialog.reject)
box.accepted.connect(dialog.accept)
layout.addWidget(label)
layout.addWidget(folderButton)
layout.addWidget(box)
label.setText(_('Choose folder for bookmarks:'))
dialog.setWindowTitle(_('Bookmark All Tabs'))
size = dialog.size()
size.setWidth(350)
dialog.resize(size)
dialog.exec_()
if dialog.result() == QDialog.Rejected:
return False
for tab in tabWidget.allTabs(False):
if tab.url().isEmpty(): continue
bookmark = BookmarkItem(BookmarkItem.Url)
bookmark.setTitle(tab.title())
bookmark.setUrl(tab.url())
gVar.app.bookmarks().addBookmark(folderButton.selectedFolder(), bookmark)
del dialog
return True
@classmethod
def editBookmarkDialog(cls, parent, item):
'''
@param: parent QWidget
@param: item BookmarkItem
'''
dialog = QDialog(parent)
layout = QFormLayout(dialog)
title = QLineEdit()
address = QLineEdit()
keyword = QLineEdit()
description = QPlainTextEdit()
box = QDialogButtonBox(dialog)
box.addButton(QDialogButtonBox.Ok)
box.addButton(QDialogButtonBox.Cancel)
box.rejected.connect(dialog.reject)
box.accepted.connect(dialog.accept)
layout.addRow(_('Title:'), title)
title.setText(item.title())
if not item.isFolder():
layout.addRow(_('Address:'), address)
address.setText(item.urlString())
layout.addRow(_('Keyword:'), keyword)
keyword.setText(item.keyword())
layout.addRow(_('Description:'), description)
description.document().setPlainText(item.description())
layout.addWidget(box)
dialog.setWindowIcon(item.icon())
dialog.setWindowTitle(_('Edit Bookmark'))
dialog.exec_()
if dialog.result() == QDialog.Rejected:
del dialog
return False
item.setTitle(title.text())
if not item.isFolder():
item.setUrl(QUrl.fromEncoded(address.text().encode()))
item.setKeyword(keyword.text())
item.setDescription(description.toPlainText())
del dialog
return True
@classmethod
def openBookmark(cls, window, item):
'''
@param: window BrowserWindow
@param: item BookmarkItem
'''
assert(window)
if not item or not item.isUrl():
return
item.updateVisitCount()
window.loadAddress(item.url())
@classmethod
def openBookmarkInNewTab(cls, window, item):
'''
@param: window BrowserWindow
@param: item BookmarkItem
'''
assert(window)
if not item:
return
if item.isFolder():
cls.openFolderInTabs(window, item)
elif item.isUrl():
item.updateVisitCount()
window.tabWidget().addViewByUrlTitle(item.url(), item.title(),
gVar.appSettings.newTabPosition)
@classmethod
def openBookmarkInNewWindow(cls, window, item):
'''
@param: window BrowserWindow
@param: item BookmarkItem
'''
if not item.isUrl():
return
item.updateVisitCount()
gVar.app.createWindow(const.BW_NewWindow, item.url())
@classmethod
def openBookmarkInNewPrivateWindow(cls, window, item):
'''
@param: window BrowserWindow
@param: item BookmarkItem
'''
if not item.isUrl():
return
item.updateVisitCount()
gVar.app.startPrivateBrowsing(item.url())
@classmethod
def openFolderInTabs(cls, window, folder):
'''
@param: window BrowserWindow
@param: folder BookmarkItem
'''
assert(window)
assert(folder.isFolder())
showWarning = len(folder.children()) > 10
if not showWarning:
for child in folder.children():
if child.isFolder():
showWarning = True
break
if showWarning:
button = QMessageBox.warning(window, _('Confirmation'),
_('Are you sure you want to open all bookmarks from "%s" folder in tabs?') % folder.title(),
QMessageBox.Yes | QMessageBox.No)
if button != QMessageBox.Yes:
return
for child in folder.children():
if child.isUrl():
cls.openBookmarkInNewTab(window, child)
elif child.isFolder():
cls.openFolderInTabs(window, child)
@classmethod
def addActionToMenu(cls, receiver, menu, item):
'''
@param: receiver QObject
@param: menu Menu
@param: item BookmarkItem
'''
assert(menu)
assert(item)
type_ = item.type()
if type_ == BookmarkItem.Url:
cls.addUrlToMenu(receiver, menu, item)
elif type_ == BookmarkItem.Folder:
cls.addFolderToMenu(receiver, menu, item)
elif type_ == BookmarkItem.Separator:
cls.addSeparatorToMenu(menu, item)
@classmethod
def addFolderToMenu(cls, receiver, menu, folder):
'''
@param: receiver QObject
@param: menu Menu
@param: folder BookmarkItem
'''
assert(menu)
assert(folder)
assert(folder.isFolder())
subMenu = Menu(menu)
title = QFontMetrics(subMenu.font()).elidedText(folder.title(), Qt.ElideRight, 250)
subMenu.setTitle(title)
subMenu.setIcon(folder.icon())
cls.addFolderContentsToMenu(receiver, subMenu, folder)
# QAction
act = menu.addMenu(subMenu)
act.setData(folder)
act.setIconVisibleInMenu(True)
@classmethod
def addUrlToMenu(cls, receiver, menu, bookmark):
'''
@param: receiver QObject
@param: menu Menu
@param: bookmark BookmarkItem
'''
assert(menu)
assert(bookmark)
assert(bookmark.isUrl())
act = Action(menu)
title = QFontMetrics(act.font()).elidedText(bookmark.title(), Qt.ElideRight, 250)
act.setText(title)
act.setData(bookmark)
act.setIconVisibleInMenu(True)
act.triggered.connect(receiver._bookmarkActivated)
act.ctrlTriggered.connect(receiver._bookmarkCtrlActivated)
act.shiftTriggered.connect(receiver._bookmarkShiftActivated)
menu.addAction(act)
@classmethod
def addSeparatorToMenu(cls, menu, separator):
'''
@param: menu Menu
@param: separator BookmarkItem
'''
assert(menu)
assert(separator.isSeparator())
menu.addSeparator()
@classmethod
def addFolderContentsToMenu(cls, receiver, menu, folder):
'''
@param: receiver QObject
@param: menu Menu
@param: folder BookmarkItem
'''
menu.aboutToShow.connect(receiver._menuAboutToShow)
menu.menuMiddleClicked.connect(receiver._menuMiddleClicked)
for child in folder.children():
cls.addActionToMenu(receiver, menu, child)
if menu.isEmpty():
menu.addAction(_('Empty')).setDisabled(True)
#@classmethod
#def migrateBookmarksIfNecessary(cls, bookmarks):
# '''
# @brief: Migration from Sql Bookmarks (returns tree if bookmarks migrated)
# '''
# pass
|
python
|
"""Merge constrained primitives as property constraints."""
import collections
from typing import Tuple, Optional, List, Mapping, MutableMapping, Sequence
from icontract import ensure
from aas_core_codegen import intermediate
from aas_core_codegen.common import Error
from aas_core_codegen.infer_for_schema import (
_len as infer_for_schema_len,
_pattern as infer_for_schema_pattern,
)
from aas_core_codegen.infer_for_schema._types import (
ConstraintsByProperty,
LenConstraint,
PatternConstraint,
)
@ensure(lambda result: (result[0] is not None) ^ (result[1] is not None))
def _infer_len_constraints_by_constrained_primitive(
symbol_table: intermediate.SymbolTable,
) -> Tuple[
Optional[MutableMapping[intermediate.ConstrainedPrimitive, LenConstraint]],
Optional[List[Error]],
]:
"""Infer the constraints on ``len(.)`` of the constrained primitives."""
# NOTE (mristin, 2022-02-11):
# We do this inference in two passes. In the first pass, we only infer
# the constraints defined for the constrained primitive and ignore the ancestors.
# In the second pass, we stack the constraints of the ancestors as well.
errors = [] # type: List[Error]
first_pass: MutableMapping[
intermediate.ConstrainedPrimitive, LenConstraint
] = collections.OrderedDict()
for symbol in symbol_table.symbols:
if isinstance(symbol, intermediate.ConstrainedPrimitive):
(
len_constraint,
len_constraint_errors,
) = infer_for_schema_len.infer_len_constraint_of_self(
constrained_primitive=symbol
)
if len_constraint_errors is not None:
errors.extend(len_constraint_errors)
else:
assert len_constraint is not None
first_pass[symbol] = len_constraint
if len(errors) > 0:
return None, errors
second_pass: MutableMapping[
intermediate.ConstrainedPrimitive, LenConstraint
] = collections.OrderedDict()
for symbol in symbol_table.symbols_topologically_sorted:
if isinstance(symbol, intermediate.ConstrainedPrimitive):
# NOTE (mristin, 2022-02-11):
# We make the copy in order to avoid bugs when we start processing
# the inheritances.
len_constraint = first_pass[symbol].copy()
for inheritance in symbol.inheritances:
inherited_len_constraint = second_pass.get(inheritance, None)
assert (
inherited_len_constraint is not None
), "Expected topological order"
if inherited_len_constraint.min_value is not None:
len_constraint.min_value = (
max(
len_constraint.min_value, inherited_len_constraint.min_value
)
if len_constraint.min_value is not None
else inherited_len_constraint.min_value
)
if inherited_len_constraint.max_value is not None:
len_constraint.max_value = (
min(
len_constraint.max_value, inherited_len_constraint.max_value
)
if len_constraint.max_value is not None
else inherited_len_constraint.max_value
)
second_pass[symbol] = len_constraint
assert len(errors) == 0
return second_pass, None
def _infer_pattern_constraints_by_constrained_primitive(
symbol_table: intermediate.SymbolTable,
pattern_verifications_by_name: infer_for_schema_pattern.PatternVerificationsByName,
) -> MutableMapping[intermediate.ConstrainedPrimitive, List[PatternConstraint]]:
"""Infer the pattern constraints of the constrained strings."""
# NOTE (mristin, 2022-02-11):
# We do this inference in two passes. In the first pass, we only infer
# the constraints defined for the constrained primitive and ignore the ancestors.
# In the second pass, we stack the constraints of the ancestors as well.
first_pass: MutableMapping[
intermediate.ConstrainedPrimitive,
List[PatternConstraint],
] = collections.OrderedDict()
for symbol in symbol_table.symbols:
if (
isinstance(symbol, intermediate.ConstrainedPrimitive)
and symbol.constrainee is intermediate.PrimitiveType.STR
):
pattern_constraints = infer_for_schema_pattern.infer_patterns_on_self(
constrained_primitive=symbol,
pattern_verifications_by_name=pattern_verifications_by_name,
)
first_pass[symbol] = pattern_constraints
second_pass: MutableMapping[
intermediate.ConstrainedPrimitive,
List[PatternConstraint],
] = collections.OrderedDict()
for symbol in first_pass:
# NOTE (mristin, 2022-02-11):
# We make the copy in order to avoid bugs when we start processing
# the inheritances.
pattern_constraints = first_pass[symbol][:]
for inheritance in symbol.inheritances:
assert inheritance in first_pass, (
f"We are processing the constrained primitive {symbol.name!r}. "
f"However, its parent, {inheritance.name!r}, has not been processed in "
f"the first pass. Something probably went wrong in the first pass."
)
inherited_pattern_constraints = second_pass.get(inheritance, None)
assert inherited_pattern_constraints is not None, (
f"Expected topological order. However, the symbol {symbol.name!r} "
f"is being processed before one of its parents, {inheritance.name!r}."
)
pattern_constraints = inherited_pattern_constraints + pattern_constraints
second_pass[symbol] = pattern_constraints
return second_pass
@ensure(lambda result: (result[0] is not None) ^ (result[1] is not None))
def infer_constraints_by_class(
symbol_table: intermediate.SymbolTable,
) -> Tuple[
Optional[MutableMapping[intermediate.ClassUnion, ConstraintsByProperty]],
Optional[List[Error]],
]:
"""Infer the constraints from the invariants and constrained primitives."""
errors = [] # type: List[Error]
pattern_verifications_by_name = (
infer_for_schema_pattern.map_pattern_verifications_by_name(
verifications=symbol_table.verification_functions
)
)
(
len_constraints_by_constrained_primitive,
some_errors,
) = _infer_len_constraints_by_constrained_primitive(symbol_table=symbol_table)
if some_errors is not None:
errors.extend(some_errors)
if len(errors) > 0:
return None, errors
assert len_constraints_by_constrained_primitive is not None
patterns_by_constrained_primitive = (
_infer_pattern_constraints_by_constrained_primitive(
symbol_table=symbol_table,
pattern_verifications_by_name=pattern_verifications_by_name,
)
)
result: MutableMapping[
intermediate.ClassUnion, ConstraintsByProperty
] = collections.OrderedDict()
for symbol in symbol_table.symbols:
if not isinstance(
symbol, (intermediate.AbstractClass, intermediate.ConcreteClass)
):
continue
# region Infer constraints on ``len(.)``
len_constraints_by_property: MutableMapping[
intermediate.Property, LenConstraint
] = collections.OrderedDict()
(
len_constraints_from_invariants,
len_constraints_errors,
) = infer_for_schema_len.len_constraints_from_invariants(cls=symbol)
if len_constraints_errors is not None:
errors.extend(len_constraints_errors)
continue
assert len_constraints_from_invariants is not None
patterns_by_property: MutableMapping[
intermediate.Property, List[PatternConstraint]
] = collections.OrderedDict()
patterns_from_invariants_by_property = (
infer_for_schema_pattern.patterns_from_invariants(
cls=symbol, pattern_verifications_by_name=pattern_verifications_by_name
)
)
# region Merge the length constraints
for prop in symbol.properties:
# NOTE (mristin, 2022-03-03):
# We need to go beneath ``Optional`` as the constraints are applied even
# if a property is optional. In cases where cardinality is affected by
# ``Optional``, the client code needs to cover them separately.
type_anno = intermediate.beneath_optional(prop.type_annotation)
len_constraint_from_type: Optional[LenConstraint] = None
len_constraint_from_invariants = len_constraints_from_invariants.get(
prop, None
)
if isinstance(type_anno, intermediate.OurTypeAnnotation) and isinstance(
type_anno.symbol, intermediate.ConstrainedPrimitive
):
len_constraint_from_type = len_constraints_by_constrained_primitive.get(
type_anno.symbol, None
)
# Merge the constraint from the type and from the invariants
if (
len_constraint_from_type is None
and len_constraint_from_invariants is None
):
pass
elif (
len_constraint_from_type is not None
and len_constraint_from_invariants is None
):
if (
len_constraint_from_type.min_value is not None
or len_constraint_from_type.max_value is not None
):
len_constraints_by_property[prop] = len_constraint_from_type
elif (
len_constraint_from_type is None
and len_constraint_from_invariants is not None
):
if (
len_constraint_from_invariants.min_value is not None
or len_constraint_from_invariants.max_value is not None
):
len_constraints_by_property[prop] = len_constraint_from_invariants
elif (
len_constraint_from_type is not None
and len_constraint_from_invariants is not None
):
# NOTE (mristin, 2022-03-02):
# We have to make the bounds *stricter* since both
# the type constraints and the invariant(s) need to be satisfied.
min_value = infer_for_schema_len.max_with_none(
len_constraint_from_type.min_value,
len_constraint_from_invariants.min_value,
)
max_value = infer_for_schema_len.min_with_none(
len_constraint_from_type.max_value,
len_constraint_from_invariants.max_value,
)
if (
min_value is not None
and max_value is not None
and min_value > max_value
):
errors.append(
Error(
symbol.parsed.node,
f"The inferred minimum and maximum value on len(.) "
f"is contradictory: "
f"minimum = {min_value}, maximum = {max_value}; "
f"please check the invariants and "
f"any involved constrained primitives",
)
)
continue
if min_value is not None or max_value is not None:
len_constraints_by_property[prop] = LenConstraint(
min_value=min_value, max_value=max_value
)
else:
raise AssertionError(
f"Unhandled case: "
f"{len_constraint_from_type=}, {len_constraint_from_invariants}"
)
# endregion
# region Infer constraints on string patterns
for prop in symbol.properties:
# NOTE (mristin, 2022-03-03):
# We need to go beneath ``Optional`` as the constraints are applied even
# if a property is optional. In cases where cardinality is affected by
# ``Optional``, the client code needs to cover them separately.
type_anno = intermediate.beneath_optional(prop.type_annotation)
patterns_from_type: List[PatternConstraint] = []
patterns_from_invariants = patterns_from_invariants_by_property.get(
prop, []
)
if isinstance(type_anno, intermediate.OurTypeAnnotation) and isinstance(
type_anno.symbol, intermediate.ConstrainedPrimitive
):
patterns_from_type = patterns_by_constrained_primitive.get(
type_anno.symbol, []
)
merged = patterns_from_type + patterns_from_invariants
if len(merged) > 0:
patterns_by_property[prop] = merged
# endregion
result[symbol] = ConstraintsByProperty(
len_constraints_by_property=len_constraints_by_property,
patterns_by_property=patterns_by_property,
)
if len(errors) > 0:
return None, errors
return result, None
@ensure(lambda result: (result[0] is not None) ^ (result[1] is not None))
def merge_constraints_with_ancestors(
symbol_table: intermediate.SymbolTable,
constraints_by_class: Mapping[intermediate.ClassUnion, ConstraintsByProperty],
) -> Tuple[
Optional[MutableMapping[intermediate.ClassUnion, ConstraintsByProperty]],
Optional[Error],
]:
"""
Merge the constraints over all the classes with their ancestors.
Usually, when you generate a schema, you do *not* want to inherit the constraints
over the properties. Most schema engines will do that for you and you want to be
as explicit as possible in the schema for readability (whereas merged constraints
might not be as readable, since you do not explicitly see their origin).
However, for some applications we indeed want to stack the constraints and merge
them. For example, this is the case when we (semi-)automatically generate test
data. In those cases, you should use this function.
The length constraints are merged by picking the smaller interval that fits.
Patterns are simply stacked together.
"""
new_constraints_by_class: MutableMapping[
intermediate.ClassUnion, ConstraintsByProperty
] = collections.OrderedDict()
for symbol in symbol_table.symbols_topologically_sorted:
if not isinstance(
symbol, (intermediate.AbstractClass, intermediate.ConcreteClass)
):
continue
this_constraints_by_props = constraints_by_class[symbol]
new_len_constraints_by_property: MutableMapping[
intermediate.Property, LenConstraint
] = collections.OrderedDict()
new_patterns_by_property: MutableMapping[
intermediate.Property, Sequence[PatternConstraint]
] = collections.OrderedDict()
for prop in symbol.properties:
# region Merge len constraints
len_constraints = []
this_len_constraint = (
this_constraints_by_props.len_constraints_by_property.get(prop, None)
)
if this_len_constraint is not None:
len_constraints.append(this_len_constraint)
for parent in symbol.inheritances:
# NOTE (mristin, 2022-05-15):
# Assume here that all the ancestors already inherited their constraints
# due to the topological order in the iteration.
that_constraints_by_props = new_constraints_by_class[parent]
that_len_constraint = (
that_constraints_by_props.len_constraints_by_property.get(
prop, None
)
)
if that_len_constraint is not None:
len_constraints.append(that_len_constraint)
min_value = None
max_value = None
for len_constraint in len_constraints:
if min_value is None:
min_value = len_constraint.min_value
else:
if len_constraint.min_value is not None:
min_value = max(len_constraint.min_value, min_value)
if max_value is None:
max_value = len_constraint.max_value
else:
if len_constraint.max_value is not None:
max_value = min(len_constraint.max_value, max_value)
if (
min_value is not None
and max_value is not None
and min_value > max_value
):
return None, Error(
symbol.parsed.node,
f"We could not stack the length constraints "
f"on the property {prop.name} as they are contradicting: "
f"min_value == {min_value} and max_value == {max_value}. "
f"Please check the invariants and the invariants of all "
f"the ancestors.",
)
if min_value is not None or max_value is not None:
new_len_constraints_by_property[prop] = LenConstraint(
min_value=min_value, max_value=max_value
)
# endregion
# region Merge patterns
# NOTE (mristin, 2022-05-15):
# The following logic has quadratic time complexity, but it seems that
# the runtime is currently no problem in practice.
patterns = [] # type: List[PatternConstraint]
this_patterns = this_constraints_by_props.patterns_by_property.get(
prop, None
)
if this_patterns is not None:
patterns.extend(this_patterns)
set_of_this_patterns = (
set()
if this_patterns is None
else set(this_pattern.pattern for this_pattern in this_patterns)
)
for parent in symbol.inheritances:
# NOTE (mristin, 2022-05-15):
# Assume here that all the ancestors already inherited their constraints
# due to the topological order in the iteration.
that_constraints_by_props = new_constraints_by_class[parent]
that_patterns = that_constraints_by_props.patterns_by_property.get(
prop, None
)
if that_patterns is not None:
for that_pattern in that_patterns:
# NOTE (mristin, 2022-06-15):
# We have to make sure that we do not inherit the same pattern
# from the parent.
#
# This is particularly important if the inherited property is a
# constrained primitive. In that case, if we didn't check for
# the duplicates, we would inherit the same pattern multiple
# times as we can not distinguish whether the pattern
# comes from an invariant of the parent or an invariant of
# the constrained primitive.
if that_pattern.pattern not in set_of_this_patterns:
patterns.append(that_pattern)
if len(patterns) > 0:
new_patterns_by_property[prop] = patterns
# endregion
new_constraints_by_class[symbol] = ConstraintsByProperty(
len_constraints_by_property=new_len_constraints_by_property,
patterns_by_property=new_patterns_by_property,
)
return new_constraints_by_class, None
|
python
|
from core.models import UrineDrugScreen
from rest_framework import serializers
class UrineDrugScreenSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = UrineDrugScreen
fields = ('id', 'participant_id', 'date_of_test', 'uds_temp', 'pregnancy_test', 'opiates', 'fentanyl', 'bup', 'coc', 'amp', 'm_amp', 'thc', 'mtd', 'pcp', 'bar', 'bzo', 'tca', 'oxy')
|
python
|
from typing import Optional, List
from pydantic import BaseModel
from feeder.api.models import BasePaginatedList
class GenericResponse(BaseModel):
success: str = "ok"
class FrontButton(BaseModel):
enable: bool = True
class UTCOffset(BaseModel):
utc_offset: int = -7
class TriggerFeeding(BaseModel):
portion: float = 0.0625
class FeedEvent(BaseModel):
device_name: Optional[str]
device_hid: str
timestamp: int
start_time: int
end_time: int
pour: Optional[int]
full: Optional[int]
grams_expected: int
grams_actual: int
hopper_start: int
hopper_end: int
source: int
fail: bool
trip: Optional[bool]
lrg: Optional[bool]
vol: Optional[bool]
bowl: Optional[bool]
recipe_id: str
error: Optional[str]
class FeedHistory(BasePaginatedList):
data: List[FeedEvent]
|
python
|
from al_utils.vaal_util import train_vae, train_vae_disc
from al_utils import vae_sampling as vs
import sys
import pickle
import torch
import numpy as np
import os
from copy import deepcopy
from pycls.core.config import custom_dump_cfg
import pycls.datasets.loader as imagenet_loader
def save_numpy_arrays(arrays, names, parent_dir, saveinText=False):
"""Saves numpy arrays"""
for i, a in enumerate(arrays):
if saveinText:
np.savetxt(parent_dir + names[i] + ".txt", a, fmt="%d")
print(
"Saved {} at path: {} !!".format(
names[i], parent_dir + names[i] + ".txt"
)
)
else:
np.save(parent_dir + names[i] + ".npy", a)
print(
"Saved {} at path: {} !!".format(
names[i], parent_dir + names[i] + ".npy"
)
)
# #train task model
def vaal_active_sampling(cfg, dataObj, debug=False):
"""Implements VAAL sampling.
Args:
cfg: Reference to the config yaml
dataObj: Reference to data class
debug (bool, optional): Switch for debug mode. Defaults to False.
"""
temp_old_im_size = cfg.TRAIN.IM_SIZE
if cfg.TRAIN.DATASET.lower() == "imagenet":
cfg.TRAIN.IM_SIZE = cfg.VAAL.IM_SIZE # args.vaal_im_size
print("cfg.TRAIN.IM_SIZE: ", cfg.TRAIN.IM_SIZE)
print("cfg.VAAL.IM_SIZE: ", cfg.VAAL.IM_SIZE)
lSet_path = cfg.ACTIVE_LEARNING.LSET_PATH
uSet_path = cfg.ACTIVE_LEARNING.USET_PATH
if debug:
print("lSetPath: {}".format(lSet_path))
if debug:
print("uSetPath: {}".format(uSet_path))
lSet = np.load(lSet_path, allow_pickle=True)
uSet = np.load(uSet_path, allow_pickle=True)
print("---------Loaded partitions--------")
print("lSet: {}, uSet: {}".format(len(lSet), len(uSet)))
if cfg.TRAIN.DATASET.upper() == "IMAGENET":
temp_cfg_worker = cfg.DATA_LOADER.NUM_WORKERS
cfg.DATA_LOADER.NUM_WORKERS = 0
if cfg.TRAIN.DATASET == "IMAGENET":
dataObj = None
noAugDataset = None
elif cfg.TRAIN.DATASET == "STL10":
oldmode = dataObj.eval_mode
dataObj.eval_mode = True
noAugDataset, _ = dataObj.getDatasetForVAAL(
save_dir=cfg.TRAIN_DIR, isTrain=True, isDownload=True
)
dataObj.eval_mode = oldmode
else:
oldmode = dataObj.eval_mode
dataObj.eval_mode = True
noAugDataset, _ = dataObj.getDataset(
save_dir=cfg.TRAIN_DIR, isTrain=True, isDownload=True
)
dataObj.eval_mode = oldmode
# First train vae and disc
vae, disc = train_vae_disc(cfg, lSet, uSet, noAugDataset, dataObj, debug)
if cfg.TRAIN.DATASET == "IMAGENET":
temp_vaal_bs = cfg.VAAL.VAE_BS
cfg.VAAL.VAE_BS = cfg.TRAIN.BATCH_SIZE
uSetLoader = imagenet_loader.construct_loader_no_aug(
cfg, indices=uSet, isShuffle=False, isDistributed=False
) # , isVaalSampling=True)
cfg.VAAL.VAE_BS = temp_vaal_bs
else:
uSetLoader = dataObj.getSequentialDataLoader(
indexes=uSet,
batch_size=int(cfg.TRAIN.BATCH_SIZE / cfg.NUM_GPUS),
data=noAugDataset,
)
# Do active sampling
print("Setting vae and disc in eval mode..!")
vae.eval()
disc.eval()
print("Done!!")
sampler = vs.AdversarySampler(budget=cfg.ACTIVE_LEARNING.BUDGET_SIZE)
print("call vae sampling to get activeSet")
activeSet, uSet = sampler.sample_for_labeling(
vae=vae, discriminator=disc, unlabeled_dataloader=uSetLoader, uSet=uSet, cfg=cfg
)
lSet = np.append(lSet, activeSet)
# save arrays in npy format
save_numpy_arrays(
[lSet, uSet, activeSet], ["lSet", "uSet", "activeSet"], cfg.OUT_DIR
)
# save arrays in txt format
save_numpy_arrays(
[lSet, uSet, activeSet],
["lSet", "uSet", "activeSet"],
cfg.OUT_DIR,
saveinText=True,
)
if cfg.TRAIN.DATASET.lower() == "imagenet":
cfg.TRAIN.IM_SIZE = temp_old_im_size
cfg.DATA_LOADER.NUM_WORKERS = temp_cfg_worker
# Dump cfg file --
temp_cfg = deepcopy(cfg)
temp_cfg.ACTIVE_LEARNING.ACTIVATE = True
temp_cfg.ACTIVE_LEARNING.LSET_PATH = os.path.join(temp_cfg.OUT_DIR, "lSet.npy")
temp_cfg.ACTIVE_LEARNING.USET_PATH = os.path.join(temp_cfg.OUT_DIR, "uSet.npy")
custom_dump_cfg(temp_cfg)
def vaal_active_sampling_minus_disc(cfg, dataObj, debug=False):
lSet_path = cfg.ACTIVE_LEARNING.LSET_PATH
uSet_path = cfg.ACTIVE_LEARNING.USET_PATH
lSet = np.load(lSet_path, allow_pickle=True)
uSet = np.load(uSet_path, allow_pickle=True)
# trainDataset = dataObj.getDataset(save_dir=cfg.TRAIN_DIR, isTrain=True, isDownload=True)
if cfg.TRAIN.DATASET == "IMAGENET":
dataObj = None
noAugDataset = None
else:
oldmode = dataObj.eval_mode
dataObj.eval_mode = True
noAugDataset, _ = dataObj.getDataset(
save_dir=cfg.TRAIN_DIR, isTrain=True, isDownload=True
)
dataObj.eval_mode = oldmode
# First train vae
vae = train_vae(cfg, lSet, uSet, noAugDataset, dataObj, debug)
if cfg.TRAIN.DATASET == "IMAGENET":
lSetLoader = imagenet_loader.construct_loader_no_aug(
cfg, indices=lSet, isShuffle=False, isDistributed=False
) # , isVaalSampling=True)
uSetLoader = imagenet_loader.construct_loader_no_aug(
cfg, indices=uSet, isShuffle=False, isDistributed=False
) # , isVaalSampling=True)
else:
lSetLoader = dataObj.getIndexesDataLoader(
indexes=lSet,
batch_size=int(cfg.TRAIN.BATCH_SIZE / cfg.NUM_GPUS),
data=noAugDataset,
)
uSetLoader = dataObj.getSequentialDataLoader(
indexes=uSet,
batch_size=int(cfg.TRAIN.BATCH_SIZE / cfg.NUM_GPUS),
data=noAugDataset,
)
# Do active sampling
vae.eval()
sampler = vs.AdversarySampler(budget=cfg.ACTIVE_LEARNING.BUDGET_SIZE)
with torch.no_grad():
activeSet, uSet = sampler.vae_sample_for_labeling(
vae=vae,
uSet=uSet,
lSet=lSet,
unlabeled_dataloader=uSetLoader,
lSetLoader=lSetLoader,
)
lSet = np.append(lSet, activeSet)
save_numpy_arrays(
[lSet, uSet, activeSet], ["lSet", "uSet", "activeSet"], cfg.OUT_DIR
)
save_numpy_arrays(
[lSet, uSet, activeSet],
["lSet", "uSet", "activeSet"],
cfg.OUT_DIR,
saveinText=True,
)
tempArgsFile = sys.argv[1]
# Getting back the objects:
with open(tempArgsFile, "rb") as f: # Python 3: open(..., 'rb')
cfg, dataObj = pickle.load(f)
if cfg.ACTIVE_LEARNING.SAMPLING_FN == "vaal":
# Run original vaal
print("--------------------------")
print("Running VAAL Sampling")
print("--------------------------")
print("dataObj: {}".format(dataObj))
vaal_active_sampling(cfg, dataObj, debug=True)
elif cfg.ACTIVE_LEARNING.SAMPLING_FN == "vaal_minus_disc":
# Run vaal[-d]
print("--------------------------")
print("Running VAAL MINUS DISC Sampling")
print("--------------------------")
vaal_active_sampling_minus_disc(cfg, dataObj, debug=True)
|
python
|
import sys
import os
import datetime
import psycopg2
import pandas
from subprocess import call, Popen
print "dropping temporary members from database..."
conn_string = "dbname='hamlethurricane' user=postgres port='5432' host='127.0.0.1' password='password'"
try:
conn = psycopg2.connect(conn_string)
except Exception as e:
print str(e)
sys.exit()
hurricane_name = 'ARTHUR'
dataframe_cur = conn.cursor()
dataframe_sql = """Select * from hurricane_{}""".format(hurricane_name)
dataframe_cur.execute(dataframe_sql)
data = dataframe_cur.fetchall()
colnames = [desc[0] for desc in dataframe_cur.description]
dataframe = pandas.DataFrame(data)
dataframe.columns = colnames
conn.commit()
range_feat = range(len(dataframe))
range_feat_strp = str(range_feat).strip('[]')
range_feat_strp_v2 = range_feat_strp.split(',')
drop_dismembered_cur = conn.cursor()
for key in range(1, len(dataframe)):
sql = """drop table if exists {}_{} cascade""".format(hurricane_name, key)
drop_dismembered_cur.execute(sql)
conn.commit()
conn.close()
|
python
|
######################################################################
######################################################################
# Copyright Tsung-Hsien Wen, Cambridge Dialogue Systems Group, 2016 #
######################################################################
######################################################################
import numpy as np
import theano
import theano.tensor as T
# numerical stability
eps = 1e-7
# gradient clipping
class GradClip(theano.compile.ViewOp):
def __init__(self, clip_lower_bound, clip_upper_bound):
self.clip_lower_bound = clip_lower_bound
self.clip_upper_bound = clip_upper_bound
assert(self.clip_upper_bound >= self.clip_lower_bound)
def grad(self, args, g_outs):
return [T.clip(g_out, self.clip_lower_bound, self.clip_upper_bound) for g_out in g_outs]
def clip_gradient(x, bound):
grad_clip = GradClip(-bound, bound)
try:
T.opt.register_canonicalize(theano.gof.OpRemove(grad_clip), name='grad_clip_%.1f' % (bound))
except ValueError:
pass
return grad_clip(x)
# obtain sent logprob by summing over word logprob
def collectSentLogp(p,cutoff_t,cutoff_b):
q = p.dimshuffle(1,0)
def sump(p_b,stop_t):
logp = T.sum(T.log10(p_b[:stop_t]))
return logp
cutoff_logp, _ = theano.scan(fn=sump,\
sequences=[q[:cutoff_b],cutoff_t[:cutoff_b]],\
outputs_info=[None])
return cutoff_logp
# Node class for performing beam search
class BeamSearchNode(object):
def __init__(self,h,c,prevNode,wordid,logp,leng):
self.h = h
self.c = c
self.logp = logp
self.leng = leng
self.wordid = wordid
self.prevNode = prevNode
self.sv = None
def eval(self):
if self.leng>40:
return self.logp/float(self.leng-1+eps)-40.0
return self.logp/float(self.leng-1+eps)
# basic class for Recurrent Language Generator
class BaseRLG(object):
def __init__(self, gentype, beamwidth, overgen,
vocab_size, hidden_size, batch_size, da_sizes):
# setting hyperparameters
self.gentype= gentype
self.di = vocab_size
self.dh = hidden_size
self.db = batch_size
self.dfs = da_sizes
self.overgen= overgen
self.beamwidth = beamwidth
def _init_params(self):
#TODO: function for initialise weight matrices
pass
def unroll(self):
#TODO: unrolling function in theano, for training
pass
def _recur(self):
#TODO: per step recurrence function in theano, for training
pass
def beamSearch(self):
#TODO: generation function in numpy, beam search decoding
pass
def sample(self):
#TODO: generation function in numpy, random sampling
pass
def _gen(self):
#TODO: per step generation function in numpy, for decoding
pass
def loadConverseParams(self):
#TODO: load numpy parameters
pass
def setParams(self,params):
# set theano parameters
for i in range(len(self.params)):
self.params[i].set_value(params[i])
def getParams(self):
# fetch theano parameters
return [p.get_value() for p in self.params]
def numOfParams(self):
# return number of parameters
return sum([p.get_value().size for p in self.params])
|
python
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2018-07-30 19:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data', '0053_merge_20180615_1859'),
]
operations = [
migrations.AddField(
model_name='vmflavor',
name='cpus',
field=models.IntegerField(default=1, help_text='How many CPUs are assigned to this flavor'),
),
]
|
python
|
"""Allow _view property in graph file schema
Revision ID: 8f6d4eef042d
Revises: a2316139e9a3
Create Date: 2021-10-20 10:04:21.668552
"""
import hashlib
import json
from os import path
import fastjsonschema
import sqlalchemy as sa
from alembic import context
from alembic import op
from sqlalchemy import table, column, and_
from sqlalchemy.orm import Session
from migrations.utils import window_chunk
# revision identifiers, used by Alembic.
revision = '8f6d4eef042d'
down_revision = 'a2316139e9a3'
branch_labels = None
depends_on = None
# reference to this directory
directory = path.realpath(path.dirname(__file__))
with open(path.join(directory, '../upgrade_data/graph_v3.json'), 'r') as f:
# Use this method to validate the content of an enrichment table
validate_graph = fastjsonschema.compile(json.load(f))
def drop_view_property():
"""
We start using _view property in graph files. By design it should not exist (file
format documentation prohibits properties starting with _). However, our schema do not used
to validate this constrain. Just to be sure this migration runs check to delete _view
property from existing files (new uploads with this property will not pass schema validation).
"""
conn = op.get_bind()
session = Session(conn)
t_files = table(
'files',
column('content_id', sa.Integer),
column('mime_type', sa.String))
t_files_content = table(
'files_content',
column('id', sa.Integer),
column('raw_file', sa.LargeBinary),
column('checksum_sha256', sa.Binary)
)
files = conn.execution_options(stream_results=True).execute(sa.select([
t_files_content.c.id,
t_files_content.c.raw_file
]).where(
and_(
t_files.c.mime_type == 'vnd.lifelike.document/graph',
t_files.c.content_id == t_files_content.c.id
)
))
for chunk in window_chunk(files, 25):
for id, content in chunk:
graph = json.loads(content)
if '_views' in graph:
del graph['_views']
validate_graph(graph)
raw_file = json.dumps(graph).encode('utf-8')
checksum_sha256 = hashlib.sha256(raw_file).digest()
session.execute(
t_files_content.update().where(
t_files_content.c.id == id
).values(
raw_file=raw_file,
checksum_sha256=checksum_sha256
)
)
session.flush()
session.commit()
def upgrade():
if context.get_x_argument(as_dictionary=True).get('data_migrate', None):
data_upgrades()
def downgrade():
if context.get_x_argument(as_dictionary=True).get('data_migrate', None):
data_upgrades()
def data_upgrades():
drop_view_property()
def data_downgrades():
drop_view_property()
|
python
|
# -*- coding: utf-8 -*-
from abc import ABC, abstractmethod
from fuocore.models import (
SongModel,
ArtistModel,
AlbumModel,
PlaylistModel,
LyricModel,
UserModel,
)
class AbstractProvider(ABC):
"""abstract music resource provider
"""
# A well behaved provider should implement its own models .
Song = SongModel
Artist = ArtistModel
Album = AlbumModel
Playlist = PlaylistModel
Lyric = LyricModel
User = UserModel
@property
@abstractmethod
def identifier(self):
"""provider identify"""
@property
@abstractmethod
def name(self):
"""provider name"""
|
python
|
import warnings
from mmdet.models.builder import (BACKBONES, DETECTORS, HEADS, LOSSES, NECKS,
ROI_EXTRACTORS, SHARED_HEADS, build)
from .registry import FUSION_LAYERS, MIDDLE_ENCODERS, VOXEL_ENCODERS
from mmdet3d.datasets.pipelines import Compose
def build_backbone(cfg):
"""Build backbone."""
return build(cfg, BACKBONES)
def build_neck(cfg):
"""Build neck."""
return build(cfg, NECKS)
def build_roi_extractor(cfg):
"""Build RoI feature extractor."""
return build(cfg, ROI_EXTRACTORS)
def build_shared_head(cfg):
"""Build shared head of detector."""
return build(cfg, SHARED_HEADS)
def build_head(cfg):
"""Build head."""
return build(cfg, HEADS)
def build_loss(cfg):
"""Build loss function."""
return build(cfg, LOSSES)
def build_detector(cfg, train_cfg=None, test_cfg=None):
"""Build detector."""
if train_cfg is not None or test_cfg is not None:
warnings.warn(
'train_cfg and test_cfg is deprecated, '
'please specify them in model', UserWarning)
assert cfg.get('train_cfg') is None or train_cfg is None, \
'train_cfg specified in both outer field and model field '
assert cfg.get('test_cfg') is None or test_cfg is None, \
'test_cfg specified in both outer field and model field '
return build(cfg, DETECTORS, dict(train_cfg=train_cfg, test_cfg=test_cfg))
def build_voxel_encoder(cfg):
"""Build voxel encoder."""
return build(cfg, VOXEL_ENCODERS)
def build_middle_encoder(cfg):
"""Build middle level encoder."""
return build(cfg, MIDDLE_ENCODERS)
def build_fusion_layer(cfg):
"""Build fusion layer."""
return build(cfg, FUSION_LAYERS)
|
python
|
from flask import Flask
from . import api_credentials_provider
def create_app(test_config=None) -> Flask:
"""Main entry point of the service. The application factory is responsible for
creating and confguring the flask app. It also defines a http ping endpoint and registers blueprints.
Returns:
Flask: the flask app
"""
app = Flask(__name__, instance_relative_config=True)
if test_config:
app.config.from_mapping(test_config)
else:
app.config.from_mapping(
GIPHY_API_KEY=api_credentials_provider.resolve_credentials()
)
@app.route("/ping")
def ping():
return "OK"
from . import search
app.register_blueprint(search.bp)
return app
|
python
|
# encapsulation
def outer(num1):
print("outer")
def inner_increment(num1):
print("inner")
return num1 + 1
num2 = inner_increment(num1)
print(num1, num2)
outer(10)
|
python
|
'''
Extract special sequences from fasta file. You can specify which sequences get extracted by using the a separator.
Usage: python extract <fasta_file> <output_file> <separator>
Author: Nicolas Schmelling
'''
from Bio import SeqIO
import sys
def extract(fasta_file, output_file, separator):
with open(output_file,"w") as f:
extract_seqs = []
for seq_record in SeqIO.parse(fasta_file, "fasta"):
if separator in seq_record.description:
extract_seqs.append(seq_record)
SeqIO.write(extract_seqs, f, "fasta")
if __name__ == "__main__":
fasta_file = sys.argv[1]
output_file = sys.argv[2]
separator = sys.argv[3]
extract(fasta_file, output_file, separator)
|
python
|
"""Utilities for interacting with ProxyStore"""
import proxystore as ps
from typing import Any, Optional, Union
from colmena.models import SerializationMethod
class ColmenaSerializationFactory(ps.store.redis.RedisFactory):
"""Custom Factory for using Colmena serialization utilities"""
def __init__(self,
key: str,
name: str,
hostname: str,
port: int,
serialization_method: Union[str, SerializationMethod] = SerializationMethod.PICKLE,
**kwargs) -> None:
"""Init ColmenaSerialization Factory
Args:
key (str): key corresponding to object in Redis.
name (str): name of store to retrive objects from.
hostname (str): hostname of Redis server containing object.
port (int): port of Redis server containing object.
serialization_method (str): Colmena serialization method to use
for deserializing the object when resolved from Redis.
kwargs: keyword arguments to pass to the RedisFactory.
"""
self.serialization_method = serialization_method
self.kwargs = kwargs
super(ColmenaSerializationFactory, self).__init__(
key, name, hostname, port, **kwargs
)
def __getnewargs_ex__(self):
"""Helper method for pickling
Note:
We override default pickling behavior because a Factory may contain
a Future if it is being asynchronously resolved and Futures cannot
be pickled.
"""
return (self.key, self.name, self.hostname, self.port), {
'serialization_method': self.serialization_method,
**self.kwargs
}
def resolve(self) -> Any:
obj_str = super(ColmenaSerializationFactory, self).resolve()
return SerializationMethod.deserialize(self.serialization_method, obj_str)
def proxy(obj: Any,
key: Optional[str] = None,
is_serialized: bool = False,
serialization_method: Union[str, SerializationMethod] = SerializationMethod.PICKLE,
**kwargs) -> ps.proxy.Proxy:
"""Place object in Value Server and return Proxy
Args:
obj: object to be placed in Value Server and proxied.
key (str): optional key to associate with object. By default, ProxyStore
will create a key for the object (default: None).
is_serialized (bool): True if obj is already serialized (default: False).
serialization_method (str): serialization method to use for the object
(default: SerializationMethod.PICKLE).
kwargs (dict): keyword arguments to pass to ProxyStore.store.redis.RedisStore.proxy().
Returns:
ps.proxy.Proxy
"""
store = ps.store.get_store('redis')
if not is_serialized:
obj = SerializationMethod.serialize(serialization_method, obj)
return store.proxy(
obj,
key,
serialize=False, # Do not use ProxyStore serialization utilities
serialization_method=serialization_method,
factory=ColmenaSerializationFactory,
**kwargs
)
def resolve_proxies_async(args: Union[object, list, tuple, dict]) -> None:
"""Begin asynchronously resolving all proxies in input
Scan inputs for instances of `Proxy` and begin asynchronously resolving.
This is useful if you have one or more proxies that will be needed soon
so the underlying objects can be asynchronously resolved to reduce the
cost of the first access to the proxy.
Args:
args (object, list, tuple, dict): possible object or
iterable of objects that may be ObjectProxy instances
"""
def resolve_async_if_proxy(obj: Any) -> None:
if isinstance(obj, ps.proxy.Proxy):
ps.proxy.resolve_async(obj)
if isinstance(args, ps.proxy.Proxy):
resolve_async_if_proxy(args)
elif isinstance(args, list) or isinstance(args, tuple):
for x in args:
resolve_async_if_proxy(x)
elif isinstance(args, dict):
for x in args:
resolve_async_if_proxy(args[x])
|
python
|
from ... import error
from ..entity import Entity
from ..component import Component
__all__ = ["Parent"]
class Parent(Component):
def __init__(self, parent: Entity):
self._parent = parent
def parent(self, err=True) -> Entity:
if self._parent is None and err:
raise error.ecs.ParentError(self.entity)
return self._parent
def __repr__(self) -> str:
return f"{super().__repr__()}<{self._parent}>"
|
python
|
from microbit import *
import utime
class Rangefinder:
def __init__(self, pin):
'''Setup a rangefinder on the specified pin'''
self.pin = pin
def distance_cm(self):
'''Returns the distance from a rangefinder in cm'''
self.pin.write_digital(0)
utime.sleep_us(200)
self.pin.write_digital(1)
utime.sleep_us(500)
self.pin.write_digital(0)
init = utime.ticks_us()
stop = init
start = init
flag = False
timeout = 100000
while not self.pin.read_digital():
if utime.ticks_us() - init > timeout:
return -1
start = utime.ticks_us()
while self.pin.read_digital():
if utime.ticks_us() - start > timeout:
return -1
stop = utime.ticks_us()
distance = (stop - start) * 343 / 20000
print(stop, start)
return distance
|
python
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from backend.accounts import bcs_perm
from backend.iam.permissions.resources.namespace_scoped import NamespaceScopedPermCtx, NamespaceScopedPermission
from backend.resources.namespace.utils import get_namespaces_by_cluster_id
from backend.templatesets.legacy_apps.configuration import constants, models
from backend.templatesets.legacy_apps.configuration.yaml_mode.res2files import get_resource_file, get_template_files
def get_namespace_id(access_token, project_id, cluster_id, namespace):
namespaces = get_namespaces_by_cluster_id(access_token, project_id, cluster_id)
for ns in namespaces:
if ns["name"] == namespace:
return ns["id"]
raise serializers.ValidationError(_("项目(id:{})下不存在命名空间({}/{})").format(project_id, cluster_id, namespace))
def add_fields_in_template_files(version_id, req_template_files):
"""
add id and content fields in template_files
"""
try:
ventity = models.VersionedEntity.objects.get(id=version_id)
except models.VersionedEntity.DoesNotExist:
raise serializers.ValidationError(f"template version(id:{version_id}) does not exist")
entity = ventity.get_entity()
template_files = []
for res_file in req_template_files:
res_name = res_file["resource_name"]
res_file_ids = entity[res_name].split(",")
resource_file = get_resource_file(res_name, res_file_ids, "id", "name", "content")
if "files" not in res_file:
template_files.append(resource_file)
continue
if not res_file["files"]:
raise serializers.ValidationError(f"empty parameter files in template_files({res_name})")
resource_file_map = {f["name"]: f for f in resource_file["files"]}
files = [resource_file_map[f["name"]] for f in res_file["files"]]
template_files.append({"resource_name": res_name, "files": files})
return template_files
class NamespaceInfoSLZ(serializers.Serializer):
cluster_id = serializers.CharField()
name = serializers.CharField()
class TemplateReleaseSLZ(serializers.Serializer):
project_id = serializers.CharField()
template_name = serializers.CharField()
show_version_name = serializers.CharField()
template_files = serializers.JSONField(required=False)
namespace_info = NamespaceInfoSLZ()
template_variables = serializers.JSONField(default={})
def _validate_template_files(self, data):
"""
template_files: [{'resource_name': 'Deployment', 'files': [{'name': ''}]}]
"""
if "template_files" not in data:
data["template_files"] = get_template_files(data["show_version"].real_version_id, "id", "name", "content")
return
template_files = data["template_files"]
if not template_files:
raise serializers.ValidationError("empty parameter template_files")
try:
data["template_files"] = add_fields_in_template_files(data["show_version"].real_version_id, template_files)
except Exception as err:
raise serializers.ValidationError(f"invalid parameter template_files: {err}")
def _validate_namespace_info(self, data):
request = self.context["request"]
namespace_info = data["namespace_info"]
namespace_info["id"] = get_namespace_id(
request.user.token.access_token, data["project_id"], namespace_info["cluster_id"], namespace_info["name"]
)
perm_ctx = NamespaceScopedPermCtx(
username=request.user.username,
project_id=data["project_id"],
cluster_id=namespace_info["cluster_id"],
name=namespace_info["name"],
)
NamespaceScopedPermission().can_use(perm_ctx)
def validate(self, data):
template_name = data["template_name"]
try:
template = models.Template.objects.get(
project_id=data["project_id"], name=template_name, edit_mode=constants.TemplateEditMode.YAML.value
)
data["template"] = template
except models.Template.DoesNotExist:
raise serializers.ValidationError(_("YAML模板集(name:{})不存在").format(template_name))
try:
show_version = models.ShowVersion.objects.get(name=data["show_version_name"], template_id=template.id)
data["show_version"] = show_version
except models.ShowVersion.DoesNotExist:
raise serializers.ValidationError(
_("YAML模板集(name:{})不存在版本{}").format(template_name, data["show_version_name"])
)
self._validate_namespace_info(data)
self._validate_template_files(data)
return data
|
python
|
def test_requirements(supported_configuration):
pass
|
python
|
import os
import sys
import math
import scipy.signal
import schemasim.schemas.l0_schema_templates as st
class PhysicalCondition(st.RoleDefiningSchema):
def __init__(self):
super().__init__()
self._type = "PhysicalCondition"
self._meta_type.append("PhysicalCondition")
self._roles = {}
def isDefaultCompatible(self):
return False
class Default(PhysicalCondition):
def __init__(self):
super().__init__()
self._type = "Default"
self._meta_type.append("DefaultPhysicalCondition")
self._roles = {}
def isDefaultCompatible(self):
return True
class CollisionEnabled(Default):
def __init__(self, obj=None):
super().__init__()
self._type = "CollisionEnabled"
self._meta_type.append("CollisionEnabled")
self._roles = {"obj": obj}
class CollisionDisabled(PhysicalCondition):
def __init__(self, obj=None):
super().__init__()
self._type = "CollisionDisabled"
self._meta_type.append("CollisionDisabled")
self._roles = {"obj": obj}
class PhysicsPrimitiveQuality(st.RoleDefiningSchema):
def __init__(self, obj=None, quality="", default=1.0):
super().__init__()
self._type = "PhysicsPrimitiveQuality"
self._meta_type.append("PhysicsPrimitiveQuality")
self._normal = default
if (None != obj) and ("ParameterizedSchema" in obj._meta_type) and (quality in obj._parameters):
self._normal = obj._parameters[quality]
self._roles = {"obj": obj}
self._quality = quality
def getReferenceValue(self):
return self._normal
def _getQuality(self):
retq = self._normal
if (None != self._roles['obj']) and (self._quality in self._roles['obj']._parameters):
retq = self._roles['obj']._parameters[self._quality]
return retq
def evaluateFrame(self, frameData, sim):
return True, 1.0
def filterPD(self, rpd, sim, strictness=0.005):
return rpd
class MassSettingSchema(PhysicsPrimitiveQuality):
def __init__(self, obj=None):
super().__init__(obj=obj, quality="mass")
self._type = "MassSettingSchema"
self._meta_type.append("MassSettingSchema")
def evaluateFrame(self, frameData, sim):
mass = self._getQuality()
ref = self.getReferenceValue()
sc = math.exp(-math.fabs(mass - ref)/(ref/5.0))
return (0.2 < sc), sc
def filterPD(self, rpd, sim, strictness=0.005):
space = sim.space()
ref = self.getReferenceValue()
for c in rpd:
c[0] = c[0]*math.exp(-math.fabs(c[1] - ref)/(ref/5.0))
return rpd
class Heavy(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "Heavy"
self._meta_type.append("Heavy")
def getReferenceValue(self):
return 5*self._normal
class VeryHeavy(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "VeryHeavy"
self._meta_type.append("VeryHeavy")
def getReferenceValue(self):
return 25*self._normal
class Lightweight(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "Lightweight"
self._meta_type.append("Lightweight")
def getReferenceValue(self):
return 0.2*self._normal
class VeryLightweight(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "VeryLightweight"
self._meta_type.append("VeryLightweight")
def getReferenceValue(self):
return 0.04*self._normal
class RestitutionSettingSchema(PhysicsPrimitiveQuality):
def __init__(self, obj=None):
super().__init__(obj=obj, quality="restitution")
self._type = "RestitutionSettingSchema"
self._meta_type.append("RestitutionSettingSchema")
def evaluateFrame(self, frameData, sim):
restitution = self._getQuality()
ref = self.getReferenceValue()
sc = math.exp(-math.fabs(restitution - ref)/(0.1))
return (0.2 < sc), sc
def filterPD(self, rpd, sim, strictness=0.005):
space = sim.space()
ref = self.getReferenceValue()
for c in rpd:
c[0] = c[0]*math.exp(-math.fabs(c[1] - ref)/(0.1))
return rpd
class Elastic(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "Elastic"
self._meta_type.append("Elastic")
def getReferenceValue(self):
return 0.6
class VeryElastic(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "VeryElastic"
self._meta_type.append("VeryElastic")
def getReferenceValue(self):
return 0.8
class Inelastic(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "Inelastic"
self._meta_type.append("Inelastic")
def getReferenceValue(self):
return 0.3
class VeryInelastic(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "VeryInelastic"
self._meta_type.append("VeryInelastic")
def getReferenceValue(self):
return 0.1
class FrictionSettingSchema(PhysicsPrimitiveQuality):
def __init__(self, obj=None):
super().__init__(obj=obj, quality="friction")
self._type = "FrictionSettingSchema"
self._meta_type.append("FrictionSettingSchema")
def evaluateFrame(self, frameData, sim):
friction = self._getQuality()
ref = self.getReferenceValue()
sc = math.exp(-math.fabs(friction - ref)/(0.1))
return (0.2 < sc), sc
def filterPD(self, rpd, sim, strictness=0.005):
space = sim.space()
ref = self.getReferenceValue()
for c in rpd:
c[0] = c[0]*math.exp(-math.fabs(c[1] - ref)/(0.1))
return rpd
class Frictious(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "Frictious"
self._meta_type.append("Frictious")
def getReferenceValue(self):
return 0.6
class Slippery(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "Slippery"
self._meta_type.append("Slippery")
def getReferenceValue(self):
return 0.3
class VeryFrictious(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "VeryFrictious"
self._meta_type.append("VeryFrictious")
def getReferenceValue(self):
return 0.8
class VerySlippery(MassSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "VerySlippery"
self._meta_type.append("VerySlippery")
def getReferenceValue(self):
return 0.1
class ParticleNumSettingSchema(PhysicsPrimitiveQuality):
def __init__(self, obj=None):
super().__init__(obj=obj, quality="particle_num")
self._type = "ParticleNumSettingSchema"
self._meta_type.append("ParticleNumSettingSchema")
self._normal = 30
def evaluateFrame(self, frameData, sim):
return True, 1.0
def filterPD(self, rpd, sim, strictness=0.005):
space = sim.space()
for c in rpd:
c[0] = c[0]*math.exp(-math.fabs(c[1] - self._normal)/(self._normal/5.0))
return rpd
class Plentiful(ParticleNumSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "Plentiful"
self._meta_type.append("Plentiful")
self._normal = 50
class Scarce(ParticleNumSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "Scarce"
self._meta_type.append("Scarce")
self._normal = 15
class VeryPlentiful(ParticleNumSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "Plentiful"
self._meta_type.append("Plentiful")
self._normal = 90
class VeryScarce(ParticleNumSettingSchema):
def __init__(self, obj=None):
super().__init__(obj=obj)
self._type = "Scarce"
self._meta_type.append("Scarce")
self._normal = 5
|
python
|
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Module authors:
# Georg Brandl <[email protected]>
#
# *****************************************************************************
"""Base classes for YAML based datasinks."""
from datetime import datetime
from time import time as currenttime
import quickyaml
from nicos import session
from nicos.core import NicosError
from nicos.devices.datasinks.image import SingleFileSinkHandler
from nicos.utils import AutoDefaultODict
def nice_datetime(dt):
if isinstance(dt, float):
dt = datetime.fromtimestamp(dt)
rounded = dt.replace(microsecond=0)
return rounded.isoformat()
class YAMLBaseFileSinkHandler(SingleFileSinkHandler):
filetype = 'MLZ.YAML' # to be overwritten in derived classes
max_yaml_width = 120
accept_final_images_only = True
yaml_array_handling = quickyaml.ARRAY_AS_SEQ
objects = ['angle', 'clearance', 'current', 'displacement', 'duration',
'energy', 'frequency', 'temperature', 'wavelength',
'offset', 'width', 'height', 'length']
units = ['deg', 'mm', 'A', 'mm', 's', 'meV', 'hertz', 'K', 'A',
'mm', 'mm', 'mm', 'mm']
def _readdev(self, devname, mapper=lambda x: x):
try:
return mapper(session.getDevice(devname).read())
except NicosError:
return None
def _devpar(self, devname, parname, mapper=lambda x: x):
try:
return mapper(getattr(session.getDevice(devname), parname))
except NicosError:
return None
def _dict(self):
return AutoDefaultODict()
def _flowlist(self, *args):
return quickyaml.flowlist(*args)
def writeData(self, fp, image):
"""Save in YAML format."""
fp.seek(0)
expdev = session.experiment
instrdev = session.instrument
o = AutoDefaultODict()
instr = o['instrument']
instr['name'] = instrdev.instrument
instr['facility'] = instrdev.facility
instr['operator'] = ', '.join(instrdev.operators)
instr['website'] = instrdev.website
instr['references'] = [AutoDefaultODict({'doi': instrdev.doi})]
o['format']['identifier'] = self.__class__.filetype
for obj, unit in zip(self.objects, self.units):
o['format']['units'][obj] = unit
exp = o['experiment']
exp['number'] = expdev.propinfo.get('session', expdev.proposal)
exp['proposal'] = expdev.proposal
exp['title'] = expdev.title
exp['authors'] = []
for user in expdev.propinfo.get('users', []):
a = AutoDefaultODict()
a['name'] = user['name']
a['affiliation'] = user.get('affiliation')
a['roles'] = self._flowlist(['principal_investigator'])
exp['authors'].append(a)
for user in expdev.propinfo.get('localcontacts', []):
a = AutoDefaultODict()
a['name'] = user['name']
a['affiliation'] = user.get('affiliation')
a['roles'] = self._flowlist(['local_contact'])
exp['authors'].append(a)
meas = o['measurement']
meas['number'] = self.dataset.number
meas['unique_identifier'] = '%s/%s/%s' % (
expdev.proposal, self.dataset.counter, self.dataset.number)
hist = meas['history']
hist['started'] = nice_datetime(self.dataset.started)
hist['stopped'] = nice_datetime(currenttime())
sample = meas['sample']['description']
sample['name'] = expdev.sample.samplename
env = meas['sample']['environment'] = []
stats = self.dataset.valuestats
for (info, val) in zip(self.dataset.envvalueinfo,
self.dataset.envvaluelist):
entry = self._dict()
entry['name'] = info.name
entry['unit'] = info.unit
entry['value'] = val
if info.name in stats:
entry['mean'] = stats[info.name][0]
entry['stddev'] = stats[info.name][1]
entry['min'] = stats[info.name][2]
entry['max'] = stats[info.name][3]
env.append(entry)
self._write_instr_data(meas, image)
quickyaml.Dumper(width=self.max_yaml_width,
array_handling=self.yaml_array_handling).dump(o, fp)
fp.flush()
def _write_instr_data(self, meas_root, image):
raise NotImplementedError('implement _write_instr_data')
|
python
|
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2020 Intel Corporation
""" ETCD Data Write Tool """
import argparse
import logging
import os
import sys
import eis_integ
def parse_arguments(_cli_args):
""" Parse argument passed to function """
parser = argparse.ArgumentParser(description=
"Adds the contents of the json file to the etcd database.")
parser.add_argument("arg", help=
"Name of the json file whose contents should be added to the database.")
return parser.parse_args()
def main(args):
""" Calls the eis_integ.etcd_put_json function to add the contents of the json file
to the etcd database """
eis_integ.init_logger()
os.environ["ETCDCTL_ENDPOINTS"] = "https://" + eis_integ.extract_etcd_endpoint()
eis_integ.check_path_variable("ETCDCTL_CACERT", os.environ.get("ETCDCTL_CACERT"))
eis_integ.check_path_variable("ETCDCTL_CERT", os.environ.get("ETCDCTL_CERT"))
eis_integ.check_path_variable("ETCDCTL_KEY", os.environ.get("ETCDCTL_KEY"))
print("Update the etcd database or add {} file contents to the etcd database".format(args.arg))
eis_integ.etcd_put_json(eis_integ.load_json(args.arg))
return eis_integ.CODES.NO_ERROR
if __name__ == '__main__':
try:
sys.exit(main(parse_arguments(sys.argv[1:])).value)
except eis_integ.EisIntegError as exception:
logging.error("Error while adding entries to ETCD database: %s", exception)
sys.exit(exception.code.value)
|
python
|
from app.validation.validation import validate, ARGS, KWARGS
import json
import os
__db_items__ = "db/items"
class Item:
def __init__(self):
pass
@validate(4, ARGS)
def save(self, id, name, price, qty):
with open(f"{__db_items__}/{name}.json", 'w') as f:
data = {
'id': id,
'name': name,
'price': price,
'qty': qty
}
json.dump(data, f)
print("Item Saved")
def __get_item_list(self, name):
try:
item_list = os.listdir(__db_items__)
return [x for x in item_list if x == f"{name}.json"][0]
except Exception as e:
return None
@validate(1, ARGS)
def find(self, name):
item = self.__get_item_list(name)
if item != None:
with open(f"{__db_items__}/{item}", "r") as f:
data = json.load(f)
print(f"\nID: {data['id']} Name: {data['name']} Price: {data['price']} QTY: {data['qty']}", end='\n')
return data
else:
print("No Item")
def getAll(self):
files = os.listdir(__db_items__)
all_items = []
if len(files) > 0:
for fs in files:
with open(f"{__db_items__}/{fs}", "r") as f:
data = json.load(f)
print(f"ID: {data['id']} Name: {data['name']} Price: {data['price']} QTY: {data['qty']}", end='\n')
all_items.append(data)
return all_items
else:
print("No Items found.!")
return None
@validate(1, ARGS)
def is_item_exist(self, name):
item = self.__get_item_list(name)
if item != None:
return item.__contains__(name)
else:
return False
|
python
|
import json
from setuptools import setup, find_packages
from pydoccano import __version__
def requirements():
requirements_list = []
with open('Pipfile.lock', "r") as requirements:
data = json.load(requirements)
data = data['default']
for i in data:
try:
req = i + data[i]['version'].replace('==', '>=')
except KeyError:
req = f"-e git+{data[i]['git']}@{data[i]['ref']}#egg={i}"
requirements_list.append(req)
return requirements_list
setup(
name='pydoccano',
version=__version__,
description='This package for API of doccano',
author='Bogdan Evstratenko)',
author_email='[email protected]',
url='https://github.com/evstratbg/pydoccano',
packages=find_packages(),
python_requires='>=3.7',
install_requires=requirements(),
)
|
python
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import json
import time
from multiprocessing import Process
import pytest
import six
import thriftpy2
from thriftpy2.http import make_server as make_http_server, \
make_client as make_http_client
from thriftpy2.protocol import TApacheJSONProtocolFactory
from thriftpy2.rpc import make_server as make_rpc_server, \
make_client as make_rpc_client
from thriftpy2.thrift import TProcessor, TType
from thriftpy2.transport import TMemoryBuffer
from thriftpy2.transport.buffered import TBufferedTransportFactory
def recursive_vars(obj):
if isinstance(obj, six.string_types):
return six.ensure_str(obj)
if isinstance(obj, six.binary_type):
return six.ensure_binary(obj)
if isinstance(obj, (int, float, bool)):
return obj
if isinstance(obj, dict):
return {k: recursive_vars(v) for k, v in obj.items()}
if isinstance(obj, (list, set)):
return [recursive_vars(v) for v in obj]
if hasattr(obj, '__dict__'):
return recursive_vars(vars(obj))
def test_thrift_transport():
test_thrift = thriftpy2.load(
"apache_json_test.thrift",
module_name="test_thrift"
)
Test = test_thrift.Test
Foo = test_thrift.Foo
test_object = Test(
tbool=False,
tbyte=16,
tdouble=1.234567,
tlong=123123123,
tshort=123,
tint=12345678,
tstr="Testing String",
tsetofints={1, 2, 3, 4, 5},
tmap_of_int2str={
1: "one",
2: "two",
3: "three"
},
tlist_of_strings=["how", "do", "i", "test", "this?"],
tmap_of_str2foo={'first': Foo("first"), "2nd": Foo("baz")},
tmap_of_str2foolist={
'test': [Foo("test list entry")]
},
tmap_of_str2mapofstring2foo={
"first": {
"second": Foo("testing")
}
},
tmap_of_str2stringlist={
"words": ["dog", "cat", "pie"],
"other": ["test", "foo", "bar", "baz", "quux"]
},
tfoo=Foo("test food"),
tlist_of_foo=[Foo("1"), Foo("2"), Foo("3")],
tlist_of_maps2int=[
{"one": 1, "two": 2, "three": 3}
],
tmap_of_int2foo={
1: Foo("One"),
2: Foo("Two"),
5: Foo("Five")
},
tbinary=b"\x01\x0fabc123\x00\x02"
)
# A request generated by apache thrift that matches the above object
request_data = b"""[1,"test",1,0,{"1":{"rec":{"1":{"tf":0},"2":{"i8":16},
"3":{"i16":123},"4":{"i32":12345678},"5":{"i64":123123123},"6":
{"dbl":1.234567},"7":{"str":"Testing String"},"8":{"lst":["str",5,
"how","do","i","test","this?"]},"9":{"map":["i32","str",3,{"1":"one",
"2":"two","3":"three"}]},"10":{"set":["i32",5,1,2,3,4,5]},
"11":{"map":["str","rec",2,{"first":{"1":{"str":"first"}},"2nd":
{"1":{"str":"baz"}}}]},"12":{"map":["str","lst",
2,{"words":["str",3,"dog","cat","pie"],"other":["str",5,"test",
"foo","bar","baz","quux"]}]},"13":{"map":["str",
"map",1,{"first":["str","rec",1,{"second":{"1":{"str":"testing"}}}]}]},
"14":{"lst":["rec",3,{"1":{"str":"1"}},
{"1":{"str":"2"}},{"1":{"str":"3"}}]},"15":{"rec":{"1":{
"str":"test food"}}},"16":{"lst":["map",1,["str","i32",
3,{"one":1,"two":2,"three":3}]]},"17":{"map":["str","lst",1,{"test":
["rec",1,{"1":{"str":"test list entry"}}]}]},
"18":{"map":["i32","rec",3,{"1":{"1":{"str":"One"}},"2":{"1":
{"str":"Two"}},"5":{"1":{"str":"Five"}}}]},
"19":{"str":"AQ9hYmMxMjMAAg=="}}}}]"""
class Handler:
@staticmethod
def test(t):
# t should match the object above
expected_a = recursive_vars(t)
expected_b = recursive_vars(test_object)
if TType.STRING != TType.BINARY:
assert expected_a == expected_b
return t
tp2_thrift_processor = TProcessor(test_thrift.TestService, Handler())
tp2_factory = TApacheJSONProtocolFactory()
iprot = tp2_factory.get_protocol(TMemoryBuffer(request_data))
obuf = TMemoryBuffer()
oprot = tp2_factory.get_protocol(obuf)
tp2_thrift_processor.process(iprot, oprot)
# output buffers should be the same
final_data = obuf.getvalue()
assert json.loads(request_data.decode('utf8'))[4]['1'] == \
json.loads(final_data.decode('utf8'))[4]['0']
@pytest.mark.parametrize('server_func', [(make_rpc_server, make_rpc_client),
(make_http_server, make_http_client)])
def test_client(server_func):
test_thrift = thriftpy2.load(
"apache_json_test.thrift",
module_name="test_thrift"
)
class Handler:
@staticmethod
def test(t):
return t
def run_server():
server = make_http_server(
test_thrift.TestService,
handler=Handler(),
host='localhost',
port=9090,
proto_factory=TApacheJSONProtocolFactory(),
trans_factory=TBufferedTransportFactory()
)
server.serve()
proc = Process(target=run_server, )
proc.start()
time.sleep(0.25)
try:
test_object = test_thrift.Test(
tdouble=12.3456,
tint=567,
tstr='A test \'{["string',
tmap_of_bool2str={True: "true string", False: "false string"},
tmap_of_bool2int={True: 0, False: 1}
)
client = make_http_client(
test_thrift.TestService,
host='localhost',
port=9090,
proto_factory=TApacheJSONProtocolFactory(),
trans_factory=TBufferedTransportFactory()
)
res = client.test(test_object)
assert recursive_vars(res) == recursive_vars(test_object)
finally:
proc.terminate()
time.sleep(1)
|
python
|
#!/usr/bin/env python
""" """
# Script information for the file.
__author__ = "Philippe T. Pinard"
__email__ = "[email protected]"
__version__ = "0.1"
__copyright__ = "Copyright (c) 2015 Philippe T. Pinard"
__license__ = "GPL v3"
# Standard library modules.
import unittest
import logging
import os
import tempfile
import shutil
# Third party modules.
import numpy as np
import tifffile
# Local modules.
from pyhmsa.datafile import DataFile
from pyhmsa.spec.condition.acquisition import AcquisitionRasterXY
from pyhmsa.spec.datum.imageraster import ImageRaster2D
from pyhmsa.type.numerical import _SUPPORTED_DTYPES
from pyhmsa_tiff.fileformat.exporter.tiff import ExporterTIFF, ExporterTIFFMultiPage
# Globals and constants variables.
def _create_datafile():
datafile = DataFile()
acq = AcquisitionRasterXY(60, 50, (0.1, 'nm'), (0.1, 'nm'))
for dtype in _SUPPORTED_DTYPES:
datum = ImageRaster2D(60, 50, dtype=dtype)
datum[:] = np.random.random((60, 50)) * 255
datum.conditions.add('Acq', acq)
datafile.data.add(dtype.name, datum)
return datafile
class TestExporterTIFF(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
self.tmpdir = tempfile.mkdtemp()
self.exp = ExporterTIFF(compress=9)
self.datafile = _create_datafile()
def tearDown(self):
unittest.TestCase.tearDown(self)
shutil.rmtree(self.tmpdir, ignore_errors=True)
def testexport(self):
self.exp.export(self.datafile, self.tmpdir)
filepaths = self.exp.get()
self.assertEqual(len(filepaths), len(_SUPPORTED_DTYPES))
for filepath in filepaths:
with tifffile.TiffFile(filepath) as tif:
actual = tif.asarray()
identifier = os.path.splitext(os.path.basename(filepath))[0].split('_')[1]
expected = self.datafile.data[identifier]
np.testing.assert_almost_equal(actual, expected.T, 4)
class TestExporterTIFFMultiPage(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
self.tmpdir = tempfile.mkdtemp()
self.exp = ExporterTIFFMultiPage(compress=9)
self.datafile = _create_datafile()
def tearDown(self):
unittest.TestCase.tearDown(self)
shutil.rmtree(self.tmpdir, ignore_errors=True)
def testexport(self):
self.exp.export(self.datafile, self.tmpdir)
filepaths = self.exp.get()
self.assertEqual(len(filepaths), 1)
with tifffile.TiffFile(filepaths[0]) as tif:
self.assertEqual(len(tif.pages), len(_SUPPORTED_DTYPES))
if __name__ == '__main__': #pragma: no cover
logging.getLogger().setLevel(logging.DEBUG)
unittest.main()
|
python
|
import argparse
from multiprocessing import Pool
from grit.occlusion_detection.occlusion_detection_geometry import OcclusionDetector2D
from grit.core.base import create_folders
from igp2.data import ScenarioConfig
def prepare_episode_occlusion_dataset(params):
scenario_name, episode_idx, debug, debug_steps = params
print('scenario {} episode {}'.format(scenario_name, episode_idx))
occlusion_detector = OcclusionDetector2D(scenario_name, episode_idx, debug=debug, debug_steps=debug_steps)
occlusion_detector.extract_occlusions()
print('finished scenario {} episode {}'.format(scenario_name, episode_idx))
def main():
parser = argparse.ArgumentParser(description='Process the dataset')
parser.add_argument('--scenario', type=str, help='Name of scenario to process', default=None)
parser.add_argument('--workers', type=int, help='Number of multiprocessing workers', default=8)
parser.add_argument('--debug',
help="if set, we plot all the occlusions in a frame for each vehicle."
"If --debug_steps is also True, this takes precedence and --debug_steps will be"
"deactivated.",
action='store_true')
parser.add_argument('--debug_steps',
help="if set, we plot the occlusions created by each obstacle. "
"If --debug is set, --debug_steps will be disabled.",
action='store_true')
args = parser.parse_args()
create_folders()
if args.debug_steps and args.debug:
args.debug_steps = False
if args.scenario is None:
scenarios = ['heckstrasse', 'bendplatz', 'frankenberg', 'round']
else:
scenarios = [args.scenario]
params_list = []
for scenario_name in scenarios:
scenario_config = ScenarioConfig.load(f"scenarios/configs/{scenario_name}.json")
for episode_idx in range(len(scenario_config.episodes)):
params_list.append((scenario_name, episode_idx, args.debug, args.debug_steps))
with Pool(args.workers) as p:
p.map(prepare_episode_occlusion_dataset, params_list)
if __name__ == '__main__':
main()
|
python
|
# This is the base module that will be imported by Django.
# Try to import the custom settings.py file, which will in turn import one of the deployment targets.
# If it doesn't exist we assume this is a vanilla development environment and import .deployments.settings_dev.
try:
from .settings import * # noqa
except ImportError as e:
if e.msg == "No module named 'config.settings.settings'":
from .settings_dev import * # noqa
else:
raise
|
python
|
http://stackoverflow.com/questions/2339101/knights-shortest-path-chess-question
|
python
|
import numpy as np
import pandas as pd
import pickle
import os
import json
import glob
import scipy
from ngboost import NGBRegressor
from ngboost.distns import Normal
from ngboost.learners import default_tree_learner
from ngboost.scores import MLE, LogScore
from sklearn.model_selection import KFold
from sklearn.metrics import mean_squared_error, mean_absolute_error, accuracy_score, confusion_matrix
from classes.qrfr import QuantileRandomForestRegressor as qfrfQuantileRandomForestRegressor
class ModelTrainer:
"""
This class will perform training on datasets. This could happen during the grid search for the best combination
of weights, or, once the weights are assessed, for the creation of the final models
"""
def __init__(self, features_analyzer, input_gatherer, forecast_type, cfg, logger):
"""
Constructor
:param features_analyzer: Features Analyzer
:type features_analyzer: FeaturesAnalyzer
:param input_gatherer: Inputs Gatherer
:type input_gatherer: InputsGatherer
:param forecast_type: Forecast type (MOR | EVE)
:type forecast_type: str
:param cfg: FTP parameters for the files exchange
:type cfg: dict
:param logger: Logger
:type logger: Logger object
"""
# set the variables
self.features_analyzer = features_analyzer
self.forecast_type = forecast_type
self.input_gatherer = input_gatherer
self.cfg = cfg
self.logger = logger
self.dataFrames = None
self.models = {}
def get_datasets(self):
self.dataFrames = self.features_analyzer.dataFrames
def get_accuracy_threshold(self, threshold, prediction, measured):
"""
Calculate accuracy of predictions whose measured value is above a certain threshold
:param threshold: threshold level
:type threshold: float
:param prediction: predicted data
:type prediction: numpy.array
:param measured: measured data
:type measured: numpy.array
:return: accuracy score
:rtype: float
"""
lcl_acc = 0.0
if not measured.loc[measured > threshold].empty:
lcl_acc = accuracy_score(self.get_classes(prediction.loc[measured > threshold]),
self.get_classes(measured.loc[measured > threshold]))
return lcl_acc
@staticmethod
def calc_mae_rmse_threshold(meas, pred, th):
mask = meas.values >= th
if len(pred[mask]) > 0:
return round(mean_absolute_error(meas[mask], pred[mask]), 3), \
round(np.sqrt(mean_squared_error(meas[mask], pred[mask])), 3)
else:
return -1.0, -1.0
@staticmethod
def calc_mape_threshold(meas, pred, th):
mask = meas.values >= th
if len(pred[mask]) > 0:
return round(np.mean(np.abs((meas[mask].values - pred[mask].values) / meas[mask].values)) * 100, 1)
else:
return -1.0
def calculate_KPIs(self, region, prediction, measured, weights, ngbPars=None):
"""
For each fold and/or train/test separation, return the KPIs to establish the best weights combination
:param prediction: predicted data
:type prediction: numpy.array
:param measured: measured data
:type measured: numpy.array
:return: pandas DF with KPIs for each dataset provided
:rtype: pandas.DataFrame
"""
threshold1 = self.cfg['regions'][region]['featuresAnalyzer']['threshold1']
threshold2 = self.cfg['regions'][region]['featuresAnalyzer']['threshold2']
threshold3 = self.cfg['regions'][region]['featuresAnalyzer']['threshold3']
w1 = weights['w1']
w2 = weights['w2']
w3 = weights['w3']
lcl_acc_1 = round(self.get_accuracy_threshold(threshold1, prediction, measured), 3)
lcl_acc_2 = round(self.get_accuracy_threshold(threshold2, prediction, measured), 3)
lcl_acc_3 = round(self.get_accuracy_threshold(threshold3, prediction, measured), 3)
lcl_acc = round(accuracy_score(self.get_classes(prediction), self.get_classes(measured)), 3)
lcl_rmse = round((mean_squared_error(measured, prediction) ** 0.5), 3)
lcl_mae = round(mean_absolute_error(measured, prediction), 3)
lcl_cm = confusion_matrix(self.get_classes(prediction), self.get_classes(measured))
mae1, rmse1 = self.calc_mae_rmse_threshold(meas=measured, pred=prediction, th=threshold1)
mae2, rmse2= self.calc_mae_rmse_threshold(meas=measured, pred=prediction, th=threshold2)
mae3, rmse3= self.calc_mae_rmse_threshold(meas=measured, pred=prediction, th=threshold3)
if ngbPars is None:
df_KPIs = pd.DataFrame([[w1, w2, w3, lcl_acc_1, lcl_acc_2, lcl_acc_3, lcl_acc, rmse1, rmse2, rmse3, lcl_rmse,
mae1, mae2, mae3, lcl_mae, str(lcl_cm.flatten().tolist())]],
columns=['w1', 'w2', 'w3', 'Accuracy_1', 'Accuracy_2', 'Accuracy_3', 'Accuracy',
'RMSE1', 'RMSE2', 'RMSE3', 'RMSE', 'MAE1', 'MAE2', 'MAE3', 'MAE', 'ConfMat'])
else:
df_KPIs = pd.DataFrame([[w1, w2, w3, ngbPars['numberEstimators'], ngbPars['learningRate'], lcl_acc_1,
lcl_acc_2, lcl_acc_3, lcl_acc, rmse1, rmse2, rmse3, lcl_rmse,
mae1, mae2, mae3, lcl_mae, str(lcl_cm.flatten().tolist())]],
columns=['w1', 'w2', 'w3', 'ne', 'lr', 'Accuracy_1', 'Accuracy_2', 'Accuracy_3', 'Accuracy',
'RMSE1', 'RMSE2', 'RMSE3', 'RMSE', 'MAE1', 'MAE2', 'MAE3', 'MAE', 'ConfMat'])
return df_KPIs
def get_numpy_df(self, df_x, df_y):
x_data_no_date = df_x.iloc[:, 1:]
y_data_no_date = df_y.iloc[:, 1:]
assert (len(x_data_no_date) == len(y_data_no_date))
x_data = np.array(x_data_no_date, dtype='float64')
y_data = np.array(y_data_no_date, dtype='float64')
return x_data, y_data
def remove_date(self, X, Y):
assert 'date' in X.columns.values
assert 'date' in Y.columns.values
X = X.iloc[:, 1:]
Y = Y.iloc[:, 1:]
assert 'date' not in X.columns.values
assert 'date' not in Y.columns.values
return X, Y
def convert_to_series(self, prediction, Y):
"""
Convert dataframes to series for easier KPIs calculation
"""
assert (len(prediction) == len(Y))
prediction = pd.Series(prediction, index=Y.index)
measured = pd.Series(Y.iloc[:, 0], index=Y.index)
return prediction, measured
@staticmethod
def calc_prob_interval(pred_dataset, lower_limit, upper_limit):
mask = np.logical_and(pred_dataset > lower_limit, pred_dataset < upper_limit)
return len(pred_dataset[mask]) / len(pred_dataset)
@staticmethod
def handle_qrf_output(cfg, qrf, input_vals, region_code):
qntls = np.array(cfg['regions'][region_code]['forecaster']['quantiles'])
pred_qntls, pred_dataset = qrf.predict(input_vals, qntls)
pred_dataset = pred_dataset[0]
pred_qntls = pred_qntls[0]
ths = cfg['regions'][region_code]['forecaster']['thresholds']
eps = np.finfo(np.float32).eps
dict_probs = {'thresholds': {}, 'quantiles': {}}
# Get probabilities to be in configured thresholds
for i in range(1, len(ths)):
dict_probs['thresholds']['[%i:%i]' % (ths[i-1], ths[i])] = ModelTrainer.calc_prob_interval(pred_dataset, ths[i-1], ths[i]-eps)
dict_probs['thresholds']['[%i:%f]' % (ths[i], np.inf)] = ModelTrainer.calc_prob_interval(pred_dataset, ths[i], np.inf)
# Get probabilities to be in the configured quantiles
for i in range(0, len(qntls)):
dict_probs['quantiles']['perc%.0f' % (qntls[i]*100)] = pred_qntls[i]
return dict_probs
@staticmethod
def handle_ngb_normal_dist_output(cfg, mu, sigma, region_code):
dist = scipy.stats.norm(loc=mu, scale=sigma)
# QUANTILES
# dist.ppf(0.1)
# dist.ppf([0.1, 0.5])
# VALUES FOR PROB
# dist.ppf(0.1)
# dist.ppf([0.1, 0.5])
samples = []
for i in range(1, 1000):
samples.append(dist.ppf(float(i / 1000)))
samples = np.array(samples)
ths = cfg['regions'][region_code]['forecaster']['thresholds']
eps = np.finfo(np.float32).eps
dict_probs = {'thresholds': {}, 'quantiles': {}}
for i in range(1, len(ths)):
dict_probs['thresholds']['[%i:%i]' % (ths[i-1], ths[i])] = ModelTrainer.calc_prob_interval(samples, ths[i-1], ths[i]-eps)
dict_probs['thresholds']['[%i:%f]' % (ths[i], np.inf)] = ModelTrainer.calc_prob_interval(samples, ths[i], np.inf)
# Get probabilities to be in the configured quantiles
for q in cfg['regions'][region_code]['forecaster']['quantiles']:
dict_probs['quantiles']['perc%.0f' % (q*100)] = dist.ppf(q)
return dict_probs
def fold_training(self, region, train_index, test_index, X, Y, weights, ngbPars=None):
"""
For each fold and/or tran/test separation, create the model and calculate KPIs to establish the best weights
combination
:param train_index: indexes of dataset that compose train set
:type train_index: pandas.Index
:param test_index: indexes of dataset that compose test set
:type test_index: pandas.Index
:param X: design matrix
:type X: pandas.DataFrame
:param Y: response vector
:type Y: pandas.DataFrame
:return: prediction performed on test dataset
:rtype: numpy.array
"""
Xtrain, Xtest = np.array(X.loc[train_index, :]), np.array(X.loc[test_index, :])
Ytrain, Ytest = Y.loc[train_index].reset_index(drop=True), Y.loc[test_index].reset_index(drop=True)
assert len(Xtrain) == len(Ytrain)
assert len(Xtest) == len(Ytest)
ngb = self.train_NGB_model(region, Xtrain, Ytrain, weights, ngbPars)[0]
return ngb.predict(Xtest)
def train_NGB_model(self, region, Xtrain, Ytrain, target_data, ngbPars=None):
"""
Return the NGB model trained on the available data
:param Xtrain: indexes of dataset that compose train set
:type Xtrain: np.array()
:param Ytrain: indexes of dataset that compose test set
:type Ytrain: pandas.DataFrame
:return: prediction model
:rtype: ngboost.NGBRegressor
"""
if 'weights' in target_data.keys():
# MT case
weights = target_data['weights'][self.forecast_type]
else:
# HPOPT case
weights = target_data
if ngbPars is None:
# Usage of the configured parameters
n_est = target_data['numberEstimatorsNGB'][self.forecast_type]
l_rate = target_data['learningRateNGB'][self.forecast_type]
else:
# Usage of the parameters passed as arguments
n_est = ngbPars['numberEstimators']
l_rate = ngbPars['learningRate']
threshold1 = self.cfg['regions'][region]['featuresAnalyzer']['threshold1'] # It should be 240
threshold2 = self.cfg['regions'][region]['featuresAnalyzer']['threshold2'] # It should be 180
threshold3 = self.cfg['regions'][region]['featuresAnalyzer']['threshold3'] # It should be 120 (old but wrong 135)
w1 = weights['w1']
w2 = weights['w2']
w3 = weights['w3']
weight = np.array(
[w1 if x >= threshold1 else w2 if x >= threshold2 else w3 if x >= threshold3 else 1.0 for x in
np.array(Ytrain)],
dtype='float64')
assert len(weight) == len(Ytrain)
ngb = NGBRegressor(n_estimators=n_est, learning_rate=l_rate, Dist=Normal,
Base=default_tree_learner, natural_gradient=True, verbose=False,
Score=MLE, random_state=500).fit(Xtrain, np.array(Ytrain).ravel(), sample_weight=weight)
return ngb, weight
def error_data(self, pred, Y, fold, weights):
"""
Create pandas df with weights, fold, measurements and predictions
:param pred: predicted data
:type pred: numpy.array
:param Y: measured data
:type Y: pandas.Series
:param fold: current fold of Cross Validation
:type fold: int
:return: pandas DF with information
:rtype: pandas.DataFrame
"""
Y = np.array(Y.values)
assert len(pred) == len(Y)
df_pred = pd.DataFrame()
df_pred['w1'] = [weights['w1']] * len(Y)
df_pred['w2'] = [weights['w2']] * len(Y)
df_pred['w3'] = [weights['w3']] * len(Y)
df_pred['Fold'] = [fold] * len(Y)
df_pred['Measurements'] = Y
df_pred['Prediction'] = pred
return df_pred
def get_weights_folder_results(self, region, target_column, weights):
root_output_folder_path = self.input_gatherer.output_folder_creator(region)
str_ws = ''
for kw in weights.keys():
str_ws = '%s%s-%s_' % (str_ws, kw, weights[kw])
str_ws = str_ws[0:-1]
if not os.path.exists(root_output_folder_path + 'gs'):
os.mkdir(root_output_folder_path + 'gs')
if not os.path.exists(root_output_folder_path + 'gs' + os.sep + target_column):
os.mkdir(root_output_folder_path + 'gs' + os.sep + target_column)
if not os.path.exists(root_output_folder_path + 'gs' + os.sep + target_column + os.sep + str_ws):
os.mkdir(root_output_folder_path + 'gs' + os.sep + target_column + os.sep + str_ws)
return '%s%s%s%s%s%s%s' % (root_output_folder_path, 'gs', os.sep, target_column, os.sep, str_ws, os.sep)
def training_cross_validated_fs(self, features, region, target_column, df_x, df_y, weights):
df_x = df_x.reset_index(drop=True)
df_y = df_y.reset_index(drop=True)
# Dataset preparation for CV
df_x_tmp = df_x
df_y_tmp = df_y
df_x_tmp = df_x_tmp.drop(['date'], axis=1)
df_y_tmp = df_y_tmp.drop(['date'], axis=1)
cv_folds = self.cfg['regions'][region]['gridSearcher']['numFolds']
if self.cfg['regions'][region]['gridSearcher']['shuffle'] is True:
kf = KFold(n_splits=cv_folds, shuffle=self.cfg['regions'][region]['gridSearcher']['shuffle'],
random_state=self.cfg['regions'][region]['gridSearcher']['randomState'])
else:
kf = KFold(n_splits=cv_folds, shuffle=False, random_state=None)
np_x = df_x_tmp.to_numpy()
np_y = df_y_tmp.to_numpy()
fold = 1
if self.cfg['regions'][region]['gridSearcher']['hyperParsOptimizationNGB'] is not None:
df_pred = pd.DataFrame(columns=['w1', 'w2', 'w3', 'ne', 'lr', 'Measurements', 'Prediction'])
for train_index, test_index in kf.split(np_x):
# Consider only the last fold
if fold == cv_folds:
# HPOPT only on the last fold
ngb_prediction = np.empty(len(test_index))
df_pred = pd.DataFrame(columns=['w1', 'w2', 'w3', 'Fold', 'ne', 'lr', 'Measurements', 'Prediction'])
# Get the I/O datasets for the training and the test
X_train, X_test = np_x[train_index], np_x[test_index]
y_train, y_test = np_y[train_index], np_y[test_index]
# Reduce the dataset to consider only to the current fold
df_x = df_x.iloc[test_index[0]:test_index[-1] + 1]
df_y = df_y.iloc[test_index[0]:test_index[-1] + 1]
df_kpis = None
for ne in self.cfg['regions'][region]['gridSearcher']['hyperParsOptimizationNGB']['numEstimators']:
for lr in self.cfg['regions'][region]['gridSearcher']['hyperParsOptimizationNGB']['learningRate']:
self.logger.info('HPOPT -> region: %s, target: %s, weights: %s -> '
'Started FS fold %i/%i; (ne=%i, lr=%s)' % (region, target_column, weights,
fold, cv_folds, ne, str(lr)))
ngbPars = { 'numberEstimators': ne, 'learningRate': lr }
selected_features = self.features_analyzer.important_features(region,
X_train,
y_train,
features[1:],
weights,
ngbPars)[0]
X, Y = self.get_reduced_dataset(df_x, df_y, selected_features)
X, Y = self.remove_date(X, Y)
self.logger.info('HPOPT -> region: %s, target: %s, weights: %s -> '
'Ended FS fold %i/%i; (ne=%i, lr=%s)' % (region, target_column, weights,
fold, cv_folds, ne, str(lr)))
# Perform the training using the training folds and the prediction with the test fold
self.logger.info('HPOPT -> region: %s, target: %s, weights: %s -> '
'Started model training fold %i/%i; (ne=%i, lr=%s)' % (region,
target_column,
weights,
fold,
cv_folds,
ne, str(lr)))
# todo this part below should be investigated
ngb = self.train_NGB_model(region, X_train, y_train, weights, ngbPars)[0]
ngb_prediction = ngb.predict(X_test)
# pred = self.fold_training(region, train_index, test_index, X, Y, weights, ngbPars)
# ngb_prediction = pred
self.logger.info('HPOPT -> region: %s, target: %s, weights: %s -> '
'Ended model training fold %i/%i; (ne=%i, lr=%s)' % (region,
target_column,
weights,
fold,
cv_folds,
ne, str(lr)))
prediction, measured = self.convert_to_series(ngb_prediction, Y)
if df_kpis is None:
df_kpis = self.calculate_KPIs(region, prediction, measured, weights, ngbPars)
else:
kpis = self.calculate_KPIs(region, prediction, measured, weights, ngbPars)
df_kpis = df_kpis.append(kpis)
return df_kpis, None
fold += 1
else:
ngb_prediction = np.empty(len(df_y))
df_pred = pd.DataFrame(columns=['w1', 'w2', 'w3', 'Fold', 'Measurements', 'Prediction'])
for train_index, test_index in kf.split(np_x):
# Get the I/O datasets for the training and the test
X_train, X_test = np_x[train_index], np_x[test_index]
y_train, y_test = np_y[train_index], np_y[test_index]
# Perform the FS using the training folds
self.logger.info('Region: %s, target: %s, weights: %s -> Started FS fold %i/%i' % (region,
target_column,
weights,
fold,
cv_folds))
selected_features = self.features_analyzer.important_features(region, X_train, y_train, features[1:],
weights)[0]
X, Y = self.get_reduced_dataset(df_x, df_y, selected_features)
X, Y = self.remove_date(X, Y)
self.logger.info('Region: %s, target: %s, weights: %s -> Ended FS fold %i/%i' % (region, target_column,
weights, fold, cv_folds))
# Perform the training using the training folds and the prediction with the test fold
self.logger.info('Region: %s, target: %s, weights: %s -> Started model training fold %i/%i' % (region,
target_column,
weights,
fold,
cv_folds))
pred = self.fold_training(region, train_index, test_index, X, Y, weights)
ngb_prediction[test_index] = pred
self.logger.info('Region: %s, target: %s, weights: %s -> Ended model training fold %i/%i' % (region,
target_column,
weights,
fold,
cv_folds))
# Concat the prediction results
df_pred = pd.concat([df_pred, self.error_data(pred, Y.loc[test_index], fold, weights)], ignore_index=True,
axis=0)
fold += 1
prediction, measured = self.convert_to_series(ngb_prediction, Y)
return self.calculate_KPIs(region, prediction, measured, weights), df_pred
def get_weights(self, input_file_name):
w = {}
str_w = ''
for elem in input_file_name.split(os.sep)[-2].split('_'):
code, val = elem.split('-')
w[code] = int(val)
str_w += val + '-'
return w, str_w[:-1]
def train_final_models(self, k_region, target_signal, hps=None):
"""
Calculates the KPIs for a set of weight with multiple Feature selection: First we create the folds of the cross
validation, then for each fold we do the feature selection and locally calculate the KPIs
"""
target_data = self.cfg['regions'][k_region]['finalModelCreator']['targets'][target_signal]
self.get_datasets()
key = k_region
df = self.dataFrames[key]
fp = self.input_gatherer.output_folder_creator(key)
_, _, _, df_x, df_y = self.features_analyzer.dataset_splitter(key, df, target_signal)
# Check if there is a hyperparameters optimization or not
if hps is None:
suffix = self.cfg['regions'][k_region]['finalModelCreator']['signalsFileSuffix']
input_files = glob.glob('%s*%s%s.json' % (fp, target_signal, suffix))
else:
str_hpars = 'ne%i-lr%s' % (hps['numberEstimators'], str(hps['learningRate']).replace('.', ''))
suffix = str_hpars
input_files = glob.glob('%shpo%s%s%s*%s*.json' % (fp, os.sep, suffix, os.sep, target_signal))
for input_file in input_files:
selected_features = json.loads(open(input_file).read())['signals']
X, Y = self.get_reduced_dataset(df_x, df_y, selected_features)
X, Y = self.remove_date(X, Y)
target_data['weights'] = self.cfg['regions'][k_region]['featuresAnalyzer']['targetColumns'][target_signal]['weights']
target_data['numberEstimatorsNGB'] = self.cfg['regions'][k_region]['featuresAnalyzer']['targetColumns'][target_signal]['numberEstimatorsNGB']
target_data['learningRateNGB'] = self.cfg['regions'][k_region]['featuresAnalyzer']['targetColumns'][target_signal]['learningRateNGB']
start_year = self.cfg['datasetSettings']['years'][0]
end_year = self.cfg['datasetSettings']['years'][-1]
self.logger.info('Train models for %s - %s; period [%s:%s], case %s, weights: %s' % (k_region,
target_signal,
start_year,
end_year,
self.forecast_type,
target_data['weights']))
# Train NGB model
self.logger.info('Target %s -> NGBoost model training start' % target_signal)
ngb, weight = self.train_NGB_model(k_region, X, Y, target_data, hps)
self.logger.info('Target %s -> NGBoost model training end' % target_signal)
# Train QRF model
rfqr = None
# self.logger.info('RFQR model training start')
# rfqr = RandomForestQuantileRegressor(n_estimators=1000).fit(X, np.array(Y).ravel())
# self.logger.info('RFQR model training end')
self.logger.info('Target %s -> pyquantrf RFQR model training start' % target_signal)
rfqr_w = qfrfQuantileRandomForestRegressor(nthreads=4,
n_estimators=target_data['numberEstimatorsNGB'][self.forecast_type],
min_samples_leaf=10)
rfqr_w.fit(X, np.array(Y).ravel(), sample_weight=weight)
self.logger.info('Target %s -> pyquantrf RFQR model training end' % target_signal)
# Check if there is a hyperparameters optimization or not
if hps is None:
str_lr = str('%.3f' % target_data['learningRateNGB'][self.forecast_type]).replace('.','')
# str_hp = 'w1%iw2%iw3%ine%ilr%s' % (target_data['weights'][self.forecast_type]['w1'],
# target_data['weights'][self.forecast_type]['w2'],
# target_data['weights'][self.forecast_type]['w3'],
# target_data['numberEstimatorsNGB'][self.forecast_type],
# str_lr)
file_name_noext = fp + 'predictor_' + target_data['label'] + '_' + \
self.cfg['regions'][k_region]['finalModelCreator']['identifier']
else:
file_name_noext = '%shpo%spredictor_%s_%s' % (fp, os.sep,target_data['label'],
str_hpars.replace('-', ''))
pickle.dump([ngb, rfqr, rfqr_w], open('%s.pkl' % file_name_noext, 'wb'))
json.dump({"signals": list(selected_features)}, open('%s.json' % file_name_noext.replace('predictor', 'inputs'), 'w'))
metadata = {
"region": k_region,
"case": self.forecast_type,
"weights": {
"w1": target_data['weights'][self.forecast_type]['w1'],
"w2": target_data['weights'][self.forecast_type]['w2'],
"w3": target_data['weights'][self.forecast_type]['w3'],
},
"NGBoostParameters": {
"estimatorsNumber": target_data['numberEstimatorsNGB'][self.forecast_type],
"learningRate": target_data['learningRateNGB'][self.forecast_type],
"numberSelectedFeatures": len(selected_features)
}
}
json.dump(metadata, open('%s.json' % file_name_noext.replace('predictor', 'metadata'), 'w'))
@staticmethod
def get_reduced_dataset(df_x, df_y, selected_features):
"""
Extract a smaller dataframe with the selected features as columns. Keep the date and refresh indices
:param selected_features: list of selected features
:type selected_features: list
:param df_x: design matrix
:type df_x: pandas.DataFrame
:param df_y: response vector
:type df_y: pandas.DataFrame
:return: pandas DF with reduced columns
:rtype: pandas.DataFrame, pandas.DataFrame
"""
lcl_df_x = df_x.loc[:, ['date'] + selected_features]
lcl_df_y = df_y
# Date must be there
assert len(lcl_df_x.columns.values) == len(selected_features) + 1
assert len(lcl_df_y.columns.values) == 2
assert len(lcl_df_y) == len(lcl_df_x)
lcl_df_x = lcl_df_x.reset_index(drop=True)
lcl_df_y = lcl_df_y.reset_index(drop=True)
return lcl_df_x, lcl_df_y
def get_classes(self, prediction):
y_classes = []
for element in prediction:
if element < 60:
y_classes.append(0)
elif element < 120:
y_classes.append(1)
elif element < 135:
y_classes.append(2)
elif element < 180:
y_classes.append(3)
elif element < 240:
y_classes.append(4)
else:
y_classes.append(5)
return y_classes
|
python
|
"""Runs the webserver."""
from absl import app
from absl import flags
from absl import logging
from icubam import config
from icubam.db import store
flags.DEFINE_string('config', 'resources/config.toml', 'Config file.')
flags.DEFINE_string('dotenv_path', None, 'Optionally specifies the .env path.')
flags.DEFINE_enum('mode', 'dev', ['prod', 'dev'], 'Run mode.')
flags.DEFINE_string('email', None, 'File for the db.')
flags.DEFINE_string('password', None, 'File for the db.')
FLAGS = flags.FLAGS
def main(argv):
cfg = config.Config(
FLAGS.config, mode=FLAGS.mode, env_path=FLAGS.dotenv_path
)
factory = store.create_store_factory_for_sqlite_db(cfg)
db = factory.create()
user_id = db.get_user_by_email(FLAGS.email)
if user_id is None:
logging.error(f"No user for email {FLAGS.email}")
return
admins = db.get_admins()
if not admins:
admin_id = db.add_default_admin()
else:
admin_id = admins[0].user_id
hash = db.get_password_hash(FLAGS.password)
db.update_user(admin_id, user_id, dict(password_hash=hash))
if __name__ == '__main__':
app.run(main)
|
python
|
from time import sleep
def msg(string):
print('~' * (len(string) + 2))
print(f' {string} ')
print('~' * (len(string) + 2))
while True:
print('\33[30;42m', end='')
msg('Sistema de ajuda PyHELP')
user = str(input('\033[mFunção ou Biblioteca \033[32m>>>\033[m '))
if user.lower() == 'fim':
break
print('\033[30;44m', end='')
msg(f'Acessando o menu do comando {user}')
sleep(1.5)
print('\033[47m', end='')
print(help(user))
print('\033[41mMuito obrigado por usar o sistema de ajuda PyHELP, volte sempre!')
|
python
|
import unittest
from streamlink.plugins.schoolism import Schoolism
class TestPluginSchoolism(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
'https://www.schoolism.com/watchLesson.php',
]
for url in should_match:
self.assertTrue(Schoolism.can_handle_url(url))
def test_can_handle_url_negative(self):
should_not_match = [
'https://www.schoolism.com',
]
for url in should_not_match:
self.assertFalse(Schoolism.can_handle_url(url))
def test_playlist_parse_subs(self):
with_subs = """var allVideos=[
{sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/44/2/part1.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Digital Painting - Lesson 2 - Part 1",playlistTitle:"Part 1",}], subtitles: [{
"default": true,
kind: "subtitles", srclang: "en", label: "English",
src: "https://s3.amazonaws.com/schoolism-encoded/44/subtitles/2/2-1.vtt",
}],
},
{sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/44/2/part2.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Digital Painting - Lesson 2 - Part 2",playlistTitle:"Part 2",}], subtitles: [{
"default": true,
kind: "subtitles", srclang: "en", label: "English",
src: "https://s3.amazonaws.com/schoolism-encoded/44/subtitles/2/2-2.vtt",
}]
}];
"""
data = Schoolism.playlist_schema.validate(with_subs)
self.assertIsNotNone(data)
self.assertEqual(2, len(data))
def test_playlist_parse(self):
without_subs = """var allVideos=[
{sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/14/1/part1.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Gesture Drawing - Lesson 1 - Part 1",playlistTitle:"Part 1",}],},
{sources:[{type:"application/x-mpegurl",src:"https://d8u31iyce9xic.cloudfront.net/14/1/part2.m3u8?Policy=TOKEN&Signature=TOKEN&Key-Pair-Id=TOKEN",title:"Gesture Drawing - Lesson 1 - Part 2",playlistTitle:"Part 2",}]}
];
"""
data = Schoolism.playlist_schema.validate(without_subs)
self.assertIsNotNone(data)
self.assertEqual(2, len(data))
|
python
|
""""Process the results of DrFact and DrKIT"""
import json
import sys
from tqdm import tqdm
prediction_file = sys.argv[1]
output_file = sys.argv[2]
outputs = []
with open(prediction_file) as f:
print("Reading", f.name)
lines = f.read().splitlines()
for line in tqdm(lines[1:], desc="Processing %s"%f.name):
instance = json.loads(line)
qid = instance["qas_id"]
pred = instance["predictions"]
concept_predictions = pred["top_5000_predictions"]
predictions_K = {100: concept_predictions} # TODO: add more
output = dict(qid = qid, \
question = pred["question"], \
predictions_K = predictions_K
)
outputs.append(output)
with open(output_file, "w") as f:
print("Writing", f.name)
for output in outputs:
f.write(json.dumps(output) + "\n")
|
python
|
# -*- coding: utf8 -*-
from __future__ import unicode_literals
def main():
print('234'.isdecimal())
if __name__ == '__main__':
main()
|
python
|
def main():
x, y = c(input()), c(input())
if x * y == 0:
return 0
return "S" + ("(S" * ((x * y) - 1)) + "(0" + (")" * (x * y))
def c(x):
return x.count('S')
if __name__ == '__main__':
print(main())
|
python
|
# @copyright@
# Copyright (c) 2006 - 2018 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
#
# @rocks@
# Copyright (c) 2000 - 2010 The Regents of the University of California
# All rights reserved. Rocks(r) v5.4 www.rocksclusters.org
# https://github.com/Teradata/stacki/blob/master/LICENSE-ROCKS.txt
# @rocks@
import os
import stack.commands
class command(stack.commands.HostArgumentProcessor,
stack.commands.iterate.command):
pass
class Command(command):
"""
Iterate sequentially over a list of hosts. This is used to run
a shell command on the frontend with with '%' wildcard expansion for
every host specified.
<arg optional='1' type='string' name='host' repeat='1'>
Zero, one or more host names. If no host names are supplied iterate over
all hosts except the frontend.
</arg>
<param optional='0' type='string' name='command'>
The shell command to be run for each host. The '%' character is used as
a wildcard to indicate the hostname. Quoting of the '%' to expand to a
literal is accomplished with '%%'.
</param>
<example cmd='iterate host backend command="scp file %:/tmp/"'>
Copies file to the /tmp directory of every backend node
</example>
"""
def run(self, params, args):
(cmd, ) = self.fillParams([ ('command', None, True) ])
self.beginOutput()
hosts = []
if len(args) == 0:
#
# no hosts are supplied. we need to exclude the frontend
#
for host in self.getHostnames(args):
if host == self.db.getHostname('localhost'):
#
# don't include the frontend
#
continue
hosts.append(host)
else:
hosts = self.getHostnames(args)
for host in hosts:
# Turn the wildcard '%' into the hostname, and '%%' into
# a single '%'.
s = ''
prev = ''
for i in range(0, len(cmd)):
curr = cmd[i]
try:
next = cmd[i + 1]
except:
next = ''
if curr == '%':
if prev != '%' and next != '%':
s += host
prev = host
continue # consume '%'
elif prev == '%':
s += '%'
prev = '*'
continue # consume '%'
else:
s += curr
prev = curr
os.system(s)
# for line in os.popen(s).readlines():
# self.addOutput(host, line[:-1])
self.endOutput(padChar='')
|
python
|
#!/usr/bin/python3
"""
Master program """
import multiprocessing
import math
import queue
import time
import pickle
import numpy as np
import pygame
import zmq
class CommProcess(multiprocessing.Process):
"""Communicates with robot."""
def __init__(self, image_queue, command_queue):
super().__init__(daemon=True)
self.done = False
self.image_queue = image_queue
self.command_queue = command_queue
def run(self):
port = 15787
context = zmq.Context()
robot = context.socket(zmq.REQ)
robot.connect('tcp://zeitgeist.local:{}'.format(port))
while not self.done:
command_flag = False
try:
while True:
command = self.command_queue.get(block=False)
command_flag = True
except queue.Empty:
pass
if command_flag:
if not len(command) == 2:
self.done = True
break
robot.send_string('c {} {}'.format(command[0], command[1]))
print("Sent to robot: {}".format(command))
response = robot.recv_string()
print("Received from robot: {}".format(response))
robot.send_string('q')
robot.recv_string()
def run():
# current speeds
left = 0
right = 0
# speed factor (left and right can be +/- 31 max)
speed = 16.0
# screen radius
size = 250
# deadzone size
deadzone = 10
# motors on
enabled = True
pygame.init()
screen = pygame.display.set_mode((2*size, 2*size))
image_queue = multiprocessing.Queue()
command_queue = multiprocessing.Queue()
robot = CommProcess(image_queue, command_queue)
robot.start()
done = False
while not done:
old_left = left
old_right = right
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
command_queue.put('q')
if event.type == pygame.MOUSEMOTION:
x = event.pos[0]-size
y = -(event.pos[1]-size)
if x**2+y**2 < deadzone**2:
left = 0
right = 0
else:
left = right = speed*y/size
left += speed*x/size
right -= speed*x/size
left = int(left)
right = int(right)
if event.type == pygame.KEYDOWN:
if event.key == 32: # space
enabled = not enabled
left = 0
right = 0
if(old_left != left or old_right != right):
print('GUI sensed movement: ({},{}):\t{}\t{}'.format(x, y, left, right))
command_queue.put((left, right))
"""
try:
image = image_queue.get(block=False)
print(image.shape)
except queue.Empty:
pass
"""
if enabled :
screen.fill((0, 0, 0))
pygame.draw.circle(screen, (255, 255, 0), (size, size), deadzone)
else:
screen.fill((255, 255, 255))
pygame.display.flip()
time.sleep(1) # allow time for threads to finish
if __name__ == "__main__":
run()
|
python
|
# Generated by Django 3.0.8 on 2020-07-15 09:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Resources', '0008_resume'),
]
operations = [
migrations.CreateModel(
name='People',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=100)),
('last_name', models.CharField(max_length=100)),
('date_of_birth', models.DateField(blank=True, null=True)),
('About', models.TextField(help_text='Resume of candidate')),
('education', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='Resources.Edu_Qualification')),
('experience', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='Resources.Experience')),
('ratings', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='Resources.Rating')),
('skills', models.ManyToManyField(help_text='enter your skills(Technical or personal ...etc)', to='Resources.Skill')),
('technologies', models.ManyToManyField(help_text='enter technology you are experience on(if freshers mention Fresher)', to='Resources.Technology')),
],
options={
'ordering': ['first_name'],
},
),
]
|
python
|
import os
import sys
import yaml
import subprocess
from cryptography.fernet import Fernet
secrets_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'secrets.yaml')
def decrypt_secrets(cfg):
with open(os.path.join(cfg['global']['fernet_tokens_path'],'fernet_tokens.txt'), 'r') as token_file:
master_key = token_file.read()
with open(secrets_file_path, 'r') as ymlfile:
secrets_file = yaml.load(ymlfile)
cipher_suite = Fernet(str.encode(master_key))
for password_key in secrets_file:
decrypted_password= (cipher_suite.decrypt(secrets_file[password_key]))
cfg[str(password_key)]=decrypted_password.decode("utf-8")
return cfg
def generate_secrets_file(cfg):
master_key = Fernet.generate_key()
with open(os.path.join(cfg['global']['fernet_tokens_path'],'fernet_tokens.txt'), 'w') as token_file:
token_file.write(master_key.decode())
logging.info('Master key has been generated and stored in: ' + os.path.join(cfg['global']['fernet_tokens_path']))
with open(secrets_file_path, 'r') as ymlfile:
secrets_file = yaml.load(ymlfile)
for password_key in secrets_file:
password_raw_value = input("Enter the password for " + str(password_key) + " :" + "\n")
cfg[str(password_key)]=password_raw_value
cipher_suite = Fernet(master_key)
ciphered_text = cipher_suite.encrypt(str.encode(password_raw_value)) # required to be bytes
secrets_file[password_key]=ciphered_text
with open(secrets_file_path, 'w') as f:
yaml.dump(secrets_file, f)
return cfg
|
python
|
#Test metadata model
from src.models import metadata
from src import data
from src import utils
import torch
import os
from pytorch_lightning import Trainer
ROOT = os.path.dirname(os.path.dirname(data.__file__))
def test_metadata():
m = metadata.metadata(sites = 1, classes=10)
sites = torch.zeros(20)
output = m(sites.int())
assert output.shape == (20,10)
def test_metadata_sensor_fusion():
sites = torch.zeros(20)
image = torch.randn(20, 3, 11, 11)
m = metadata.metadata_sensor_fusion(bands=3, sites=1, classes=10)
prediction = m(image, sites.int())
assert prediction.shape == (20,10)
def test_MetadataModel(config, dm):
model = metadata.metadata_sensor_fusion(sites=1, classes=3, bands=3)
m = metadata.MetadataModel(model=model, classes=3, label_dict=dm.species_label_dict, config=config)
trainer = Trainer(fast_dev_run=True)
trainer.fit(m,datamodule=dm)
|
python
|
from PyQt5 import QtWebEngineWidgets, QtWidgets
from tootbox.core.framework import LayoutView
from tootbox.views.toot import Toot
class Timeline(LayoutView):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initialize_ui()
def initialize_ui(self):
self.button = QtWidgets.QPushButton("Refresh!")
self.toot_list = QtWidgets.QVBoxLayout()
self.toot_list.setContentsMargins(0, 0, 0, 0)
self.toot_list.setSpacing(20)
self.toot_list.addStretch()
self.scrollbox = QtWidgets.QScrollArea()
self.scrollbox.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.scrollbox.setFrameStyle(0)
self.scrollbox.setWidgetResizable(True)
self.scrollbox.verticalScrollBar().valueChanged.connect(self.timeline_scrolled)
scrollContainer = QtWidgets.QWidget()
scrollContainer.setLayout(self.toot_list)
self.scrollbox.setWidget(scrollContainer)
vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(self.button)
vbox.addWidget(self.scrollbox)
self.setLayout(vbox)
def update_list(self, toots):
for toot in reversed(toots):
# print(toot.__str__() + "\n\n\n")
t = Toot(toot)
self.toot_list.insertWidget(0, t)
def timeline_scrolled(self, value):
maximum = self.scrollbox.verticalScrollBar().maximum()
scroll_perc = value / maximum
if scroll_perc > 0.9:
# Request more toots
pass
# print(str(value) + ", " + str(maximum) + ", " + str(scroll_perc) + "%")
|
python
|
from __future__ import unicode_literals
import csv
import io
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save, pre_save
from django.utils.text import slugify
from yourapp.signals import csv_uploaded
from yourapp.validators import csv_file_validator
def upload_csv_file(instance, filename):
qs = instance.__class__.objects.filter(user=instance.user)
if qs.exists():
num_ = qs.last().id + 1
else:
num_ = 1
return f'csv/{num_}/{instance.user.username}/{filename}'
class CSVUpload(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
file = models.FileField(upload_to=upload_csv_file, validators=[csv_file_validator])
completed = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def convert_header(csvHeader):
header_ = csvHeader[0]
cols = [x.replace(' ', '_').lower() for x in header_.split(",")]
return cols
def csv_upload_post_save(sender, instance, created, *args, **kwargs):
if not instance.completed:
csv_file = instance.file
decoded_file = csv_file.read().decode('utf-8')
io_string = io.StringIO(decoded_file)
reader = csv.reader(io_string, delimiter=';', quotechar='|')
header_ = next(reader)
header_cols = convert_header(header_)
parsed_items = []
'''
if using a custom signal
'''
for line in reader:
parsed_row_data = {}
i = 0
row_item = line[0].split(',')
for item in row_item:
key = header_cols[i]
parsed_row_data[key] = item
i+=1
parsed_items.append(parsed_row_data)
csv_uploaded.send(sender=instance, user=instance.user, csv_file_list=parsed_items)
'''
if using a model directly
for line in reader:
new_obj = YourModelKlass()
i = 0
row_item = line[0].split(',')
for item in row_item:
key = header_cols[i]
setattr(new_obj, key) = item
i+=1
new_obj.save()
'''
instance.completed = True
instance.save()
post_save.connect(csv_upload_post_save, sender=StaffCSVUpload)
|
python
|
import cv2
import numpy as np
# Let's load a simple image with 3 black squares
image = cv2.imread('Hough.jpg')
cv2.waitKey(0)
# Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Find Canny edges
edged = cv2.Canny(gray, 30, 200)
cv2.waitKey(0)
# Finding Contours
# Use a copy of the image e.g. edged.copy()
# since findContours alters the image
contours, hierarchy = cv2.findContours(edged,
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.imshow('Canny Edges After Contouring', edged)
cv2.waitKey(0)
print("Number of Contours found = " + str(len(contours)))
# Draw all contours
# -1 signifies drawing all contours
cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
cv2.imshow('Contours', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
python
|
import numpy as np
import tensorrt as trt
import cv2
import os
import pycuda.autoinit
import pycuda.driver as cuda
try:
from . import TRT_exec_tools
except ImportError:
import TRT_exec_tools
class Semantic_Segmentation:
def __init__(self, trt_engine_path):
"""
Parameters:
-----------
trt_engine_path: string
Path to TRT engine.
"""
# Create a Context on this device,
self.cfx = cuda.Device(0).make_context()
TRT_LOGGER = trt.Logger()
TRT_LOGGER.min_severity = trt.Logger.Severity.VERBOSE
# Load TRT Engine
with open(trt_engine_path, "rb") as f, trt.Runtime(TRT_LOGGER) as runtime:
self.engine = runtime.deserialize_cuda_engine(f.read())
# Create Context
self.context = self.engine.create_execution_context()
# Allocate buffers required for engine
self.inputs, self.outputs, self.bindings, self.stream = TRT_exec_tools.allocate_buffers(self.engine)
# Input image height
self.height = 720
# Input image width
self.width = 1280
# RGBA Colour map for segmentation display
self.colour_map = None
def segment_image(self, image):
"""
Parameters:
-----------
image: np.array
HWC uint8 BGR
"""
assert image.shape == (self.height, self.width, 3)
# Infer
self.inputs[0].host = np.ascontiguousarray(image.astype('float32')).ravel()
# Make self the active context, pushing it on top of the context stack.
self.cfx.push()
trt_outputs = TRT_exec_tools.do_inference_v2(
context=self.context,
bindings=self.bindings,
inputs=self.inputs,
outputs=self.outputs,
stream=self.stream,
)
# Remove any context from the top of the context stack, deactivating it.
self.cfx.pop()
o = trt_outputs[0].reshape(self.height, self.width)
# HW np.array uint8
self.depth = o
if __name__ == "__main__":
import time
model = Semantic_Segmentation("sample.trt")
N = 500
images = np.random.randint(0, 255, size=[N, model.height, model.width, 3], dtype='uint8')
t1 = time.perf_counter()
for i in images:
model.segment_image(i)
t2 = time.perf_counter()
print(N/(t2-t1))
model.cfx.pop()
|
python
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from quant_benchmark.data.base_data_source.default_data_source import DefaultDataSource
import jqdatasdk
#see https://github.com/JoinQuant/jqdatasdk/blob/master/tests/test_api.py
jqdatasdk.auth(username='13922819479', password='123456')
data_source = DefaultDataSource()
order_book_id = "000001.XSHE"
bar_count = 10
dt = "2019-09-20"
data = data_source.history_bars(order_book_id=order_book_id, bar_count=bar_count, frequency="1w", dt=dt)
|
python
|
def f06(word1 = 'paraparaparadise', word2 = 'paragraph'):
ngram = lambda n: lambda tl: [''.join(tl[i:i + n]) for i in range(len(tl) - n + 1)]
X = set(ngram(2)(list(word1)))
Y = set(ngram(2)(list(word2)))
print(X.union(Y))
print(X.difference(Y))
print(X.intersection(Y))
|
python
|
import math
def get_digit(n, i):
return n // 10**i % 10
def int_len(n):
if n == 0:
return 1
return int(math.log10(n))+1
def get_new_recipes(n):
recipes = []
for i in range(int_len(n)):
recipes.append(get_digit(n, i))
return recipes[::-1]
def part1(count):
recipes = [3, 7]
elf1, elf2 = 0, 1
while len(recipes) < count + 10:
elf1_score = recipes[elf1]
elf2_score = recipes[elf2]
new_score = elf1_score + elf2_score
new_recipes = get_new_recipes(new_score)
recipes.extend(new_recipes)
elf1 = (1 + elf1 + elf1_score) % len(recipes)
elf2 = (1 + elf2 + elf2_score) % len(recipes)
return ''.join(map(str, recipes[count:count+10]))
def part2(goal):
recipes = [3, 7]
elf1, elf2 = 0, 1
while True:
elf1_score = recipes[elf1]
elf2_score = recipes[elf2]
new_score = elf1_score + elf2_score
new_recipes = get_new_recipes(new_score)
recipes.extend(new_recipes)
elf1 = (1 + elf1 + elf1_score) % len(recipes)
elf2 = (1 + elf2 + elf2_score) % len(recipes)
suffix = ''.join(map(str, recipes[-10:]))
if goal in suffix:
return len(recipes) -10 + suffix.index(goal)
if __name__ == '__main__':
INPUT = 793061
print(part1(INPUT))
# runs for about a minute or so on my machine
print(part2(str(INPUT)))
|
python
|
from ._Activate import *
from ._Deactivate import *
from ._Completed import *
from ._Startup import *
from ._Shutdown import *
from ._Recs import *
|
python
|
# %% codecell
import os
import numpy as np
from tqdm import tqdm
from shutil import copyfile
# %% codecell
class_indices_S2_rev = {
'Waterbuck': 1,
'Baboon': 2,
'Warthog': 3,
'Bushbuck': 4,
'Impala': 5,
'Oribi': 6,
'Elephant': 7,
'Genet': 8,
'Nyala': 9,
'Setup': 10,
'Bushpig': 11,
'Porcupine': 12,
'Civet': 13,
'Vervet': 14,
'Reedbuck': 15,
'Kudu': 16,
'Buffalo': 17,
'Sable_antelope': 18,
'Duiker_red': 19,
'Hartebeest': 20,
'Wildebeest': 21,
'Guineafowl_helmeted': 22,
'Hare': 23,
'Duiker_common': 24,
'Fire': 25,
'Mongoose_marsh': 26,
'Aardvark': 27,
'Honey_badger': 28,
'Hornbill_ground': 29,
'Mongoose_slender': 30,
'Mongoose_bushy_tailed': 31,
'Samango': 32,
'Mongoose_white_tailed': 33,
'Mongoose_banded': 34,
'Mongoose_large_grey': 35,
'Bushbaby': 36,
'Guineafowl_crested': 37,
'Eland': 38,
'Lion': 39,
'Serval': 40
}
class_indices_S2 = {class_indices_S2_rev[k]: k for k in class_indices_S2_rev}
# %% codecell
root = '/home/zhmiao/datasets/ecology/GNP'
# confident_path = '/home/zhmiao/repos/AnimalActiveLearing_srv/weights/GTPSMemoryStage2_ConfPseu/051620_MOZ_S2_0_preds_conf.txt'
# confident_path = '/home/zhmiao/repos/AnimalActiveLearing_srv/weights/GTPSMemoryStage2_ConfPseu_SoftIter/072520_MOZ_S2_soft_iter_0_preds_conf.txt'
confident_path = '/home/zhmiao/repos/AnimalActiveLearning/weights/SemiStage2OLTR_Energy/111620_MOZ_PSLABEL_OLTR_Energy_0_preds_conf.txt'
# %% codecell
f = open(confident_path, 'r')
file_id_list = []
cat_list = []
for line in tqdm(f):
line_sp = line.replace('\n', '').rsplit(' ', 1)
file_id = line_sp[0]
cat = class_indices_S2[int(line_sp[1])]
file_id_list.append(file_id)
cat_list.append(cat)
f.close()
# %% codecell
file_id_list = np.array(file_id_list)
cat_list = np.array(cat_list)
# %% codecell
np.random.seed(10)
rand_idx = np.random.choice(range(len(cat_list)), 1000)
file_id_sel = file_id_list[rand_idx]
cat_sel = cat_list[rand_idx]
# %% codecell
save_root = os.path.join(root, 'S3_pickout_soft_iter_120220')
os.makedirs(save_root, exist_ok=True)
# %% codecell
for file_id, cat in tqdm(zip(file_id_sel, cat_sel)):
from_path = os.path.join(root, file_id)
file_id = file_id.replace('/', ':::')
save_path = os.path.join(save_root, file_id)
if '.JPG' in save_path:
save_path = save_path.replace('.JPG', '_{}.JPG'.format(cat))
elif '.jpg' in save_path:
save_path = save_path.replace('.jpg', '_{}.jpg'.format(cat))
copyfile(from_path, save_path)
# %%
|
python
|
import csv
import os
import random
from .utils import write_into_file, train_val_test_split
def preprocess(in_csv_paths, out_dir_path, val_split, test_split):
dataset = []
for path in in_csv_paths:
with open(path, "r") as file:
reader = csv.DictReader(file)
for row in reader:
text, label = row["text"], row["label"]
dataset.append((text, label))
random.shuffle(dataset)
train_dataset, val_dataset, test_dataset = train_val_test_split(dataset, val_split, test_split)
write_into_file(dataset, out_path=os.path.join(out_dir_path, "data_full.csv"))
write_into_file(train_dataset, out_path=os.path.join(out_dir_path, "data_train.csv"))
write_into_file(val_dataset, out_path=os.path.join(out_dir_path, "data_val.csv"))
write_into_file(test_dataset, out_path=os.path.join(out_dir_path, "data_test.csv"))
|
python
|
"""Output timeseries in NetCDF format.
"""
import glob,os,sys
import pandas as pd
import datetime as dt
import copy
def defaultExtensions():
return ['.nc']
def NCfile(filename,datas):
datas=copy.deepcopy(datas)
fileout=copy.deepcopy(filename)
for i,df in enumerate(datas):
if len(datas)>1:
fileout=filename[:-3]+str(i)+'.txt'
del df['dataframe'][df['dataframe'].index.name]
xar=df['dataframe'].to_xarray()
cols=list(df['dataframe'].columns)
for i,col in enumerate(cols):
attr={}
uni=df['metadata'][col]['units']
if uni and uni!='None':
attr['units']=uni
uni=df['metadata'][col]['long_name']
if uni and uni!='None':
attr['long_name']=uni
xar[col].attrs=attr
xar.to_netcdf(path=fileout, mode='w')
|
python
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CassandraCluster(object):
"""Implementation of the 'CassandraCluster' model.
Specifies an Object containing information about a Cassandra cluster.
Attributes:
primary_host (string): Primary host from this Cassandra cluster.
seeds (list of string): Seeds of this Cassandra Cluster.
"""
# Create a mapping from Model property names to API property names
_names = {
"primary_host":'primaryHost',
"seeds":'seeds'
}
def __init__(self,
primary_host=None,
seeds=None):
"""Constructor for the CassandraCluster class"""
# Initialize members of the class
self.primary_host = primary_host
self.seeds = seeds
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
primary_host = dictionary.get('primaryHost')
seeds = dictionary.get('seeds')
# Return an object of this model
return cls(primary_host,
seeds)
|
python
|
"""
A Work-In-Progress agent using Tensorforce
"""
from . import BaseAgent
from .. import characters
class TensorForceAgent(BaseAgent):
"""The TensorForceAgent. Acts through the algorith, not here."""
def __init__(self, character=characters.Bomber, algorithm='ppo'):
super(TensorForceAgent, self).__init__(character)
self.algorithm = algorithm
def act(self, obs, action_space):
"""This agent has its own way of inducing actions. See train_with_tensorforce."""
return None
def initialize(self, env):
from gym import spaces
from tensorforce.agents import PPOAgent
if self.algorithm == "ppo":
if type(env.action_space) == spaces.Tuple:
actions = {
str(num): {
'type': int,
'num_actions': space.n
}
for num, space in enumerate(env.action_space.spaces)
}
else:
actions = dict(type='int', num_actions=env.action_space.n)
return PPOAgent(
states=dict(type='float', shape=env.observation_space.shape),
actions=actions,
network=[
dict(type='dense', size=64),
dict(type='dense', size=64)
],
batching_capacity=1000,
step_optimizer=dict(
type='adam',
learning_rate=1e-4
)
)
return None
|
python
|
## 2. Frequency Distribution ##
fandango_distribution = reviews['Fandango_Ratingvalue'].value_counts().sort_index()
imdb_distribution = reviews['IMDB_norm'].value_counts().sort_index()
print(fandango_distribution)
print('--'*12)
print(imdb_distribution)
## 4. Histogram In Matplotlib ##
fig, ax = plt.subplots()
plt.hist(reviews['Fandango_Ratingvalue'], range=(0,5))
plt.show()
## 5. Comparing histograms ##
fig = plt.figure(figsize=(5,20))
ax1 = fig.add_subplot(4,1,1)
ax2 = fig.add_subplot(4,1,2)
ax3 = fig.add_subplot(4,1,3)
ax4 = fig.add_subplot(4,1,4)
ax1.hist(reviews['Fandango_Ratingvalue'], bins=20, range=(0,5))
ax1.set_title('Distribution of Fandango Ratings')
ax1.set_ylim(0, 50)
ax3.hist(reviews['Metacritic_user_nom'], bins=20, range=(0,5))
ax3.set_title('Distribution of Metacritic Ratings')
ax3.set_ylim(0, 50)
ax2.hist(reviews['RT_user_norm'],bins=20, range=(0,5))
ax2.set_title('Distribution of Rotten Tomatoes Ratings')
ax2.set_ylim(0, 50)
ax4.hist(reviews['IMDB_norm'], bins=20, range=(0,5))
ax4.set_title('Distribution of IMDB Ratings')
ax4.set_ylim(0,50)
plt.show()
## 7. Box Plot ##
fig, ax = plt.subplots()
ax.boxplot(norm_reviews['RT_user_norm'])
ax.set_ylim(0,5)
ax.set_xticklabels(['Rotten Tomatoes'])
plt.show()
## 8. Multiple Box Plots ##
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue']
fig, ax = plt.subplots()
ax.boxplot(norm_reviews[num_cols].values)
ax.set_xticklabels(num_cols, rotation=90)
ax.set_ylim(0,5)
plt.show()
|
python
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 03. 円周率
sentence = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
print([len(c.strip(",.")) for c in sentence.split()])
|
python
|
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db import models
from problem.models import Submit, ProblemStats, LogEvent
@receiver(post_save, sender=Submit)
def update_problem_status(sender, instance, **kwargs):
try:
stats: ProblemStats = ProblemStats.objects.get(problem=instance.problem)
except ProblemStats.DoesNotExist:
stats: ProblemStats = ProblemStats(problem=instance.problem)
queryset = Submit.objects.annotate(
ordering=models.Case(
models.When(status="OK", then=models.Value(0)),
models.When(status="AW", then=models.Value(1)),
default=models.Value(2),
output_field=models.IntegerField()
)
).filter(problem=instance.problem).order_by('student', 'ordering', '-id').distinct('student')
stats.green = len(list((filter(lambda x: x.status == Submit.OK, queryset))))
stats.yellow = len(list((filter(lambda x: x.status in [Submit.AWAITING_MANUAL, Submit.DEFAULT_STATUS], queryset))))
stats.red = len(list((filter(
lambda x: x.status not in [Submit.OK, Submit.AWAITING_MANUAL, Submit.DEFAULT_STATUS],
queryset
))))
stats.save()
@receiver(post_save, sender=Submit)
def create_log_event(sender, instance: Submit, created, **kwargs):
log_event = LogEvent(problem=instance.problem, student=instance.student)
if created:
log_event.type = LogEvent.TYPE_SUBMIT
log_event.submit = instance
log_event.author = instance.student
log_event.data = dict(message=instance.id)
log_event.save()
return
if kwargs['update_fields'] and 'status' in kwargs['update_fields']:
log_event.type = LogEvent.TYPE_STATUS_CHANGE
log_event.submit = instance
if log_event.submit.updated_by:
log_event.author = log_event.submit.updated_by
log_event.data = dict(message=f'Статус изменён на {instance.status}')
log_event.save()
return
post_save.connect(update_problem_status, weak=False, sender=Submit)
post_save.connect(create_log_event, weak=False, sender=Submit)
|
python
|
km = float(input('Informe a distância em KM: '))
v = float(input('Informe a velocidade média: '))
t = km / v
t_h = t // 1
t_m = (t - t_h) * 60
print(f'O tempo da viagem será de {t_h:.0f} horas e {t_m:.0f} minutos.')
|
python
|
# from .runner import main
|
python
|
import re
from typing import List, Dict, Type
import pkgutil
import inspect
import importlib
import HABApp
from HABApp.core import Items
from HABApp.core.items.base_item import BaseItem
import zone_api.core.actions as actions
from zone_api import platform_encapsulator as pe
from zone_api import device_factory as df
from zone_api.alert_manager import AlertManager
from zone_api.core.action import Action
from zone_api.core.devices.activity_times import ActivityTimes
from zone_api.core.devices.gas_sensor import NaturalGasSensor, SmokeSensor, Co2GasSensor, RadonGasSensor
from zone_api.core.immutable_zone_manager import ImmutableZoneManager
from zone_api.core.zone import Zone, Level
from zone_api.core.zone_manager import ZoneManager
from zone_api.core.neighbor import NeighborType, Neighbor
"""
This module contains functions to construct an ImmutableZoneManager using the following convention
for the OpenHab items.
1. The zones are defined as a String item with this pattern Zone_{name}:
String Zone_GreatRoom
{ level="FF", displayIcon="player", displayOrder="1",
openSpaceSlaveNeighbors="FF_Kitchen" }
- The levels are the reversed mapping of the enums in Zone::Level.
- Here are the list of supported attributes: level, external, openSpaceNeighbors,
openSpaceMasterNeighbors, openSpaceSlaveNeighbors, displayIcon, displayOrder.
2. The individual OpenHab items are named after this convention:
{zone_id}_{device_type}_{device_name}.
Here's an example:
Switch FF_Office_LightSwitch "Office Light" (gWallSwitch, gLightSwitch, gFirstFloorLightSwitch)
[shared-motion-sensor]
{ channel="zwave:device:9e4ce05e:node8:switch_binary", durationInMinutes="15" }
"""
def parse(activity_times: ActivityTimes, actions_package: str = "zone_api.core.actions",
actions_path: List[str] = actions.__path__) -> ImmutableZoneManager:
"""
- Parses the zones and devices from the remote OpenHab items (via the REST API).
- Adds devices to the zones.
- Adds default actions to the zones.
- For each action, invoke Action::on_startup method.
- Start the scheduler service.
:return:
"""
mappings = {
'.*AlarmPartition$': df.create_alarm_partition,
'.*_ChromeCast$': df.create_chrome_cast,
'.*Door$': df.create_door,
'[^g].*_Window$': df.create_window,
'.*_Camera$': df.create_camera,
'[^g].*MotionSensor$': df.create_motion_sensor,
'[^g].*LightSwitch.*': df.create_switches,
'.*FanSwitch.*': df.create_switches,
'.*Wled_MasterControls.*': df.create_switches,
'[^g].*_Illuminance.*': df.create_illuminance_sensor,
'[^g](?!.*Weather).*Humidity$': df.create_humidity_sensor,
'[^g].*_NetworkPresence.*': df.create_network_presence_device,
'[^g].*_Plug$': df.create_plug,
'[^g].*_Co2$': df.create_gas_sensor(Co2GasSensor),
'[^g].*_NaturalGas$': df.create_gas_sensor(NaturalGasSensor),
'[^g].*_RadonGas$': df.create_gas_sensor(RadonGasSensor),
'[^g].*_Smoke$': df.create_gas_sensor(SmokeSensor),
'.*_Tv$': df.create_television_device,
'.*_Thermostat_EcobeeName$': df.create_ecobee_thermostat,
# not matching "FF_Office_Computer_Dell_GpuTemperature"
'[^g](?!.*Computer)(?!.*Weather).*Temperature$': df.create_temperature_sensor,
'[^g].*WaterLeakState$': df.create_water_leak_sensor,
'[^g].*_TimeOfDay$': df.create_astro_sensor,
'.*_Computer_[^_]+$': df.create_computer,
'.*_Weather_Temperature$': df.create_weather,
}
zm: ZoneManager = ZoneManager()
immutable_zm = zm.get_immutable_instance()
immutable_zm = immutable_zm.set_alert_manager(AlertManager())
zone_mappings = {}
for zone in _parse_zones():
zone_mappings[zone.get_id()] = zone
items: List[BaseItem] = Items.get_all_items()
for item in items:
for pattern in mappings.keys():
device = None
if re.match(pattern, item.name) is not None:
device = mappings[pattern](immutable_zm, item)
if device is not None:
zone_id = df.get_zone_id_from_item_name(item.name)
if zone_id is None:
pe.log_warning("Can't get zone id from item name '{}'".format(item.name))
continue
if zone_id not in zone_mappings.keys():
pe.log_warning("Invalid zone id '{}'".format(zone_id))
continue
zone = zone_mappings[zone_id].add_device(device)
zone_mappings[zone_id] = zone
# Add specific devices to the Virtual Zone
zone = next((z for z in zone_mappings.values() if z.get_name() == 'Virtual'), None)
if zone is not None:
zone = zone.add_device(activity_times)
zone_mappings[zone.get_id()] = zone
action_classes = get_action_classes(actions_package, actions_path)
zone_mappings = add_actions(zone_mappings, action_classes)
for z in zone_mappings.values():
zm.add_zone(z)
immutable_zm.start()
return immutable_zm
def _parse_zones() -> List[Zone]:
"""
Parses items with the zone pattern in the name and constructs the associated Zone objects.
:return: List[Zone]
"""
pattern = 'Zone_([^_]+)'
zones: List[Zone] = []
items = Items.get_all_items()
for item in items:
match = re.search(pattern, item.name)
if not match:
continue
zone_name = match.group(1)
item_def = HABApp.openhab.interface.get_item(
item.name,
"level, external, openSpaceNeighbors, openSpaceMasterNeighbors, openSpaceSlaveNeighbors, displayIcon, "
"displayOrder")
metadata = item_def.metadata
level = Level(df.get_meta_value(metadata, "level"))
external = df.get_meta_value(metadata, "external", False)
display_icon = df.get_meta_value(metadata, "displayIcon", '')
display_order = int(df.get_meta_value(metadata, "displayOrder", 9999))
zone = Zone(zone_name, [], level, [], {}, external, display_icon, display_order)
neighbor_type_mappings = {
'closeSpaceNeighbors': NeighborType.CLOSED_SPACE,
'openSpaceNeighbors': NeighborType.OPEN_SPACE,
'openSpaceMasterNeighbors': NeighborType.OPEN_SPACE_MASTER,
'openSpaceSlaveNeighbors': NeighborType.OPEN_SPACE_SLAVE,
}
for neighbor_type_str in neighbor_type_mappings.keys():
neighbor_str = df.get_meta_value(metadata, neighbor_type_str)
if neighbor_str is not None:
for neighbor_id in neighbor_str.split(','):
neighbor_id = neighbor_id.strip()
neighbor = Neighbor(neighbor_id, neighbor_type_mappings[neighbor_type_str])
zone = zone.add_neighbor(neighbor)
zones.append(zone)
return zones
def add_actions(zone_mappings: Dict, action_classes: List[Type]) -> Dict:
"""
Create action instances from action_classes and add them to the zones.
A set of filters are applied to ensure that only the application actions are added to each zone.
As the Zone class is immutable, a new Zone instance is created after adding an action. As such, a zone_mappings
dictionary must be provided.
:param str zone_mappings: mappings from zone_id string to a Zone instance.
:param str action_classes: the list of action types.
"""
for clazz in action_classes:
action: Action = clazz()
for zone in zone_mappings.values():
if not _can_add_action_to_zone(zone, action):
continue
if action.must_be_unique_instance():
zone = zone.add_action(clazz())
else:
zone = zone.add_action(action)
zone_mappings[zone.get_id()] = zone
return zone_mappings
def _can_add_action_to_zone(zone: Zone, action: Action) -> bool:
satisfied = True # must have all devices
for device_type in action.get_required_devices():
if len(zone.get_devices_by_type(device_type)) == 0:
satisfied = False
break
if not satisfied:
return False
if zone.is_internal() and not action.is_applicable_to_internal_zone():
return False
if zone.is_external() and not action.is_applicable_to_external_zone():
return False
if len(action.get_applicable_levels()) > 0 and (zone.get_level() not in action.get_applicable_levels()):
return False
zone_name_pattern = action.get_applicable_zone_name_pattern()
if zone_name_pattern is not None:
match = re.search(zone_name_pattern, zone.get_name())
if not match:
return False
return True
def get_action_classes(actions_package: str = "zone_api.core.actions",
actions_path: List[str] = actions.__path__) -> List[Type]:
"""
Retrieve a list of action class types defined in the actions_path with the given actions_package.
To avoid loading the non-action classes (the package might contain helper modules), the following restrictions
are used:
1. The normalized action name must be the same as the normalized module name.
e.g. action 'ManagePlugs' is defined in the file 'manage_plugs.py'.
2. The class defined in the module must be an instance of 'Action'.
:param str actions_package: the package of the action classes.
:param str actions_path: the absolute path to the action classes.
"""
classes = []
for importer, module_name, is_pkg in pkgutil.iter_modules(actions_path):
module = importlib.import_module(f"{actions_package}.{module_name}")
for (name, value) in inspect.getmembers(module, lambda member: inspect.isclass(member)):
normalized_module_name = module_name.replace('_', '').lower()
if name.lower() == normalized_module_name:
try:
clazz = getattr(module, name)
obj = clazz()
if isinstance(obj, Action):
classes.append(clazz)
except AttributeError:
pass
except TypeError:
pass
return classes
|
python
|
from unittest import TestCase
from unittest.mock import patch, call
import os
import pytest
from osbot_utils.utils.Dev import pprint
from osbot_utils.utils.Json import json_load_file
from cdr_plugin_folder_to_folder.processing.Analysis_Elastic import Analysis_Elastic
from cdr_plugin_folder_to_folder.utils.testing.Setup_Testing import Setup_Testing
FIXTURE_DIR = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'test_files',
)
class test_Report_Elastic(TestCase):
test_file = None
@classmethod
def setUpClass(cls) -> None:
cls.file_hash = '458d2ceb57b1bac2866c43e16cc9392b017aa48f0689876df25399d0f7ad198c'
@classmethod
def tearDownClass(cls) -> None:
pass
def setUp(self) -> None:
analysis_file_path = os.path.join(FIXTURE_DIR, 'analysis.json')
assert os.path.isfile(analysis_file_path)
self.analysis_data = json_load_file(analysis_file_path)
assert self.analysis_data is not None
assert len(self.analysis_data ) == 6
self.original_hash = self.analysis_data[self.file_hash]['original_hash']
assert self.original_hash == self.file_hash
self.analysis_elastic = Analysis_Elastic()
self.analysis_elastic.setup()
if self.analysis_elastic.enabled is False:
pytest.skip('Elastic server not available')
def test_add_analysis(self):
analysis_add_report = self.analysis_elastic.add_analysis(self.analysis_data)
assert analysis_add_report.get('_shards').get('successful') == 1
assert self.analysis_elastic.get_analysis (original_hash=self.original_hash) == self.analysis_data[self.file_hash]
assert self.analysis_elastic.delete_analysis(original_hash=self.original_hash).get('result') == 'deleted'
assert self.analysis_elastic.get_analysis (original_hash=self.original_hash) == {}
def test_clear_all_report(self):
self.analysis_elastic.delete_all_analysis()
assert len(self.analysis_elastic.get_all_analysis()) == 0
|
python
|
from seleniumbase import BaseCase
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from parameterized import parameterized
import pytest
from test_thermal.test_CompanyAdmin.test_RoleManagement.RoleManageBase import RoleManageBase
from utilities import utilities
from utilities.Authority import Authority
from config.constants import *
class TestRead(RoleManageBase):
TNB = COMPANYADMIN_ROLE_READ_TNB
datafile = COMPANYADMIN_ROLE_READ_DATA_FILE
test_data_read_normal = utilities.gen_testdata(datafile, delimiter=',', header=0, scenario='normal')
@parameterized.expand(test_data_read_normal)
@pytest.mark.scenario_regression_companyadmin(TNB + 1)
def test_read_normal(self, companyname, rolename, expectation):
self.role_read(companyname, rolename, expectation)
authority = Authority()
test_data_read_check_authority_info = authority.get_role_authority_info()
@parameterized.expand(test_data_read_check_authority_info, skip_on_empty=True) # skip_on_empty=True doesn't work
@pytest.mark.scenario_regression_companyadmin(TNB + 2)
@pytest.mark.scenario_regression(TNB + 1)
def test_read_check_authority_info(self, company, role, email_list):
self.check_authority_info(company=company, role=role, email_list=email_list, expectation="pass")
|
python
|
"""
Here we're going to code for the local rotations. We're doing an object oriented approach
Left and right are in reference to the origin
"""
__version__ = 1.0
__author__ = 'Katie Kruzan'
import string # just to get the alphabet easily iterable
import sys # This just helps us in our printing
from typing import Dict # This helps us in our documentation
# Getting the structure for the classes we're putting together
class Segment:
"""
These are going to represent the outer segments and the mysteries they hold.
The segments will be adjacent to 2 outer nodes
"""
def __init__(self, name: str):
"""
Initialize the segment, keeping a place for the right left outer vertices to which it is adjacent
:param name: How we will reference this segment. In this implementation, it is expected to be a negative integer
"""
self.leftOuter = None
self.rightOuter = None
self.name = name
def getName(self) -> str:
"""
Return the name we gave to this segment.
:return: name
"""
return self.name
def getLeftOuter(self):
"""
Return the outer node to the left of this segment with respect to the origin
:return: leftOuter
"""
return self.leftOuter
def getRightOuter(self):
"""
Return the outer node to the right of this segment with respect to the origin
:return: rightOuter
"""
return self.rightOuter
def setLeftOuter(self, left):
"""
Set the outer node to the left of this segment with respect to the origin
Also, set left's right segment to this segment.
:param left: A outer node object to be referenced as this segment's left outer node
:return: None
"""
self.leftOuter = left
if left.getRightSegment() is None:
left.setRightSegment(self)
def setRightOuter(self, right):
"""
Set the outer node to the right of this segment with respect to the origin
Also, set right's left segment to this segment.
:param right: A outer node object to be referenced as this segment's right outer node
:return: None
"""
self.rightOuter = right
if right.getLeftSegment() is None:
right.setLeftSegment(self)
def isValidObject(self) -> bool:
"""
Checks to see if this segment has been full initialized.
:return: valid returns true if it has both the left and right outer nodes set
"""
if (self.leftOuter is None) or (self.rightOuter is None):
return False
return True
def toString(self) -> str:
"""
Returns a formatted string of the left and right outer nodes this is associated with
:return: Description string
"""
return 'left Outer: ' + self.leftOuter.getName() + '\nright Outer: ' + self.rightOuter.getName()
class Outer:
"""
Class to represent the outer vertices that are adjacent to an inner vertex and 2 outer segments
"""
def __init__(self, name: str):
"""
Initialize the outer node
Keeping a place for the inner vertex and right and left outer segments to which it is adjacent.
:param name: How we will reference this outer node. In this implementation, it is expected to be a positive integer
"""
self.adjInner = None
self.leftSegment = None
self.rightSegment = None
self.name = name
def getName(self) -> str:
"""
Return the name we gave to this outer node.
:return: name
"""
return self.name
def getLeftSegment(self) -> Segment:
"""
Return the segment object to the left of this outer node with respect to the origin
:return: leftSegment
"""
return self.leftSegment
def getRightSegment(self) -> Segment:
"""
Return the segment object to the right of this outer node with respect to the origin
:return: rightSegment
"""
return self.rightSegment
def getAdjInner(self):
"""
Return the inner node object adjacent to this outer note object
:return: adjInner
"""
return self.adjInner
def setLeftSegment(self, left: Segment):
"""
Set the segment to the left of this outer node with respect to the origin
Also, set left's right outer node to self.
:param left: A segment object to be referenced as this node's left outer segment
:return: None
"""
self.leftSegment = left
if left.getRightOuter() is None:
left.setRightOuter(self)
def setRightSegment(self, right: Segment):
"""
Set the segment to the right of this outer node with respect to the origin
Also, set right's left outer node to self.
:param right: A segment object to be referenced as this node's right outer segment
:return: None
"""
self.rightSegment = right
if right.getLeftOuter() is None:
right.setLeftOuter(self)
def setAdjInner(self, inner):
"""
Set the inner node adjacent to this outer node
Also, set inner's adjacent outer node to self.
:param inner: A inner node object to be referenced as this node's adjacent inner node
:return: None
"""
self.adjInner = inner
if inner.getAdjOuter() is None:
inner.setAdjOuter(self)
def isValidObject(self) -> bool:
"""
Checks to see if this outer node has been full initialized.
:return: valid returns true if it has the left segment, right segment, and inner node set
"""
if (self.leftSegment is None) or (self.rightSegment is None) or (self.adjInner is None):
return False
return True
def toString(self) -> str:
"""
Returns a formatted string of the left segment, right segment, and inner node this outer node is associated with
:return: Description string
"""
return 'left Segment: ' + self.leftSegment.getName() + '\nright Segment: ' + self.rightSegment.getName() \
+ '\nadj Inner: ' + self.adjInner.getName()
class Inner:
"""
Class to represent the inner vertices that are adjacent to an outer vertex and 2 neighboring inner vertices
"""
def __init__(self, name: str):
"""
Initialize the inner node object
Keeping a place for the outer vertex and right and left adjacent inner nodes.
:param name: How we will reference this inner node. In this implementation, it is expected to be a lowercase letter
"""
self.adjOuter = None
self.leftInner = None
self.rightInner = None
self.name = name
def getName(self) -> str:
"""
Return the name we gave to this inner node.
:return: name
"""
return self.name
def getLeftInner(self):
"""
Return the inner node object to the left of this inner node with respect to the origin
:return: leftInner
"""
return self.leftInner
def getRightInner(self):
"""
Return the inner node object to the right of this inner node with respect to the origin
:return: rightInner
"""
return self.rightInner
def getAdjOuter(self) -> Outer:
"""
Return the outer node object adjacent to this inner node
:return: adjOuter
"""
return self.adjOuter
def setLeftInner(self, left):
"""
Set the inner node to the left of this inner node with respect to the origin
Also, set left's right inner node to self.
:param left: An inner node object to be referenced as this node's left inner node
:return: None
"""
self.leftInner = left
if left.getRightInner() is None:
left.setRightInner(self)
def setRightInner(self, right):
"""
Set the inner node to the right of this inner node with respect to the origin
Also, set right's left inner node to self.
:param right: An inner node object to be referenced as this node's right inner node
:return: None
"""
self.rightInner = right
if right.getLeftInner() is None:
right.setLeftInner(self)
def setAdjOuter(self, outer: Outer):
"""
Set the outer node adjacent to this inner node
Also, set outer's adjacent inner node to self.
:param outer: An outer node object to be referenced as this node's adjacent outer node
:return: None
"""
self.adjOuter = outer
if outer.getAdjInner() is None:
outer.setAdjInner(self)
def isValidObject(self) -> bool:
"""
Checks to see if this inner node has been full initialized.
:return: valid returns true if it has the left inner node, right inner node, and adjacent outer node set
"""
if (self.leftInner is None) or (self.rightInner is None) or (self.adjOuter is None):
return False
return True
def toString(self) -> str:
"""
Returns a formatted string of the left inner node, right inner node, and adjacent outer node this inner node
is associated with
:return: Description string
"""
return 'left Inner: ' + self.leftInner.getName() + '\nright Inner: ' + self.rightInner.getName() \
+ '\nadj Outer: ' + self.adjOuter.getName()
def standardCircle(num_verts: int) -> (Dict[str, Segment], Dict[str, Outer], Dict[str, Inner]):
"""
This will go through and initialize our standard starting circle
:param num_verts: the number of outer nodes we will have
:returns: tuple(segs, outs, inns)
-segs - dictionary of str: Segment objects in the circle \\
-outs - dictionary of str: Outer objects in the circle \\
-inns - dictionary of str: Inner objects in the circle
"""
# Initializing our dictionaries
segs = dict()
outs = dict()
inns = dict()
# Running through the number of vertices we will be edning up with
for i in range(num_verts):
# start with an inner node - labeling with lowercase letters
inn = Inner(string.ascii_letters[i])
# If we aren't on the first one, connect it to the previous one.
if i != 0:
inn.setLeftInner(inns[string.ascii_letters[i - 1]])
# If we've hit the end of the line, go ahead and close up the circle.
if i == num_verts - 1:
inn.setRightInner(inns[string.ascii_letters[0]])
# then make the outer
out = Outer(str(i + 1))
# Go ahead and connect the inner we just made with this outer node
out.setAdjInner(inn)
# If we aren't on the first one, go ahead and connect it to the previous segment
if i != 0:
out.setLeftSegment(segs[str(-i)])
# Now time to make the segment
seg = Segment(str(-i - 1))
# Go ahead and connect the outer node we just made with this segment
seg.setLeftOuter(out)
# If we're at the end of the circle, then we close it up. Otherwise, move on
if i == num_verts - 1:
seg.setRightOuter(outs[str(1)])
# add them to our dictionaries
segs[seg.getName()] = seg
outs[out.getName()] = out
inns[inn.getName()] = inn
# If we've made it here, then we've made the full circle and are ready to return it
return segs, outs, inns
def findTheFace(source_in: Inner) -> list:
"""
This will take an inner node and use the algorithm to walk the face that it is on.
The order of the face will be i, o, s, o, i repeat
:param source_in: Inner node object we are starting from.
:return: face: a list representing the face. This list is of inner, outer, and segment objects in the
order i, o, s, o, i, repeat.
"""
# initialize the list
face = list()
# starting the face with the source inner node.
face.append(source_in)
# initialize the ending inner node we will be using for comparison
end_in = None
# As long as we haven't looped back around, go through the following process.
while source_in != end_in:
# inner: find adjacent outer
face.append(face[-1].getAdjOuter())
# outer: go to right seg
face.append(face[-1].getRightSegment())
# segment: go to right outer
face.append(face[-1].getRightOuter())
# outer: then adj inner
face.append(face[-1].getAdjInner())
# then left inner and repeat.
# set this inner node as our node to compare to our starting node.
end_in = face[-1].getLeftInner()
face.append(end_in)
return face
def faceCannonOrder(face: list) -> list:
"""
Just list the face with the face elements in order.
We will do it with the first numerical face, and then go right before it for an order that will be consistent.
:param face: a list representing the face. This list is of inner, outer, and segment objects in the
order i, o, s, o, i, repeat.
:return: ordered face in canonical order
"""
# find the first numerical face then go right before it
# initialize face num as a relatively high number we won't encounter
facenum = 333
# initialize the int for where we will split the list
start_ind = 0
# loop through and find the face we want to find
for i in range(len(face)):
try:
if int(face[i].getName()) < facenum:
# To get here, we must have found a lower face
# keep track of where this is located in the list
start_ind = i - 1
# make our current lowest face the new lowest face to keep comparing to.
facenum = int(face[i].getName())
# if we try casting a letter to a number, python will get upset, but that also means we're looking at
# an inner node, which we don't want for this anyways.
except ValueError:
continue
# make our ordered face getting from the starting index to the end, then wrapping around and getting the rest of
# the face
ord_face = face[start_ind:] + face[:start_ind]
# go through and make sure we don't have any duplicate elements right by each other. If we do, then drop them.
for i in range(len(ord_face) - 1):
if ord_face[i].toString() == ord_face[i + 1].toString():
ord_face.pop(i)
break
# return the ordered face
return ord_face
def grabAllTheFaces(inns: Dict[str, Inner]) -> list:
"""
Function to get the list of unique faces for our circle.
:param inns: dictionary of Inner objects. We will loop through these to get the faces
:return: faces: List of distinct faces in canonical order.
"""
# initialize the list of faces
faces = list()
# a set of all the elements we have covered by the faces. Will use this for a completeness check
covered = set()
# run through every inner node we've been given
for inn in inns:
# Generate the face that inner node lies on
face = findTheFace(inns[inn])
# put the face we've gotten in canonical order
face = faceCannonOrder(face)
# Check if we've already captured it.
if face not in faces:
# If not, then add it to our list of faces
faces.append(face)
# Go ahead and add the elements in this face to our covered set
covered.update(face)
# check we've gotten all the elements
if len(covered) == (3 * len(inns)):
print('We got em!!!')
# Now return a list of all the faces we have.
return faces
def printCircleStatus(segs: Dict[str, Segment], outs: Dict[str, Outer], inns: Dict[str, Inner]):
"""
Helper function that prints the status of the circle to the console
:param segs: dictionary of str: Segment objects in the circle
:param outs: dictionary of str: Outer objects in the circle
:param inns: dictionary of str: Inner objects in the circle
:return: None
"""
# Run through the segments
print('\nSegments:')
for k in segs:
print()
print(k)
print(segs[k].toString())
# Run through the Outer nodes
print('\nOuters:')
for k in outs:
print()
print(k)
print(outs[k].toString())
# Run through the Inner nodes
print('\nInners:')
for k in inns:
print()
print(k)
print(inns[k].toString())
if __name__ == '__main__':
# This is where you change the variables.
# must be a positive integer > 2
verts = 12
# Must be a string with spaces between each element. If you want to denote multiple cycles, you must add a |
switch_txt = '2 3 4 5 | 12 7'
# we're going to make a list of all the switches and all the cycles
switches = list()
# first, we get the cycles, split by '|'
cycles = switch_txt.split('|')
for c in cycles:
# We're going to split the switch into a list split by the whitespace
s = c.strip().split()
# Then we're going to append the switches in the cycle to the new list
switches.append(s)
# Go ahead and make the standard circle given the number of vertices we want to use.
segments, outers, inners = standardCircle(verts)
# Go through and grab the faces for our standard circle
facs = grabAllTheFaces(inners)
print('\nPrinting the faces')
for f in facs:
print()
for p in f:
sys.stdout.write(p.getName() + ' ')
# Go through and do the switches for each cycle
for switch in switches:
for num in range(len(switch)):
# store the current part of the switch we're working on
cs = switch[num]
# store the next part of the switch we're working on, looping to the beginning if we're at the end
ns = switch[(num + 1) % len(switch)]
# Do the actual switch
# Getting the new inner and outer validly switched up
inners[string.ascii_letters[int(cs) - 1]].setAdjOuter(outers[ns])
outers[ns].setAdjInner(inners[string.ascii_letters[int(cs) - 1]])
# print how the final rotation sits
printCircleStatus(segments, outers, inners)
# Go through and generate and print the new faces
new_facs = grabAllTheFaces(inners)
print('\nPrinting the new faces')
for f in new_facs:
print()
for p in f:
sys.stdout.write(p.getName() + ' ')
|
python
|
from controller.csi_general import csi_pb2
SUPPORTED_FS_TYPES = ["ext4", "xfs"]
access_mode = csi_pb2.VolumeCapability.AccessMode
SUPPORTED_ACCESS_MODE = [access_mode.SINGLE_NODE_WRITER]
# VolumeCapabilities fields which specify if it is volume with fs or raw block volume
VOLUME_CAPABILITIES_FIELD_ACCESS_TYPE_MOUNT = 'mount'
VOLUME_CAPABILITIES_FIELD_ACCESS_TYPE_BLOCK = 'block'
SECRET_USERNAME_PARAMETER = "username"
SECRET_PASSWORD_PARAMETER = "password"
SECRET_ARRAY_PARAMETER = "management_address"
PARAMETERS_POOL = "pool"
PARAMETERS_CAPABILITIES_SPACEEFFICIENCY = "SpaceEfficiency"
PARAMETERS_VOLUME_NAME_PREFIX = "volume_name_prefix"
PARAMETERS_SNAPSHOT_NAME_PREFIX = "snapshot_name_prefix"
PARAMETERS_CAPACITY_DELIMITER = "="
PARAMETERS_CAPABILITIES_DELIMITER = "="
PARAMETERS_OBJECT_ID_DELIMITER = ":"
PARAMETERS_NODE_ID_DELIMITER = ";"
PARAMETERS_FC_WWN_DELIMITER = ":"
SUPPORTED_CONNECTIVITY_TYPES = 2
OBJECT_TYPE_NAME_VOLUME = "volume"
OBJECT_TYPE_NAME_SNAPSHOT = "snapshot"
VOLUME_SOURCE_SNAPSHOT = "snapshot"
VOLUME_SOURCE_VOLUME = "volume"
|
python
|
import pybamm
import numpy as np
import sys
# set logging level
pybamm.set_logging_level("INFO")
# load (1+1D) SPMe model
options = {
"current collector": "potential pair",
"dimensionality": 1,
"thermal": "lumped",
}
model = pybamm.lithium_ion.SPM(options)
# create geometry
geometry = model.default_geometry
# load parameter values and process model and geometry
param = model.default_parameter_values
C_rate = 1
current_1C = 24 * param.process_symbol(pybamm.geometric_parameters.A_cc).evaluate()
param.update(
{
"Typical current [A]": C_rate * current_1C,
#"Initial temperature [K]": 298.15,
#"Negative current collector conductivity [S.m-1]": 1e7,
#"Positive current collector conductivity [S.m-1]": 1e7,
"Heat transfer coefficient [W.m-2.K-1]": 1,
}
)
param.process_model(model)
param.process_geometry(geometry)
# set mesh
var = pybamm.standard_spatial_vars
var_pts = {var.x_n: 5, var.x_s: 5, var.x_p: 5, var.r_n: 10, var.r_p: 10, var.z: 15}
# depending on number of points in y-z plane may need to increase recursion depth...
sys.setrecursionlimit(10000)
mesh = pybamm.Mesh(geometry, model.default_submesh_types, var_pts)
# discretise model
disc = pybamm.Discretisation(mesh, model.default_spatial_methods)
disc.process_model(model)
# solve model -- simulate one hour discharge
tau = param.evaluate(pybamm.standard_parameters_lithium_ion.tau_discharge)
t_end = 3600 / tau
t_eval = np.linspace(0, t_end, 120)
solution = model.default_solver.solve(model, t_eval)
# plot
output_variables = [
"X-averaged negative particle surface concentration [mol.m-3]",
"X-averaged positive particle surface concentration [mol.m-3]",
"X-averaged cell temperature [K]",
#"Local potenital difference [V]",
"Current collector current density [A.m-2]",
"Terminal voltage [V]",
"Volume-averaged cell temperature [K]",
]
plot = pybamm.QuickPlot(model, mesh, solution, output_variables)
plot.dynamic_plot()
|
python
|
#
# Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS,
# BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, [email protected].
#
# Distributed under 3-Clause BSD license. See LICENSE file for more information.
#
"""
Mapping Module
"""
# -- STANDARD MAPPING --
from .mapping_standard import *
|
python
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.