blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
283
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
41
| license_type
stringclasses 2
values | repo_name
stringlengths 7
96
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 58
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 12.7k
662M
⌀ | star_events_count
int64 0
35.5k
| fork_events_count
int64 0
20.6k
| gha_license_id
stringclasses 11
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 43
values | src_encoding
stringclasses 9
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 7
5.88M
| extension
stringclasses 30
values | content
stringlengths 7
5.88M
| authors
sequencelengths 1
1
| author
stringlengths 0
73
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
db35bccee94dc72ea2b03ff75a6e3b1036691f5b | efc9b70544c0bc108aaec0ed6a2aefdf208fd266 | /swap_two_value.py | 25897ecbcc46b07ca1f799983ab63bebbb923c35 | [] | no_license | fxy1018/Leetcode | 75fad14701703d6a6a36dd52c338ca56c5fa9eff | 604efd2c53c369fb262f42f7f7f31997ea4d029b | refs/heads/master | 2022-12-22T23:42:17.412776 | 2022-12-15T21:27:37 | 2022-12-15T21:27:37 | 78,082,899 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 354 | py | """
no extra space, swap two value
"""
'''
Created on Mar 18, 2017
@author: fanxueyi
'''
#bit manipularion
class Solution(object):
'''
input: int, int
rType: int, inte
'''
def swap(self,a,b):
a = a^b
b = a^b
a = a^b
return(a,b)
s = Solution()
print(s.swap(3,4))
print(s.swap(0,-2)) | [
"[email protected]"
] | |
81594cdf4cc52ad02830471a6e4c0a2e4016e45e | 5655b699aafe9d3518534459ca7fb0e73cc66b06 | /day5.py | f4633c8e733ed9bb124cb9cbcafc46d96011a843 | [] | no_license | yohanswanepoel/adventofcode2017 | cc62c04b00f3bf2692976f20d96437e7e9873ae0 | f79c8f75f8c0e4c14294afa64fc592869a0bfd16 | refs/heads/master | 2021-08-28T13:33:22.411249 | 2017-12-12T09:55:51 | 2017-12-12T09:55:51 | 113,157,032 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 719 | py | import sys
def day5():
steps = [0,3,0,1,-3]
steps = []
with open('day5.txt') as f:
mylist = f.read().splitlines()
for l in mylist:
steps.append(int(l))
print (steps)
performTask(steps)
def performTask( steps ):
step_counter = 0
current_instruction = 0
next_instruction = 0
size = len(steps)
while(True):
if(current_instruction < len(steps) and current_instruction > -1):
step_counter += 1
next_instruction += steps[current_instruction]
steps[current_instruction] += 1
current_instruction = next_instruction
else:
break
print(step_counter)
if __name__ == '__main__':
day5() | [
"[email protected]"
] | |
8e9f3948ab5c1e5a196edddb2fe11e19304dd0e5 | 1cd0c5706f5afcabccf28b59c15d306b114dd82a | /siteapi/migrations/0004_auto_20170220_2215.py | b448ea88ca4bcdc7a5f1e878f3326138726cde40 | [] | no_license | jacobbridges/scribbli | fb1ed8633fc8ebcd7d989fbab2e051612bdc07d2 | eb21ca9f5ee4c7caba5a25b76c6cdfe81af5d995 | refs/heads/master | 2021-01-12T10:32:38.466332 | 2018-01-27T19:48:39 | 2018-01-27T19:48:39 | 81,711,757 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 720 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-20 22:15
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('siteapi', '0003_auto_20170220_2213'),
]
operations = [
migrations.AlterField(
model_name='alphainvitation',
name='date_expires',
field=models.DateTimeField(default=datetime.datetime(2017, 2, 21, 22, 15, 51, 651428), verbose_name='date expires'),
),
migrations.AlterField(
model_name='alphainvitation',
name='unik',
field=models.CharField(max_length=36),
),
]
| [
"[email protected]"
] | |
7056f3d1611086a2888f755ce101e11b34ac26bb | 6c1d0916be8f26c82c2cab642a6ed0953efc2481 | /src/arm_bringup/scripts/old_or_unused/sac.py | 3c18813e56d52fd883c6d4153ce31a528f1a72f1 | [] | no_license | dVeon-loch/ReinforcementLearning_Arm | d69a6e6c822fea9f92850b986156f62e5e1d3087 | 71215294af5ea030b4018f58040d9806589514c2 | refs/heads/master | 2023-02-18T02:00:52.978174 | 2021-01-14T13:49:39 | 2021-01-14T13:49:39 | 312,808,040 | 6 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,563 | py | from arm_pyenv import ArmEnv
import numpy as np
import rospy
from tf_agents.environments import tf_py_environment
from tf_agents.environments import utils
from tf_agents.environments import wrappers
from tf_agents.trajectories import time_step as ts
from tf_agents.networks import actor_distribution_network, value_network
import base64
#import imageio
#import IPython
import matplotlib.pyplot as plt
import os
import reverb
import tempfile
import PIL.Image
import tensorflow as tf
from tf_agents.agents.ddpg import critic_network
from tf_agents.agents.sac import sac_agent
from tf_agents.agents.sac import tanh_normal_projection_network
from tf_agents.experimental.train import actor
from tf_agents.experimental.train import learner
from tf_agents.experimental.train import triggers
from tf_agents.experimental.train.utils import spec_utils
from tf_agents.experimental.train.utils import strategy_utils
from tf_agents.experimental.train.utils import train_utils
from tf_agents.metrics import py_metrics
from tf_agents.networks import actor_distribution_network
from tf_agents.policies import greedy_policy
from tf_agents.policies import py_tf_eager_policy
from tf_agents.policies import random_py_policy
from tf_agents.replay_buffers import reverb_replay_buffer
from tf_agents.replay_buffers import reverb_utils
tempdir = tempfile.gettempdir()
fc_layer_params = (100,)
importance_ratio_clipping
lambda_value
train_timed_env = wrappers.TimeLimit(
ArmEnv(),
1000
)
eval_timed_env = wrappers.TimeLimit(
ArmEnv(),
1000
)
train_env = tf_py_environment(train_timed_env)
eval_env = tf_py_environment(eval_timed_env)
observation_tensor_spec, action_spec, time_step_tensor_spec = (
spec_utils.get_tensor_specs(train_env))
normalized_observation_tensor_spec = tf.nest.map_structure(
lambda s: tf.TensorSpec(
dtype=tf.float32, shape=s.shape, name=s.name
),
observation_tensor_spec
)
actor_net = actor_distribution_network.ActorDistributionNetwork(
normalized_observation_tensor_spec, ...)
value_net = value_network.ValueNetwork(
normalized_observation_tensor_spec, ...)
# Note that the agent still uses the original time_step_tensor_spec
# from the environment.
agent = ppo_clip_agent.PPOClipAgent(
time_step_tensor_spec, action_spec, actor_net, value_net, ...)
actor_fc_layer_params = (256, 256)
critic_joint_fc_layer_params = (256, 256)
log_interval = 5000 # @param {type:"integer"}
num_eval_episodes = 20 # @param {type:"integer"}
eval_interval = 10000 # @param {type:"integer"}
policy_save_interval = 5000 # @param {type:"integer"}
| [
"[email protected]"
] | |
84c9288217995f2610547ebe92e52a2f6e69d003 | d5ee3688c0df793a765aa7fca25253ef450b82e9 | /src/scs_mfr/opc_conf.py | a821e3faf7068277766ea4005206cbf8c299d8b0 | [
"MIT"
] | permissive | seoss/scs_mfr | 0e85146c57dfefd605967e7dd54c666bfefddf74 | 997dd2b57160df30ef8750abed7efa87831e4c66 | refs/heads/master | 2023-01-20T23:58:16.547082 | 2020-11-27T09:40:20 | 2020-11-27T09:40:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,256 | py | #!/usr/bin/env python3
"""
Created on 13 Jul 2016
@author: Bruno Beloff ([email protected])
DESCRIPTION
The opc_conf utility is used to specify whether an Alphasense optical particle counter (OPC) is present and if so,
which model is attached. An option is also available to override the host's default SPI bus and SPI chip select
lines for the OPC.
The specification also includes the number of seconds between readings by the OPC monitor sub-process. The maximum
time between readings is 10 seconds, the minimum five. A 10 second period provides the highest precision, but sampling
at this rate may be subject to clipping in extremely polluted environments.
The --restart-on-zeroes flag can be used to test the OPC in some situations, by overriding the default behaviour,
which is to restart the OPC if repeated zero readings are presented.
Flags are included to add or remove data interpretation exegetes, together with the source of T / rH readings.
Use of these is under development.
Sampling is performed by the scs_dev/particulates_sampler utility. If an opc_conf.json document is not present, the
scs_dev/particulates_sampler utility terminates.
Note that the scs_dev/particulates_sampler process must be restarted for changes to take effect.
The Alphasense OPC-N2, OPC-N3, OPC-R1, and Sensirion SPS30 models are supported.
Alternate exegetes (data interpretation models) can be added or removed - available interpretations can be listed with
the --help flag.
SYNOPSIS
opc_conf.py [-n NAME] [{ [-m MODEL] [-s SAMPLE_PERIOD] [-z { 0 | 1 }] [-p { 0 | 1 }]
[-b BUS] [-a ADDRESS] [-i INFERENCE_UDS] [-e EXEGETE] [-r EXEGETE] | -d }] [-v]
EXAMPLES
./opc_conf.py -m N2 -b 0 -a 1 -e ISLin/Urban/N2/v1
./opc_conf.py -m S30 -b 1
DOCUMENT EXAMPLE
{"model": "N3", "sample-period": 10, "restart-on-zeroes": true, "power-saving": false,
"inf": "/home/scs/SCS/pipes/lambda-model-pmx-s1.uds", "exg": []}
FILES
~/SCS/conf/opc_conf.json
SEE ALSO
scs_dev/particulates_sampler
scs_mfr/opc_cleaning_interval
REFERENCES
https://github.com/south-coast-science/scs_core/blob/develop/src/scs_core/particulate/exegesis/exegete_catalogue.py
BUGS
The specification allows for a power saving mode - which enables the OPC to shut down between readings - but
this is not currently implemented.
"""
import sys
from scs_core.data.json import JSONify
from scs_dfe.particulate.opc_conf import OPCConf
from scs_host.sys.host import Host
from scs_mfr.cmd.cmd_opc_conf import CmdOPCConf
# --------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
incompatibles = []
# ----------------------------------------------------------------------------------------------------------------
# cmd...
cmd = CmdOPCConf()
if not cmd.is_valid():
cmd.print_help(sys.stderr)
exit(2)
if cmd.verbose:
print("opc_conf: %s" % cmd, file=sys.stderr)
sys.stderr.flush()
# ----------------------------------------------------------------------------------------------------------------
# resources...
# OPCConf...
conf = OPCConf.load(Host, name=cmd.name)
# ----------------------------------------------------------------------------------------------------------------
# run...
if cmd.set():
if conf is None and not cmd.is_complete():
print("opc_conf: No configuration is stored - you must therefore set the required fields.",
file=sys.stderr)
cmd.print_help(sys.stderr)
exit(2)
model = cmd.model if cmd.model else conf.model
sample_period = cmd.sample_period if cmd.sample_period else conf.sample_period
restart_on_zeroes = cmd.restart_on_zeroes if cmd.restart_on_zeroes is not None else conf.restart_on_zeroes
power_saving = cmd.power_saving if cmd.power_saving is not None else conf.power_saving
if conf is None:
conf = OPCConf(None, 10, True, False, None, None, None, []) # permit None for bus and address settings
bus = conf.bus if cmd.bus is None else cmd.bus
address = conf.address if cmd.address is None else cmd.address
inference = conf.inference if cmd.inference is None else cmd.inference
conf = OPCConf(model, sample_period, restart_on_zeroes, power_saving,
bus, address, inference, conf.exegete_names)
if cmd.use_exegete:
conf.add_exegete(cmd.use_exegete)
if cmd.remove_exegete:
conf.discard_exegete(cmd.remove_exegete)
# compatibility check...
try:
incompatibles = conf.incompatible_exegetes()
except KeyError as ex:
print("opc_conf: The following exegete is not valid: %s." % ex, file=sys.stderr)
exit(1)
if incompatibles:
print("opc_conf: The following exegetes are not compatible with %s: %s." %
(conf.model, ', '.join(incompatibles)),
file=sys.stderr)
exit(1)
conf.save(Host)
elif cmd.delete:
conf.delete(Host, name=cmd.name)
conf = None
if conf:
print(JSONify.dumps(conf))
| [
"[email protected]"
] | |
6a1dc5ed224a04492551f23e2dc5763ece6cd56d | 4bb9c661c33a9f057e05bf2a17e30c2eb633b0ee | /python_exec/Test/TextFileOrder.py | da8fea76d6b7262061719e15673a5dbfc39186ec | [] | no_license | Czy2GitHub/Python | 3fa8089f10eb9fcfd5975d7ddcaa9dccbe742ce2 | deb767ebf685f8c49446c49db92ffd808a995913 | refs/heads/master | 2022-07-14T05:40:54.061944 | 2019-12-27T12:42:36 | 2019-12-27T12:42:36 | 225,591,496 | 0 | 0 | null | 2022-06-21T23:41:29 | 2019-12-03T10:22:12 | Python | UTF-8 | Python | false | false | 1,039 | py | # coding:utf-8
# 测试文件的读写,与创建
# open()方法打开文件
# 使用with expression as file 的格式
# open()的参数:第一个为文件名 第二个为权限
# w:只写 w+:清空文件,只写 a:追加模式打开文件 a+:读写权限,若文件不存在,则创建 r:只读
with open("TextFile.txt","r") as file:
# file.write(" 我曾难自拔于世界之大,也沉浸于其中梦话 ") # 写入内容,必须为w,w+,a,a+下有效
massage = file.readlines() # 读一行,仅r,r+下有效
for value in massage:
print(value)
# .read()方法
# 读取指定字符个数,不给参数默认全部字符
with open("TextFile.txt", "r") as file:
# massage = file.read()
massage1 = file.read(5)
print(massage, " ", massage1)
# .seek()方法
# 改变文件指针的位置
with open("TextFile.txt", "r") as file:
file.seek(22) # 移动的是字节位 一个汉字两个字节 UNICODE
print(file.read(8)) # 读取的是字符
| [
"[email protected]"
] | |
1d4e4568720e0575719b81a9775a7b63dfcd1c08 | 88be5f5b633132a3b2b691541aa742c6f70bc366 | /dancer/dancer/settings.py | 55861e8ea0a4d151163afe086599ba115df0d95f | [] | no_license | lzj3278/360-OPS | 8078748fc51a282643c7c56d79d1d79ad58d0ec5 | c50d53b208aef12640fcd6ea18baeda10fe04d23 | refs/heads/master | 2020-06-11T09:32:37.890428 | 2016-12-08T01:40:52 | 2016-12-08T01:40:52 | 75,691,758 | 0 | 0 | null | 2016-12-06T03:40:42 | 2016-12-06T03:40:42 | null | UTF-8 | Python | false | false | 3,274 | py | """
Django settings for dancer project.
Generated by 'django-admin startproject' using Django 1.9.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '**n5r07ou!12r_uhwgy!ppbovn2%ao9y97e__h7v30a@rlg%m4'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'demo',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'dancer.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'demo/templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'dancer.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATICFILES = os.path.join(BASE_DIR, 'demo/static')
| [
"[email protected]"
] | |
8b0e177182553e777299a443085a2ae29cf7eaba | d3eb3bfbd07b282e23b414a88c50cb2a48223ac4 | /final/num2.b.py | 8719694d08c5f6c7b537db8416177d30e08f540d | [] | no_license | JosephBingham/math3732017 | 9f423b30c4abf3e6d7c5b0b0be75ecb30090a80d | 4885265054648df0f648959a873476c160e9a46d | refs/heads/master | 2021-05-08T00:17:19.691969 | 2017-12-11T22:13:32 | 2017-12-11T22:13:32 | 107,632,143 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,302 | py | #!/usr/bin/python
from math import sin
import numpy as np
import matplotlib.pyplot as plt
#solve -u''(x) = f(x), [xmin, xmax]
def gauss(A):
n = len(A)
for i in range(0, n):
maxEl = abs(A[i][i])
maxRow = i
for k in range(i+1, n):
if abs(A[k][i]) > maxEl:
maxEl = abs(A[k][i])
maxRow = k
for k in range(i, n+1):
tmp = A[maxRow][k]
A[maxRow][k] = A[i][k]
A[i][k] = tmp
for k in range(i+1, n):
c = -A[k][i]/A[i][i]
for j in range(i, n+1):
if i == j:
A[k][j] = 0
else:
A[k][j] += c * A[i][j]
x = [0 for i in range(n)]
for i in range(n-1, -1, -1):
x[i] = A[i][n]/A[i][i]
for k in range(i-1, -1, -1):
A[k][n] -= A[k][i] * x[i]
return x
n = 40
xmin = 0
xmax = 1
alpha = 0
beta = sin(2)
x = np.linspace(float(xmin), float(xmax), n)
h = (xmax - xmin)/2.
u = [0] * (n+1)
u[0] = alpha
u[-1] = beta
f = lambda x: 4*sin(2*x)
A = 2*np.eye(n) - np.eye(n, k = 1) - np.eye(n, k = -1)
rhs = map(f, x)
rhs = map(lambda x: .5*x, rhs)
rhs[0] += alpha
rhs[-1] += beta
An = np.c_[A,rhs]
uu = gauss(An)
plt.plot(x, uu, 'ro')
plt.savefig('num2.b.40.png')
| [
"[email protected]"
] | |
463c19066420695e6962096ac166f6fc925d6922 | 240aba0d30a93b31e12426b95deea240c4e6f883 | /tree_model/scr.py | 454c31e354c218fc6f24d652c38f4db0645ae643 | [
"Apache-2.0"
] | permissive | EPgg92/solat | d001dd45ada3f859fba884dd77b0612e5f4bd356 | 18eb132fbfef39c67b3a41b5014e488da8d90307 | refs/heads/master | 2021-04-27T17:09:07.547378 | 2018-04-10T18:27:03 | 2018-04-10T18:27:03 | 122,315,744 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 326 | py | import os
for x in range(1,10):
print('clean tmp')
os.system('bash cleantmp.sh')
print(x)
print('python generateFeatures.py {}'.format(x))
os.system('python generateFeatures.py {}'.format(x))
print('python xgb_train_cvBodyId.py {}'.format(x))
os.system('python xgb_train_cvBodyId.py {}'.format(x))
| [
"[email protected]"
] | |
3a5e3a9076882a87027c00689734bedef960925d | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03425/s478084192.py | 7e20b760b92578dea372ba9ffdd4d4f5431cd5bc | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 397 | py | from itertools import combinations
N = int(input())
A = [0 for _ in range(5)]
for _ in range(N):
a = input().strip()
if a[0]=="M":
A[0] += 1
elif a[0]=="A":
A[1] += 1
elif a[0]=="R":
A[2] += 1
elif a[0]=="C":
A[3] += 1
elif a[0]=="H":
A[4] += 1
cnt = 0
for x in combinations(range(5),3):
cnt += A[x[0]]*A[x[1]]*A[x[2]]
print(cnt) | [
"[email protected]"
] | |
70b83421da906c6fb4f01ff32342f572ebfc40c2 | 2f0796e2aba7e30cbd8e0cd7da00731ec57fd597 | /Lab2/insertTableDHT_1.py | 3993b45972b6364290681d1393dcb45f3d7d3f74 | [
"MIT"
] | permissive | MStevenTowns/Advanced-Computer-Networks | 34d2b146fce879a2fe1599c658d3f38d70245155 | a7987cdea403a0892831b91d5695c0e65a475657 | refs/heads/master | 2020-04-13T16:24:10.208600 | 2018-12-27T18:25:58 | 2018-12-27T18:25:58 | 163,315,708 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 308 | py |
import sqlite3 as lite
import sys
con=lite.connect('SensorsData.db')
with con:
cur=con.cursor()
cur.execute("INSERT INTO DHT_data VALUES(datetime('now'), 20.5,30)")
cur.execute("INSERT INTO DHT_data VALUES(datetime('now'), 28.5,40)")
cur.execute("INSERT INTO DHT_data VALUES(datetime('now'), 30.5,50)")
| [
"[email protected]"
] | |
163437f7bc5dcbf9e5d279128031d1d5a1aa8189 | e1c15a8e8ae78184b09894024db98d946ab20de4 | /BuildTools/Python/generate.py | dcee73ab95d1034445bab90afbd198657528e7ac | [] | no_license | Sunday111/D3D_Samples | d33721a36d2557a2aa4807305253be36afa6b06e | 76851283b9f7950d0080deabae829c1751f9a179 | refs/heads/master | 2021-06-04T22:03:36.288475 | 2020-01-12T01:00:27 | 2020-01-12T01:00:27 | 118,942,545 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 66 | py | from build_tools import *
generate_project(default_generator, [])
| [
"[email protected]"
] | |
9c386ae35e39d738c13f3b989b48ca34d0c6f9a0 | eef479eafa0645146246d10f56ed92470ca65ab2 | /listtest2.py | ce8c6ef8366a94545c85fa14a23fede236b159e1 | [] | no_license | swaminatarajan/sn | 6b15d5eb1619251c863f395ce4acecd19d62f790 | 0816c1868c4ff838ab9be817d59b055d0f149558 | refs/heads/master | 2020-08-18T09:31:03.007094 | 2019-10-17T11:51:22 | 2019-10-17T11:51:22 | 215,774,795 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 144 | py | # -*- coding: utf-8 -*-
astring = input("Enter the String:")
alist = astring.split(",")
print("alist:", alist)
print("alist:", len(alist))
| [
"[email protected]"
] | |
2d17b34a34f912e0caa9aefde207cbd96a75f9f7 | 78f1cc341cd6313d02b34d910eec4e9b2745506a | /p01_team_project/p02_team_source/base_ball_1.0.0.py | 80e9963266f04648b0b5d9a5c83b40d1694b41e9 | [] | no_license | python-cookbook/PythonStudy | a4855621d52eae77537bffb01aae7834a0656392 | cdca17e9734479c760bef188dcb0e183edf8564a | refs/heads/master | 2021-01-20T17:23:35.823875 | 2017-07-30T10:56:13 | 2017-07-30T10:56:13 | 90,873,920 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 50,890 | py | '''
확실히 게임 엔진에 loop문이 들어가면 안되는 것 같음.
그래서 해결책이 멀티스레드를 이용해서 돌려라,
콜백함수를 써라 이거인것 같은데...
어떻게 사용하는지 모름
http://stupidpythonideas.blogspot.kr/2013/10/why-your-gui-app-freezes.html
'''
from tkinter import Frame, Canvas, Label, Button, LEFT, ALL, Tk, TOP
import random,re,time,csv
import ctypes
############# 기록을 저장할 경로 설정 ################### #지은 #태흠 ~
##### 저장할 경로는 항상 새로운 경로일 것! ##########
### 실시간 선수 기록 저장 ####
save_player_path = "c:\\data\\baseball_save_player2.csv"
### 최종 경기 기록 저장 ###
save_result_path = "c:\\data\\baseball_save_result.csv"
############ 파일을 load할 경로 설정 ###################
##### load할 파일이 없으면 None 으로 설정! ###########
### 게임을 이어서 할 경우 실시간 경기 기록 불러오기 ###
load_player_path = "c:\\data\\baseball_save_player1.csv"
### 기록 분석을 위한 최종 경기 기록 데이터가 필요할 경우 ###
load_result_path = None # ~ 태흠
########################################################
#판정관련
#0 : 헛스윙
#0 : 파울
#1 : 단타
#2 : 2루타
#3 : 3루타
#4 : 홈런
###################################################################################################
## 기록 관련 클래스
###################################################################################################
class Record:
def __init__(self):
self.__hit = 0 # 안타 수
self.__bob = 0 # 볼넷 수 융
self.__homerun = 0 # 홈런 수
self.__atbat = 0 # 타수
self.__avg = 0.0 # 타율
@property
def hit(self):
return self.__hit
@hit.setter
def hit(self, hit):
self.__hit = hit
@property
def bob(self):
return self.__bob
@bob.setter
def bob(self,bob):
self.__bob = bob
@property
def homerun(self):
return self.__homerun
@homerun.setter
def homerun(self, homerun):
self.__homerun = homerun
@property
def atbat(self):
return self.__atbat
@atbat.setter
def atbat(self, atbat):
self.__atbat = atbat
@property
def avg(self):
return self.__avg
@avg.setter
def avg(self, avg):
self.__avg = avg
# 타자 기록 관련 메서드
def batter_record(self, hit, bob, homerun):
self.hit += hit
self.bob += bob
self.homerun += homerun
self.atbat += 1
self.avg = self.hit / self.atbat
###################################################################################################
## 선수 관련 클래스
###################################################################################################
class Player:
def __init__(self, team_name, number, name):
self.__team_name = team_name # 팀 이름
self.__number = number # 타순
self.__name = name # 이름
self.__record = Record() # 기록
@property
def team_name(self):
return self.__team_name
@property
def number(self):
return self.__number
@property
def name(self):
return self.__name
@property
def record(self):
return self.__record
@property
def player_info(self):
return self.__team_name + ', ' + str(self.__number) + ', ' + self.__name
# 선수 타율 관련 메서드
def hit_and_run(self, hit, bob, homerun):
self.__record.batter_record(hit, bob,homerun)
###################################################################################################
## 팀 관련 클래스
###################################################################################################
class Team:
def __init__(self, team_name, players):
self.__team_name = team_name # 팀 이름
self.__player_list = self.init_player(players) # 해당 팀 소속 선수들 정보
@property
def team_name(self):
return self.__team_name
@property
def player_list(self):
return self.__player_list
# 선수단 초기화
def init_player(self, players):
temp = []
for player in players:
number, name = list(player.items())[0]
temp.append(Player(self.__team_name, number, name))
return temp
def show_players(self):
for player in self.__player_list:
print(player.player_info)
###################################################################################################
## 저장 및 불러오기 관련 클래스 -원주/지은
#####################################################################################################
"""
d:/data/ 폴더 만들어야 합니다.
"""
'''
제껀 없어도 돼용 - 지은
'''
class Saveandload:
DATA_SET = 0
FILE_PATH = 'c:/data/'
CHECK = 0
LOAD_YN = False
print('LOAD_YN = ', LOAD_YN)
@staticmethod
def make_data_set(cnt, game_info, adv, score, batter_number):
'''
:param player_info: 선수정보
:param cnt: 스트라이크, 아웃, 볼 개수
:param game_info: 등등..
:param adv:
:return:
여기서 실시간 데이터를 수집하는 곳이니까,
선수 누적하는 거 여기에서 처리할 수 있도록 제껄 빼서 넣으시거나
제 메소드에 넣으시거나 하면 될 것 같아요.
'''
DATA_SET = []
cnt = [str(data) for data in cnt] # S B O
game_info = [str(data) for data in game_info] # 이닝, 체인지
adv = [str(data) for data in adv] # 어드밴스
score = [str(data) for data in score] # 점수
batter_number = [str(data) for data in batter_number] # 배터 순서
DATA_SET.append([game_info, adv, cnt, score, batter_number])
Saveandload.save(DATA_SET)
# 여기에서 저장한 이유는, 따로 세이브 버튼 활성화 되는게 아니라서, 계속 데이터를 쓰고 지우고 때문에 하고 있어요.
@staticmethod
def save(DATA_SET):
with open(Saveandload.FILE_PATH + "test.csv", "wt", encoding="utf-8") as f:
print('여기', DATA_SET)
for row in DATA_SET:
for idx, value in enumerate(row, 1):
if idx == 1:
print(value)
f.write(value[0] + '\n')
f.write(value[1] + '\n')
if idx == 2:
print(value)
f.write(value[0] + "," + value[1] + "," + value[2] + '\n')
if idx == 3:
print(value)
f.write(value[0] + "," + value[1] + "," + value[2] + '\n')
if idx == 4:
print(value)
f.write(value[0] + "," + value[1] + '\n')
if idx == 5:
print(value)
f.write(value[0] + "," + value[1] + '\n')
@staticmethod
def load():
# Saveandload.make_data_set()
INNING = 0
adv = 0
CHANGE = 0
STRIKE_CNT = 0 # 스트라이크 개수
BALL_CNT = 0 # 볼 개수 융
OUT_CNT = 0 # 아웃 개수
SCORE = 0 # [home, away]
BATTER_NUMBER = 0
import csv
f = open(Saveandload.FILE_PATH + 'test.csv') # 파일명이 바뀌어야 할 것.
reader = csv.reader(f, delimiter=',')
for idx, line in enumerate(reader, 1):
if idx == 1:
INNING = int(line[0])
elif idx == 2:
CHANGE = int(line[0])
elif idx == 3:
adv = [int(i) for i in line]
elif idx == 4:
STRIKE_CNT = int(line[0])
BALL_CNT = int(line[1])
OUT_CNT = int(line[2])
elif idx == 5:
SCORE = [int(i) for i in line]
else:
BATTER_NUMBER = [int(i) for i in line]
return [INNING, CHANGE, adv, STRIKE_CNT, BALL_CNT, OUT_CNT, SCORE, BATTER_NUMBER]
@staticmethod
def load_to_start_game():
if Game.LOAD_CHK == True and Saveandload.LOAD_YN == True:
temp = Saveandload.load() # list
# INNING = 0
Game.INNING = temp[0]
# CHANGE = 0 # 0 : hometeam, 1 : awayteam
Game.CHANGE = temp[1]
# ADVANCE = [0, 0, 0] # 진루 상황
Game.ADVANCE = temp[2]
Game.STRIKE_CNT = temp[3]
Game.BALL_CNT = temp[4]
Game.OUT_CNT = temp[5]
# SCORE = [0, 0] # [home, away]
Game.SCORE = temp[6]
# BATTER_NUMBER = [1, 1] # [home, away] 타자 순번
Game.BATTER_NUMBER = temp[7]
@staticmethod
def load_chk():
if Saveandload.LOAD_YN == False:
Saveandload.LOAD_YN = True
print(Saveandload.LOAD_YN)
else:
pass
@staticmethod
def save_record(save_path, *save_col): # 지은
csvFile = open(save_path, 'a')
try:
writer = csv.writer(csvFile)
writer.writerow(save_col)
finally:
csvFile.close()
@staticmethod
def load_record(hometeam, home, away, load_path): # 지은
if Saveandload.LOAD_YN == True:
try:
if load_path == None:
print("불러올 파일이 없습니다. 새 게임을 시작합니다.")
return Main.start_game
else:
# load한 csv파일을 records 리스트에 담기
records = [records for records in csv.reader(open(load_path, 'r')) if len(records) != 0]
print(records)
# records 리스트를 선수별로 unpacking
for record in records:
curr_team = home if record[0] == hometeam else away
player_list = curr_team.player_list
player = player_list[int(record[1]) - 1] # 선수를 순서대로 player에 할당
_, _, _, atbat, hit, bob, homerun, avg = record
player.record.atbat = int(atbat)
player.record.hit = int(hit)
player.record.bob = int(bob)
player.record.homerun = int(homerun)
player.record.avg = float(avg)
return Main.Loadgame
except FileNotFoundError:
print('파일 위치를 잘못 입력하셨습니다.') # ~ 태흠
###################################################################################################
## 게임 관련 클래스
###################################################################################################
class Game(object):
TEAM_LIST = {
'한화': ({1: '정근우'}, {2: '이용규'}, {3: '송광민'}, {4: '최진행'}, {5: '하주석'}, {6: '장민석'}, {7: '로사리오'}, {8: '이양기'}, {9: '최재훈'}),
'롯데': ({1: '나경민'}, {2: '손아섭'}, {3: '최준석'}, {4: '이대호'}, {5: '강민호'}, {6: '김문호'}, {7: '정훈'}, {8: '번즈'}, {9: '신본기'}),
'삼성': ({1: '박해민'}, {2: '강한울'}, {3: '구자욱'}, {4: '이승엽'}, {5: '이원석'}, {6: '조동찬'}, {7: '김헌곤'}, {8: '이지영'}, {9: '김정혁'}),
'KIA': ({1: '버나디나'}, {2: '이명기'}, {3: '나지완'}, {4: '최형우'}, {5: '이범호'}, {6: '안치홍'}, {7: '서동욱'}, {8: '김민식'}, {9: '김선빈'}),
'SK': ({1: '노수광'}, {2: '정진기'}, {3: '최정'}, {4: '김동엽'}, {5: '한동민'}, {6: '이재원'}, {7: '박정권'}, {8: '김성현'}, {9: '박승욱'}),
'LG': ({1: '이형종'}, {2: '김용의'}, {3: '박용택'}, {4: '히메네스'}, {5: '오지환'}, {6: '양석환'}, {7: '임훈'}, {8: '정상호'}, {9: '손주인'}),
'두산': ({1: '허경민'}, {2: '최주환'}, {3: '민병헌'}, {4: '김재환'}, {5: '에반스'}, {6: '양의지'}, {7: '김재호'}, {8: '신성현'}, {9: '정진호'}),
'넥센': ({1: '이정후'}, {2: '김하성'}, {3: '서건창'}, {4: '윤석민'}, {5: '허정협'}, {6: '채태인'}, {7: '김민성'}, {8: '박정음'}, {9: '주효상'}),
'KT': ({1: '심우준'}, {2: '정현'}, {3: '박경수'}, {4: '유한준'}, {5: '장성우'}, {6: '윤요섭'}, {7: '김사연'}, {8: '오태곤'}, {9: '김진곤'}),
'NC': ({1: '김성욱'}, {2: '모창민'}, {3: '나성범'}, {4: '스크럭스'}, {5: '권희동'}, {6: '박석민'}, {7: '지석훈'}, {8: '김태군'}, {9: '이상호'})
}
INNING = 1 # 1 이닝부터 시작
CHANGE = 0 # 0 : hometeam, 1 : awayteam
STRIKE_CNT = 0 # 스트라이크 개수
BALL_CNT = 0 #볼 개수 융
OUT_CNT = 0 # 아웃 개수
ADVANCE = [0, 0, 0] # 진루 상황
SCORE = [0, 0] # [home, away]
BATTER_NUMBER = [1, 1] # [home, away] 타자 순번
LOAD_CHK = True #태흠
MATRIX = 5
LOCATION = {0: [0, 0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4],
5: [1, 0], 6: [1, 1], 7: [1, 2], 8: [1, 3], 9: [1, 4],
10: [2, 0], 11: [2, 1], 12: [2, 2], 13: [2, 3], 14: [2, 4],
15: [3, 0], 16: [3, 1], 17: [3, 2], 18: [3, 3], 19: [3, 4],
20: [4, 0], 21: [4, 1], 22: [4, 2], 23: [4, 3], 24: [4, 4]
} #던지는 위치의 좌표를 리스트로 저장.
ANNOUNCE= ''
def __init__(self, master, game_team_list, root):
print('Home Team : ' + game_team_list[0]+' : ', Game.TEAM_LIST[game_team_list[0]])
print('Away Team : ' + game_team_list[1]+' : ', Game.TEAM_LIST[game_team_list[1]])
self.__hometeam = Team(game_team_list[0], Game.TEAM_LIST[game_team_list[0]])
self.__awayteam = Team(game_team_list[1], Game.TEAM_LIST[game_team_list[1]])
self.game_team_list = game_team_list #태흠
self.root = root
@property
def hometeam(self):
return self.__hometeam
@property
def awayteam(self):
return self.__awayteam
# 게임 수행 메서드
def start_game(self):
pass
# 팀별 선수 기록 출력
def show_record(self):
print('===================================================================================================================')
print('== {} | {} =='.format(self.hometeam.team_name.center(52, ' ') if re.search('[a-zA-Z]+', self.hometeam.team_name) is not None else self.hometeam.team_name.center(50, ' '),
self.awayteam.team_name.center(52, ' ') if re.search('[a-zA-Z]+', self.awayteam.team_name) is not None else self.awayteam.team_name.center(50, ' ')))
print('== {} | {} =='.format(('('+str(Game.SCORE[0])+')').center(52, ' '), ('('+str(Game.SCORE[1])+')').center(52, ' ')))
print('===================================================================================================================')
print('== {} | {} | {} | {} | {} | {} '.format('이름'.center(8, ' '), '타율'.center(5, ' '), '타석'.center(4, ' '), '안타'.center(3, ' '), '홈런'.center(3, ' '), '볼넷'.center(3, ' ')), end='')
print('| {} | {} | {} | {} | {} | {} =='.format('이름'.center(8, ' '), '타율'.center(5, ' '), '타석'.center(4, ' '), '안타'.center(3, ' '), '홈런'.center(3, ' '), '볼넷'.center(3, ' ')))
print('===================================================================================================================')
hometeam_players = self.hometeam.player_list
awayteam_players = self.awayteam.player_list
for i in range(9):
hp = hometeam_players[i]
hp_rec = hp.record
ap = awayteam_players[i]
ap_rec = ap.record
save_hp=[self.hometeam.team_name, hp.name, hp_rec.avg, hp_rec.atbat, hp_rec.hit, hp_rec.homerun, hp_rec.bob ] # 지은
save_ap=[self.awayteam.team_name, ap.name, ap_rec.avg, ap_rec.atbat, ap_rec.hit, ap_rec.homerun, ap_rec.bob ] # 지은
self.save_record("c:\\data\\baseball_save_result2.csv", *save_hp) # 지은
self.save_record("c:\\data\\baseball_save_result2.csv", *save_ap) # 지은
print('== {} | {} | {} | {} | {} | {} |'.format(hp.name.center(6+(4-len(hp.name)), ' '), str(hp_rec.avg).center(7, ' '),
str(hp_rec.atbat).center(6, ' '), str(hp_rec.hit).center(5, ' '), str(hp_rec.homerun).center(5, ' '), str(hp_rec.bob).center(5,' ')), end='')
print(' {} | {} | {} | {} | {} | {} =='.format(ap.name.center(6+(4-len(ap.name)), ' '), str(ap_rec.avg).center(7, ' '),
str(ap_rec.atbat).center(6, ' '), str(ap_rec.hit).center(5, ' '), str(ap_rec.homerun).center(5, ' ') , str(ap_rec.bob).center(5, ' ')))
print('===================================================================================================================')
# 공격 수행 메서드
def attack(self): #태흠
pass
# 진루 및 득점 설정하는 메서드
def advance_setting(self, hit_cnt, base_num, bob=False, double_play=False, sb=False):
if hit_cnt == 4: # 홈런인 경우
Game.SCORE[Game.CHANGE] += (Game.ADVANCE.count(1)+1)
Game.ADVANCE = [0, 0, 0]
elif hit_cnt == -1: # 태흠
pass
elif double_play is True: # 태흠
for i in range(len(Game.ADVANCE), 0, -1):
if Game.ADVANCE[i-1] == 1:
Game.ADVANCE[i-1] = 0
break
# 여기서 병살주자 비워주고 시작
for i in range(len(Game.ADVANCE), 0, -1):
if Game.ADVANCE[i-1] == 1:
if (i + hit_cnt) > 3: # 기존에 출루한 선수들 중 득점 가능한 선수들에 대한 진루 설정 예, 1루+3루타 / 2루+2루타 / 3루+1루타
Game.SCORE[Game.CHANGE] += 1 # 득점 해주고
Game.ADVANCE[i - 1] = 0 # 자리 다시 비워주고
else: # 기존 출루한 선수들 중 득점권에 있지 않은 선수들에 대한 진루 설정
Game.ADVANCE[i - 1 + hit_cnt] = 1
Game.ADVANCE[i - 1] = 0
else:
if bob==False: #볼넷이 아닐때
if sb == False: # 볼넷도 아니고 도루도 아니고, hit_cnt만 필요함, 이 줄만 태흠
for i in range(len(Game.ADVANCE), 0, -1):
if Game.ADVANCE[i-1] == 1:
if (i + hit_cnt) > 3: # 기존에 출루한 선수들 중 득점 가능한 선수들에 대한 진루 설정
Game.SCORE[Game.CHANGE] += 1
Game.ADVANCE[i-1] = 0
else: # 기존 출루한 선수들 중 득점권에 있지 않은 선수들에 대한 진루 설정
Game.ADVANCE[i-1 + hit_cnt] = 1
Game.ADVANCE[i-1] = 0
Game.ADVANCE[hit_cnt-1] = 1 # 타석에 있던 선수에 대한 진루 설정
elif sb == True: # 도루인 경우!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!, 태흠
if (base_num + hit_cnt) > 3:
Game.SCORE[Game.CHANGE] += 1 # 즉 3루에 서있으면 득점이란 소리, 위하고 코드 깔맞춤
Game.ADVANCE[base_num - 1] = 0
else:
Game.ADVANCE[base_num - 1 + hit_cnt] = 1 # 진루상황 넣어주고
Game.ADVANCE[base_num - 1] = 0 # 서있던 곳 빼주고
elif bob==True: #볼넷일때
if Game.ADVANCE[0]==1: #1루에 주자가 있을때.
if Game.ADVANCE[1]==0 and Game.ADVANCE[2]==1:#1,3루 일때
Game.ADVANCE[1]=1
else: #그 외의 경우
for i in range(len(Game.ADVANCE), 0, -1):
if Game.ADVANCE[i-1] == 1:
if (i + hit_cnt) > 3: # 기존에 출루한 선수들 중 득점 가능한 선수들에 대한 진루 설정
Game.SCORE[Game.CHANGE] += 1
Game.ADVANCE[i-1] = 0
else: # 기존 출루한 선수들 중 득점권에 있지 않은 선수들에 대한 진루 설정
Game.ADVANCE[i-1 + hit_cnt] = 1
Game.ADVANCE[i-1] = 0
Game.ADVANCE[hit_cnt-1] = 1 # 타석에 있던 선수에 대한 진루 설정
else: #1루에 주자가 없을때는 1루에만 주자를 채워 넣는다.
Game.ADVANCE[0] = 1
# 컴퓨터가 생성한 랜덤 수와 플레이어가 입력한 숫자가 얼마나 맞는지 판단
def hit_judgment(self, random_ball, hit_numbers): #(공던질위치, 구질) #융
cnt = 0
Foul = False
Double_Play = False # 태흠
fly_ball = False # 태흠
UPDOWN = abs(Game.LOCATION[random_ball[1]][0] - Game.LOCATION[hit_numbers[1]][0]) #투수와 타자의 선택한 공 위치의 높낮이차이 #융
#UPDOWN = abs(Game.LOCATION[random_ball[1]][0] - Main.Y1) # 투수와 타자의 선택한 공 위치의 높낮이차이 #융
L_OR_R = abs(Game.LOCATION[random_ball[1]][1] - Game.LOCATION[hit_numbers[1]][1]) #투수와 타자의 선택한 공 위치의 좌우차이 #융
#L_OR_R = abs(Game.LOCATION[random_ball[1]][1] - Main.X1) #투수와 타자의 선택한 공 위치의 좌우차이 #융
if random_ball[0] == hit_numbers[0]: #투수가 던진 공의 구질과 타자가 선택한 구질이 같을 때 #융
if random_ball[1] == hit_numbers[1]:#위치가 같으니까 홈런 #융
cnt += 4
elif UPDOWN == 0:#높낮이가 같은 선상일 때 #융
if L_OR_R == 1: #좌우로 1칸 차이 #융
Game.ANNOUNCE = '3루타~'
cnt += 3
if self.doble_play_OUT() is True: # 태흠
Double_Play = True
elif L_OR_R == 2: #좌우로 2칸 차이 #융
Game.ANNOUNCE = '2루타~'
cnt += 2
if self.doble_play_OUT() is True: # 태흠
Double_Play = True
elif L_OR_R >= 3: #좌우로 3칸 차이 #융
Game.ANNOUNCE = '1루타~'
cnt += 1
if self.doble_play_OUT() is True: # 태흠
Double_Play = True
elif UPDOWN == 1:#높낮이 차이가 하나일때 #융
if L_OR_R ==1:
Game.ANNOUNCE = '2루타~'
cnt += 2
if self.doble_play_OUT() is True: # 태흠
Double_Play = True
elif L_OR_R ==2:
Game.ANNOUNCE = '1루타~'
cnt += 1
if self.doble_play_OUT() is True: # 태흠
Double_Play = True
elif L_OR_R >= 3:
Game.ANNOUNCE = '파울'
cnt += 0
Foul = True
elif UPDOWN >= 2:#높낮이가 두개이상 차이날때 #융
Game.ANNOUNCE = '헛스윙~!'
cnt += 0
else: #투수가 던진 공의 구질과 타자가 선택한 구질이 다를 때 융
if random_ball[0] == hit_numbers[0]:#위치가 같지만 구질은 다르니 3루타 융
cnt += 3
if self.flyball_OUT() is True: # 플라이볼 판정
cnt = -1 # 0이면 스트라이크 판정 나서 -1로 해줌
elif UPDOWN == 0:#높낮이가 같은 선상일 때 #융
if L_OR_R == 1:
Game.ANNOUNCE = '2루타~'
cnt += 2
if self.doble_play_OUT() is True: # 태흠
Double_Play = True
elif L_OR_R == 2:
Game.ANNOUNCE = '1루타~'
cnt += 1
if self.doble_play_OUT() is True: # 태흠
Double_Play = True
elif L_OR_R >= 3:
Game.ANNOUNCE = '파울 ㅜㅜ'
cnt += 0
Foul = True
elif UPDOWN == 1:#높낮이 차이가 하나일때 융
if L_OR_R ==1:
Game.ANNOUNCE = '1루타~'
cnt += 1
if self.doble_play_OUT() is True: # 태흠
Double_Play = True
elif L_OR_R ==2:
Game.ANNOUNCE = '파울ㅠㅠ'
cnt += 0
Foul = True
elif L_OR_R >= 3:
Game.ANNOUNCE = '헛스윙'
cnt += 0
elif UPDOWN >= 2:#높낮이가 두개이상 차이날때 융
Game.ANNOUNCE = '헛스윙~!'
cnt += 0
return cnt, Foul, Double_Play, fly_ball
def doble_play_OUT(self): # 태흠
self.r1 = random.random()
if self.r1 < 0.25:
return True
return False
def flyball_OUT(self): # 태흠
self.r2 = random.random()
if self.r2 < 0.1:
return True
return False
#선수가 입력한 숫자 확인
#융
def hit_number_check(self,hit_numbers): #구질(0~1),위치(0~24)가 들어옴 융
if len(hit_numbers) == 2:
if (hit_numbers[0] >= 0 and hit_numbers[0] <= 1) and (hit_numbers[1] >= 0 and hit_numbers[1] <= 24):
return True
else:
return False
# 선수 선택
def select_player(self, number, player_list):
for player in player_list:
if number == player.number:
return player
# 랜덤으로 숫자 생성(1~20)
def throws_numbers(self):
while True:
random_loc = random.randint(0, 24) # 0 ~ 24 중에 랜덤 수를 출력
random_ball= random.randint(0, 1) #
return random_ball, random_loc
class Main(Game):
HITORNOT = -1
FORB = -1
BALLLOC = -1
COLOR = ["white", "red"]
def __init__(self, master, game_team_list, root):
super().__init__(master,game_team_list,root)
self.root = root
self.game = Game(master, game_team_list, root)
self.frame = Frame(master)
self.frame.pack(fill="both", expand=True)
self.canvas = Canvas(self.frame, width=1000, height=600)
self.canvas.pack(fill="both", expand=True)
# self.label = Label(self.frame, text='야구 게임', height=6, bg='white', fg='black')
# self.label.pack(fill="both", expand=True)
# self.label.place(x=0, y=0, width=1000, height=100, bordermode='outside')
self.frameb = Frame(self.frame)
self.frameb.pack(fill="both", expand=True)
self.newgame = Button(self.frameb, text='New Game', height=4, command=self.start_game, bg='purple', fg='white')
self.newgame.pack(fill="both", expand=True, side=LEFT)
self.loadgame = Button(self.frameb, text='Load Game', height=4, command=self.Loadgame, bg='white', fg='purple')
self.loadgame.pack(fill="both", expand=True, side=LEFT)
self.hit = Button(self.frameb, text='타격', width=5, height=2, command=self.Hitbutton, bg='orange', fg='white')
self.hit.pack(fill="both", expand=True)
self.nohit = Button(self.frameb, text='타격안함', width=5, height=2, command=self.Nohitbutton, bg='orange', fg='white')
self.nohit.pack(fill="both", expand=True, side=TOP)
self.stolen_base = Button(self.frameb, text='도루', width=5, height=2, command=self.Stolenbasebutton, bg='orange', fg='white')
self.stolen_base.pack(fill="both", expand=True, side=TOP)
self.fastball = Button(self.frameb, text='직구', width=5, height=2, command=self.FastBall, bg='purple', fg='white')
self.fastball.pack(fill="both", expand=True, side=TOP)
self.breakingball = Button(self.frameb, text='변화구', width=5, height=2, command=self.BreakingBall, bg='purple', fg='white')
self.breakingball.pack(fill="both", expand=True, side=TOP)
self.canvas.bind("<ButtonPress-1>", self.Throwandhit)
#self.canvas.bind("<Motion>", self.board)
self.ball_color=[]
self.strike_color=[]
self.out_color=[]
self.board()
def attack(self):
curr_team = self.hometeam if Game.CHANGE == 0 else self.awayteam
player_list = curr_team.player_list
MATRIX = 5
PITCH_LOCATION = "| " + "{:^6s} | " * MATRIX #투구 영역 융
PITCH_LOCATION = (PITCH_LOCATION + '\n') * MATRIX #융
PITCH_LOCATION = "---------" * MATRIX + "\n" + PITCH_LOCATION + "---------" * MATRIX #융
hit_numbers = []
if Game.OUT_CNT < 3:
player = self.select_player(Game.BATTER_NUMBER[Game.CHANGE], player_list)
# print('====================================================================================================')
Game.ANNOUNCE += '\n' + '[{}] {}번 타자[{}] 타석에 들어섭니다.\n 현재 타석 : {}번 타자[{}], 타율 : {}, 볼넷 : {}, 홈런 : {}'.format(curr_team.team_name, player.number, player.name,player.number, player.name, player.record.avg, player.record.bob, player.record.homerun)
# print('====================================================================================================\n')
self.board()
random_numbers = self.throws_numbers() # 컴퓨터가 랜덤으로 숫자 2개 생성(구질[0](0~1), 던질위치[1](0~24))
# print('== [전광판] =========================================================================================')
# print('== {} | {} : {}'.format(Game.ADVANCE[1], self.hometeam.team_name, Game.SCORE[0]))
# print('== {} {} | {} : {}'.format(Game.ADVANCE[2], Game.ADVANCE[0], self.awayteam.team_name, Game.SCORE[1]))
# print('== [OUT : {}, BALL : {}, STRIKE : {}]'.format(Game.OUT_CNT, Game.BALL_CNT, Game.STRIKE_CNT))
# print('====================================================================================================')
# print(PITCH_LOCATION.format(*[str(idx) for idx in range(26)])) #투구 영역 5 * 5 출력 융
# print('====================================================================================================')
# print('== 현재 타석 : {}번 타자[{}], 타율 : {}, 볼넷 : {}, 홈런 : {}'.format(player.number, player.name, player.record.avg, player.record.bob, player.record.homerun))
while True:
PLAYER_INFO = [curr_team.team_name, player.number, player.name, player.record.atbat, player.record.hit, player.record.bob,
player.record.homerun, player.record.avg] #태흠
CNT = [Game.STRIKE_CNT, Game.BALL_CNT, Game.OUT_CNT]
GAME_INFO = [Game.INNING, Game.CHANGE]
ADV = Game.ADVANCE
SCORE = Game.SCORE
BATTER_NUMBER = Game.BATTER_NUMBER
Saveandload.make_data_set(CNT, GAME_INFO, ADV, SCORE, BATTER_NUMBER) #태흠
Saveandload.save_record(save_player_path, *PLAYER_INFO) #지은 #태흠
Main.FORB = -1
Main.BALLLOC = -1
Main.HITORNOT = -1
while True:
self.root.update()
if Main.HITORNOT != -1:
# hit_yn = int(input('타격을 하시겠습니까?(타격 : 1 타격안함 : 0)'))
hit_yn = Main.HITORNOT
# print(hit_yn)
break
else:
#print('Hit 여부 선택하세요.')
#print(Main.HITORNOT)
# self.attack()
time.sleep(0.05)
continue
if hit_yn == 1 :#################타격 시############################ #융
while True :
self.root.update()
time.sleep(0.05)
#hit_numbers = [Main.FORB, Main.BALLLOC]
if Main.FORB != -1 and Main.BALLLOC != -1 :
# print('▶ 컴퓨터가 발생 시킨 숫자 : {}\n'.format(random_numbers))
hit_numbers = [Main.FORB, Main.BALLLOC]
# print(hit_numbers)
# if self.hit_number_check(hit_numbers) is False:
# raise Exception()
hit_cnt = self.hit_judgment(random_numbers, hit_numbers) # 안타 판별
print('hit_cnt : ', hit_cnt)
# print(hit_cnt,'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
break
# else :
# print('== ▣ 잘못된 숫자가 입력되었습니다.')
# print(hit_numbers)
# print('====================================================================================================')
# print('▶ 컴퓨터가 발생 시킨 숫자 : {}\n'.format(random_numbers))
# continue
if hit_cnt[0] == 0: # strike !!!
if hit_cnt[1] == False: # 파울이 아닐 때 융
Game.STRIKE_CNT += 1
Game.ANNOUNCE = '스트라이크!!!'
self.board()
if Game.STRIKE_CNT == 3:
Game.ANNOUNCE = '삼진 아웃!!!'
Game.STRIKE_CNT = 0
Game.OUT_CNT += 1
player.hit_and_run(0,0,0)
break
if hit_cnt[1] == True:#파울일 때
if Game.STRIKE_CNT <= 1: #스트라이크 카운트가 1 이하일때는 원래대로 진행 융
Game.STRIKE_CNT += 1
Game.ANNOUNCE = '파울!!!'
self.board()
if Game.STRIKE_CNT == 3:
Game.ANNOUNCE = '삼진 아웃!!!'
self.board()
Game.STRIKE_CNT = 0
Game.OUT_CNT += 1
player.hit_and_run(0, 0, 0)
break
# if Game.STRIKE_CNT == 2: #스트라이크 카운트가 2일때가 문제. 2일때는 파울이어도 스트라이크 카운트가 늘어나선 안됨 융
# Game.ANNOUNCE = '파울이므로 아웃이 아닙니다. 다시 치세요!!!!'
else:
Game.STRIKE_CNT = 0
if hit_cnt[0] != 4:
if hit_cnt[0] == -1: # 플라이볼일때, 태흠
Game.OUT_CNT += 1
Game.ANNOUNCE = '== ▣ 높게 뜬공! 그대로 외야수에 잡혀 아웃됩니다. \n'
player.hit_and_run(1 if hit_cnt[0] > 0 else 0, 0, 1 if hit_cnt[0] == 4 else 0)
self.advance_setting(hit_cnt[0], None, False, False, False)
self.board()
break
elif hit_cnt[2] == True and 1 in Game.ADVANCE: # 출루인줄 알았지만 병살타ㅜ({}루타, 병살타 판단), 태흠
Game.STRIKE_CNT = 0
Game.BALL_CNT = 0
Game.OUT_CNT += 2
player.hit_and_run(1 if hit_cnt[0] > 0 else 0, 0, 1 if hit_cnt[0] == 4 else 0) # 진루타, 볼넷, 홈런
Game.ANNOUNCE = '== ▣ 병살타!!! 아~ 이게 무슨일입니까!! \n'
self.advance_setting(hit_cnt[0], None, False, True, False)
self.board()
break
Game.ANNOUNCE = '{}루타!!!'.format(hit_cnt[0])
player.hit_and_run(1 if hit_cnt[0] > 0 else 0, 0, 1 if hit_cnt[0] == 4 else 0)
self.board()
else: # 홈런일 때
Game.ANNOUNCE = '홈런!!!'
player.hit_and_run(1 if hit_cnt[0] > 0 else 0, 0, 1 if hit_cnt[0] == 4 else 0)
self.board()
self.advance_setting(hit_cnt[0], None, False, False, False)
break
elif hit_yn == 0:######타격안하고 지켜보기 시전########################### 융
#컴퓨터가 던진 공이 볼일때 융
if (random_numbers[1] >= 0 and random_numbers[1] <= 4) or (random_numbers[1] % 5 == 0) or (random_numbers[1] >= 20) or ((random_numbers[1]-4) % 5 ==0) or ((random_numbers[1]-3) % 5 == 0):
Game.BALL_CNT += 1
Game.ANNOUNCE = '볼 !!!!!!!!!!!!!!!!!!!!!!'
self.board()
if Game.BALL_CNT == 4:
Game.ANNOUNCE = '볼넷 1루출루 !!!!!!!!!!!!!!!!!!!!!! 투수가 정신을 못차리네요!'
self.advance_setting(1, None, True, False, False)
self.board()
Game.STRIKE_CNT = 0
Game.BALL_CNT = 0
player.hit_and_run(0,1,0)
break
#컴퓨터가 던진 공이 스트라이크 일 때 융
if random_numbers[1] in [6, 7, 11, 12, 16, 17]:
Game.STRIKE_CNT += 1
Game.ANNOUNCE = '스트라이크!!!!!!!!!!!!!'
self.board()
if Game.STRIKE_CNT == 3:
Game.ANNOUNCE = '방망이도 못 휘두르고 삼진!!!!!!!!!!!!!! 제구력이 훌륭하군요!'
Game.STRIKE_CNT = 0
Game.BALL_CNT = 0
Game.OUT_CNT += 1
player.hit_and_run(0, 0, 0)
self.board()
break
elif hit_yn == 2: # 도루선택, 태흠
if Game.ADVANCE in [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]:
Game.ANNOUNCE = '====================================================================================================\n' \
'★★★★★★★★도루 가능한 주자가 없습니다.★★★★★★★★'
self.board()
self.attack()
else:
rn = random.random()
while 1:
base_num = int(input('도루시킬 주자를 선택하세요[1, 2] : {} / {}'.format(
'1루주자' if Game.ADVANCE[0] == 1 and Game.ADVANCE[1] == 0 else '도루 불가',
'2루주자' if Game.ADVANCE[1] == 1 and Game.ADVANCE[2] == 0 else '도루 불가')))
if Game.ADVANCE[base_num - 1] == 1 and Game.ADVANCE[base_num] == 0:
Game.ANNOUNCE = '도루 가능'
self.board()
break
else:
print('도루불가라고 난독증이냐?')
self.board()
continue
if rn < 0.3: # 도루 성공확률, 태흠
self.advance_setting(1, base_num, False, False, True)
print('도루성공, 게임창을 확인해주세용~')
Game.ANNOUNCE = '도루성공, Stolen Base'
self.board()
break
else: # 도루 실패할 경우, 태흠
Game.ANNOUNCE = '도루실패, Caught Stealing'
Game.OUT_CNT += 1
Game.ADVANCE[base_num - 1] = 0
self.board()
break
else :
continue
PLAYER_INFO = [curr_team.team_name, player.number, player.name, player.record.atbat, player.record.hit, player.record.bob,
player.record.homerun, player.record.avg] #태흠
Saveandload.save_record(save_player_path, *PLAYER_INFO) # 지은 #태흠
if Game.BATTER_NUMBER[Game.CHANGE] == 9:
Game.BATTER_NUMBER[Game.CHANGE] = 1
else:
Game.BATTER_NUMBER[Game.CHANGE] += 1
self.attack()
else:
Game.CHANGE += 1
Game.STRIKE_CNT = 0
Game.BALL_CNT = 0
Game.OUT_CNT = 0
Game.ADVANCE = [0, 0, 0]
self.board()
def start_game(self):
Saveandload.load_to_start_game() #태흠
Saveandload.load_record(self.game_team_list[0], self.hometeam, self.awayteam, load_player_path) #지은 #태흠
Game.LOAD_CHK = False #태흠
if Game.INNING <= 3: #게임을 진행할 이닝을 설정. 현재는 1이닝만 진행하게끔 되어 있음.
# print('====================================================================================================')
Game.ANNOUNCE = '{} 이닝 {} 팀 공격 시작합니다.'.format(Game.INNING, self.game.hometeam.team_name if Game.CHANGE == 0 else self.game.awayteam.team_name)
# print('====================================================================================================\n')
self.board()
self.attack()
if Game.CHANGE == 2: # 이닝 교체
Game.INNING += 1
Game.CHANGE = 0
self.start_game()
# print('============================================================================================================')
Game.ANNOUNCE = '게임 종료!!!'
# print('============================================================================================================\n')
self.game.show_record()
def Loadgame(self):
Saveandload.load_chk()
self.start_game()
def board(self):
hometeam = self.game.hometeam.team_name
awayteam = self.game.awayteam.team_name
homescore = self.game.SCORE[0]
awayscore = self.game.SCORE[1]
announce = self.game.ANNOUNCE
inning = self.game.INNING
change = self.game.CHANGE
attackordefence = [["공격", "수비"] if change == 0 else ["수비", "공격"]]
scoreformat = '{} : {} ({}) | {}이닝 | ({}) {} : {}'
if self.game.BALL_CNT==0:
self.ball_color=["white","white","white"]
elif self.game.BALL_CNT==1:
self.ball_color=["orange","white","white"]
elif self.game.BALL_CNT==2:
self.ball_color=["orange","orange","white"]
elif self.game.BALL_CNT==3:
self.ball_color=["orange","orange","orange"]
if self.game.STRIKE_CNT==0:
self.strike_color=['white','white']
elif self.game.STRIKE_CNT==1:
self.strike_color=["blue","white"]
elif self.game.STRIKE_CNT==2:
self.strike_color=["blue","blue"]
if self.game.OUT_CNT==0:
self.out_color=['white','white']
elif self.game.OUT_CNT==1:
self.out_color=["red","white"]
elif self.game.OUT_CNT==2:
self.out_color=["red","red"]
#Ball 존
self.canvas.create_rectangle(500, 0, 1000, 600, outline="black")
self.canvas.create_rectangle(500, 0, 1000, 100, outline="black")
self.canvas.create_rectangle(600, 600, 700, 0, outline="black")
self.canvas.create_rectangle(500, 100, 1000, 200, outline="black")
self.canvas.create_rectangle(500, 100, 1000, 200, outline="black")
self.canvas.create_rectangle(600, 300, 900, 500, fill="yellow")
self.canvas.create_rectangle(700, 600, 800, 0 ,outline="black")
self.canvas.create_rectangle(500, 200, 1000, 300, outline="black")
self.canvas.create_rectangle(800, 600, 900, 0, outline="black")
self.canvas.create_rectangle(500, 300, 1000, 400, outline="black")
self.canvas.create_rectangle(900, 600, 1000, 0, outline="black")
self.canvas.create_rectangle(500, 400, 1000, 500, outline="black")
self.canvas.create_rectangle(500, 600, 1000, 600, outline="black")
self.canvas.create_rectangle(0, 100, 480, 600, fill="green")
self.canvas.create_rectangle(220, 300, 260, 340, fill="white")
#진루 선
self.canvas.create_line(240, 135, 35, 330, width=4, fill="white")
self.canvas.create_line(240, 135, 445, 330, width=4, fill="white")
self.canvas.create_line(40, 330, 240, 515, width=4, fill="white")
self.canvas.create_line(445, 330, 240, 515, width=4, fill="white")
self.canvas.create_oval(225, 120, 255, 150, fill=Main.COLOR[self.game.ADVANCE[1]]) # 2루
self.canvas.create_oval(20, 315, 50, 345, fill=Main.COLOR[self.game.ADVANCE[2]]) # 3루
self.canvas.create_oval(430, 315, 460, 345, fill=Main.COLOR[self.game.ADVANCE[0]]) # 1루
self.canvas.create_oval(225, 500, 255, 530, fill="white")
self.canvas.create_text(350, 490, font=("Courier", 12), text="B")
self.canvas.create_oval(370, 480, 390, 500, fill=self.ball_color[0])#볼
self.canvas.create_oval(405, 480, 425, 500, fill=self.ball_color[1])#볼
self.canvas.create_oval(440, 480, 460, 500, fill=self.ball_color[2])#볼
self.canvas.create_text(350, 525, font=("Courier", 12), text="S")
self.canvas.create_oval(370, 515, 390, 535, fill=self.strike_color[0])#스트라이크
self.canvas.create_oval(405, 515, 425, 535, fill=self.strike_color[1]) # 스트라이크
self.canvas.create_text(350, 560, font=("Courier", 12), text="O")
self.canvas.create_oval(370, 550, 390, 570, fill=self.out_color[0]) # 아웃
self.canvas.create_oval(405, 550, 425, 570, fill=self.out_color[1]) # 아웃
self.label = Label(self.frame, text=scoreformat.format(hometeam, homescore, attackordefence[0][0], inning, attackordefence[0][1], awayscore, awayteam), height=6, bg='white', fg='black')
self.label.config(font=("Courier", 20))
self.label.pack(fill="both", expand=True)
self.label.place(x=0, y=0, width=1000, height=38, bordermode='outside')
self.label = Label(self.frame, text=announce, height=6, bg='white', fg='black')
self.label.config(font=("Courier", 10))
self.label.pack(fill="both", expand=True)
self.label.place(x=0, y=30, width=1000, height=70, bordermode='outside')
def Throwandhit(self,event):
loclist = [[5 * i + j for j in range(5)] for i in range(5)]
for k in range(500, 1000, 100):
for j in range(100, 600, 100):
if event.x in range(k, k + 100) and event.y in range(j, j + 100):
X1 = int((k - 500) / 100)
Y1 = int((j - 100) / 100)
# print('마우스 위치 좌표', X1, Y1)
# print('리턴 좌표', loclist[Y1][X1])
Main.BALLLOC = loclist[Y1][X1]
self.board()
def Hitbutton(self):
# print('hit')
Main.HITORNOT = 1
self.board()
def Nohitbutton(self):
print('no hit')
Main.HITORNOT = 0
self.board()
def Stolenbasebutton(self):
print('stolen base')
Main.HITORNOT = 2
print(Main.HITORNOT)
self.board()
def FastBall(self):
# print('Fastball')
Main.FORB = 1
self.board()
def BreakingBall(self):
# print('Brakingball')
Main.FORB = 0
self.board()
if __name__ == '__main__':
while True:
try:
game_team_list = []
print('====================================================================================================')
print('한화 / ', '롯데 / ', '삼성 / ', 'KIA / ', 'SK / ', 'LG / ', '두산 / ', '넥센 / ', 'KT / ', 'NC / ')
game_team_list = input('=> 게임을 진행할 두 팀을 입력하세요 : ').split(' ')
print('====================================================================================================')
if (game_team_list[0] in Game.TEAM_LIST) and (game_team_list[1] in Game.TEAM_LIST):
print('게임이 시작되었습니다. 작업표시줄에 실행된 게임콘솔창을 확인해주세요~\n')
break
else:
ctypes.windll.user32.MessageBoxW(None, '팀명을 잘못 입력하셨습니다.', "Error", 0)
except:
ctypes.windll.user32.MessageBoxW(None, '팀명을 잘못 입력하셨습니다.', "Error", 0)
root = Tk()
app = Main(root, game_team_list, root)
root.mainloop()
| [
"[email protected]"
] | |
0a472f6e96a00dfe4c19d566f86199c70912b332 | 195fdf812bd2bc6170bbe46174950d70641b55a0 | /datastream/__init__.py | 749076dc121bff3050789b1051782f5074da5f87 | [] | no_license | ohwong/jy_manager | 7c1dda37b819065d1c80eb670af94b04da33d81c | a0098e54004150c1be0f521407727705a77a86d9 | refs/heads/master | 2021-07-03T17:16:19.859188 | 2018-12-01T10:58:44 | 2018-12-01T10:58:44 | 95,996,307 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 336 | py | from django.apps import AppConfig
import os
default_app_config = 'datastream.DataStreamConfig'
VERBOSE_APP_NAME = "数据管理"
def get_current_app_name(_file):
return os.path.split(os.path.dirname(_file))[-1]
class DataStreamConfig(AppConfig):
name = get_current_app_name(__file__)
verbose_name = VERBOSE_APP_NAME
| [
"[email protected]"
] | |
615955adb580e1338842797759b11d768ece2b85 | 0c33849e47952664b6c93218627181b57094f0b8 | /run.py | 55f8eb402a4aae71a59a6bc74fd721c3ce45f62e | [] | no_license | GabeMeister/router-app | 2b514223fe6114ceda1a22c2fa11eb438b1e2167 | 85c06c609a7359771b7865dee3d30abcf4e63321 | refs/heads/master | 2021-08-28T00:30:54.446857 | 2017-12-10T21:34:03 | 2017-12-10T21:34:03 | 113,784,301 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 177 | py | """ Run the app in debug mode """
# pylint: disable=C0103,C0111,C0413,C0412,C0411,C0330
from flask import Flask, render_template
from backend import app
app.run(debug=True)
| [
"[email protected]"
] | |
66247010991d0515b20060847c80edb1cd76d051 | 5326cd6af9dc2a1466c31ff763468eee9abce702 | /blogengine/urls.py | 2eb9a214e3750e4dd549d2e3097e502c7cba18d4 | [] | no_license | dgiart/fblog | 8f14aa22fcb0cf8886a6ba1ff417530392459060 | 3f90bc229c3ba3bbf4706b1e1365f2fcb0600723 | refs/heads/master | 2020-06-02T10:05:33.748467 | 2019-05-26T14:06:21 | 2019-05-26T14:06:21 | 191,122,623 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 976 | py | """blogengine URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import include
from .views import redirect_blog, hello
urlpatterns = [
path('',redirect_blog),
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
path('hi/',hello),
path('accounts/', include('django.contrib.auth.urls'))
]
| [
"[email protected]"
] | |
45b28c612e1bd492c10238a493208446a0ab44c6 | 6f3f5c797fd60c360971af808c6bd2f3a1b54ceb | /MYAPPNAME/children/admin.py | c3e65894cd2aea186271ccbcdef7712d76838ca8 | [] | no_license | oscarsj/django-react-template | f2e798f0c0b9231598161dfa509583aa108c9094 | 79f8750c9232f08636b402ac99d7518d9cda8768 | refs/heads/master | 2023-01-04T16:24:32.496367 | 2020-11-02T18:17:04 | 2020-11-02T18:17:04 | 305,813,598 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 527 | py | from django.contrib import admin
from children.models import (Child, Parent, RegisteredChild, Course,
Season, Monitor, PaymentMethods, Payments,
Days, PricesPerDay)
admin.site.register(Child)
admin.site.register(Parent)
admin.site.register(RegisteredChild)
admin.site.register(Course)
admin.site.register(Season)
admin.site.register(Monitor)
admin.site.register(PaymentMethods)
admin.site.register(Payments)
admin.site.register(Days)
admin.site.register(PricesPerDay)
| [
"[email protected]"
] | |
24cfd9890765970054c84fe09a54642c03bcf6f8 | 78b48272ba74fee13b40b0cce8aad2406c1a77f5 | /core/utils/loggers/app_logger.py | 60968ce64bcfe74c4eb2f6790bcdb836ac04c703 | [
"MIT"
] | permissive | glassyweirdo/fastapi-boilerplate | 97e78360658048a57e7f7e3e0ae1cd1bab5186fb | 753261df16b0ae1ad6d67cff52c1da0f4243b8dc | refs/heads/master | 2023-08-18T13:24:20.180143 | 2021-10-03T23:17:10 | 2021-10-03T23:17:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 57 | py | import logging
app_logger = logging.getLogger(__name__)
| [
"[email protected]"
] | |
c5230e396bd6c2e75f84e8b9d4d5048b07a1534d | 7903809bf9f34c58af8879d9275ded0b5e661dce | /PasswordDataEncryption/shaserver.py | e5df84003e6843372bb33e43572e452b34e8dcd7 | [] | no_license | nikhalster/ComputerLab3 | 1abf31e763b9835512257e4ad7385e2237557284 | 855bcd8122875481b923bbf9c08b81210dd940d6 | refs/heads/master | 2021-01-20T00:27:41.072863 | 2017-04-25T05:36:19 | 2017-04-25T05:36:19 | 89,131,115 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 709 | py | import hashlib
import socket
import os
import base64
registeredPassword = raw_input("Enter registered password")
#salt = os.urandom(32).decode()
salt = base64.urlsafe_b64encode(os.urandom(32))
print("Salt is {}".format(salt))
digest = hashlib.sha1(salt + registeredPassword)
digest = digest.hexdigest()
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
ss.bind(("", 5000))
ss.listen(5)
clientsocket, address = ss.accept()
receivedPasswordDigestInKbs = clientsocket.recv(1024)
print("Digest is {}".format(digest))
print("Recieved is {}".format(receivedPasswordDigestInKbs))
if digest == receivedPasswordDigestInKbs:
print("match")
else:
print("no match")
clientsocket.close()
ss.close()
| [
"[email protected]"
] | |
8336c642c46de7acd13d8feb2bf4e88ba38d55a8 | 271c613f8fcad47a4c2cfeec0a2e11e3eace5466 | /pwndb-convert.py | e39ae23bf9fbc776fb95c1c04e01776067a7da53 | [] | no_license | vysecurity/PWNDB | d3b226f9cca9b200c77cfa09bfce5319a6e34400 | 9576108102e17bb479b031999f4ae731ad9700a6 | refs/heads/master | 2020-04-14T19:50:33.858517 | 2019-01-04T07:19:53 | 2019-01-04T07:19:53 | 164,072,400 | 5 | 2 | null | null | null | null | UTF-8 | Python | false | false | 504 | py | import sys
with open(sys.argv[1]) as fp:
line = fp.readline().strip()
start = 0
user = ""
domain = ""
password = ""
while line:
if "[luser]" in line:
start = 1
user = line.split("=> ")[1]
if "[domain]" in line:
if start == 1:
domain = line.split("=> ")[1]
start = 2
if "[password]" in line:
if start == 2:
password = line.split("=> ")[1]
print user.strip() + "@" + domain.strip() + ":" + password.strip()
start = 0
user = ""
# print line
line = fp.readline()
| [
"[email protected]"
] | |
ad5ae115186a694489f6794a6279b0b75e037ee8 | 051c3ee44478265c4510530888335335ec9f7fdf | /ML_Applications/SVM/Mutants/code/SVM_rbf/DigitRecognitionApp_47.py | 2be1dd52e2ea4cb532d52028ef938535d52fe789 | [] | no_license | PinjiaHe/VerifyML | b581c016012c62d8439adfce0caef4f098b36d5e | 3bd7c49e45720c1cdfe0af4ac7dd35b201056e65 | refs/heads/master | 2020-03-25T19:40:39.996370 | 2018-01-30T08:58:58 | 2018-01-30T08:58:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,166 | py | """
Created on Fri May 26 15:20:01 2017
#Digit Recognition for V & V
#Following note added by RR
Note:
1. The actual digits data from the http://archive.ics.uci.edu/ml/datasets/Pen-Based+Recognition+of+Handwritten+Digits is different than the one referred in this sklearn example
2. For more info, refer this link http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html and the above one.
3. The digits data referred by this Sklearn example can be downloaded from the following link.
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/data/digits.csv.gz
"""
import matplotlib.pyplot as plt
from sklearn import datasets, svm, metrics
import numpy as np
import _pickle as cPickle
digits = np.loadtxt('digits_Train.csv', delimiter=',')
digits_images_flat = digits[:,:(-1)]
digits_images = digits_images_flat.view()
digits_images.shape = ((-1), 8, 8)
digits_target = digits[:,(-1)].astype(np.int)
digits_test = np.loadtxt('digits_Test.csv', delimiter=',')
digits_test_images_flat = digits_test[:,:(-1)]
digits_test_images = digits_test_images_flat.view()
digits_test_images.shape = ((-1), 8, 8)
digits_test_target = digits_test[:,(-1)].astype(np.int)
images_and_labels = list(zip(digits_images, digits_target))
n_samples = len(digits_images)
classifier = svm.SVC(gamma=0.001)
classifier.fit(digits_images_flat, digits_target)
expected = digits_test_target
predicted = classifier.predict(digits_test_images_flat)
print('Classification report for classifier %s:\n%s\n' % (
classifier, metrics.classification_report(expected, predicted)))
print('Confusion matrix:\n%s' % metrics.confusion_matrix(expected, predicted))
print("accuracy:", metrics.accuracy_score(expected, predicted))
images_and_predictions = list(zip(digits_test_images, predicted))
np.savetxt('output.txt', classifier.decision_function(digits_test_images_flat))
outputData = {'data_array': metrics.confusion_matrix(expected, predicted)}
with open('output.pkl', 'wb') as outputFile:
cPickle.dump(outputData, outputFile)
with open('model.pkl', 'mutpy') as modelFile:
cPickle.dump(classifier, modelFile) | [
"[email protected]"
] | |
dd9a63e1aaad0dc5bdcdff237e138d25cdbc9716 | c4eecf1885da13b4c240eec7a73e657cead8c483 | /V1.0/NeuralNet_TEMP.py | 36ac6c5ab365b0620028bb74737503d3efdae252 | [] | no_license | BarryDing/Hongxin | d16d2c5f8fc568c7705b5c542e6f46d4c73eb65a | 8f76dcfb988cb1ad3c9e110cdaeca035db2b9745 | refs/heads/master | 2020-03-17T22:48:33.979170 | 2018-05-19T02:09:38 | 2018-05-19T02:09:38 | 134,018,930 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 123,207 | py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
######## Copyright 成都信息过程大学 李方平
######## Time 2018年4月26日
######## Function 将输入的矩阵 经过这个脚本,转换为w温度
#################### 输入Inputdata为一个60*n的矩阵,输出y1为一个93*n的矩阵
######=================测试可读一列或两列数据==================================
import numpy as np
def NeutalNet(Inputdata):
#######Map Minimum and Maximum Input Processing Function
def mapminmax_apply(data, **setting):
offset = np.array(setting['xoffset'])
if Q != 1:
offset = np.tile(offset, (Q, 1)) ####b = tile(a,(m,n)):即是把a数组里面的元素复制n次放进一个数组c中,然后再把数组c复制m次放进一个数组b中
offset = np.transpose(offset)
y = data - offset
xgain = np.array(setting['gain'])
if Q != 1:
xgain = np.tile(xgain, (Q, 1))
xgain = np.transpose(xgain)
y = y * xgain
y = y + setting['ymin']
return y
def tansig_apply(n):
y = 2 / (1 + np.power(np.e, -2 * n)) - 1
return y
def mapminmax_reverse(data, **setting):
y = data - setting['ymin']
xgain = np.array(setting['gain'])
if Q != 1:
xgain = np.tile(xgain, (Q, 1))
xgain = np.transpose(xgain)
y = y / xgain
offset = np.array(setting['xoffset'])
if Q != 1:
offset = np.tile(offset, (Q, 1))
offset = np.transpose(offset)
y = y + offset
return y
x1_step2 = {
'xoffset': [7.85,7.31,6.5,6.44,6.22,6.51,8.49,100.42,138.13,232.69,258.44,262.64,263.14,263.5,990.7,11,-9.7],
'gain': [0.00782533844588778,0.00781280518770264,0.00782595085302864,0.00788115222445522,0.00788177339901478,0.00780579189758801,0.00767194752387894,0.0103423311614438,0.012831205491756,0.0306138068268789,0.0486263068319961,0.0507485409794468,0.0503778337531486,0.0501378791677112,0.0464037122969839,0.0232558139534884,0.043859649122807], 'ymin': -1}
# ##### Layer 1
b1 = [-0.24083009551663642211,-0.14078377292955926436,0.037983014160748840293,-0.074333816557691542726,0.14154445141039964651,-0.0075244133357378886404,-0.33136118470348324694,0.46889821863452291195,-0.64524066169211391486,-0.069553726027309262236,0.005242702738335228152,0.027025157665727723988,-0.58458731534837793387,-0.069069713842964494677,0.12903777925320741859,0.51152078566952863259,0.064549108158987525408,-0.036002500654198334173,-0.050716511122690620395,-2.1473121219685888938,-0.33501988254435799419,-0.13607479606422079321,-0.49490461397340790306,-0.2645660060116201695,-0.17195518474156684663,0.83509712243608202886,-0.45495062916988848745,-0.29836031042794763923,-0.030809067713133443667,0.22058072072966183885,0.55227492236912245627,-0.26612692803609089287,-0.11153234666121367158,-0.31377083628661306403,-0.82448012426084738014,0.0030760326108590432814,0.11125530189257358538,-0.44615780239078067781,0.81313276307321313841,0.024317030591851584997,-0.05331798178548300543,0.094749730699039316772,0.12265884395199685986]
IW1_1 = [-0.1513276944642346078,-0.023394275620704660379,0.076802097580919811981,0.0066466235889355122779,0.042925156409081559328,-0.041786603588628283557,-0.11620849522461611236,-0.081224744570633264362,0.12875188797267761442,-0.12805150714205357221,-0.4571303574569796635,-0.34348452118252548182,-0.15066748529877246887,0.21003737009954481785,-0.2671193157842211563,-0.098243340319960625884,0.087164960326012216885,0.027018461511456998841,0.1302082870952153415,0.14087934313998259905,0.083898677158883841476,0.26209333932295891811,0.20355460952751414094,0.11252416727001825214,0.067987724007552097216,-0.049691559619072400711,-0.4640657808880943036,-0.5099268584841234464,-0.37532277685383858001,-0.22841411984484735753,-0.075887505183453815572,0.083071166196183474084,-0.04088741002567602284,0.27183604262443650246,0.039572224575712154626,-0.22765791196907583793,-0.18852875663831622499,-0.12548482523559834068,-0.21174905033354601835,-0.13810883838978482707,0.012224664594466218975,0.17247673253583278852,0.10460334352356617793,0.29207210963018864769,-0.21270437800210401091,0.35673231554056183956,0.28356261266434479307,0.40597433000817778614,-0.49732185993055866291,0.43113142446323104995,-0.04507334522579201086,-0.020504215954026350222,0.10048891435571481734,0.078351603477878534187,-0.020455994020510910592,0.10164300024268442535,0.039501316409239026206,-0.047134613441388487076,-0.031977534851264158289,0.047128246501721010597,-0.2270809911950966431,-0.2021412016398164424,-0.2796015984365087248,-0.14583381329044908803,-0.041744169058177189868,0.11540190527969404477,-0.096037756921411601696,0.0477804714268557848,0.14971520625537834692,-0.073541132932441730108,-0.023998130749014731644,-0.1018493636069505992,-0.028818283363064051139,-0.074219300846414232309,-0.17429608384697101164,-0.30270435125479389082,-0.0074178880442019633559,0.032266750525888884815,-0.83876519766325152716,-0.43786091259553067134,-0.19050249677819242056,0.2776975135376727466,0.47313055589002689372,-0.51232169100471136591,-0.049391748246377285836,-0.034032872327888069597,-0.50743138699081136167,-0.082034311401998710744,0.20561363970005902546,-0.035408132505788489364,0.077010980295023109821,0.27291200125056136461,-0.26933025786484232622,0.034044241292392682374,0.88437493429724101102,-0.43935778828733934587,0.12517348424649679672,-0.0048068857216742102989,0.28169457017656696074,-0.22237676004534906449,0.23973615097929526496,-0.46879851808273970137,0.1177566589899457089,0.25515539884747856503,-0.23662460991443670655,-0.36758984910159497872,-0.018017310069364755182,0.04275449167913941001,0.082709564380393535421,0.27854316270607792916,-0.20325336855278822168,-0.85478219921734721609,0.5295201708474555069,0.39527327857733524086,0.18135464139742146772,-0.36740282249160477468,0.059165884007404592748,-0.1170053753937616986,-0.22454760858018765757,0.052820732076675730449,0.03171010789097691851,-0.035690054576104204842,-0.05240709427657538888,-0.0063092022019452936865,0.01107289055826831542,0.063505153498233976594,0.16100673073286281278,-0.046625488660483022096,-0.30252539318758081555,-0.22538442384153223319,0.22497754747223724925,0.24800499000673018046,0.57500222278765455997,-0.074983530964247896433,-0.31601369792577954643,0.56859463863063453015,0.96772555112984048886,-0.83670194334148584314,-0.43681105558288041424,0.014530415820621162687,-0.48116589241142276867,-0.25021337197894055748,0.11644738061459476708,-0.41117329091650661743,-0.064768774995969266572,2.2048530832455082162,-1.3088165341320117108,0.30849633169311474479,0.15453572404814786001,0.99469297357820773975,1.109420162985415681,0.35460083043230133937,0.076300232536618939339,-0.069751235227440561149,0.064423342458327620408,0.084009470563879223848,-0.023884914452718303962,0.094935913013530937032,0.016663236999549243395,-0.077679104328824202796,-0.061249804645584306206,0.070952479738130361242,-0.24905418898569886554,-0.38768946040811286258,-0.32141095212124615177,-0.12303715374997395426,0.1393206680445953638,-0.013749519555990595554,-0.039360671550860551471,0.038605896482903037659,0.13086474958288088488,-0.1133188333169555112,-0.20435285320918869512,-0.11060962547766511888,-0.12968345813396875421,-0.023696229861146663603,0.11087662874036875726,0.024137465409564826807,-0.20868389134994830281,0.033659420481735959074,0.18720363395767961046,0.3978071252043781092,0.11933175199655376986,-0.16234582321118301573,-0.24862324687793918576,-0.00070544420471547238799,-0.069924960602272434596,0.11636733407290049402,-0.012910578174806250015,-0.048574559771120566498,-0.018909544359069638958,-0.082191022515184050667,-0.077773425174390314885,-0.082660652200983175675,-0.051496236770907831415,-0.14212588998587621925,0.076846287195683898874,0.036085159527414548131,0.056116693099279267576,0.067614057516241846124,0.077528892828834516937,-0.22706024009350606052,0.11319605410909258647,0.32773312371681467825,0.36372921662592178071,0.33374241508144980584,0.52176479888886362346,0.33328579127424551309,-0.023308146293803920501,-0.23084785918644590286,-0.48905249615060608637,-1.3763518716140179521,-0.86662863211654650453,0.16465180033124265924,-0.088652703243128003208,-0.53533115911997708469,0.018484462903005108303,0.49174052071395724095,-0.14283645487185822609,-0.52290565461167148875,0.4484494093767897871,0.39244355282131154761,-0.21791724765020026311,-0.24372698482010332621,-0.12587701995710223746,-0.24826046284853447998,-0.11890410456536576467,0.055217108828921487862,-0.044349505148387133313,-0.19377204600062952755,0.38042345706513797099,-0.26434686946507429672,0.19611284714708376864,0.066151726354755455151,-0.021038708016458153999,-0.47966963587660044199,0.31188250926890465076,0.11532325259200311429,0.2054970198201166165,0.15571957247995565909,0.10616113528382303821,0.088989997272990339905,0.077049825720077472213,0.11249158676118101163,0.23807366855861836208,0.94265327153281586181,0.71908110973408523314,-0.30735980939802765022,-0.93101427640463574331,-0.5310154623614917746,-0.44173063652551336489,-0.37562031377815324751,1.0205141041713940986,-0.75833397255044909802,-0.56800265659837545495,0.67920792167032240094,0.056525821814371587926,-0.14529437249534798982,-0.0075928272090198924496,0.32749678684488414682,0.48701755744543290261,0.64179523518349068656,0.04970779109584006622,-0.29209202849152698933,-0.95904692168045602152,-1.1562225560313073025,0.40695131165418185759,0.2663466599483607089,0.21183863650648251942,-0.30422435691931598578,0.49392695278529730185,-0.25569258669477185064,0.31397642117542479134,0.18347586879693661421,-0.017443398322575832948,0.035882194671521573659,0.13149274570007157825,0.22512822244437136199,0.30055866007362436187,0.42412072785380022788,0.042044767166065692698,-0.05619060884700874392,0.29333718408496134433,0.35537835161386610583,0.408744107702839643,0.25694293003690149568,-0.25156811406322077129,-0.10947226458697155438,-0.22995211704356802174,0.054972074833870128441,0.27570119374905682763,-0.059122950810598970395,-0.27727595302145924272,0.07450600641446950001,0.02056160624663217959,-0.089632520216444286354,0.18029256933685894326,-0.063667483572461339159,-0.77015175929881640737,-0.15331192943015092833,0.0039290592346125589179,0.13596262805206904556,0.17516981631866504476,-0.050844891356328990317,-0.047701158881294239422,-0.060510023101627070929,0.21984723171445028078,-0.28110987092205003135,-0.12107780788665167826,0.078213311774790073017,-0.18573441652199046414,-0.076575515750460218523,0.11097920177391934482,0.022844640952099821984,0.053727388201479556185,0.82385777471363552671,-0.028658622774604753519,0.12226310731799668041,-0.041346982088975858805,-0.13244750106323177619,-0.07773211147380609809,0.042154657399641998206,-0.17677170377708548155,1.1434737451623948612,-0.81548745321501958649,-0.7769817146367526961,-0.065887767614598025112,-0.23222282979439262673,0.31339846127209214366,0.89677672815926312566,-0.27764395429495714041,-1.1732164696424363104,1.7266966088209916297,0.29648307495542502998,0.93722957115310479015,0.79924583731113163498,0.43510437747433305944,0.06506929994467688938,-0.39174500871410894431,0.21170906236922729104,0.41984676734147619026,-0.23458760227977493162,-0.30489753979023087593,-0.27006111946930883017,-0.40434876504490552263,-0.26460138666181420852,-0.0041166415648106911493,0.080500520609941256245,-0.023443662164037856743,0.45029346472745823693,-0.48030988870526752921,0.49460589213320899082,0.48765333332186105997,0.63221175293118170302,-0.22544220105631618267,0.87741755723824410573,0.099913976805107010404,-0.65447714454543526319,0.19854601089185514029,-0.34095468993749705744,-0.50696825752339846893,0.27216264734936301828,0.33488904962982263269,0.26363986742024070331,0.55288522160412456596,0.018531084778346605668,-1.7096594603767460985,0.79347742977909074824,0.60611624383054019116,0.73133678302349769407,0.20160861235278459969,0.4511888533565561743,0.17476181132719972866,-1.3025188485846945774,0.51882335942861479428,0.18526910285347628071,-0.33882011850843313239,-0.28431191156738977455,-0.18262432858404609171,-0.057577149174682824839,0.11349318483811655922,0.41940944271365943052,-0.29040285270816779128,0.19543212703920942452,1.2689122930130747324,0.59036207575985488738,0.30855934239653531881,-0.80433332474240504251,-0.042331440340455703253,-0.035583554898777881859,0.27279464939959507941,0.28771661160451761363,-0.70026676467902282397,-0.27072304180873368873,0.14530284723953348913,-0.15041236995928991549,0.068224808864189356861,0.37335884126120177928,-0.24376967817055772425,-0.14035715567290843464,1.0595716398137207115,-1.0824635567545741743,0.23204914694078104809,0.11959765996167619206,0.55576654774208933407,-0.3238487227960063497,0.20003273193936027541,-0.30219666683647733452,-0.38971132737578778604,-0.013431372357134237563,0.15842928701969824501,0.092881959150853204976,0.19896506337073860404,0.12567830697013171459,0.011269154630952842033,0.015347175533225655697,0.13452278406912401842,-0.49275818505957086346,-0.86683184077754582564,-0.13756164085542413322,0.21899469038707802815,0.9789638608774267059,0.56005805177784273585,-0.060932666767706505917,-0.26248888919207979953,1.3374404865012072818,-1.0091290304708853132,-0.93271490255124211988,-0.5519559576077995855,-0.7446380142525870216,-0.24971715488560786156,0.48608692209039272569,-0.043720297270440092174,-0.32279533052617087607,1.7920037836237190376,-1.4108771880579307201,-0.69597543913098813828,-0.62626504218218803643,-0.75960863694346336672,0.13740233343340813033,0.61230732973749757431,0.059602207863370518237,0.47370595654664116037,-0.51607204815670004727,-0.55076963020313307595,-0.27497129556928595617,-0.27279306269098058113,-0.063644295903309777707,0.142297627791698994,-0.1421605819323304154,-0.19794263467698985925,0.89970779499574338178,-1.5193198740334679098,-0.66916325130748066652,-0.2833469316129353377,-0.029424600382158251632,0.99753744170148450632,-0.7612625154938783556,0.3807042250818905571,-0.53238088053975729519,-0.093980910001620773797,0.070691685141617346955,0.08117634780179859566,0.057402693238717522606,-0.017229061760013000826,-0.11474553235653557615,-0.025778383479488343327,0.14769087498605545927,-0.23441833816670451518,0.24669452642064096382,-0.38443186642893301119,-0.39164196874881140875,-0.34403240016624564435,0.070484521472225183936,-0.17805406052325256638,-0.66000196395370447355,-0.18674009904265564952,-0.15321279678397367596,-0.027084944194651319055,-0.028473099259325309468,0.054485661519457266599,0.062153762033122485209,0.068144143995722702978,-0.14533490819376820857,-0.025501445931936209816,-0.041711477375895388009,-0.52965552579992491999,0.072540858013600648113,0.072146370326700168252,0.37391036167751318109,0.010607832228228827529,-0.087903934679184420053,-0.13591185347641654424,-0.29202802892810725277,-0.2553973495307438335,-0.19241296364003088182,-0.08688239479594260517,0.039864138762701693819,0.14997724152263927633,0.3012739779283410968,0.11863283184382436564,-0.1613028478790469733,-0.62694478756913885054,-0.6295758729905075457,0.57644025828884726259,0.29804604086837366284,0.52948841934424895062,0.14297633927591291148,-0.31935833186698964203,0.13578464024793687748,-0.50620218564963836982,-0.18364732320814763922,-0.24355881250605573851,-0.40898602257609761867,0.040926799523985438189,0.082530632096593559144,0.12299579217758434269,0.46559066907429591531,0.66976374528301951816,-0.1792368084123569516,-0.68066565745404616905,-0.0098639221593051183701,0.26880518911667355964,0.6014963517156913797,0.77347552060381730143,0.58958949653202274988,-0.16402278438109585412,-0.26854644040028735619,0.020651092746828508123,0.095702801457875644187,0.061767572364822304065,0.19911058609346826698,0.1300799867392888054,0.07298695627419309051,0.17787017447807204618,0.18972411343160794361,-0.3883821516616677294,-0.38576789811113443296,-0.27718961244657586152,-0.17283195874017195925,0.061624577480367030702,-0.1672304403962601993,-0.3784402238550496067,-0.15069651838017592005,0.36626328198914076539,0.38330131051681587406,-0.56955942789238966917,-0.84581575731254932116,0.1824787836919713746,0.3878491315761624092,0.46160914377967660061,0.99608919956892305603,-0.16228561417103923303,-2.2123478803475618015,-0.76165168140377847994,0.50383390289146179342,0.46302087063725078098,-0.023474293374004917556,-0.32455069746015419163,0.0045811711299630023669,0.64363222614793513809,-1.6925801712857460046,0.26141750105003763727,0.075826594349227269265,0.021103207234245177637,0.17635612238187470258,-0.11375807468692471225,-0.47102746019192298643,0.97961120690591740878,0.85448713678684096173,-1.6657368119626756453,1.0407250629978068712,-0.655832449038417864,0.21368443043273388504,-0.093257480633291908734,-0.039950348566412136053,1.1234474623961248074,0.36156626927150692374,0.64665148801351124419,0.14941314865697166714,-0.62602034683461749154,-0.67623577648929089623,-0.12313046608456046371,0.058331627279004240327,0.22538315709183101565,0.41047944533981839399,-0.4359547161592004505,-0.97433155173440277874,0.17894165622558885764,0.65720550714649483837,0.43749328793143138494,-0.1709361254460860513,0.1704039572492768162,0.10892439440252529859,-0.60044657701571513275,0.14323711329896821054,0.081525206059433641403,0.004930449627490757214,0.03336223044669485438,-0.1286743071462334298,-0.13709632777591437836,-0.17254162851767787523,-0.095364561869941480432,-0.1194881400802356719,0.30489298617540133707,0.7628869645987043091,0.05751988461330265201,0.022068559151304685539,-0.30968909981406478327,0.11932510610971139298,-0.043402064775241055994,0.19038953766551927616,0.091319652417026539459,-0.038461132589722550612,0.0098271924774839796574,0.062305849728740203552,-0.065035824347902046472,-0.037057679352285342878,0.0067611428624225122438,-0.0051861541967160116468,-0.051834732951177429905,0.12968322750494340467,-0.18513353529432896583,0.18269666857060121168,0.24180631379663930502,0.45835478396591916583,-0.047407876940054147208,0.096157181510117942236,-0.038777214131443304979,-0.063906853119100603955,0.14938604193075119553,-0.23519093912552027636,-0.2802178320805319145,-0.077870930847716651746,-0.089149106116944015765,-0.16399440393652695014,-0.032571106202734456669,-0.47441676828607587391,-1.0463824609269765098,0.42748892338873251129,-0.15177391938716766617,-0.10039559800311198545,-0.75937906007888034132,0.69335354728150533354,-0.003400414241837769469,-0.62032171297450278136,0.95734471217169958557,-0.75808239860920711983,-0.54341659055772384423,-0.17003193116198830892,-0.21198464225474314415,0.047656791730260654461,0.35315570272510909966,-0.35668935524663603065,-0.15103640596006592811,1.810664974392297788,-0.69213092097251727175,-0.46478424799027201475,-0.4675024763856601151,-0.12233399837663895549,-0.97236654442019543332,0.27051272691136668547,-0.29997973331172123057,0.13952540124685272604,0.0051556131226842905405,-0.017686522309460467328,-0.10262289936742920171,0.063240962348520834979,0.048919307050753396693,0.024418899509861209662,-0.076805450161984867297,0.038718552859553993784,-0.13256041519803871132,-0.65313135177387859898,-0.25064974053845118229,-0.094178662644677377247,0.17013685025909797144,-0.012746982282456688698,-0.02395817720437131218,0.10604890231431454706,0.0026756211844708374659,0.029227013021601473686,0.015775726877941875781,-0.069584126044063332461,0.089959585594792168539,0.054305636089819836476,0.018678857990941419298,0.025874117702089756421,0.041210724551878373523,-0.30974493219090165619,-0.56874711623160856266,-0.23918732106791276704,-0.10799848776224356406,0.12997006855057485764,-0.060000078085006472439,-0.015300065906766783033,0.060976363892333851346,0.9862942055230300431,0.19690667550519055928,-0.026201723600955705018,-0.1208302611887551864,-0.20263208363930843015,-0.14454474693558541643,-0.079508707332549027891,-0.31300175403810592822,-0.34479851261454280698,0.68499426011880515386,-0.16553640163864671853,0.21328199117711832411,0.28309650595028368336,0.052268136626006878043,0.011889126903577573735,0.63355884205951296106,1.290691593504947221,0.019217346484682200358,-0.027476640926737402187,-0.038491279803557217065,-0.0025765816551961834291,-0.19409390713589536048,-0.16720871631541453506,-0.1492443967421589468,-0.18610434046241661199,0.0067718561620238454379,0.54371973425878228348,0.70664042142467109464,0.26416717045003168529,0.17159140665232494594,-0.025445032317933512223,0.15018678250690725706,-0.040847903932826550022,-0.24558629796274142332]
temp1 = np.array(IW1_1)
IW1_1 = temp1.reshape((43, 17))
# ####### Layer 2
b2 = [0.02992756614134727336,0.0020177830919498483328,-0.011317192919325206463,-0.019782363435328940288,-0.016035028468548821051,-0.015601947248009864072,-0.0065540830219884653463,-0.016332161950257700206,-0.010952090928589381866,-0.014833764335665558867,-0.022740497400578922604,-0.018559543648269338778,-0.013998658443446495431,-0.021889575388722343902,-0.01874695116108886922,-0.019566146074233688179,-0.024582845053004946656,-0.021350396253950632008,-0.032899960429792506067,-0.025025308722854081728,-0.016705796123595476055,-0.011680643033834982661,-0.020524622062853697252,-0.015814418857220326198,-0.019587154667366615812,-0.022645886490078818293,-0.014838775445901146097,-0.023006102494960566085,-0.013878883222503921382,-0.014746257329480882275,-0.012004020603244975468,-0.011167927717343808722,-0.0061892170196985027072,-0.0049230413190097365578,-0.022911966094344527606,-0.023929499717950258181,-0.010052625453973633787,-0.021362565251306458308,-0.036909594899498993081,-0.068397699768125860831,-0.073531722976929614344,-0.078405439509067267889,-0.073143516312259751477,-0.04566788222318330509,-0.043017751022649985959,-0.043653826270736488524,-0.035470779466794465085,-0.011085256213819788193,0.022752556460691977791,0.069973329757038862931,0.063970407491800093669,0.041419351576331163434,0.019217904260906193414,0.0243588442777537377,0.017980129650535591618,0.016158268333480229478,0.024867085349366768732,0.036589186237740232988,0.03813945656810321938,0.034454995453454102805,0.05416345385220816544,0.059321695143723186805,0.080078100129457679968,0.073408760152133337162,0.10100629415064353578,0.10475924085538837471,0.14285032041300385619,0.13250291314515577623,0.1040829601237344415,0.057405896552483806627,0.071017593381322560719,0.065727685029290633389,0.043270218776706836916,0.04764978844235644162,0.041258723046447606797,0.011782496369474286177,-0.018608631897656276177,-0.048916038509218086328,-0.085467950843700568608,-0.049332555053138944789,-0.013077305241717860143,0.00156963481177336368,-0.022604278075564070843,-0.049994661234014352302,-0.027878885532392483348,-0.014354588137429229178,-0.013558482409228887061,-0.036500474609252313296,-0.03463819130370368593,0.0089320543887336130429,0.011094556466008839365,0.06303906277267208591,0.085617844870157097659]
LW2_1 = [-0.047649748183048054595,0.064408764342227003974,0.02378962229704813594,-0.067631747436760161762,-0.07245310373828127426,-0.13610619555715791629,-0.22201167113251080165,0.088651685125090029516,0.088231676796594965539,-0.061640586612233490282,-0.017804769484660070561,0.24293638904224582054,0.041962600050662088313,0.11475394342053014951,0.020600804141801747765,-0.103235253358448964,-0.047533400092426361661,-0.11240315060873767861,-0.061799958842161349659,0.087538132955193165285,-0.087428756815166625005,-0.10274718521350968692,-0.0035756132977757346808,0.079586808174422554729,-4.2783270254492626605e-05,0.017666786915879060388,0.035432948023248207747,0.053788038537523306937,-0.032810071239204652294,0.047294374377310016699,-0.13724151287751065742,-0.12534101541511583067,0.31427269179312294911,0.10271313035055078255,-0.40918043052031649598,0.15044571952275326288,0.10329811547100477276,0.049292090825123244247,-0.24632243599214850849,-0.042590315044561774527,-0.068406827503415104652,0.069294597356167747515,0.0048210005395116052943,-0.059011125857546684048,0.020630956117298402536,0.028873028855150702221,-0.071848500876202814336,-0.045742397732993572701,-0.1249739745610679853,-0.19523336974403324162,0.080421205055266647976,0.10111660980693620848,-0.060301459441026598884,-0.0062407494716533121887,0.19309977172641523691,0.036117098727556876114,0.10542568178634824372,-0.0021803096695494064358,-0.066834892675850840482,0.019544973063027014371,-0.082836491487424793179,-0.034993347989905186635,0.089965453698444677877,-0.13689109788621434127,-0.0926234648315806125,0.0071395573946132721149,0.10446822342351275159,0.054194577734263622848,0.030751003788628921559,0.028459889454360398631,0.0054840022609846756849,-0.0065397722359630608424,0.099441283059187396409,-0.15909051832958037709,-0.12160975009112628964,0.28259223781083314675,0.10563003745493923513,-0.31277709739863424065,0.11239640561505388761,0.15209732729094085912,0.047253157208303822601,-0.20474630418485073591,-0.046266995327525567427,-0.060662613264919069966,0.051139234514665385389,0.017146657849891031727,-0.057966173430323029991,-0.013942907744067076226,0.018485543391388796486,-0.073737599786013047209,-0.037141545795942448871,-0.13081647398028597995,-0.17685610918070207576,0.13056491726880278814,0.096876767206053288062,-0.051708274014939298313,-0.0020494551982005539993,0.19341872294602607818,0.027971372194940290895,0.11161734257646159507,-0.016581295376096087668,-0.056808385750181406015,0.05713963010020681188,-0.050745776715790121003,-0.0060280300198326964428,0.098819856875986974987,-0.17114566581259080258,-0.11239983090717642344,-0.041375496805993131066,0.12767199694194150683,0.087792341102385984541,0.011852162742453516489,0.0096307028186813151138,-0.017947341300224319699,-0.00088342965924146353053,0.10882340106097733445,-0.12655636201504455451,-0.11171513351241767198,0.24711275564202359045,0.1061115590450826679,-0.2126922603727500749,0.083836884045349183148,0.17027929861061355532,0.04034953550930615862,-0.19532790102306812896,-0.032601374613853519036,-0.047656687410838276253,0.057221266149193032724,0.034659112068395975248,-0.064197280085663055438,-0.02168863609343412574,0.02452782784773906849,-0.064960376569039010586,-0.038075485638312728254,-0.11962314325250525404,-0.14611489466883129107,0.17321352905086695451,0.10050565565094628229,-0.042682290068371209202,0.0013181587137613493335,0.16111836963852493865,0.025797154440435888373,0.11095144202374357389,-0.031696771271968418593,-0.063014683455857173344,0.093767449039703201774,-0.0079816538381436586552,0.0049049409404684418332,0.10654787795416088836,-0.17179631685632695826,-0.097924528421096793118,-0.072330753494317015506,0.13267097977449823776,0.12006701697081692548,-0.0031159463078205438744,0.0086421044509644318748,-0.067257490089533744637,0.0077642031435499400671,0.10468506916597569711,-0.10099047254924141404,-0.10833635313258253852,0.22466381135003501979,0.095238378129188075438,-0.14199413277170677694,0.060942180367647036388,0.18854463041748312224,0.033198504543840393066,-0.15702361216158641777,-0.022049641625726427302,-0.036803211632354650151,0.051800948737997856708,0.038132661482708954392,-0.07147153031500935727,-0.049546291212563410566,0.029888604401193348548,-0.073725180574192458738,-0.041182923829413610461,-0.08591908286458652122,-0.097467041476493834762,0.16244509931168746308,0.10005736736285300581,-0.051743879065344187962,0.02441412229733981934,0.13005956124273082564,0.016195512722765190161,0.092318605059954109149,-0.030910954954781407616,-0.03247970107778119786,0.089146725046555713723,0.0068755291443431554993,-0.0089279168584815507548,0.10250534761835020103,-0.13425234610648381639,-0.13556849520756067418,-0.074097838902942858574,0.14004478991645066821,0.16312351705703431737,-0.0058975560996164123201,0.016033694065413651303,-0.085058881163408761594,0.037130394720302550837,0.12311425854705372596,-0.082318449846914901191,-0.083338985634375764566,0.19828801764952752595,0.072518119905615047172,-0.07579672474992857345,0.034717176000727406615,0.18290885590897709712,0.008741388275624491222,-0.14163710474363017111,-0.039184518820601456357,-0.040384938729129821189,0.038480667289400152797,0.048190774668602796849,-0.07892480724026067207,-0.073336198462244275853,0.045548694625722842277,-0.080078934662219228291,-0.046342304711018293684,-0.055591426456591985783,-0.060918234574203894427,0.15636637877975620436,0.11472974204717818758,-0.057615349204218742341,0.047219134886491764824,0.093850159645888706073,0.010713641936560306181,0.078623281277124368316,-0.018346104615898424506,0.0090192133368845444491,0.075524565181027777938,0.039780143934213030299,0.0017097620909240496268,0.089063778683446587214,-0.082629725329255623856,-0.16607904127614986356,-0.07212045285716299492,0.14782566593610418915,0.18761536250586496877,-0.012115620284857296293,0.021312995510531770882,-0.077987280982933504525,0.054922695411830257939,0.15596308496774505259,-0.074900147007139789013,-0.065639379928085536675,0.17538386143767142888,0.044922410573298966752,-0.027778765493996656483,0.0013417103808681216277,0.18980399100779413168,-0.017847075266724483217,-0.1362548250475614231,-0.048345771262278708358,-0.044887385278012364997,0.012431204064361123587,0.064753156889119381501,-0.089817138367962207068,-0.078085792611464824309,0.067315683135347595401,-0.07984943477562737868,-0.057577718758572225821,-0.047113249459746209258,-0.030235450752868184982,0.16970203346284790102,0.11800451857590804616,-0.061330021673671318572,0.052877672577413090127,0.061170889141184237037,2.5604299152656403212e-05,0.062093274935969298978,-0.01912697219716032182,0.027314752209852227044,0.080832197569625507949,0.061581576348284927658,-0.0079350552024137835372,0.085381334780895434822,-0.048885981166708475376,-0.17913271066407449039,-0.063280069768341759562,0.15536925201523418827,0.21252068745716537479,-0.012650475695899691606,0.016730766691229425475,-0.090177287217228369043,0.059489636300253008472,0.18521642653873673923,-0.073212467915969650645,-0.059261415306559046823,0.15215163726159314228,0.030734335077705510209,0.0097362864796013554036,-0.013094459070290113273,0.19189772756694090106,-0.021862431631505887392,-0.12100875905277688749,-0.046740433064821784725,-0.042691327802047540629,-0.023434924681993998807,0.069909648686576730814,-0.093174870171235685268,-0.087465363080138219809,0.062234067071814100358,-0.076642531360342047719,-0.058692959332956241847,-0.045543776089363934012,-0.012327380731851736093,0.18000802745363023161,0.10839209457852963525,-0.056369871088707522444,0.059717984918407913952,0.042979929194811333781,-0.003628858309660892411,0.056356737040575533015,-0.021912898543661872564,0.03747517067679209668,0.10189544677299701425,0.062934221056317546372,-0.0068878462938840789506,0.090266710770577449074,-0.014655688265387267766,-0.16842351401291907886,-0.05099962556513867179,0.13490797628868492208,0.22560461415459814871,-0.00426847064125769355,0.016456098900602501162,-0.098487465010371866292,0.064555273506141708229,0.20256561656895896717,-0.067416953670582313585,-0.053615950031725236047,0.14103884659163909432,0.027335314738954369362,0.024592211265103167822,-0.022479613128582529025,0.2056442041580214819,-0.019770655833279745378,-0.11037655540945166821,-0.05227833021503373867,-0.037833773890042513011,-0.044102914312900601268,0.065990191755082069913,-0.10268803050473229721,-0.086399422525990837718,0.050386121878549572362,-0.08400844264650478288,-0.065605347231778007866,-0.038345893725474818059,-0.013950363833831859808,0.17284975411246969457,0.10758671479830132778,-0.063406960825654015701,0.063218309444063550129,0.038902448200435292558,-0.0093539075832750721851,0.043528068455526279512,-0.026792637229350973332,0.047045741227479273561,0.10166741960617249607,0.057877313952339984326,0.001735565763438885788,0.085230588715811100853,0.00020310794411775804497,-0.14142191801522788208,-0.018249848387039125513,0.13745134017184384989,0.22334780990875521822,0.0091097152038963451204,0.013813939982195194006,-0.095510493649673330885,0.067502359619545690417,0.22435117636016718712,-0.082504127855678816017,-0.049630386516920164952,0.13984648008475911163,0.023020951220591313879,0.034892617688853690139,-0.031284043207670128584,0.19428748658101199775,-0.018390134589842600799,-0.1112274479037849706,-0.062242019245868834831,-0.039702202087915743067,-0.062743867757341253988,0.0622001518858345398,-0.10510491065624856521,-0.076265181162951251048,0.059024520468059830935,-0.080821297073120412779,-0.071743179907955437202,-0.015606336822730661543,0.0064411478727110591663,0.17633047512213784191,0.11377532938273154928,-0.064013908015113779593,0.07047550103333606597,0.021756736867727659301,-0.014070776389458260897,0.044813047104505912555,-0.021059988228769744439,0.04331514834885020343,0.1132706776772539059,0.054950699682234788179,-0.011451368089230475403,0.081911064497148314278,0.015471008051841126513,-0.12017193903910609876,0.002552336780764083695,0.13422506383714677414,0.22243562534638883221,0.0170796527996261438,0.0087581907603049465039,-0.092878757488640037443,0.078744848909456044428,0.22043819310271445255,-0.09522829190264797683,-0.057732010927196202033,0.12771062656989856654,0.0083523539824164570733,0.042101852883978593822,-0.029019033979260751982,0.19833174824809809977,-0.0062257278712739977378,-0.092862717992091614594,-0.0571379611068477955,-0.037134627523652943837,-0.075306912744097911916,0.056580609333863184085,-0.1034799052008780057,-0.082779688240066248706,0.048580717633528634758,-0.090297992862741233155,-0.068928916789653529862,-0.0074968176413295469981,0.019697297050257533274,0.15423158415827725731,0.089776127369020408686,-0.074773742437229867575,0.070192255510036133392,0.026769226411520300607,-0.01554398587411076442,0.024280509154860040189,-0.0050682976417914284151,0.030879959386351619327,0.1263888573757135092,0.039985511404690546322,-0.0058123948073356855246,0.071015472826672532136,0.066591266498312720601,-0.12107707651427018769,0.014062402060361590614,0.13635200312217873875,0.21970214487633604739,0.018678820347951465008,0.013225342202601148706,-0.076237905468686320565,0.079210649672486810324,0.23285826053231739596,-0.079444545095190860495,-0.061402317307849320349,0.10805772150929597586,-0.0053216989184100040033,0.071726813881515846805,-0.036598400708193333519,0.18247111976875374229,-0.01131895143309243415,-0.0854028223392803848,-0.076469431571949228466,-0.047384745555528150207,-0.079311254350325391393,0.063799394763418684762,-0.10462546283486343079,-0.075814198439302288302,0.039550093385646641064,-0.090976347871004822898,-0.083650232546117975208,0.0048102552883639293491,0.038094079316212330066,0.14725688296744410266,0.074615198118592074294,-0.079011704986467035106,0.08182949741102756025,0.020345585298724367523,-0.027958748180010716683,0.034991967503522632132,0.0095881796434017889375,0.018351104579664139632,0.13226757775087655267,0.045028361717084672278,0.0052939182929442754957,0.057524998512779881854,0.10896299717020430098,-0.10429330038696574268,0.02458234629346842115,0.12459981011168662357,0.16385135019821031599,0.015539844120433106769,0.015013844528110909318,-0.059956466349525151804,0.077912179743157908285,0.22471595939611341275,-0.069549737792008459181,-0.052360060439482596084,0.090367373730033784263,-0.022066036648104400686,0.097365580003220764116,-0.02681226181500484182,0.1603815845457173539,-0.0017753485560891100331,-0.1043898945906413106,-0.087169187060365305175,-0.058687241843456840196,-0.09804300996070061669,0.057313207586884538924,-0.097381078293069509022,-0.070693901516152485298,0.071882954879321406261,-0.091544383348410710011,-0.1099261761373744456,0.027493423408626427307,0.063055891517642598254,0.14856091052729816782,0.058235356223104640938,-0.083470118608742663313,0.097162167042340999434,0.017669380952635010962,-0.045578987624527438072,0.041622390849522350464,0.028487972847658572101,0.022797144039374224456,0.12977591772632721123,0.041935873964063376251,-0.0099935698758529516866,0.065172208205981380091,0.12641672063041567431,-0.10003193624113916604,0.054315516369280440745,0.11789130438045669624,0.14233586920309768131,0.035807172933857919772,0.017960287159705132926,-0.05034727072504698725,0.076747475639330056674,0.22772284708043560864,-0.060462812305669494384,-0.065885119387727744678,0.071599009915410641303,-0.040461032462686501165,0.10889126226127646135,-0.023540254654185594624,0.14920005305913386362,0.014009564042969949171,-0.12448766326840621232,-0.072514003847040500728,-0.054717052301549738702,-0.12119449638992589591,0.049428899823542031544,-0.099349184049220468085,-0.077643745626521015746,0.064897317674917728847,-0.095287628467511098496,-0.13563341355687902334,0.033290661887891391524,0.069942827761021300614,0.146404991595933065,0.038765113507788578895,-0.086223213095070902479,0.10610443641071590215,0.020603039039746629674,-0.059879971744708770931,0.048532095143729095388,0.048254743207383189729,0.035290684894947452199,0.12759210562042647141,0.035232103747182476339,-0.0080285841410919576294,0.080610964723052264125,0.15579516615283142689,-0.083995564075946355098,0.057669216712821519399,0.10975262330447355108,0.12085193243805629482,0.062659438148258306267,0.029068873016445631596,-0.038382337068922169065,0.074929413568319280792,0.2451248955406701846,-0.06646937305821862263,-0.067661482557655222569,0.063171885881845260546,-0.047540582611092181697,0.10574959866204000636,-0.023629554640017109285,0.14330957626103724145,0.025582684596466936239,-0.14055028537568417524,-0.08101758613156119504,-0.061578555444705578015,-0.12728801741749204424,0.054969487011432227597,-0.10218986416634753822,-0.076604740676336366412,0.055999391712229451556,-0.096138088727398568478,-0.15095056987833344042,0.031933428517457257412,0.074655210845618019677,0.13525351462171661399,0.020585943767866349274,-0.089693272919919020403,0.10679804640944565164,0.02849913152322508525,-0.067339102313656806764,0.047951224549830806509,0.050363596552883305169,0.032980993037353766029,0.12225220807035006021,0.022864667326139100079,-0.018411731581621126885,0.085304392754745828054,0.16755278545700064141,-0.076036829111328918529,0.066791912072663772726,0.10947895927632543545,0.1129754439912408065,0.076174581040953370792,0.023420903004226820143,-0.029716630729397858907,0.069539744246341059219,0.24484795625819816278,-0.066936554591778982259,-0.071942841383074107586,0.057565888303675163962,-0.050967446168336510981,0.10376655045544611045,-0.018375794193176791386,0.13440069574356883209,0.034338179178011213333,-0.15330594800408200995,-0.084793867852201942892,-0.064209010416862194459,-0.13249989511076853965,0.054863431699811400499,-0.10616707081164729332,-0.074930872425128774994,0.058949054714919034426,-0.09526615439840592503,-0.15836707485903100956,0.032915110919796694566,0.079952035781169675244,0.12014159464249278553,0.0069328949866479050793,-0.092166837767046871921,0.11081352905742189452,0.025691076918375650023,-0.070139430082796175303,0.0478285735881480642,0.049970610156689208858,0.027726353350048364016,0.11887370622223857042,0.023463448503961224778,-0.016306777543115293788,0.083992498804655868483,0.17071644388210174825,-0.059504225946311259388,0.085927841582262146081,0.095605983622684437284,0.086022927952092653747,0.079832630695582523783,0.020712573973936356658,-0.018141917004703821126,0.062188587995066373082,0.23001233364547185589,-0.064492316956995920929,-0.071991867072437307207,0.052544468156626333855,-0.058091359972922917976,0.10910206167391250931,-0.011652476174680972965,0.12933061706904699917,0.044725839753488025319,-0.15975789020504613247,-0.083491436267110502589,-0.06594366920525671083,-0.13391140334432163894,0.057639359699101173906,-0.092977571202503023207,-0.088933006467510511417,0.064609478993850916195,-0.095297151046216915793,-0.16743207949514093968,0.030321556610951504174,0.084385506895997802745,0.08773360166790471204,-0.0055556019060472392607,-0.09152502228179094923,0.11210224545806303509,0.033454602096648120013,-0.07199308957811205445,0.049846888465041379324,0.049687222500606344211,0.030837438710977119194,0.10955968973626131757,0.025412704781540295523,0.0045017084387971367451,0.085696717228349733597,0.1576634213585816624,-0.043279250549237410772,0.099533389919982881433,0.09333449493872358893,0.050101952848115617611,0.084778711518116792178,0.024208712419354374429,-0.012755884444076917919,0.053995717029451328894,0.22976816137771921555,-0.053504365158102029643,-0.071764738592804466766,0.05063476591080237621,-0.068831142117785029666,0.11120265507606759414,-0.0096450637781427366046,0.11495113634597170504,0.049377974915084776875,-0.17022902762805833254,-0.084297517488528789231,-0.068876795043563615595,-0.12052916566760761563,0.068904767959987456294,-0.09555068287980275632,-0.091689761233661223883,0.081558537843744824403,-0.091642758292507869866,-0.17724463355017466837,0.02353567586998954464,0.091542687429554209233,0.065163535495186553081,-0.023282413714557970152,-0.091155902086065485057,0.11477224470948647894,0.024219499771710655683,-0.079558078463841053196,0.048656716753947698573,0.041279280750840023628,0.028265630844964331064,0.10285552868491412704,0.024297122480274543216,0.00024154702316241870265,0.086094366325800045225,0.14829891240153786347,-0.025055548565475489753,0.12713013391590780032,0.078372550249328015726,0.012011487874153575425,0.09356937660711467375,0.026383743384678168958,-0.018039738884395629254,0.042563660902609039283,0.22924184987939202895,-0.045016539057894509879,-0.058576527015917236041,0.041376746897626083543,-0.073311982933318337041,0.10980536318280054164,-0.0028659679531906913884,0.10856598828409405599,0.057884272734157776741,-0.183614047512243167,-0.077271683524543277599,-0.065290934425979302302,-0.12352335665628939865,0.065963289880425962641,-0.096420909923108061301,-0.10141543502019260969,0.075972496409202394663,-0.091453989024402701502,-0.17813683998930651686,0.015955969823050555195,0.099632324330801713685,0.045799743400732249865,-0.038677677525371927103,-0.094028934937355618251,0.11734695338024228595,0.029578353354925101398,-0.08462649053898940732,0.055583003523452766126,0.034574114511798800797,0.030198558737064177399,0.10142518530877404903,0.015629186642093648857,0.0079034711049253431742,0.090822752522009386755,0.14201852250057425686,-0.0030457950950746968261,0.15969502581399067087,0.060467470561094686932,-0.0067131326200190188924,0.11301267822190272372,0.030142895079573052419,-0.016678566090334811384,0.026966510524126512116,0.22446043737746421143,-0.038030632511735648627,-0.060209508661347409253,0.049458010839756372246,-0.081793940420944677427,0.11720028484856423456,0.0028253272917493008065,0.085507385137989319612,0.059104684193375799095,-0.18294750673991533318,-0.087237631180493505068,-0.067560164752158216595,-0.11734609580918951843,0.062094620003240869055,-0.10257999887003969863,-0.1023846586451447882,0.089029539923066280949,-0.090309317654862816815,-0.17242561762211167098,0.0061197949244178638864,0.097643688143863538453,0.038228129482935364891,-0.05147937136223069976,-0.092711159082057001402,0.12169238343437714656,0.029128807272095130765,-0.088371041824864118852,0.064624866444042070035,0.038032993578782411936,0.047247910235285850433,0.098344954932974806838,0.016602929402087022309,0.028908583855406854574,0.09602957808929263317,0.14006026389605377713,0.027429724066269232235,0.18723264021725760653,0.039576850159679911878,-0.049712556601887440688,0.13045827976421392469,0.035195147639200154155,-0.0028804458250010103564,-0.00067129749627077052454,0.23653073352002684793,-0.044505097174959741546,-0.054910685255668119364,0.046031494440548527403,-0.080442059746585192759,0.1193751119702420177,0.0068887029983926142615,0.077057145068300594848,0.05881269435232896331,-0.20416898022019316916,-0.082599649256986332202,-0.062055946899750219492,-0.11713265117905556634,0.053146849466895206004,-0.10537241484784623524,-0.10244320536850765047,0.077226222132636912487,-0.090892196590747140195,-0.17898259775895014601,0.0077177617971665732691,0.10435734548991684734,0.016940710460078493849,-0.088328285085874633231,-0.098248453104166064143,0.12598138008632056573,0.03037104129451425466,-0.08242668238160021088,0.063233178348246932288,0.031137662899814788631,0.040942389685068455996,0.098453932872561641942,-0.0099872116054381902123,0.047977304132526876757,0.098565631690198884929,0.13750339513911000178,0.05739943373918272862,0.2197762866667699877,0.017027095542906954539,-0.10557147871747779577,0.14547908573977882951,0.042214217500041582853,0.015866146047569546634,-0.014730114399105315517,0.21929131684770455935,-0.040120756463415521709,-0.057095492866831423773,0.047976449846638763441,-0.072761703564645299758,0.12848712054725727749,0.017881272286668633414,0.039427720134228023963,0.063842643371215659909,-0.2387515442595508075,-0.082414859939715562342,-0.062762065933932575934,-0.098313589634762471592,0.052541715647670086953,-0.10327306783908259125,-0.10736322054163392747,0.076513850937886651593,-0.085510161832214062749,-0.18036606457883019861,0.0015272043508058850969,0.12419075563896547765,0.0086789438991750622598,-0.11728210612607942176,-0.10037219405349320778,0.12640114845417710354,0.018055073971531589161,-0.079555974698207618245,0.050493744035184542907,0.021503336914377939315,0.037540162971975300776,0.10160984789648683235,-0.021145712160456697076,0.031405899922614166631,0.10448954225437434573,0.12259920788371453382,0.062322296982367283991,0.24350722775742569826,-0.001971394971538231386,-0.12138945368328549201,0.15611779778352818937,0.035487776828718439748,0.024488540685465777502,-0.0087289332215680585231,0.19747426742924306664,-0.037940158805528638453,-0.05905794670850386674,0.034618403262800370723,-0.053872750043729059066,0.11655202038798327668,0.028963046267872685074,0.039563891520157670745,0.076343522101657415591,-0.24931524008456959485,-0.085666975081705565298,-0.068804314019559886795,-0.090933999180084032488,0.058900366067072384979,-0.085672994313175807046,-0.11843655377954140362,0.078427508036396975655,-0.090302415019822751541,-0.19008070440480659413,-0.0097039093748918000409,0.1030535887023720093,-0.028126744045952993545,-0.12291564135820343129,-0.10459767213619462767,0.11990550262087386335,0.040016089991398266779,-0.074431405457590027464,0.062958244279167296931,0.028890174095555391093,0.025466087130532999439,0.093072171994541180728,-0.028674231136799857578,0.053575203799839120344,0.11511090839192013313,0.099332244738170982767,0.086384385111733713591,0.22387272552566769845,0.010307546590664538877,-0.14800665696876022515,0.15751685537118625957,0.025361115130521069694,0.036583245541120898436,-0.023001917811852321677,0.17513057676926080397,-0.025091171401801330709,-0.081226971804214440076,0.053004790023987398417,-0.06800586171767539212,0.088268279646241551428,0.032730951274384544047,0.02113730761495580604,0.096696100547650473689,-0.25264612863343233196,-0.086490957234782631091,-0.077320322546524322682,-0.074235959195067882654,0.076868265065652072177,-0.087240055863907567391,-0.12077539450928367892,0.061393939291618390697,-0.087339284379670381608,-0.19282216867253804127,-0.015283787163392247715,0.095211732827071571261,-0.044710266168607959436,-0.13765726560216953733,-0.1030421122147105184,0.11517795447118940599,0.044489973393852459693,-0.070344633466378342357,0.073428477900617947216,0.011976567438685626482,0.013858132377207376881,0.090558210611744058283,-0.031857547801427466005,0.0583923417767193767,0.12167751001711625547,0.081086711914990658445,0.11166030158951455176,0.2401425519700906841,-0.0049410963748290955694,-0.16682454986237171823,0.16697432252220409388,0.0090309783470569737068,0.036414483626132018723,-0.021973278519527905672,0.14101189505874225927,-0.035681280346466261177,-0.083688175263296055162,0.038183939564821953172,-0.06622745096619321592,0.082382784110554233004,0.039714045163920269621,0.008624768616562283538,0.10914193560236487568,-0.25675888853282391455,-0.08598603219244527196,-0.078994632104076506485,-0.072446056619565338264,0.080846182956447520951,-0.093444157517061268714,-0.12537746601803140267,0.060195058622386492242,-0.086738320529430215644,-0.19124854188092668683,-0.010627692994961831022,0.097317776455950619208,-0.071109974286648891528,-0.15623060243534397928,-0.10746364255206827809,0.11952742213667921778,0.032668387081860969512,-0.05805705293923196092,0.064191482927848125817,0.00070638534141993693932,-0.014150741557308152418,0.095021480043518846692,-0.04003247560814241629,0.057893208436299997688,0.12602458140156544419,0.062593482228948962853,0.12355602848589757048,0.24905558224101906339,-0.031488810331576709556,-0.19502943288005278322,0.16689949046632462926,0.0027514634991575685763,0.038431891021581121581,-0.033563327135648905741,0.10012806509430788315,-0.022777762848617013475,-0.08223594602867131953,0.047760183647065489188,-0.055233113188847424158,0.079433220203352944422,0.051807363577191428705,-6.6141336854033195083e-05,0.12266203455916650789,-0.25530932637130282492,-0.088436242793915820215,-0.083603728501079513369,-0.066096123950739812947,0.094548592393978003745,-0.089449138501041206006,-0.12903711085922112134,0.057509956164779003907,-0.081363601916462066632,-0.19859292511684165095,-0.0066271165840884353401,0.10004011198246885728,-0.094421500982685258041,-0.15166562244183251495,-0.10895065817807056407,0.11946318887998598479,0.02699124821965259019,-0.050193302913559674494,0.058858263308449405848,-0.013948359134373757365,-0.040719561345283081244,0.08578024555019100883,-0.044304995544933757634,0.044669126237531504853,0.11999216275919559471,0.038278631606607792237,0.13806320578596867343,0.25225136407683096396,-0.035410421960940303976,-0.20759485820356485264,0.15119701087171125153,-0.0075694442640101052694,0.041402741496568348789,-0.040449089737404873846,0.051021631223257722654,-0.019787032199009815109,-0.086826834686507439742,0.059126914047333417601,-0.055601198719878688892,0.07082726565802283103,0.068404552457877326743,-0.0097203842831501945793,0.13269635403604182478,-0.23960862203089330902,-0.083879667191816012495,-0.090564769176387449612,-0.060310748631055378921,0.10999924328393435868,-0.090159443299139316319,-0.13991266013448511174,0.019027700899720292882,-0.085694417099937567062,-0.18571569307508214997,-0.0050057132537725109941,0.091797989763632042992,-0.11180241031604090662,-0.17155804996638893134,-0.11203071902831833462,0.11441660042381437967,0.040395515493136045782,-0.037114053402104323076,0.059414904171724305937,-0.024691705654344267562,-0.065271184012207245084,0.086566347598834636479,-0.065790672858482016072,0.070149933880048587209,0.11862175752601884782,0.022180180849769901008,0.14463907690032001829,0.24090588937038917572,-0.037412201871010963838,-0.23394192474147373906,0.14405435723946719007,-0.018992579454380029147,0.049938013864675508124,-0.046074572139504228752,0.016811073493833011971,-0.0084590938182161172498,-0.080083309728041743303,0.06281077500440303274,-0.042417479803930062399,0.081191553667342070133,0.073919957637469668743,-0.035440227649818897837,0.13382325420216936718,-0.25006072049251115708,-0.10066264764222239425,-0.09929324877548055539,-0.036240328243272536268,0.12297419169204795719,-0.095394206286094074265,-0.1345499074411169449,0.023071246473176019315,-0.079207873463907688127,-0.18464725807247617251,-0.022266234634177282936,0.10042546330797551268,-0.12616309810143719328,-0.18475795279608805965,-0.11357521761140293437,0.10392400187668460187,0.033562842854188860986,-0.036988634653097603178,0.043278169842958465197,-0.050948893570053957469,-0.083316583862454718368,0.083272951462559724467,-0.059402487401950233858,0.064061266415487247428,0.12419678834027987613,-0.018266867852609648681,0.15801370451223553659,0.25499649287479358994,-0.058395207096090646914,-0.23856325194330080253,0.14161271630862962145,-0.032194362471153190053,0.050044861245435140473,-0.055610356845154682026,-0.0068357556939615798236,-0.01221599964670782093,-0.087808035683565349716,0.057848911669588942708,-0.026300010805595130936,0.075515492194114783309,0.084426327491542954573,-0.036597137558716720529,0.14411731435197625006,-0.23254460345628272244,-0.098880913808747639138,-0.10392628533113468237,-0.021550360666471320148,0.12797366689788339245,-0.094799413300031484808,-0.15154557305707297421,-0.00087602365310858281138,-0.081589709177015898312,-0.18409461913909211384,-0.026900319100634832725,0.11475466697334255062,-0.1299578344169711186,-0.18897440334187673439,-0.11665528875533513753,0.10329749837071398877,0.042046316542351545864,-0.044510435566964524912,0.044570069605963553994,-0.057398237276124211559,-0.093432199349809674782,0.078519988250449312961,-0.065751149503951542008,0.073433498151150133904,0.12871603866156069995,-0.050653519317916374798,0.15523060651983655589,0.26340864809807296165,-0.08184552965752564524,-0.24829224456235313157,0.13635155968066059451,-0.052050462473445156808,0.053901410459761836536,-0.046849223271679743541,-0.037264404757101708687,-0.0081647630842327772321,-0.092502954357368855076,0.061870453957613556761,-0.016234220242992043748,0.092217794935558150549,0.092257811559866578777,-0.052088178062681421421,0.1609245076724069301,-0.21920663712735022344,-0.1146092021721229065,-0.11231393301284790798,-0.01061904744917670923,0.13741840620963091668,-0.098860062950935842507,-0.15059727701281830359,-0.0040969511322905350151,-0.075138185192963793946,-0.1967500813514543867,-0.024878748469986444736,0.1269781963036750172,-0.14040090428795493072,-0.19526624218085866791,-0.11817500141775630351,0.10384291968469532008,0.030683759815794520165,-0.05252379110927996031,0.038473243600908056672,-0.065341568301006153208,-0.11258693547403951507,0.066763540974717677789,-0.075547990723888694409,0.055699768028660036345,0.13499384679432840928,-0.078240433136449419327,0.16144438684998271838,0.26291526262807174419,-0.092726873020359742994,-0.25847772687487996501,0.13103730806757721283,-0.05322911259308999582,0.045893081732334799205,-0.050065473355025383317,-0.06733105192063972011,-0.0029170572432247999194,-0.098469915015529943525,0.070528110036118696335,-0.011502785608427894617,0.093317911694676666801,0.10597308242023258107,-0.048471637039345601139,0.17639313014895352527,-0.20521795088306901689,-0.10991750146147304112,-0.11454143855751590386,0.0039040340768845206883,0.14516104365854326508,-0.10090928318423475485,-0.15816424019367761322,-0.0056489020566831511447,-0.076953747524874618891,-0.20095792349401414567,-0.034116207879212816223,0.1248141531960283851,-0.15463553861027234948,-0.19908952945623123454,-0.118409316467772599,0.10452403425446478435,0.039465886545953919595,-0.053051606574272477945,0.03326749585543353066,-0.066926474307328218116,-0.12867149190758819799,0.056975931030481180573,-0.07957317982741070328,0.05702377711885189826,0.13601044538462578326,-0.10627062020961321187,0.16670429061672220605,0.26466450736746099937,-0.10134844363808011292,-0.2677235787209480411,0.12478881899503592445,-0.060460746728165266906,0.046246705724628460465,-0.065424507327589670469,-0.087230691240592489466,-0.0012268667886882540959,-0.099826547974092155746,0.069553214981347463719,-0.0041518711565171062539,0.090198830525484205434,0.1081477461583814359,-0.046317725147588126311,0.1921036884773699438,-0.19446220422586471543,-0.10894544556784163669,-0.11635257688266058274,0.017898430113837810601,0.15210650210276402405,-0.10601497196577837345,-0.16572964443296364645,-0.013282941353186064962,-0.079772809297980265542,-0.21080488458232973792,-0.053211919736930290981,0.13322148090725902114,-0.16698373420337492279,-0.20745735367455561682,-0.11837473710576172647,0.10626857236754247427,0.045182150061696700616,-0.052249315509317509343,0.033164901399960838857,-0.065645888798868540226,-0.14047943424517783662,0.052301556633918132311,-0.076826644840504124123,0.064043725917071553377,0.12984459926532024299,-0.11009905781910710176,0.16660637609292297534,0.25601477186850996048,-0.11434070411294262881,-0.28224076387303098645,0.11127247816208087061,-0.066476733836679499645,0.052222425997929040886,-0.081179330280819569921,-0.11126835723305485149,0.0074544781708179479532,-0.087063943458985160184,0.068153908316218397845,-0.0001118861891199365681,0.098752740101028718689,0.11288586339249512269,-0.036048729162402551318,0.20440688617540694882,-0.19113854463040447218,-0.12373273904951807844,-0.12276301472315458152,0.019841370164073744708,0.15679415317255768203,-0.1217771257506422844,-0.16520527297582143778,-0.030693791684096680128,-0.087067226141098602588,-0.22021508070543294178,-0.051030322411669340466,0.12979113681247536616,-0.17146377734383702607,-0.21658174727080922728,-0.12612752861130280269,0.11211728028207595953,0.048097597749586204485,-0.060753972771500491801,0.023699449665424386635,-0.06347391741148461497,-0.14176795068291889179,0.031958081662785228771,-0.085592071896387081353,0.058868571091632446168,0.12193466378369768877,-0.12230028429563165326,0.16649663251092003402,0.25158597436224761079,-0.11290228559852186208,-0.29585935081532677149,0.10113358451283072093,-0.065087326493702066244,0.070862755527355242302,-0.088069643123717455957,-0.11116260418324661052,0.0020911244982839386104,-0.081089397060817955398,0.071568047307759119491,0.0098279035972639906815,0.10466436606601851877,0.12299147489484704709,-0.037397756101571179299,0.20352992296674529693,-0.20116216497382105599,-0.12702955307964625131,-0.1272514412390010341,0.037508155186923193558,0.16450239598722513068,-0.12809862943610161867,-0.16663067263789821393,-0.027244663460296268676,-0.084824653103185584935,-0.23079596722389136843,-0.056764787252102301418,0.13668852428547439981,-0.17858006979670057457,-0.22655015051311860885,-0.12633985091807217738,0.11686079899171430974,0.033399384331443356111,-0.058572038451186546337,0.016644407256727115213,-0.063435428314522174231,-0.15189375989055586835,0.025299872401912011644,-0.085056508381124662499,0.05255573193953584632,0.11789627044777421794,-0.12516910586437407504,0.17544277421045284537,0.26690778668994680212,-0.12894883999713796507,-0.29342287016610202333,0.10242999168314341485,-0.058514179152639220205,0.073644430520693346387,-0.096544095426628770418,-0.1300159393621529158,0.0031268238746453309168,-0.083107651183045819221,0.080559926336475642938,0.016998745255365120543,0.094788615301230949584,0.12865554579231527899,-0.028972383365255951343,0.20530701300137246812,-0.19652754620741372249,-0.12460537759595559371,-0.12818801835663398703,0.043521979287675684189,0.17350269614569566179,-0.12701581540853551511,-0.17961482271862042048,-0.025321987653048431965,-0.080057945667052696215,-0.23790243828708790286,-0.075047294634121380907,0.13498824308764745261,-0.19581059753993046435,-0.24677874230895943675,-0.12705604592794789154,0.11172909638135111732,0.018387562302584890828,-0.05697537793651083482,0.0086956342169400534237,-0.062447119134887672798,-0.16549267142158896604,0.02938034067875059871,-0.07078631522103506768,0.046516409482527776298,0.11687525097125807394,-0.12615107336282943562,0.16987559127077864196,0.27224457016978631518,-0.14765341525617745044,-0.30078786393240281027,0.095789247486061879222,-0.057484353229875918834,0.074330687604458087203,-0.11024978472731243595,-0.1482839767410377152,0.016448717269805075702,-0.080927966005691368001,0.089454384765107489152,0.031080099749785858321,0.090046842960848305637,0.13925343634727538333,-0.038894695594580835918,0.21877122142377683489,-0.19971640658979605831,-0.12816542453403120816,-0.13640985365737773316,0.048791174980680404594,0.19670080505731238341,-0.12841271997896192003,-0.17821790163616629821,-0.021340611088919072408,-0.079870051084627996518,-0.22847106544433359865,-0.076920941947836010688,0.13328653462073244973,-0.19473807271914972405,-0.25748657690819271027,-0.12734201458144789321,0.11035929277620359912,0.017786265938350555998,-0.053003350148401129349,0.010566196515397278596,-0.054911280035459544835,-0.18103057814174006168,0.044120356993381959487,-0.073341853031071338465,0.048759810422586237488,0.11737947965165267117,-0.12251491738871495008,0.15821023961879376873,0.26610108018641165373,-0.14606360002277193888,-0.29465715485642696159,0.092296710561446920762,-0.058106595613115111232,0.06122843934544325295,-0.1155095523518484546,-0.14964426845936659727,0.013875171356527056521,-0.077650833915913528016,0.07255557084281132052,0.047848709590792834478,0.090296306961781189204,0.14031587987944041385,-0.040041438708286296311,0.22923430731674157568,-0.19608204976671686492,-0.13307384768486382742,-0.13643198240776149843,0.044714241980674085397,0.19754637857800350087,-0.13714027616332399861,-0.17580917543912621959,-0.019156582557339599943,-0.081181575668518801692,-0.22467615147714467549,-0.076663018954912523495,0.14065890191339786019,-0.18896067020172119255,-0.26255340088971862444,-0.12912852693153015204,0.10987743921152270943,0.015385774522949341447,-0.052037890913148379668,0.0061618477647458020849,-0.05363798419805309442,-0.19093126300874754819,0.05165628189031534756,-0.076512560741747545623,0.055831152563308034109,0.1197815472349517546,-0.12051348300631238575,0.14418562872093940164,0.2623588409098210894,-0.14732410619440827748,-0.29309966589660468861,0.09101680541439387262,-0.062330357879116449205,0.053331919357938607773,-0.12074526094762484674,-0.15773259913881287897,0.0092957009909901654188,-0.078249973419215135273,0.062898446499273660826,0.057362048946687213546,0.10693344885386341092,0.13882707261920093633,-0.042895984855228851129,0.23423811787347822988,-0.19455471623414091753,-0.13512176480597615225,-0.13658608159154334016,0.034042438789408255295,0.19610001842954852269,-0.14926114424008274373,-0.18639701677067446739,-0.035568243217345869855,-0.079554199416833837333,-0.20714682484486920955,-0.076153422851573060459,0.15025201548205546764,-0.18903181073978836402,-0.27000712545977312296,-0.12855463973923525467,0.11721838027303317642,-0.00013584205613421658325,-0.046684660044319432892,-0.00064903818170731109212,-0.055570202629056111854,-0.2106052786599586224,0.075142086516365141913,-0.060721444422667171514,0.053424975927740661619,0.12208412020548883858,-0.13103668970194548571,0.12052596396431408676,0.24775137960777404711,-0.15718937927487799944,-0.28627503781765850643,0.080781107010953742686,-0.069574576602111526391,0.026109050320846524662,-0.1207494128838910441,-0.17291064659935709291,0.0062040278619759098994,-0.06705797546241798468,0.039192510483446504899,0.087375569405563555114,0.11463769045027014104,0.14467914216028690544,-0.026400311217595846813,0.24956535007946886728,-0.17116339754972589859,-0.14601025146360976925,-0.14602378929606435465,0.030056098235823162923,0.2139280781791515762,-0.15663704263137739892,-0.18334539678267111618,-0.041913775694203125877,-0.084148447323470959569,-0.19850709707360275624,-0.079720501636457191674,0.13708965701154657291,-0.17971101294835398199,-0.27286491689580216757,-0.13673745665278161376,0.11483169336269302696,0.013577564320640025247,-0.050587490286788820704,-0.0014729597593039413673,-0.044056983427747227478,-0.22913281999110748921,0.080045883651588198293,-0.06109554330598688382,0.043590361257036996934,0.11682601692910712932,-0.1441488763124713357,0.1186982444270889836,0.25612211696300274388,-0.14877350886787646389,-0.2842104828828687646,0.073271127102925506791,-0.074066362974938862451,0.033189131694807125217,-0.12569860915041380922,-0.18976505402326782068,-0.021159187851574896844,-0.080375848553166401311,0.02347808559959565014,0.11539597772047012481,0.11023607567728987977,0.16230212283551181951,-0.034887956031421009373,0.26071565699613274969,-0.16701185407423890794,-0.15303699002124424022,-0.15685633747953464656,0.021286436891778837133,0.22513871748675703954,-0.15804559226122852356,-0.18889041226797387285,-0.037529657411848549309,-0.083346100531200492667,-0.17428098812584144617,-0.08169827969228556086,0.12207969640682046764,-0.17005165661303203728,-0.27552779315590908427,-0.13931742804460439666,0.10940666086822800618,0.01612581446599684748,-0.040807220307482787447,-0.0052934995076082862545,-0.0312598532820548905,-0.25013566558350103231,0.076120980667033460998,-0.06616000640958413781,0.04723478989542371359,0.11460026585356929141,-0.16500811431966513898,0.11360887039864331349,0.25915771464475034769,-0.143687771505480677,-0.28896174488629577937,0.059543567001347191825,-0.087934041037389859552,0.038709052936264719269,-0.1360536583381573017,-0.20720146864781407992,-0.046209129461958278751,-0.091357284843451097567,0.0076791588733136594003,0.16131396611127701846,0.086479676278913578114,0.17481900307404382722,-0.032027548081291379312,0.26420358742525296147,-0.16747407965316296607,-0.15879419310462358772,-0.16569804003042867824,0.0078992892522351289275,0.24387362788655886359,-0.16511187347426828365,-0.18988026053995366027,-0.04998053852054608337,-0.09470950902636801616,-0.1333474017699679548,-0.074581728193999302645,0.091676828914459149167,-0.18853739127728461056,-0.27875154967584098165,-0.14413720192418263966,0.11237846778795769487,0.029412274263995241003,-0.0041796316567070234543,0.0028671476604270476965,-0.006453297046094551119,-0.25682164514604682859,0.082239975195668224561,-0.087193633126964126268,0.056313823970058768387,0.09811209017831033774,-0.17424663418073479959,0.11876457147720703711,0.22822827096480630127,-0.14185920615753877527,-0.2788330173145819324,0.044040871895214737941,-0.091172397283369968624,0.045540057014700145721,-0.14307689124851513673,-0.22623717031981593895,-0.056529845840962135439,-0.10310585430614967184,-0.0014705607423407384554,0.18816820085991703415,0.05861945310162381545,0.18521378900349999563,-0.014254098869619405768,0.24506081950999911157,-0.17215582858216876838,-0.17856781181953368387,-0.17355874182900499214,0.015844204765000015345,0.2494772249279592069,-0.17308767625666546253,-0.15401960570927553107,-0.04815246105853890346,-0.088777027720965837054,-0.1109120370156314872,-0.091749053706213473669,0.073980326767550730338,-0.18972414478393045956,-0.26575645845049389315,-0.14545048092289095121,0.10136065206225415569,0.029745956646101173043,0.026435804495835428518,0.0041271383384748399833,0.010933364191199371543,-0.27121038833364591314,0.10424025470337408561,-0.094998328450531008271,0.025926561282197942843,0.09055664769377158585,-0.1544732467384017649,0.15307586320380517364,0.21112541037514412356,-0.16191704018104924323,-0.25681248454497668243,0.041504458809972874511,-0.083660318335467359629,0.038892504240268910287,-0.15475305704570552212,-0.26598155908328746655,-0.084081303973156107379,-0.13989865362323863907,0.0048743503812809863343,0.20270251871626218665,0.013993365441167726279,0.21385057779109073461,0.013398385527646772264,0.23603877837852210719,-0.14156735558266531072,-0.18436215605477127011,-0.17993042570389050638,0.0082534575956230878113,0.22941878287935157932,-0.18069968656815602048,-0.12575088400074849182,-0.047401755222053240657,-0.093450617984252110082,-0.080308678269982905484,-0.09831110247187917206,0.03207072243436809994,-0.19719221741631903777,-0.25262152857333991518,-0.14527497753924215051,0.093146632127816958446,0.052203999417051095977,0.045838391771634547089,0.025572567911488753439,0.033719941714370794961,-0.27888724071292964046,0.12304963328636998876,-0.0905193567654674347,0.041849034827394999969,0.074949576086500324656,-0.15039445492716407848,0.17094463277039328997,0.20489009136911401354,-0.1508301515714603469,-0.25261999830232517716,0.038613005365336877661,-0.081823034755962364972,0.044613798460734627183,-0.17003663785063694025,-0.27093115767500042246,-0.10986659391402635311,-0.15117160229236223379,0.0028042561188384926285,0.21284263739602576893,-0.010604894230942137068,0.22445890284909661427,0.02181331929070487799,0.23253626665646190408,-0.14779258606470524473,-0.18682331272205149331,-0.17983889529012508923,0.0015276529886068394067,0.21062793540414537219,-0.18113753655872449899,-0.12304114617025094236,-0.032305073055776241386,-0.091623418459882838283,-0.054415072118596460871,-0.11408555197432643236,0.027490950312838331737,-0.18898094490414252267,-0.25668516093415394419,-0.14412724817050670545,0.083039409333255750911,0.060129413818844221207,0.045254319990490114722,0.035180779823186854316,0.050883076669489137045,-0.27009368950926510022,0.13829312193720283419,-0.078520809553906140144,0.039568343888996708457,0.068902262708633005284,-0.15879168121452066909,0.1454335882862616558,0.24136878463096436698,-0.15989336329356673705,-0.22517904186941381517,0.040082852769300174323,-0.08904461070911802445,0.049655551562324283521,-0.16898515799443955543,-0.27362037741946421132,-0.13839136088221731802,-0.17278499572963201825,-0.022188333719968502539,0.24490321337271686586,-0.0071607776442756086721,0.2325067981756268054,0.031338378082146407799,0.24325253788898992813,-0.1573563592044210091,-0.17399442258199693256,-0.17287969359843927131,-0.006629730099031528115,0.20929774618416219223,-0.17786675418569175555,-0.1318467624809346872,-0.021008594915196909803,-0.088364023078279160806,-0.045301118273501451983,-0.12152399910124950244,0.019980536895744912401,-0.18948045879156977245,-0.24781921122654798628,-0.13807940791292053206,0.080858994657919514015,0.059070731888683822297,0.058110903598000598902,0.037972171941767572656,0.063553807951028815082,-0.25890558538025637558,0.13569099320513974827,-0.070134271629622199629,0.037539722149948537289,0.057343386024897607944,-0.16286009118009742158,0.14847919727839381521,0.2571065671375371009,-0.16585738732308705212,-0.20226093266365111067,0.029582743824370181379,-0.082008736175149365977,0.049981814282328132504,-0.18499361384591048174,-0.26454082681789908849,-0.16627348150651430347,-0.17348203139836307352,-0.049327877611858826634,0.26769848115148942025,-0.028173664578033833644,0.23067679019633391402,0.048420989642772679917,0.23936149075516827134,-0.14879729690550061449,-0.17053058257579989387,-0.17002782843509051114,-0.0087863388499902217443,0.21262538637648112361,-0.18508087246156781913,-0.11543276800620311251,-0.03361986106261759949,-0.086958522506001792451,-0.02777424812313709912,-0.11780919614957907626,0.0053402433425548522655,-0.19366413386928812979,-0.23370791718274391835,-0.1388147266352751652,0.074204347822115893085,0.052536779268934123699,0.071453229631828402146,0.034106871017912737676,0.043923803958601952135,-0.26267410215840475418,0.12664947406281071296,-0.074545919225837906086,0.038915059928319867266,0.045197970907623716275,-0.16375118516774728183,0.15371985278406063991,0.2754156875538892324,-0.16556259913383733484,-0.20045492863596553468,0.021284470400135223345,-0.091430595572689704609,0.058636599584545923136,-0.18950746203913060306,-0.26707797328862981079,-0.17770601472314184743,-0.16604937498509683702,-0.050613877634455940735,0.27288050674804509299,-0.035028052509448133478,0.23764531830672316892,0.048919776614811567861,0.23004928896531376403,-0.13298259965500602853,-0.18307828121442193403,-0.17247522034737466923,-0.014009360120961038276,0.19666587543847255382,-0.17790176625855522174,-0.093852309270974390576,-0.042058986367963291375,-0.085320022589434274529,-0.016246254179305967547,-0.1195670595975362599,-0.010125341412789276227,-0.1745566476063895589,-0.20672712041475629907,-0.13722276160034965753,0.065363063603247020805,0.075982080613856806117,0.068399688041616377165,0.047716753552106236369,0.040437178147209512646,-0.27184189556975457691,0.11898737569153282345,-0.074011687441905588125,0.050319570197463317496,0.030990016540822819258,-0.16770271577143006092,0.16756369051151098759,0.29143331513854242587,-0.16393705409748965396,-0.20621388868527290583,0.0093660217375602476675,-0.097979783665173084128,0.083659693189790093615,-0.19256979298766926934,-0.27971470855714930526,-0.19042082158365070121,-0.18421449050756971699,-0.043088667613319510397,0.27080434831798111395,-0.042604250368016120809,0.24832520987030640147,0.036112462480384834029,0.22146502394147193904,-0.11707238873458361561,-0.18105930507014950104,-0.17084877899811751201,-0.021244007031497695592,0.17562555674469865208,-0.16833314988540543089,-0.075616205595847502119,-0.059205455822221551843,-0.080606791292671953197,0.0073891735932594222389,-0.14001258661854151799,-0.019053411851546058625,-0.1325847448123233796,-0.17520788592689132135,-0.13035228192807793435,0.043323467874289652013,0.08535341619075893782,0.081145128353170253854,0.050384599139771987786,0.030971848167406546698,-0.25492406398967187853,0.11401718185386096327,-0.069252510686924131922,0.047810849321655232713,0.013416194265022420018,-0.17907050652677147795,0.16257011657355563417,0.30480994279839573879,-0.16985146399441333753,-0.18487266328958462669,-0.011039267012343791097,-0.11149364401639233479,0.10885038980964602262,-0.17600688307842790592,-0.30029165729203166624,-0.23530475405025075286,-0.20195329684191704045,-0.075619515084384289483,0.29910413710097633055,-0.058797828884898699353,0.25791210552293364344,0.049832997609702882336,0.21434167066729939433,-0.091605745452023781827,-0.18302398509969958207,-0.17031621461280840868,-0.032310214682809278164,0.16014496597864655292,-0.15699327128597784231,-0.06782085493038714219,-0.058594758622136901283,-0.072442084813132329169,0.011458467120600585032,-0.15070868903883685719,-0.021221729720817306825,-0.091186865487910884198,-0.16006273788446023776,-0.12048316659098642911,0.028277626842069272101,0.094202664971328162191,0.079530260396926732991,0.058624660180539682475,0.036189865626610751015,-0.25262241909174715238,0.11339324517576578055,-0.045207593873696008679,0.045432219365337297989,0.013016387722250008854,-0.19359745719672458164,0.11219053323550808032,0.30222438740614915309,-0.16173660230860423259,-0.16939447011956404454,-0.019417960060109207276,-0.11647549699555892477,0.12313543537346005596,-0.16295672128229318765,-0.31976698072716119858,-0.27930634890646649504,-0.21332640842164871109,-0.13635822251545995365,0.3327021978662222379,-0.067408958535858543026,0.26596545089100825932,0.058106645095838321824,0.22950501602786010924,-0.099180290582303418101,-0.16154610965300605918,-0.16423310803312701767,-0.03101169433778926815,0.15508687770968851427,-0.10547249191894797482,-0.084885771745699875601,-0.083180873865301749315,-0.065734108934173043903,-0.0046807560319168219423,-0.1251062103173126161,-0.021862853874839955487,-0.04304953397790167724,-0.086534229150530217467,-0.10181374855737811147,0.020648627699629329424,0.11210060394633920844,0.12393038112779786175,0.056270459609237398479,0.017868576950729523484,-0.18503740981641950136,0.040952514433013439965,-0.053185680486709269177,0.071584924769023061675,-0.022292478388360001396,-0.20110409530790196442,0.053936881701987474114,0.29449789096340778238,-0.1628410399928288399,-0.16682543431138574519,-0.043818461788858148465,-0.14758697101504619775,0.20148715265596170432,-0.17590123668637355769,-0.31445234026557217222,-0.35036574604214149042,-0.19080964503726671744,-0.23358497578924314331,0.33054867610971244707,-0.093320724239576602344,0.26181375512370935743,0.037888728096726172201,0.19006273473618728875,-0.12323269686123390632,-0.14613808362090435766,-0.14756890991613785813,-0.033989979402639737549,0.13931663488776635518,-0.10657907192693294451,-0.081460912614076105842,-0.10889312727586794582,-0.073687290868836380353,-0.012052489764853806589,-0.11443467590431324887,-0.03066633215109438107,-0.042271273178554946703,-0.06351767292472812465,-0.10898153101575661084,0.015562112387347925777,0.10571951058480810737,0.15174483225802962161,0.026442404846441173311,0.002106570289238960357,-0.19844976755951745928,0.022227946093842480824,-0.079753372017390661286,0.078625806989364124822,-0.031876697773661796798,-0.19528232996115299502,0.031838758459124517908,0.30581915603099762979,-0.16899537478796342049,-0.1558805951470794704,-0.046269413610850053387,-0.16158177127516254457,0.21726228687290569108,-0.1886028920030743683,-0.30447632896114984469,-0.38643342860467311262,-0.17887312961018711488,-0.25600976158110877456,0.3485244214992581635,-0.12785835006366222388,0.2497749721618105212,0.026585048172431242908,0.1917922242462519189,-0.11776989930508430238,-0.17578193204338340982,-0.15777083811127703972,-0.040790121419963611127,0.13404715570677666614,-0.11510403431667724783,-0.081598613721388602027,-0.10424084217907318706,-0.076779060113077737815,-0.016163700868089964091,-0.097206521097307568846,-0.042630519104589724433,-0.079956157949735595647,-0.047006540100299289142,-0.11175096478614147955,0.014867882926843442939,0.07928170928107544646,0.18798876911781989274,0.0082240274135781214759,-0.0011457149612586795765,-0.22011883275826207851,0.024346911924828365525,-0.095443907717843751159,0.061470438137034497106,-0.041371058174513287986,-0.17024772914337452101,0.0018772404567793002199,0.27815407471431580211,-0.16395300904872911474,-0.15082571973948391553,-0.056341431692481673543,-0.15167075357154138904,0.19897030450945837887,-0.18449555191382774333,-0.29192400060971412934,-0.3689640787627110341,-0.14990857136534402327,-0.27620728140777017767,0.33051787333683257941,-0.15081883985627744793,0.24668602565238112456,0.041595270406108712791,0.18375818300149673878,-0.085952860017140822468,-0.1849303445224050324,-0.16019745269479865324,-0.041458459149206670913,0.13567658852829905802,-0.11322343931140642359,-0.094038098808287090558,-0.12047792230518007683,-0.068322504515989201934,0.0051768061690175412246,-0.10065201380300700662,-0.050042920702091132912,-0.075077320132997046875,-0.044191547001595013477,-0.10570645399497273498,-0.0064779621993275139993,0.05974630918723352474,0.22258146808280368512,-0.021215836613605265626,-0.021869487260482996238,-0.22602688193985034926,0.027457461157702638122,-0.10803231832736309714,0.057756309384457124589,-0.026541368996327325408,-0.16660874733779473811,-0.0071445208096451275417,0.26768968219577665701,-0.17354859097233726883,-0.14392157986028764061,-0.06214775341164619632,-0.13885094117532681413,0.16727389710204243478,-0.18489512778635242007,-0.29736390440923987644,-0.35976677071639845407,-0.13599745262884038732,-0.3072870626309382458,0.34523566546515899178,-0.15873326454313085865,0.24057291956692791746,0.036818616735052031586,0.17141011429701236146,-0.035391338029750980809,-0.18374191698445102583,-0.15676169529572756001,-0.019016548423239805488,0.15157110901011652815,-0.094102495587182130588,-0.10883918483866696081,-0.13958815545686026338,-0.054341419502038856848,-0.0093954610148286425708,-0.081953684565610265822,-0.051899782313632875086,-0.031837005217579150695,-0.044623216457502112853,-0.090200698749755989225,-0.022792074039810223535,0.048942431547213643972,0.23237936387863986076,-0.027361528675278128098,-0.018365559462401325613,-0.24118684461320469281,0.0063816929904171463064,-0.10304525281633095113,0.076524024707458476735,-0.020196499586194609915,-0.1396867436021821951,-0.045404545199979412518,0.25615718642620088907,-0.15142267268610962172,-0.12276294994123911064,-0.063464932992320477467,-0.14423133621920733449,0.19013631062744670852,-0.17732674917276713966,-0.31006009650815335998,-0.33356202106413146424,-0.1355318018465379859,-0.3334545176800667865,0.33050893471376568966,-0.16552526393025479567,0.22855369649298531987,0.032673019546287894455,0.1518964541327009754,-0.03965555422954859105,-0.16206204912746444147,-0.1449507000203218432,-0.017970734637938343137,0.17714080468648049638,-0.0712414269310722853,-0.11233678685688672227,-0.14134882688705510678,-0.046215538482655776908,-0.038244295976218908861,-0.042707612224420918312,-0.042194892953366272548,0.013583057826240160434,-0.040353012018203557321,-0.083868355137106512243,-0.030085589607793485067,0.036350178576898636851,0.24941942856160645436,-0.029368353645889987147,-0.0055384244372218040253,-0.2487180488039375803,-0.032598578500983521611,-0.11011202278569059976,0.077222057216431966298,-0.015878906696278269339,-0.10483776737043271066,-0.1101449556546964248,0.22710966161038206867,-0.11050301760151355623,-0.088994573706710378147,-0.063962378188650387267,-0.15041634234628803446,0.2130531568084287064,-0.16621252664691024692,-0.32193862924961763605,-0.29314750113221571537,-0.15352076149232074531,-0.37660463323837567451,0.29824737990313149316,-0.16171591965323353635,0.2128410381294789655,0.030586708298104666598,0.11634907641146388646,-0.055325130481249769343,-0.14445380893511622356,-0.1373134791599908977,-0.043178019199420145102,0.18756817598326316898,-0.056811300085131133386,-0.1094031858315797634,-0.094406423631767738547,-0.053106484651378696449,-0.031239749270722573515,0.0054447847652096892715,-0.047830093213845681355,0.0087497280843105516152,-0.015209906446702215616,-0.081241908678997762361,-0.0063384233682060708154,0.039804615764796713595,0.26841621027854484227,-0.0031676714012642106025,0.014145489075262288395,-0.22009680528415095924,-0.058943092030631777378,-0.12442272831523941423,0.086189830243766057949,-0.016145648640176431254,-0.070868314953965866332,-0.14899932217133668444,0.21579956141899950262,-0.081233122480316832803,-0.10986421075186865448,-0.053981983343119467611,-0.13021305993213863617,0.19736535323448978207,-0.15010501967867478923,-0.29416035455389527575,-0.27722061646365192544,-0.12491015656682497026,-0.43015418089462381657,0.26545586099971457683,-0.17827696886649854746,0.18962724980203263248,0.032469383374361636407,0.086664522704208143966,-0.079441247024571851054,-0.14055161621544187689,-0.12895722684392965651,-0.086763245057773857871,0.15319786705013699324,-0.042754886132468070126,-0.11236011505192612658,-0.062953134223846074491,-0.058779851685436292075,-0.035883307450423257423,0.026720854033480841844,-0.059050461723278283022,0.022088906999292431954,0.01882755057397466833,-0.07434309391707183412,0.00073401687309234298507,0.053967229239794953233,0.26945483926970620336,0.014073501425179027816,0.02361740686023492547,-0.20726759260447447097,-0.077842733291387147809,-0.12298817651112561866,0.099187250179306213349,0.00041255282450282132652,-0.056542551761331036331,-0.18650563901249361809,0.19749878412547794415,-0.057748453006988678671,-0.10689195132387860343,-0.029314748516274368589,-0.097311229957296144222,0.18258886467338542037,-0.13860803311907185509,-0.27560819657660146076,-0.26906235867146571783,-0.10320817599566228795,-0.46767157491877220377,0.23294403417638889775,-0.18592007247201505771,0.16549217297845800201,0.043606630737725651792,0.060587419121581137516,-0.070657247576133161426,-0.13410331067394762328,-0.11899981154728642152,-0.09825490739294602538,0.13113572211446780647,-0.043295814359288913031,-0.11418590113811689923,-0.039496880972355555284,-0.062109411497830967208,-0.047175455055784847047,0.073437613418075919913,-0.071160353557748481923,-0.016750135245304650922,0.046421141103402188688,-0.078363011455926528948,0.012387842858488363335,0.022637221262792061455,0.26487328487040479041,-0.0020166979620845877988,0.038779664884374454026,-0.1974299854899491391,-0.10057609147629945068,-0.14541841470179273088,0.087712458625575875915,0.011999362917118977512,-0.019622622897576137702,-0.2029637624858114664,0.21646104406515698226,-0.037418654097205392151,-0.10361750181590356767,0.014379683482787179033,-0.044174451850921302165,0.15475844027662216673,-0.11423484064481793931,-0.22292918935004477077,-0.29319110204360432359,-0.081045883266383039745,-0.47814969338044721603,0.20782760434944064221,-0.2210034425872849928,0.14340901709931938579,0.042624804931678271502,0.038176910024051852188,-0.071687444218662965678,-0.13530404404192275525,-0.11688121306319418369,-0.090444294481006201614,0.12003733685217668481,-0.017857774063261080272,-0.13536615847674368651,-0.0097251688013541195271,-0.066953765161201855838,-0.05410105032193113922,0.098613983740585026139,-0.090299731309647732203,-0.022671769702399237334,0.037729547736495533394,-0.076871604084758973774,0.015826763193662690687,0.018938697295537796489,0.27651128970920479944,0.0061193222218986287678,0.065992453449837937263,-0.18622809048286090294,-0.092957007867389168654,-0.16085218732145314946,0.1110306170427580591,0.040809174607609431662,0.012516345326798274107,-0.24892359634321711837,0.18495698511457134283,-0.0043755790724495551361,-0.097989487364128616265,0.057766649188524109293,-0.024441100291515995696,0.15409568340175561207,-0.097543715710926029439,-0.1946738714501044798,-0.27548899352323469314,-0.078568259928122691216,-0.51259784946534081573,0.18490191481285569997,-0.24213569065091930521,0.11683255808021679456,0.02461543615645949909,0.028259992914976727468,-0.11439121785092623562,-0.13372823743672196395,-0.10951607553050544952,-0.09112785509351682689,0.12270805329278627882,-0.0087560912302087415271,-0.14113904662719345406,0.013715982919831101738,-0.072154875053074662983,-0.028018336642981329226,0.10017176460829897711,-0.11781624213685749913,0.002516110317225729847,0.045342557060458386908,-0.0725859724250268179,0.010987349877887100241,0.031363509006283048219,0.28470190476671480839,0.020172209189940577129,0.11566417809093425262,-0.14730057190487735874,-0.099909550601194108133,-0.15254500706748658212,0.15001288666570680719,0.055643213832826866894,0.068355886817091912611,-0.26878742681522971303,0.13092329747832193165,0.033568593250987342758,-0.10380483768256322519,0.079228683089375695481,0.0066192638030689171513,0.16223160184869930833,-0.088356122037251239032,-0.15462220979629440198,-0.2666028659668009948,-0.072446143577295452065,-0.5637344751816401045,0.15927451110489534991,-0.24969343560470613763,0.10182944305750599168,0.031777947764324993019,-0.015555562406376755372,-0.1222948232234202931,-0.12499417594123569952,-0.10488536855503548251,-0.098618233911047972762,0.13123374461651302059,0.0053195597302344811361,-0.1434163276497041617,0.042849931441296305878,-0.066253344852480633431,-0.049506324822856731527,0.1188370536997026411,-0.12562633396236608241,0.021706236481840147923,0.081830261878917120999,-0.066366095177965309104,0.0072422421283877954842,0.010967285720587712991,0.30658277593019062079,0.0066653055039204251939,0.11606206539841942837,-0.14788109322853615346,-0.1050768204040801318,-0.16205739867017301958,0.13851213715247215341,0.082455805385218156056,0.11056036773525601546,-0.29259616815828970449,0.07938461743951150118,0.049034836932710081092,-0.075771899860693991968,0.096338130877316255352,0.035187954358831326218,0.14122178191717965623,-0.066981627833661350202,-0.18286209477381440425,-0.26922500754632006092,-0.063950607766245101682,-0.5707209363735278318,0.13224547419402274406,-0.26814778584076925938,0.083649975878968024778,0.036362997765151040819,-0.030397760289459022087,-0.097242501763658950598,-0.10684950126485416588,-0.092446526721349536748,-0.10339416295911844912,0.14182002910904795145,0.00739123402892444617,-0.14412916534411010505,0.060950397653431132028,-0.069323494278227898446,-0.045316474699750065869,0.12544385039840560969,-0.15259093184322264358,0.031170365327015555484,0.089911567247872192787,-0.064815053963275234827,-0.0005931183267100853182,0.011858753332025242025,0.32319585038788783971,0.012567356381578371344,0.14589446974707814819,-0.15335053911475984845,-0.081728547925517494588,-0.16657820184259936047,0.15328924271409713476,0.093975586091150739576,0.15687619600485583349,-0.28766968483399552037,0.039296961451408179977,0.059235131692150326532,-0.055495105957507999406,0.11642003984888656121,0.063820131366017995855,0.13180835567259827079,-0.062427736904417031882,-0.18755048421660741598,-0.2677529935001296546,-0.071693793127290794676,-0.57482043005202965169,0.11696208238645779132,-0.28366012685639840907,0.073763136894600664362,0.027483591916769363472,-0.043919532101746976138,-0.098229559271256886022,-0.10523553371084876096,-0.089315417690723791777,-0.10747115950491871461,0.14250106545437846162,0.006123492807904890034,-0.13684876559179853794,0.095324209826543923607,-0.066452548997762123095,-0.069643393459417876623,0.14449587911751951563,-0.14987303288535569479,0.058617878098420853061,0.096845512874755679267,-0.057507734407676536215,0.0019731728852021759163,-0.013610446417888538012,0.32829331040977532963,0.0098531195433853926979,0.16697230960620981777,-0.14323222266353305421,-0.078132375131750322894,-0.15273520884120136976,0.15622074468654809087,0.11141387069242293661,0.2024965973487641846,-0.32102400221311916395,-0.028367473812366060526,0.076931379147674353036,-0.036107025070302570247,0.1316601478898353772,0.090699597725096281486,0.10286217610803480293,-0.057256668785200484639,-0.16460796418663306562,-0.26360691821815707137,-0.052054435573111131064,-0.61658374552779593447,0.095185716982149837229,-0.26766643338677098551,0.063005669382585977045,0.039966039951946495667,-0.06262259654043743351,-0.10360420840287452859,-0.096217292608501273077,-0.083610361912398886708,-0.11791210020702221073,0.12803718723192220041,0.015227109558917380217,-0.13097373097455969337,0.12278537831291770621,-0.06414082794787226427,-0.12471238808040219226,0.15953370467310365455,-0.15094719576454052046,0.053727241664116458242,0.11610259737766183419,-0.051171960921446213444,0.0076449877743573878969,-0.028159202373359313448,0.31093042914046598035,0.00057743663867421070497,0.16736073140661891778,-0.12182804188952973956,-0.074150009565422267399,-0.14717499869944156154,0.14138031261087138923,0.12855992412833602834,0.24912753275289131749,-0.32345828413689886593,-0.05842831491962372642,0.090118326292962916413,-0.020255884188060294809,0.14657357038628582302,0.12098693782102139249,0.074981067325578923399,-0.058167178634075757115,-0.095824432950209093018,-0.26092608849284182337,-0.030494758951641044026,-0.62132712777968324147,0.052740460647505683911,-0.27554942450489039452,0.038120545088609958384,0.027871410852462828733,-0.056350125913118595533,-0.086371431416385313629,-0.078269392835771375849,-0.070520756870832437824,-0.11911692506297670568,0.12111279725494761283,0.024210203354581027319,-0.11685425578192722151,0.15408038008515054229,-0.060905558897819192521,-0.15682767241445128015,0.17948032058748625284,-0.17869139510318782227,0.038667060567222535927,0.14748778109396840086,-0.041567045221622703211,0.0029645194654357620752,-0.04309351401325948322,0.31578519074203437178,-0.0078878898426942116451,0.16285864624762572128,-0.11857647666007589682,-0.08064997169327368931,-0.15628464183854856584,0.1163436510028368065,0.15615968779676742129,0.28221333843060936175,-0.3166221791488311732,-0.096997683269321566257,0.10682705034215284057,0.0074620379714079882599,0.16501416824637690772,0.14697658950400846467,0.037366537145979455969,-0.036097253893086954368,-0.083696584050712632963,-0.27509496068481897879,-0.010348119301350834284,-0.61130268989223246479,0.011773969275046512056,-0.31170901749063306685,0.015288072955939289305,0.039728667761452521323,-0.05420563649627767322,-0.057486982085944965393,-0.064903530207621462633,-0.056616143208709203416,-0.12311254688425468662,0.10507505561138182071,0.033290946254753407685,-0.12453566291949813571,0.16575648963465564045,-0.07577173606154305463,-0.14105391904491054733,0.22474822479581882395,-0.19094190893435863954,0.027020664765716521233,0.1812689563955733052,-0.047715944434037663169,0.020206484305897859377,-0.031550336598752615203,0.31991148201621877334,0.0013674028638092550116,0.17838066015020176414,-0.092189089977444640955,-0.093779704213486761444,-0.17975738841097138598,0.11134500227236632242,0.16616257287201696702,0.2776553397823778857,-0.34505806347649942145,-0.12337439647025291722,0.13790832953223822188,0.016216390412515421793,0.18164600146233136901,0.16655438464399277554,0.0328726110721162465,-0.011738947998697204372,-0.040140181374246318435,-0.28207359846515639434,-0.0079254318508707212454,-0.62617282752560110559,-0.019059854320635706559,-0.32977394076815313984,-0.013697338948721493601,0.051299763727322998663,-0.079057922935914057283,-0.040593748233816694115,-0.072100843002011374971,-0.061164088629099194749,-0.12133761402272967567,0.084430660421966244322,0.040626165037951494918,-0.11982267831327501895,0.19549133619669303852,-0.098338598005994926066,-0.14452047402616108318,0.26377649659088797662,-0.22171980816598682584,-0.0054947415339306575344,0.24266338019382013846,-0.051090417397983069192,0.044516751450101380017,-0.0021675180644596479113,0.33869221376368685572,0.025281947848343051116,0.19086255032967092138,-0.053772002085326585374,-0.12658046045556223258,-0.21195571916955785463,0.10548194652435431695,0.16269159422772405676,0.26289687681792989205,-0.36055864765064765676,-0.19379519000849809718,0.1946130431939102623,0.032559651107746799548,0.18259250361673673435,0.16066075684029260118,0.01962624239013512073,0.024003615828330143039,-0.028335888222668484393,-0.30032344859319065611,0.016145904186068746333,-0.63851728955160136358,-0.060489637198361353998,-0.35499246809213769183,-0.047024794710072773118,0.09513155344876246533,-0.10775077098355086147,-0.070483170733838682032,-0.071010037450881122179,-0.052229935663893015119,-0.14455051172618588184,0.056386077267590109519,0.051229486664486248437,-0.11248258861135518316,0.22668564917364220079,-0.10214071787933513835,-0.16890624603882622989,0.24692736366494277833,-0.24665222041775897166,0.0015470837419230187761,0.27796753761407017036,-0.048635005251277778349,0.040131234278178620767,0.035181894976126754093,0.31831446911276672918,0.054071316534122212949,0.21531166154460648632,-0.011941443715943227816,-0.17014385971188372704,-0.19789043435736167198,0.097018870008900567892,0.17663544180047982546,0.25350597222413617793,-0.33854509799584819874,-0.23831412514444449968,0.20482297904724308668,0.044958676703656823281,0.20506776028545933843,0.18470170079794107076,0.0083891525375312039903,0.025399690806050527481,-0.017528093773312929116,-0.32589609663173296772,0.0003324827059639500512,-0.65118318562022214913,-0.095658603276159090423,-0.39198047235658500798,-0.038414879376371446895,0.12305190222926915,-0.13427359402311619951,-0.066723556976698683574,-0.060759936008111449512,-0.05449934944924572644,-0.16556317379640186904,0.054019814657218390153,0.058059149558541925384,-0.11306844159865764299,0.22625444048619591797,-0.0918601013024835239,-0.17003687853597024282,0.24007246096846360239,-0.27247259424930325711,-0.027647088614531804135,0.31796241184776713462,-0.039952367997207645367,0.033126456253536530616,0.05141321687376124161,0.32245074208060003906,0.072296553287820072842,0.20325780533957363283,-0.011355218656176781569,-0.18875681495380747243,-0.1934645565509045817,0.098312312460650100321,0.17914051411344306119,0.23051492561074604648,-0.3417558498970784675,-0.27667697541815000628,0.22514228587141763005,0.02721233731057156463,0.18652091634637063544,0.1678339096018355292,-0.0020593254485972638072,0.018596878589215496552,-0.016404364573077527545,-0.28535456215655380374,0.00011960470925958535063,-0.61338060139697236917,-0.13678295885816799116,-0.41250412134261571495,-0.022616450112869855571,0.091989016452468277962,-0.13806534806422474104,-0.038840289293854954322,-0.036126045266969296355,-0.048782274698508328037,-0.15244901794782833582,0.06844217668175442415,0.06209398846010051598,-0.1300637566376109111,0.22104104042883304659,-0.083378683349646154355,-0.16716971390657889285,0.2432602492353217738,-0.28704860256195069423,-0.062784208041843578285,0.33487918409394384911,-0.031465569794281139648,0.031837999882054088263,0.044742664283863010921,0.33687568074433404952,0.068243098673064384041,0.19661050411731617604,-0.01331150729253090248,-0.20924559338466872105,-0.18452691392564926631,0.10285026728996311818,0.15822928749693732087,0.22755442422526522828,-0.34627258524582898991,-0.31458603815383284763,0.24531683058851236345,0.017673546264293935742,0.16337026842380172886,0.1764786234250431407,-0.010635617881153502581,0.017401848143200442098,0.0044071548590307371013,-0.24174493881999503664,0.004411411330409467646,-0.6134906689977336347,-0.17306521559316742631,-0.42757464908685177685,-0.020876387292901182197,0.094859267115187911878,-0.18662873391541037749,-0.0062413392346707570468,-0.03287333980952956286,-0.052533882718132272893,-0.14897560946883245392,0.098445174595217177504,0.044455348617560855318,-0.13028035833089410267,0.21809606452185514858,-0.090676376868614849691,-0.16773255710454879064,0.23548913949800853729,-0.29160087650678589988,-0.092217391531448020259,0.34214109879534698733,-0.041509798031100685056,0.033768426626255912404,0.045757947068980099614,0.32815538289528856097,0.072875075302077804706,0.17740024279020841225,-0.029834225532254975144,-0.21804868267391566694,-0.18902334372351958791,0.10970996551004456865,0.14697084887030922862,0.1754978054922567976,-0.35085358895624313424,-0.30468736021109499301,0.22970758938846444486,0.0091498208116696476411,0.15707521567748417013,0.15380669798731977371,0.0013777937594168692195,0.011658014284960353454,-0.0034848853171928874731,-0.23868551953241651242,0.0062488148867367579106,-0.57730229705472790869,-0.17181238286315414499,-0.42949527541610338366,-0.0069382511331062060589,0.10905153873489360772,-0.17694867610308651074,-0.0087433213184513608462,-0.04135973030980322207,-0.056657972701343026212,-0.15175397117428054972,0.090651638823754668306,0.045168187379159688288,-0.13416483832458231396,0.22593597344562235674,-0.088299204877180265116,-0.15513837173204472752,0.24068922024842304142,-0.29326125143742681756,-0.08901299882821575582,0.35042251945249464073,-0.043683945526651682401,0.033230650985682376464,0.035684572729188068774,0.32976182834817679979,0.067892005006807837342,0.18244630757856056258,-0.037284019768674278583,-0.22542134576886060926,-0.18776219872847002557,0.11339779142605942164,0.14527638713468390974,0.17511875135116963809,-0.35419864039209497664,-0.2917418478285148109,0.22750800535885476461,0.00051595788681690402978,0.15298437221809343955,0.14058868194366480608,0.014008276004680709007,0.0068504200778279431688,-0.015058900558745022535,-0.23134793267964898211,0.0037440711022873516232,-0.56265745516561549433,-0.17639542784874898129,-0.43329411907497372702,-0.0045441287569732077833,0.10772366787552364875,-0.17634392963514511354,0.0039190016246828498006,-0.034351560699982346125,-0.057311085500030882478,-0.15907121611792340854,0.10134733966567481545,0.050516457025542624293,-0.12419825639734868861,0.20469731237164806581,-0.086269378781250224963,-0.150275212183128698,0.22953127819625790407,-0.3045230724452326343,-0.092388597828394161682,0.37050523347722258416,-0.041520208779703984825,0.011334274918438271701,0.046230586209470049541,0.33110239852495287893,0.072583558173363885158,0.1588814525283523682,-0.050919208853389900937,-0.23353410951164119136,-0.19233595117715621137,0.13871899144663832337,0.14348121634549951264,0.16076060427734709113,-0.36896667702348828755,-0.2637771319060539521,0.23900831413027645578,0.017742558692127402553,0.15475708022017531373,0.11169772209941661312,0.026629048004423887253,0.017443916528059367349,-0.0054795887678893819353,-0.2208135325201838195,-0.006833044385822542241,-0.55815848414962665469,-0.18605474218821616006,-0.44102195672688820904,-0.017594254239207178514,0.095170549665423459507,-0.17107248301386659972,0.028825107073817267389,-0.047227875933764748573,-0.054921963313027656606,-0.15547859520922083232,0.088720218530835434634,0.055088104906482450451,-0.14944359533730591783,0.21392927322025359627,-0.081063757518318360629,-0.089073437715522521541,0.25946675897031795666,-0.30555260842428288992,-0.10472138825078677882,0.39414201955055094828,-0.037981956809823747001,0.016010774339443180347,0.027131263663561278054,0.36079583064768139256,0.085035190491780834887,0.17681169276342914576,-0.035543655961104717034,-0.23016105976706247027,-0.19800157277007099377,0.16207974671088989926,0.1428520487199026745,0.17105518952460480042,-0.40773573775346738657,-0.21257154901818164916,0.25890760156777209433,0.0070559726551832121361,0.1904964891353905232,0.11398065743628416069,0.032369606982453807964,0.023225875405006871782,-0.030238967934280450156,-0.21574797327505679245,-0.0038198877233051277066,-0.55141409186362100314,-0.2031493071130122674,-0.43236523109436086898,-0.031838128136053321648,0.098769882502578232319,-0.19417256758778048131,0.026532971006382403967,-0.038674514813651431067,-0.044166882523261501159,-0.13545718271068837857,0.10063761915700969451,0.045937215093876958283,-0.14933384700377907994,0.20520405517717349442,-0.071849524956260082953,-0.059566980376569871047,0.27657936195729504458,-0.28962728068584836505,-0.11166994805137396563,0.40646189919089786846,-0.036455997355447279651,0.012036233480219149516,0.012659946003648078414,0.37090084207559870233,0.082400785769144418991,0.16875122635904230006,-0.028135713329267585114,-0.20593492916701977569,-0.20535873316717109804,0.17623319164097073219,0.16948200695726042819,0.170018595447977372,-0.4243113732940632099,-0.17316810338061924823,0.26008724987869302758,0.0040509229338161973147,0.2419285710533860545,0.11240233791926154683,0.014116309311758210021,0.023864237789707289095,-0.019269887527286644335,-0.21990797114302118587,-0.01314634584867757465,-0.57601057841195846265,-0.22608930982766037299,-0.41785439324321521637,-0.031110015072089540478,0.089211643435876522568,-0.19043708018512114921,0.044643176014756230652,-0.029313929939282019205,-0.036069231471829839297,-0.1134285499100346345,0.089723441030031478305,0.019695517703491999956,-0.13730445331857174529,0.17821624147800585458,-0.072485302507777335523,-0.048940333994003201723,0.26735581399168673045,-0.29879355126457207703,-0.13409175465246439551,0.39733078701154378454,-0.044375057294894895699,-0.0049022629365012950278,0.012757859715570845499,0.3743873261619663495,0.070837598194691070441,0.17682678127444567684,-0.020773401347588683896,-0.18296404248471492826,-0.2307541132019158836,0.20486934457284636246,0.20825656438871734122,0.22169563707711481548,-0.44838921925892322173,-0.14021419560429485007,0.27460567178070355299,0.001297084726678808704,0.30607617040393525487,0.13667956557604374335,0.047251831546753920998,0.017815564667536393229,0.021282454422982828579,-0.21608250579229529298,-0.031835551619044298588,-0.55726693366747714897,-0.24560875756471703402,-0.42002307749379608204,-0.028035738507943538944,0.079235526017666341181,-0.18836742228495928497,0.058465658483412626112,-0.046287419282621568295,-0.038122185203065837855,-0.065643908147129517716,0.093293835748006384567,0.0011401870183656665977,-0.12308427678729669252,0.15509538000419503812,-0.072857099472107209048,-0.031254401138917239922,0.26768606755887724979,-0.30585501103245860133,-0.13268281701083048385,0.42473722848747957892,-0.050696491643400225235,-0.0050119901423044989353,0.023727367906262151337,0.38357800973719641258,0.083327641749885827949,0.18827786940408755556,0.011135020680006635016,-0.18060371025508414888,-0.22951502077678970215,0.19219019456392300027,0.25743081193528499773,0.22101284513477795213,-0.45086399199974697138,-0.13665526743508785157,0.31200846135863169462,0.012350660942336106132,0.36164134112209717076,0.17077512129556302045,0.071558421852841336275,0.0012976458575480616896,0.0088028627825350504871,-0.20650540674720616052,-0.059373931380301156469,-0.53400206571683517254,-0.2879984231924844762,-0.4033012685263506758,-0.0051521882734060914233,0.085941674175236848487,-0.20162141048589804493,0.12559818114950405121,-0.036433132162176404267,-0.043494150409665990886,0.0046305716394362990418,0.1130067847396407088,-0.00099146981190878632692,-0.11840236237964704702,0.15776362962039072735,-0.070494337207928164935,-0.02953521131308671846,0.25048559015295257524,-0.2943971747731908839,-0.14230267885128905503,0.47075435326964337746,-0.052630486637078394141,0.0032039454748021235428,0.044428279457986073753,0.39247133561599423235,0.11772687175398041659,0.20766121547567067962,0.061003846741401988873,-0.18158982475061311024,-0.22295236194305753652,0.19544330177894708722,0.27172675085449760068,0.2327061396810279903,-0.4462825575006466039,-0.13940640888518870955,0.335127783403439794,-0.0010127353220724941759,0.3925604813182734798,0.21482861921432747088,0.094021122719789601563,-0.013223346908334087171,-0.0095272515481378324681,-0.18672476461735909581,-0.084520363608403287214,-0.49064231566175564581,-0.35519726219006886314,-0.37270309007427587789,0.017880167501773045619,0.071331479843181860856,-0.22192297844942987517,0.19043343947808655248,-0.02249279601095628342,-0.043823652907148825941,0.061794396104829868444,0.11711246374774833545,-0.0060988885113842919092,-0.112874392596116771,0.14425342502206420225,-0.053538207895212110154,-0.03958989220756434918,0.22894594559052861005,-0.26716378974789317668,-0.12997143052599602342,0.47213184489079024209,-0.04267363626083696404,-0.0094465011334568613904,0.013476171117257407239,0.36740110977003548332,0.094895587298925998532,0.1954834452712638504,0.074799206050370992127,-0.13492125953386216453,-0.21499334606722769747,0.1412881760992660829,0.32003238670376288333,0.27798977822740900123,-0.42736410074413622162,-0.13080489734413092151,0.31708287468662244013,0.046468404243499801531,0.4404246245837779572,0.24930258498326240968,0.077407757469575372289,0.011942905346712105394,0.0053139992577600153947,-0.19462167180768488728,-0.084594239873890988979,-0.45987895873766926336,-0.37440577950113712591,-0.35675219384007528234,0.022670031918901267787,0.096632458783977137617,-0.21668037756102032088,0.28464171351078054739,-0.014060074245605571133,-0.040639574001803180359,0.098474775738013012316,0.13339435315805117654,-0.011163568305934044173,-0.10188377794302266866,0.11623385323484197729,-0.047128341670507598038,0.016072454258203007493,0.2201801456602066609,-0.25627826761273181377,-0.080265439185299256031,0.48187685549279751784,-0.037504820439527276899,-0.01121168680947750261,0.035247091479418006521,0.34290462300874452461,0.11196737490963697137,0.20693743742680062447,0.10680049423409182507,-0.1015780160509422575,-0.19045034823587730921,0.14366932597526854698,0.3835346774669136094,0.25892881354983382503,-0.41690973607466169648,-0.1013551444716650346,0.34159302804689833932,0.061350231642073253802,0.52415747775911902817,0.29986358983178756921,0.058687346356899233735,0.011147408539914941891,-0.032561416284282267142,-0.20006652837490021546,-0.11344949669676894499,-0.40762829117948945479,-0.38520004339510371949,-0.29507248503152166963,0.027955316769453470577,0.10192204561276621555,-0.24626855265956251739,0.34055131908710600808,0.00086042149786533727533,-0.041973280611255846251,0.14085072112713528658,0.14274725869814880452,-0.037791888593039973943,-0.10072802060659621914,0.072405050640282783703,-0.042350658336591753828,0.097875916354759451288,0.24174521421550410061,-0.22015314184005987941,-0.071485619024881430494,0.47016281471650789303,-0.046479336352644992636,-0.0031952763031529076571,0.018349215691434269532,0.34812544285080837536,0.13914713160182845542,0.2083006922035831876,0.1451359052447107334,-0.030221507291733163553,-0.20221263789993573767,0.17771474975686113451,0.45403851580871218419,0.22398567010670650257,-0.44483156432910325728,-0.078257810872744554276,0.3646230789795214533,0.01551751269705419975,0.62111366097334763658,0.3613953157909363112,-0.011085325661667935759,0.017487869238305909364,-0.028268677601384715331,-0.15644050787766816679,-0.15279256728956858158,-0.36349534444807801714,-0.40543225476268784924,-0.21295494262633099525,0.039299834568035256488,0.071223324823621703139,-0.2530365033543818809,0.36561687011824212101,0.0018128097610537246762,-0.045228023217422134994,0.19136115767210273853,0.12710099462812324278,-0.057621753114528669049,-0.097682307363060355554,0.043106513477908732501,-0.03699619779867163033,0.1513308519291921006,0.24664898122096906574,-0.18418889560398718497,-0.033286314895099970712,0.47577692898652851339,-0.049282249864483672341,0.022561065328615660663,-0.017580059585176797954,0.37334955825326821,0.14817283408086248664,0.22107382207878550906,0.21286664073669758768,0.045190813436049810659,-0.20790735157209591644,0.19732991870312852067,0.49739847433697920165,0.26200428211854798199,-0.44832477810046983402,-0.029615161713946770716,0.36058243972124681687,-0.03630733022643019281,0.7050501150258764449,0.42297872750952508758,-0.039896952016068479296,0.021270652043752329152,-0.016852979745741441392,-0.15994268988687779243,-0.14866622118876465786,-0.34919375938007202187,-0.40140238898075236706,-0.16618133959643363595,0.021735944488559529736,0.051034639331098141657,-0.24035362429136050699,0.38212721557312073761,-1.2098544913614683394e-05,-0.04063766858513299246,0.21441024007702222387,0.11114688916595150125,-0.067236781000242468176,-0.093789454302406149999,0.015008957677237061423,-0.022745889806639246755,0.1333737692607507852,0.21520870172328415704,-0.12593490888520808557,-0.037023550114963083013,0.47954608823851851973,-0.050172628153909222537,0.029084031847994764458,-0.051507323553317885256,0.36456996926140816662,0.13535998242334953967,0.18774450537525791405,0.24145981399234708875,0.086058801005998636358,-0.17985248768715220158,0.18123385951914386394,0.52279232500742023326,0.25084728400354378008,-0.45419310540554003186,0.069790867869243905508,0.35911626735084573037,-0.013900431258495653253,0.76481585603539314899,0.42201589145635270972,-0.021300965755319402339,0.01450877562641136008,-0.040748991568639737759,-0.14268835021504996941,-0.19059848495529010948,-0.29594263659144798284,-0.44583056749855048961,-0.093463041924700299146,0.012988254876395819923,0.047571980240718722555,-0.195329486882971054,0.42813231516475508398,0.027425847804994605422,-0.028501474301385588961,0.24375181971524459423,0.11789574292447582704,-0.078362892732425387665,-0.081380369582240416615,0.0043148928945963152884,-0.019692753029243115215,0.16509749493376937868,0.22046762053246365953,-0.11824124598428603639,-0.046145323787354385059,0.5639318083742861365,-0.045860644331181650568,0.04735665150977448612,-0.051673841646078029488,0.36324439186831597448,0.17108419588417092538,0.18290208982492037193,0.27596813867449998536,0.090069581208161483832,-0.15757173461978793427,0.20444775435068257563,0.5746488370977589355,0.23073470929994530088,-0.43986731862635647383,0.0097731583306447534359,0.37604760419754240663,-0.052723464527841656935,0.80083990190893372674,0.45994457952545497736,-0.072236880868211311713,-0.00017976243803783211253,-0.038839754061565541499,-0.11966424554176088857,-0.18242801310232395484,-0.27224303875777600137,-0.53033107180316185758,-0.039908838500165015606,0.012984083845568480248,0.042185933181149527782,-0.22276324848715176041,0.54184922141608826696,0.034906245955932495295,-0.025656172742269743592,0.29450105238029872234,0.087546987355132471764,-0.072941028049029049685,-0.081280808447585117804,0.0075699865550601826147,-0.014580170979808616122,0.18607553090231615522,0.23223076922644969589,-0.12257162278299074676,-0.024812033448627705129,0.62548184458697675403,-0.042306175939280134257,0.057205547007326593145,-0.038497009832970809085,0.37272695179812465049,0.21732230950777298162,0.21697066772570938742,0.33129960772423905357,0.10584888898724859052,-0.16295837487282524569,0.24156789750486640234,0.61257522464614355684,0.25732618383140909435,-0.40746666526398450658,-0.027091861969882832101,0.37866190419009609913,-0.12151114136738565275,0.84644047106855635487,0.51812790402254260691,-0.090569944106901598135,-0.023611031872321719405,-0.046142285169206334605,-0.12939721588820352061,-0.18138105771544665856,-0.26266326250102822737,-0.60414583268575572372,-0.0086119534286203773543,0.02285565278388678595,8.7324615453580737602e-05,-0.23673729141757218764,0.59657376921757099275,0.053259198233911266007,-0.012150079500932440754,0.34272919007259872171,0.071040462529876266529,-0.08748210631748484789,-0.056063403137068486271,0.054827422961309851823,-0.032824169976022180006,0.20639340812684164872,0.25756179618219127159,-0.11379263920414819933,-0.040020279331630125019,0.67499446877124402722,-0.062488593711759354843,0.067861089070331379047,-0.010214267676292593939,0.34805750819948177988,0.25231866108463263387,0.26788373902164885898,0.38271474808362859754,0.077847396522090245297,-0.15540266106260380852,0.27148307413821076706,0.64972311290559914276,0.26256743663211107309,-0.4593114416833122271,-0.050656890556514885815,0.43560579477675182014,-0.13016652075421084045,0.90381999816345293119,0.56685300925780368608,-0.10194671242788919119,0.0076205741797656535025,-0.019022199433921010286,-0.13265872976516759896,-0.21312924236997179972,-0.25667063583263927118,-0.67328152408016506136,0.02710054631589552121,0.026992585090783009077,0.0077798261643922915487,-0.25913954184931453639,0.62597527595694146818,0.04597081780029915743,-0.028329778602686893352,0.33630361494499849684,0.0551305706971391557,-0.097666124808301363336,-0.048311141558605545654,0.077524100137439086455,-0.048988363735550564948,0.23652124866050150409,0.26674513216547002248,-0.089176618612883340464,-0.023085130852671859047,0.65824248281518960013,-0.073887228856309120073,0.091495331516932842941,-0.007561262451100694143,0.32860555020896536904,0.25419416242909304016,0.27276984050492386613,0.40845719278728159773,0.096399101601249995164,-0.1573888105038787899,0.2582937050079182062,0.70782575343288600678,0.25310924771035919756,-0.47555845387383305356,-0.071928149463456242385,0.4262949529365565593,-0.13732461518913419152,0.95626515968610681373,0.59517179508595541293,-0.1409978748311199459,0.0031784170431253450963,-0.0048661891089137225899,-0.093758638281348199994,-0.18289969691391289031,-0.24961566925599523725,-0.68263405551457911891,0.090168448370030102046,0.018326658691580254013,0.014916854862398978843,-0.26883258046531183227,0.63762099650654879834,0.028948519184158878065,-0.030850099576681652702,0.34367653599978886803,0.025221464699485815486,-0.051205793974993391027,-0.080370134681178886926,0.065720514945648900174,-0.035816887261330664083,0.22314101267309982557,0.24605845944716001061,-0.048884344216428433916,0.085474061785818997161,0.66570183973206020767,-0.05216990983986163205,0.11662950974253383229,0.049290307720999348984,0.20874806947895338527,0.30075011344392160728,0.31669466606085006077,0.50635021554979875447,0.098999735990458762047,-0.13507276696902903446,0.22463729159052753248,0.7781142220709731383,0.24470102548078995208,-0.44245367817598174609,-0.061558429135275267996,0.38929141841565739757,-0.2000688857005820942,0.99870720515307698228,0.6537085083930002094,-0.10605683036990805335,-0.020352241824842725454,0.086028702603691789563,-0.085485797486384754174,-0.18216864567638851868,-0.28155991349317166517,-0.69325584497824921382,0.12852208736154877022,0.038872985556270354957,-0.017677116672129601638,-0.27535626509292165931,0.64838452360202725178,0.073441733290269886614,-0.017243737371094570304,0.39537772360170075903,0.040689467367118092866,-0.02004630046291999354,-0.08086016860671081663,0.095323384341223033056,-0.044960566363712942128,0.21480313320566110646,0.24023933563657881574,-0.017842043522104236719,0.06449712895501198695,0.6720807882595004612,-0.052186542927810518344,0.13329953397454330499,0.10370273969426767324,0.14785012846736139691,0.30487289060524014328,0.33092136316582465572,0.49205715257040594235,0.092213169389046875657,-0.11920345638689691659,0.20367023952512325335,0.83898199002538753621,0.20585731322130709775,-0.44991477954744540924,-0.060403733117922346618,0.39605518052772004101,-0.18560606796862241796,1.04259097906645537,0.6967547821515942541,-0.13318603414980842436,-0.016698401199338120532,0.039929923286029130047,-0.038080457721029685458,-0.1708692393422584499,-0.21122978205210940494,-0.73136752572214291934,0.18389666866977344428,0.034935536958162455301,0.0094262594069857777446,-0.26502642876958915075,0.69124513874094439814,0.082827646623915368584,-0.015354530919677599615,0.4510354264907144306,0.055215837198699026234,0.017594968528519074752,-0.063975690382966812764,0.093716686947054372858,-0.053889320814307153928,0.26584722259872139993,0.25741436180578297632,-0.023329494155127177696,0.046729186213466507305,0.7504831711604500466,-0.042038616345569913835,0.14125658874542307286,0.12730077795950345276,0.15154296138813630468,0.28529647764679288979,0.26317417430483225349,0.48982508963381526934,0.097830112696248416881,-0.12448479534762529886,0.20999595029890791298,0.88793170196404824779,0.147349241863427044,-0.45779233350834463989,-0.041769775321942141655,0.38813806507603865192,-0.22779529777829626846,1.039288390946991214,0.69374244998730472123,-0.1994376649575067828,0.0057884194350391526482,0.016642659159987777118,0.029182340234142924856,-0.085861819143466619475,-0.12379382742328791378,-0.75346349655951172508,0.23717549756693820373,0.0018500017846073374232,0.017601804074736163847,-0.259913404794936298,0.79140200802487481457,0.07334147286264904031,0.0047449468528492000016,0.47162159184264046408,-0.0040892047224266236602,0.041111148507932057661,0.021394696434184425765,0.15372439783517785616,-0.04481647919397563351,0.27137241748487783699,0.25485364857845715925,-0.090260272266544608333,0.045716245415985970468,0.8986026682565196877,-0.019038949080831112093,0.12781325058049011756,0.14365502170556077033,0.18299964496307077888,0.30318921675890042611,0.2597548013763388286,0.51662304433332806308,0.13896579246867826751,-0.096267431421172888761,0.25287801010200883223,1.0279319930453136855,0.24418807012292154113,-0.4744606757778045969,0.012008934004566762521,0.43753543336346351067,-0.27108158095201695392,1.1657767082541634629,0.81708740160834048005,-0.26765029849007615503,0.0017564544032301217767,0.031673013465986638026,0.059630807951297534752,-0.020583280278810015679,-0.052523661794871910613,-0.86257891210970316642,0.25142835418720327345,-0.022379253824570576742,0.037331056720289475248,-0.2284361098669971113,0.9617396958849235844,0.091116932769314470941,0.044208570046046599678,0.51241644553474141599,-0.11777244791422732118,0.049131070056621727049,0.070189609606985711721,0.22623592324040051049,-0.035760412912298575328,0.2059021259110489499,0.25478279786552154862,-0.093253004696505575888,0.0447157407787938041,0.9389875261881387436,-0.0045053113374397164848,0.11107985847731079165,0.13372902378303769266,0.1827312227310367021,0.27950307170013249936,0.25463916809267050922,0.51750334793591401539,0.13626312955993163945,-0.070693278493561412246,0.23117264116799465801,1.0650846939573797023,0.31823547888162562192,-0.45661853170137467473,0.025219703961693859529,0.42674067886986527531,-0.22623048848831098234,1.1834769265670832539,0.89051895798813562877,-0.33595707752312342631,0.0059415488265719025585,0.036798699077473809305,0.06552124631460856663,0.017280257351101422497,-0.00063690131927407987733,-0.89841921504656463426,0.26995653232128091759,-0.049090628011741632708,0.058585965441731419068,-0.21383956275834192784,1.040654144741436804,0.10729800195113559091,0.070199218853982753297,0.48983181283649224191,-0.16627339327499407462,0.039573680010176269517,0.11383159215494845218,0.2759152123925186495,-0.051350417668010378547,0.18815005345689556071,0.25158254487953157774,-0.091393648931623633347,0.049191786889841840336,0.88575113367312274804,-0.013914286891611763256,0.1119513393509472543,0.12067228411210963179,0.16853266035579772542,0.23845737652254600514,0.28001601888785149219,0.54425018143826175976,0.13731640829535782244,-0.073800659594878248448,0.21906833315048832023,1.0995300117061725942,0.41379603658537128519,-0.50601356696691934811,0.056048571782913503281,0.43704134355038887216,-0.18430785928698362186,1.2106158038480450134,0.92944383456584089842,-0.36539776169621146495,0.0034585705214183939255,0.15633942806875958387,0.14662853909907558325,0.04932776523024776788,0.047431433537747751117,-0.89063596197480532357,0.29546622348949286296,-0.096351289964327985205,0.09023815980265177672,-0.21011489224762847083,1.0555538305449592151,0.078765482549832191439,0.075584401514666221811,0.4478075292538453156,-0.22250549040066316953]
temp2 = np.array(LW2_1)
LW2_1 = temp2.reshape((93, 43))
# ######## Output 1
y1_step1 = {'ymin': -1,
'gain': [0.043859649122807,0.044432513390484,0.0457417796837631,0.0473559947894652,0.0474735112919784,0.0477637822267266,0.0484050620716164,0.0486934176339923,0.0487290414271462,0.0487323390463977,0.0487376981156927,0.0488331083484923,0.0488783937341623,0.0491401805333158,0.0490966562039708,0.0491086072284748,0.0493631166499366,0.0492514416233219,0.0493859678261437,0.049537375183834,0.0497758306455687,0.0495474612103816,0.0493795037998211,0.0494335821606349,0.0492821957342268,0.0492530019353055,0.0492868366313963,0.0490319427830352,0.0491621820544462,0.048718608660081,0.0485476918011754,0.0486474650386642,0.0485584083505289,0.0485856772864948,0.0480788930326349,0.0481314948730762,0.0484266805339406,0.0489916808014502,0.0499906063564033,0.0513357135021671,0.0512780370973281,0.0512862135287764,0.0503694936649585,0.0503884862777959,0.050509996223982,0.0505552291154644,0.0505564947000966,0.0502390049950428,0.0500104848686487,0.0493624667912096,0.0513217768701024,0.0517775131696413,0.0526146330386633,0.0526527147107106,0.0527118235285031,0.0532140378881637,0.0540124428140577,0.0539100090669279,0.0535829030998376,0.0530738426668209,0.0535721234974637,0.0530006685023741,0.0530503978779841,0.0529300554005592,0.0517027567379992,0.0512355524651148,0.0505048930078384,0.0499839556000501,0.0489116367208205,0.0482448698775708,0.0477093628447898,0.0476495164834308,0.047321131374345,0.0486089841718837,0.0496044398535496,0.0516935789292232,0.0531010950173294,0.0537793979056641,0.0528644668100087,0.0520159373110468,0.0514365795277021,0.0505854035702524,0.0483347150164136,0.04827069401161,0.0491621495798401,0.0493487781414441,0.0485149185479138,0.0488425318640875,0.0492780521274358,0.0501991494507252,0.0568499896284246,0.0579752915415808,0.0586550527309614],
'xoffset': [-9.7,-8.36853581366338,-7.6311114713103,-7.3,-7.41575075961383,-7.47273090113216,-7.71799267276954,-7.9018978099516,-8.1,-8.32169352622345,-8.65296879459462,-8.83286033114985,-9.10845167142618,-9.20831649393743,-9.48536124533385,-9.69609898027269,-9.83603929546296,-10.2352740616718,-10.295373474522,-10.5,-10.5917680976192,-11.1640641142507,-11.5923804406991,-11.9238552940994,-12.3,-12.5864409060617,-12.8884821516731,-13.3013186054304,-13.7644248853015,-14.2678649020519,-14.8165594279917,-15.0676400584796,-15.368501244824,-15.8,-16.0982955065634,-16.301619242649,-16.4670837022787,-16.5959823957399,-16.2014919077065,-15.5065854786604,-15.9919750325206,-16.3901106930281,-16.8147251249279,-17.2916071059137,-17.6931446296129,-17.8606950060922,-18.2578138911386,-19.0683123920656,-19.5853801432019,-20.6923844247438,-19.807030993261,-19.9979096210209,-20.2602059190445,-20.6845395589527,-20.9996465771089,-21.0984099433285,-21.4002413456806,-21.7987210329207,-22.2,-23.2038737833372,-23.7,-24.5247949108117,-25.1,-25.4823591624888,-26.8837369044822,-28.0372473800327,-29.1,-30.3976307989663,-31.60252040691,-32.9930125996283,-34.2040047385683,-34.5445571586337,-35.3985757162141,-35.6659077597772,-36.2164499382529,-35.8985336882364,-36.366679477399,-37.1889622771206,-38.5862327186166,-41.058574812408,-43.5907204816083,-45.6910013200123,-47.7040684397082,-49.4848359228044,-51.4883926377285,-53.4685700291625,-55.7120213797104,-57.9461469192178,-59.2919471256105,-60.4416606341393,-58.0188863343265,-58.7974548090986,-59.83771958218],}
# ###########===== SIMULATION ========###########
if np.size(Inputdata) == 17:
Q = 1
else:
Q = len(Inputdata[0]) #####输入矩阵的列数
#####===========Input 1================
##### Remove Constants Input Processing Function
xp1 = mapminmax_apply(Inputdata, **x1_step2)
##### =============Layer 1============
if Q != 1:
a1 = np.tile(np.array(b1), (Q, 1)) ##repmat(b1,1,Q)
a1 = np.transpose(a1)
else:
a1 = b1
a1 = tansig_apply(a1 + np.dot(IW1_1, xp1)) ### xp1为归一化处理后
if Q != 1:
n = np.tile(np.array(b2), (Q, 1))
n = np.transpose(n)
else:
n = b2
a2 = n + np.dot(LW2_1, a1)
y1 = mapminmax_reverse(a2, **y1_step1)
return y1
| [
"[email protected]"
] | |
4b8d6169d7fb234c6643e2c07068d091c93fb197 | 006e45e8910f028d8337955022f18c40f0275da6 | /fourtytwo.py | 99ad6e1a3bd6c808f9ea17ae07366ce7117ce027 | [] | no_license | Harryhar1412/assignement4 | c5b93fd7fcc52393ed69be378e10884a74e41f94 | 4abd0e351f754866a5fdf8ba9dc5745a38363153 | refs/heads/master | 2022-11-07T04:13:05.197468 | 2020-06-28T13:29:09 | 2020-06-28T13:29:09 | 275,589,716 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 207 | py | # 42. Write a Python program to convert a list to a tuple.
input_string = input("Enter a list elements separated by space ")
userList = input_string.split()
print (userList)
tupp=tuple(userList)
print (tupp) | [
"[email protected]"
] | |
c47ec3b06c58efce2ed9f6ca599d3017ad05f1e1 | 50f36fade526519d8e4eed33685e54a26b9f6b43 | /lb4.py | f761a64e55e72450f82d516700913368b321fd18 | [] | no_license | myusernameisalreadytakenn/MND | 0bfaf9b8c33fd29484d8a228785f7db2f535a7ab | fd0393f10eda90a79cd6806408867b1b649edc87 | refs/heads/main | 2023-05-05T11:58:43.403192 | 2021-05-24T08:10:27 | 2021-05-24T08:10:27 | 340,164,535 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 4,658 | py | import random
import numpy as np
from numpy.linalg import solve
from scipy.stats import f,t
n = 8
x1min = -20
x1max = 30
x2min = 20
x2max = 60
x3min = -20
x3max = -5
y_max = 200 + (x1max + x2max + x3max) / 3
y_min = 200 + (x1min + x2min + x3min) / 3
xn = [[1, 1, 1, 1, 1, 1, 1, 1],
[-1, -1, 1, 1, -1, -1, 1, 1],
[-1, 1, -1, 1, -1, 1, -1, 1],
[-1, 1, 1, -1, 1, -1, -1, 1]]
x1x2_norm, x1x3_norm, x2x3_norm, x1x2x3_norm = [0] * 8, [0] * 8, [0] * 8, [0] * 8
for i in range(n):
x1x2_norm[i] = xn[1][i] * xn[2][i]
x1x3_norm[i] = xn[1][i] * xn[3][i]
x2x3_norm[i] = xn[2][i] * xn[3][i]
x1x2x3_norm[i] = xn[1][i] * xn[2][i] * xn[3][i]
y1 = [random.randint(int(y_min), int(y_max)) for i in range(8)]
y2 = [random.randint(int(y_min), int(y_max)) for i in range(8)]
y3 = [random.randint(int(y_min), int(y_max)) for i in range(8)]
y_matrix = [[y1[0], y2[0], y3[0]],
[y1[1], y2[1], y3[1]],
[y1[2], y2[2], y3[2]],
[y1[3], y2[3], y3[3]],
[y1[4], y2[4], y3[4]],
[y1[5], y2[5], y3[5]],
[y1[6], y2[6], y3[6]],
[y1[7], y2[7], y3[7]]]
print("Матриця планування y : \n")
for i in range(n):
print(y_matrix[i])
x0 = [1, 1, 1, 1, 1, 1, 1, 1]
x1 = [10, 10, 50, 50, 10, 10, 50, 50]
x2 = [20, 60, 20, 60, 20, 60, 20, 60]
x3 = [20, 25, 25, 20, 25, 20, 20, 25]
x1x2, x1x3, x2x3, x1x2x3 = [0] * 8, [0] * 8, [0] * 8, [0] * 8
for i in range(n):
x1x2[i] = x1[i] * x2[i]
x1x3[i] = x1[i] * x3[i]
x2x3[i] = x2[i] * x3[i]
x1x2x3[i] = x1[i] * x2[i] * x3[i]
Y_average = []
for i in range(len(y_matrix)):
Y_average.append(np.mean(y_matrix[i], axis=0))
list_for_b = [xn[0], xn[1], xn[2], xn[3], x1x2_norm, x1x3_norm, x2x3_norm, x1x2x3_norm]
list_for_a = list(zip(x0, x1, x2, x3, x1x2, x1x3, x2x3, x1x2x3))
print("Матриця планування X:")
for i in range(n):
print(list_for_a[i])
bi = []
for k in range(n):
S = 0
for i in range(n):
S += (list_for_b[k][i] * Y_average[i]) / n
bi.append(round(S, 3))
ai = [round(i, 3) for i in solve(list_for_a, Y_average)]
print("Рівняння регресії: \n" "y = {} + {}*x1 + {}*x2 + {}*x3 + {}*x1x2 + {}*x1x3 + {}*x2x3 + {}*x1x2x3".format(ai[0],
ai[1], ai[2], ai[3],ai[4], ai[5], ai[6], ai[7]))
print("Рівняння регресії для нормованих факторів: \n" "y = {} + {}*x1 + {}*x2 + {}*x3 + {}*x1x2 + {}*x1x3 +"
" {}*x2x3 + {}*x1x2x3".format(bi[0], bi[1], bi[2], bi[3], bi[4], bi[5], bi[6], bi[7]))
print("Перевірка за критерієм Кохрена")
print("Середні значення відгуку за рядками:", "\n", +Y_average[0], Y_average[1], Y_average[2], Y_average[3],
Y_average[4], Y_average[5], Y_average[6], Y_average[7])
dispersions = []
for i in range(len(y_matrix)):
a = 0
for k in y_matrix[i]:
a += (k - np.mean(y_matrix[i], axis=0)) ** 2
dispersions.append(a / len(y_matrix[i]))
Gp = max(dispersions) / sum(dispersions)
Gt = 0.5157
if Gp < Gt:
print("Дисперсія однорідна")
else:
exit("Дисперсія неоднорідна") #print замiнив на exit
print(" Перевірка значущості коефіцієнтів за критерієм Стьюдента")
sb = sum(dispersions) / len(dispersions)
sbs = (sb / (8 * 3)) ** 0.5
t_list = [abs(bi[i]) / sbs for i in range(0, 8)]
d = 0
res = [0] * 8
coef_1 = []
coef_2 = []
m = 3
F3 = (m - 1) * n
for i in range(n):
if t_list[i] < t.ppf(q=0.975, df=F3):
coef_2.append(bi[i])
res[i] = 0
else:
coef_1.append(bi[i])
res[i] = bi[i]
d += 1
print("Значущі коефіцієнти регресії:", coef_1)
print("Незначущі коефіцієнти регресії:", coef_2)
y_st = []
for i in range(n):
y_st.append(res[0] + res[1] * xn[1][i] + res[2] * xn[2][i] + res[3] * xn[3][i] + res[4] * x1x2_norm[i]\
+ res[5] * x1x3_norm[i] + res[6] * x2x3_norm[i] + res[7] * x1x2x3_norm[i])
print("Значення з отриманими коефіцієнтами:\n", y_st)
print("\nПеревірка адекватності за критерієм Фішера\n")
Sad = m * sum([(y_st[i] - Y_average[i]) ** 2 for i in range(8)]) / (n - d)
Fp = Sad / sb
F4 = n - d
if Fp < f.ppf(q=0.95, dfn=F4, dfd=F3):
print("Рівняння регресії адекватне при рівні значимості 0.05")
else:
print("Рівняння регресії неадекватне при рівні значимості 0.05")
| [
"[email protected]"
] | |
b4631acdfaeba6632543932c6d6b336b5eb9fa7f | 2485f7d6e12daa2c29926a7c87e2ab18f951a107 | /pypilot/signalk.py | a49f9d16378428197f19f51b84213e2e9ee31e36 | [] | no_license | mielnicz/pypilot | add65367b9b1d2630bad463aa82ce6463e177147 | f0c9b2d2c8a1107a0f114ebe528af2beee7ad161 | refs/heads/master | 2023-07-13T15:58:08.306890 | 2020-03-16T06:24:02 | 2020-03-16T06:24:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 23,095 | py | #!/usr/bin/env python
#
# Copyright (C) 2020 Sean D'Epagnier
#
# 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 3 of the License, or (at your option) any later version.
import time, socket, multiprocessing, os
from nonblockingpipe import NonBlockingPipe
import pyjson
from client import pypilotClient
from values import Property, RangeProperty
from sensors import source_priority
signalk_priority = source_priority['signalk']
radians = 3.141592653589793/180
meters_s = 0.5144456333854638
# provide bi-directional translation of these keys
signalk_table = {'wind': {('environment.wind.speedApparent', meters_s): 'speed',
('environment.wind.angleApparent', radians): 'direction'},
'gps': {('navigation.courseOverGroundTrue', radians): 'track',
('navigation.speedOverGround', meters_s): 'speed',
('navigation.position', 1): {'latitude': 'lat', 'longitude': 'lon'}},
'rudder': {('steering.rudderAngle', radians): 'angle'},
'apb': {('steering.autopilot.target.headingTrue', radians): 'track'},
'imu': {('navigation.headingMagnetic', radians): 'heading_lowpass',
('navigation.attitude', radians): {'pitch': 'pitch', 'roll': 'roll', 'yaw': 'heading_lowpass'}}}
token_path = os.getenv('HOME') + '/.pypilot/signalk-token'
def debug(*args):
#print(*args)
pass
class signalk(object):
def __init__(self, sensors=False):
self.sensors = sensors
if not sensors: # only signalk process for testing
self.client = pypilotClient()
self.multiprocessing = False
else:
server = sensors.client.server
self.multiprocessing = server.multiprocessing
self.client = pypilotClient(server)
self.initialized = False
self.missingzeroconfwarned = False
self.signalk_access_url = False
self.last_access_request_time = 0
self.sensors_pipe, self.sensors_pipe_out = NonBlockingPipe('signalk pipe', self.multiprocessing)
if self.multiprocessing:
import multiprocessing
self.process = multiprocessing.Process(target=self.process, daemon=True)
self.process.start()
else:
self.process = False
def setup(self):
try:
f = open(token_path)
self.token = f.read()
print('signalk' + _('read token'), self.token)
f.close()
except Exception as e:
print('signalk ' + _('failed to read token'), token_path)
self.token = False
try:
from zeroconf import ServiceBrowser, ServiceStateChange, Zeroconf
except Exception as e:
if not self.missingzeroconfwarned:
print('signalk: ' + _('failed to') + ' import zeroconf, ' + _('autodetection not possible'))
print(_('try') + ' pip3 install zeroconf' + _('or') + ' apt install python3-zeroconf')
self.missingzeroconfwarned = True
time.sleep(20)
return
self.last_values = {}
self.last_sources = {}
self.signalk_last_msg_time = {}
# store certain values across parsing invocations to ensure
# all of the keys are filled with the latest data
self.last_values_keys = {}
for sensor in signalk_table:
for signalk_path_conversion, pypilot_path in signalk_table[sensor].items():
signalk_path, signalk_conversion = signalk_path_conversion
if type(pypilot_path) == type({}): # single path translates to multiple pypilot
self.last_values_keys[signalk_path] = {}
self.period = self.client.register(RangeProperty('signalk.period', .5, .1, 2, persistent=True))
self.uid = self.client.register(Property('signalk.uid', 'pypilot', persistent=True))
self.signalk_host_port = False
self.signalk_ws_url = False
self.ws = False
class Listener:
def __init__(self, signalk):
self.signalk = signalk
self.name_type = False
def remove_service(self, zeroconf, type, name):
print('signalk zeroconf ' + _('service removed'), name, type)
if self.name_type == (name, type):
self.signalk.signalk_host_port = False
self.signalk.disconnect_signalk()
print('signalk ' + _('server lost'))
def update_service(self, zeroconf, type, name):
self.add_service(zeroconf, type, name)
def add_service(self, zeroconf, type, name):
print('signalk zeroconf ' + _('service add'), name, type)
self.name_type = name, type
info = zeroconf.get_service_info(type, name)
if not info:
return
properties = {}
for name, value in info.properties.items():
properties[name.decode()] = value.decode()
if 'swname' in properties and properties['swname'] == 'signalk-server':
try:
host_port = socket.inet_ntoa(info.addresses[0]) + ':' + str(info.port)
except Exception as e:
host_port = socket.inet_ntoa(info.address) + ':' + str(info.port)
self.signalk.signalk_host_port = host_port
print('signalk ' + _('server found'), host_port)
zeroconf = Zeroconf()
listener = Listener(self)
browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener)
#zeroconf.close()
self.initialized = True
def probe_signalk(self):
print('signalk ' + _('probe') + '...', self.signalk_host_port)
try:
import requests
except Exception as e:
print('signalk ' + _('could not') + ' import requests', e)
print(_('try') + " 'sudo apt install python3-requests' " + _('or') + " 'pip3 install requests'")
time.sleep(50)
return
try:
r = requests.get('http://' + self.signalk_host_port + '/signalk')
contents = pyjson.loads(r.content)
self.signalk_ws_url = contents['endpoints']['v1']['signalk-ws'] + '?subscribe=none'
except Exception as e:
print(_('failed to retrieve/parse data from'), self.signalk_host_port, e)
time.sleep(5)
self.signalk_host_port = False
return
print('signalk ' + _('found'), self.signalk_ws_url)
def request_access(self):
import requests
if self.signalk_access_url:
dt = time.monotonic() - self.last_access_request_time
if dt < 10:
return
self.last_access_request_time = time.monotonic()
try:
r = requests.get(self.signalk_access_url)
contents = pyjson.loads(r.content)
print('signalk ' + _('see if token is ready'), self.signalk_access_url, contents)
if contents['state'] == 'COMPLETED':
if 'accessRequest' in contents:
access = contents['accessRequest']
if access['permission'] == 'APPROVED':
self.token = access['token']
print('signalk ' + _('received token'), self.token)
try:
f = open(token_path, 'w')
f.write(self.token)
f.close()
except Exception as e:
print('signalk ' + _('failed to store token'), token_path)
# if permission == DENIED should we try other servers??
self.signalk_access_url = False
except Exception as e:
print('signalk ' + _('error requesting access'), e)
self.signalk_access_url = False
return
try:
def random_number_string(n):
if n == 0:
return ''
import random
return str(int(random.random()*10)) + random_number_string(n-1)
if self.uid.value == 'pypilot':
self.uid.set('pypilot-' + random_number_string(11))
r = requests.post('http://' + self.signalk_host_port + '/signalk/v1/access/requests', data={"clientId":self.uid.value, "description": "pypilot"})
contents = pyjson.loads(r.content)
print('signalk post', contents)
if contents['statusCode'] == 202 or contents['statusCode'] == 400:
self.signalk_access_url = 'http://' + self.signalk_host_port + contents['href']
print('signalk ' + _('request access url'), self.signalk_access_url)
except Exception as e:
print('signalk ' + _('error requesting access'), e)
self.signalk_ws_url = False
def connect_signalk(self):
try:
from websocket import create_connection, WebSocketBadStatusException
except Exception as e:
print('signalk ' + _('cannot create connection:'), e)
print(_('try') + ' pip3 install websocket-client ' + _('or') + ' apt install python3-websocket')
self.signalk_host_port = False
return
self.subscribed = {}
for sensor in list(signalk_table):
self.subscribed[sensor] = False
self.subscriptions = [] # track signalk subscriptions
self.signalk_values = {}
self.keep_token = False
try:
self.ws = create_connection(self.signalk_ws_url, header={'Authorization': 'JWT ' + self.token})
self.ws.settimeout(0) # nonblocking
except WebSocketBadStatusException:
print('signalk ' + _('bad status, rejecting token'))
self.token = False
self.ws = False
except ConnectionRefusedError:
print('signalk ' + _('connection refused'))
#self.signalk_host_port = False
self.signalk_ws_url = False
time.sleep(5)
except Exception as e:
print('signalk ' + _('failed to connect'), e)
self.signalk_ws_url = False
time.sleep(5)
def process(self):
time.sleep(6) # let other stuff load
print('signalk process', os.getpid())
self.process = False
while True:
time.sleep(.1)
self.poll(1)
def poll(self, timeout=0):
if self.process:
msg = self.sensors_pipe_out.recv()
while msg:
sensor, data = msg
self.sensors.write(sensor, data, 'signalk')
msg = self.sensors_pipe_out.recv()
return
t0 = time.monotonic()
if not self.initialized:
self.setup()
return
self.client.poll(timeout)
if not self.signalk_host_port:
return # waiting for signalk to detect
t1 = time.monotonic()
if not self.signalk_ws_url:
self.probe_signalk()
return
t2 = time.monotonic()
if not self.token:
self.request_access()
return
t3 = time.monotonic()
if not self.ws:
self.connect_signalk()
if not self.ws:
return
print('signalk ' + _('connected to'), self.signalk_ws_url)
# setup pypilot watches
watches = ['imu.heading_lowpass', 'imu.roll', 'imu.pitch', 'timestamp']
for watch in watches:
self.client.watch(watch, self.period.value)
for sensor in signalk_table:
self.client.watch(sensor+'.source')
return
# at this point we have a connection
# read all messages from pypilot
while True:
msg = self.client.receive_single()
if not msg:
break
debug('signalk pypilot msg', msg)
name, value = msg
if name == 'timestamp':
self.send_signalk()
self.last_values = {}
if name.endswith('.source'):
# update sources
for sensor in signalk_table:
source_name = sensor + '.source'
if name == source_name:
self.update_sensor_source(sensor, value)
self.last_sources[name[:-7]] = value
else:
self.last_values[name] = value
t4 = time.monotonic()
while True:
try:
msg = self.ws.recv()
except Exception as e:
break
if not msg:
print('signalk server closed connection')
if not self.keep_token:
print('signalk invalidating token')
self.token = False
self.disconnect_signalk()
return
try:
self.receive_signalk(msg)
except Exception as e:
debug('failed to parse signalk', e)
return
self.keep_token = True # do not throw away token if we got valid data
t5 = time.monotonic()
# convert received signalk values into sensor inputs if possible
for sensor, sensor_table in signalk_table.items():
for source, values in self.signalk_values.items():
data = {}
for signalk_path_conversion, pypilot_path in sensor_table.items():
signalk_path, signalk_conversion = signalk_path_conversion
if signalk_path in values:
try:
value = values[signalk_path]
if type(pypilot_path) == type({}): # single path translates to multiple pypilot
for signalk_key, pypilot_key in pypilot_path.items():
data[pypilot_key] = value[signalk_key] / signalk_conversion
else:
data[pypilot_path] = value / signalk_conversion
except Exception as e:
print(_('Exception converting signalk->pypilot'), e, self.signalk_values)
break
elif signalk_conversion != 1: # don't require fields with conversion of 1
break # missing fields? skip input this iteration
else:
for signalk_path_conversion in sensor_table:
signalk_path, signalk_conversion = signalk_path_conversion
if signalk_path in values:
del values[signalk_path]
# all needed sensor data is found
data['device'] = source + 'signalk'
if self.sensors_pipe:
self.sensors_pipe.send([sensor, data])
else:
debug('signalk ' + _('received'), sensor, data)
break
#print('sigktimes', t1-t0, t2-t1, t3-t2, t4-t3, t5-t4)
def send_signalk(self):
# see if we can produce any signalk output from the data we have read
updates = []
for sensor in signalk_table:
if sensor != 'imu' and (not sensor in self.last_sources or\
source_priority[self.last_sources[sensor]]>=signalk_priority):
#debug('signalk skip send from priority', sensor)
continue
for signalk_path_conversion, pypilot_path in signalk_table[sensor].items():
signalk_path, signalk_conversion = signalk_path_conversion
if type(pypilot_path) == type({}): # single path translates to multiple pypilot
keys = self.last_values_keys[signalk_path]
# store keys we need for this signalk path in dictionary
for signalk_key, pypilot_key in pypilot_path.items():
key = sensor+'.'+pypilot_key
if key in self.last_values:
keys[key] = self.last_values[key]
# see if we have the keys needed
v = {}
for signalk_key, pypilot_key in pypilot_path.items():
key = sensor+'.'+pypilot_key
if not key in keys:
break
v[signalk_key] = keys[key]*signalk_conversion
else:
updates.append({'path': signalk_path, 'value': v})
self.last_values_keys[signalk_path] = {}
else:
key = sensor+'.'+pypilot_path
if key in self.last_values:
v = self.last_values[key]*signalk_conversion
updates.append({'path': signalk_path, 'value': v})
if updates:
# send signalk updates
msg = {'updates':[{'$source':'pypilot','values':updates}]}
debug('signalk updates', msg)
try:
self.ws.send(pyjson.dumps(msg)+'\n')
except Exception as e:
print('signalk ' + _('failed to send updates'), e)
self.disconnect_signalk()
def disconnect_signalk(self):
if self.ws:
self.ws.close()
self.ws = False
self.client.clear_watches() # don't need to receive pypilot data
def receive_signalk(self, msg):
try:
data = pyjson.loads(msg)
except:
if msg:
print('signalk ' + _('failed to parse msg:'), msg)
return
if 'updates' in data:
updates = data['updates']
for update in updates:
source = 'unknown'
if 'source' in update:
source = update['source']['talker']
elif '$source' in update:
source = update['$source']
if 'timestamp' in update:
timestamp = update['timestamp']
if not source in self.signalk_values:
self.signalk_values[source] = {}
if 'values' in update:
values = update['values']
elif 'meta' in update:
values = update['meta']
else:
debug('signalk message update contains no values or meta', update)
continue
for value in values:
path = value['path']
if path in self.signalk_last_msg_time:
if self.signalk_last_msg_time[path] == timestamp:
debug('signalk skip duplicate timestamp', source, path, timestamp)
continue
self.signalk_values[source][path] = value['value']
else:
debug('signalk skip initial message', source, path, timestamp)
self.signalk_last_msg_time[path] = timestamp
def update_sensor_source(self, sensor, source):
priority = source_priority[source]
watch = priority < signalk_priority # translate from pypilot -> signalk
if watch:
watch = self.period.value
for signalk_path_conversion, pypilot_path in signalk_table[sensor].items():
if type(pypilot_path) == type({}):
for signalk_key, pypilot_key in pypilot_path.items():
pypilot_path = sensor + '.' + pypilot_key
if pypilot_path in self.last_values:
del self.last_values[pypilot_path]
self.client.watch(pypilot_path, watch)
else:
# remove any last values from this sensor
pypilot_path = sensor + '.' + pypilot_path
if pypilot_path in self.last_values:
del self.last_values[pypilot_path]
self.client.watch(pypilot_path, watch)
subscribe = priority >= signalk_priority
# prevent duplicating subscriptions
if self.subscribed[sensor] == subscribe:
return
self.subscribed[sensor] = subscribe
if not subscribe:
#signalk can't unsubscribe by path!?!?!
subscription = {'context': '*', 'unsubscribe': [{'path': '*'}]}
debug('signalk unsubscribe', subscription)
try:
self.ws.send(pyjson.dumps(subscription)+'\n')
except Exception as e:
print('signalk failed to send', e)
self.disconnect_signalk()
return
signalk_sensor = signalk_table[sensor]
if subscribe: # translate from signalk -> pypilot
subscriptions = []
for signalk_path_conversion in signalk_sensor:
signalk_path, signalk_conversion = signalk_path_conversion
if signalk_path in self.signalk_last_msg_time:
del self.signalk_last_msg_time[signalk_path]
subscriptions.append({'path': signalk_path, 'minPeriod': self.period.value*1000, 'format': 'delta', 'policy': 'instant'})
self.subscriptions += subscriptions
else:
# remove this subscription and resend all subscriptions
debug('signalk remove subs', signalk_sensor, self.subscriptions)
subscriptions = []
for subscription in self.subscriptions:
for signalk_path_conversion in signalk_sensor:
signalk_path, signalk_conversion = signalk_path_conversion
if subscription['path'] == signalk_path:
break
else:
subscriptions.append(subscription)
self.subscriptions = subscriptions
self.signalk_last_msg_time = {}
subscription = {'context': 'vessels.self'}
subscription['subscribe'] = subscriptions
debug('signalk subscribe', subscription)
try:
self.ws.send(pyjson.dumps(subscription)+'\n')
except Exception as e:
print('signalk failed to send subscription', e)
self.disconnect_signalk()
def main():
sk = signalk()
while True:
sk.poll(1)
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
fd07b9fdad8d5582f4438aab1c8fef51b1643eff | c9ff64bd016899a1a7df0cc514fb41fbeaf3869d | /dicionario_extra_1.py | 51cf13bdf7b9c67e5de49e7d9d207343dae24d45 | [] | no_license | Viccari073/extra_excercises | a7f4931b2eccaf0800d54360ddc28b83804166ae | 826cd3a1bc174841a600ee20ac07d242a3978515 | refs/heads/master | 2022-12-16T18:15:50.681195 | 2020-08-25T01:03:49 | 2020-08-25T01:03:49 | 275,982,418 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 629 | py | """
Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário.
No final, mostre o conteúdo da estrutura na tela.
"""
cadastro = dict()
cadastro['nome'] = str(input('Nome: '))
media = float(input(f'Media de {cadastro["nome"]}: '))
cadastro['media'] = media
if media >= 7.0:
cadastro['situacao'] = 'APROVADO'
elif media < 7.0:
cadastro['situacao'] = 'REPROVADO'
print(f'Com a média de {cadastro["media"]}, o aluno {cadastro["nome"]} está {cadastro["situacao"]}!')
""" EXEMPLO PROFESSOR
for k, v in aluno.items():
print(f'{k} é igual a {v}')
"""
| [
"[email protected]"
] | |
191c73858214f3e5e42fa3ed6e23dc6d14551952 | 9f04c2977434c5854e889b424e34593fa9f938d1 | /stock_1.py | 858bfe43a44cf134f81de45903084da658bce44f | [
"MIT"
] | permissive | B10856017/chatbot_telegram_dialogflow | f5ca40d1d5568864c9944ea919fa36707d356523 | b33172951c5513b1b60e68a1b5893506a073c397 | refs/heads/main | 2023-05-04T19:57:51.495156 | 2021-05-26T04:00:17 | 2021-05-26T04:00:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 691 | py | class Stock(object):
def __init__(self, req):
self.type = req.get("queryResult").get("parameters").get("serviceterm")
self.chat_id = req.get("user").get("chat").get("id")
def dayTrend(self, req, bot):
self.chat_id = req.get("user").get("chat").get("id")
#https://github.com/python-telegram-bot/python-telegram-bot/wiki/Code-snippets#working-with-files-and-media
bot.sendPhoto(chat_id=self.chat_id, photo=open('images/fig1.png', 'rb'), caption='台積電 2330')
speech = "台積電 2330"
return {
"textToSpeech": speech,
"ssml": speech,
"displayText": speech
} | [
"[email protected]"
] | |
14d1850b73a3dd252891052bf7061504ebac69cc | 78199e980b57060267f89c3cb83abe7d98317bf4 | /Java/LeetCode/DFS&Backtracking/Tree/DiameterBinaryTree.py | 2336263c446a09d5a04754ebe75786321f421049 | [] | no_license | l0uvre/Simple-Codes | 2a836ed3aec8fe32134a831fcdb804daa901f9f3 | 05fcc28da12013852358363207921bb6d8cacab8 | refs/heads/master | 2022-08-28T22:45:57.758605 | 2022-08-06T03:23:07 | 2022-08-06T03:23:07 | 116,573,952 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 890 | py | # Definition for a binary tree node.
from typing import Optional
## LC 543 Tree, DFS, DP
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
diameter = float('-inf')
'''
Return the maximum level of breadth can be gained from a node
'''
def gainFrom(node : TreeNode): -> int
nonlocal diameter
if node is None:
return -1
else:
leftGain = gainFrom(node.left) + 1
rightGain = gainFrom(node.right) + 1
diameter = max(diameter, leftGain + rightGain)
return max(leftGain, rightGain)
gainFrom(root)
return int(diameter)
| [
"[email protected]"
] | |
600726e9c8157d2680f567b3c5ae22beb6afcaf8 | df5931ac3b2d4f4769f422d351bf6f35becb57ac | /apps/users/migrations/0002_banner_emailverifyrecord.py | 3ce9db4eaa1b3dd379e8bea68363b1d712357a94 | [] | no_license | chendongyi/MxOnline | 420e730da52c78a29e9a0c90af641fcdb144a185 | 6c24e258c80a0aa63a21d96fcbcf291d4c2fefb9 | refs/heads/master | 2020-03-23T04:41:38.893804 | 2018-07-20T04:45:27 | 2018-07-20T04:45:27 | 141,099,618 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,797 | py | # Generated by Django 2.0.6 on 2018-06-05 08:18
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Banner',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100, verbose_name='标题')),
('image', models.ImageField(upload_to='banner/%Y/%m', verbose_name='轮播图')),
('url', models.URLField(verbose_name='访问地址')),
('index', models.IntegerField(default=100, verbose_name='顺序')),
('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')),
],
options={
'verbose_name': '轮播图',
'verbose_name_plural': '轮播图',
},
),
migrations.CreateModel(
name='EmailVerifyRecord',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('code', models.CharField(max_length=20, verbose_name='验证码')),
('email', models.EmailField(max_length=50, verbose_name='邮箱')),
('send_type', models.CharField(choices=[('register', '注册'), ('forget', '找回密码')], max_length=10)),
('send_time', models.DateTimeField(default=datetime.datetime.now)),
],
options={
'verbose_name': '邮箱验证码',
'verbose_name_plural': '邮箱验证码',
},
),
]
| [
"[email protected]"
] | |
e23bc12419592f4b9956c4150d64796a12d4900f | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03329/s950503139.py | 06a2ed1899ce879a8061ac47bf453dca06be7b16 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 490 | py | import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
def main():
n = int(input())
nums = []
n6 = 6
while n6 <= n:
nums.append(n6)
n6 = n6 * 6
n9 = 9
while n9 <= n:
nums.append(n9)
n9 = n9 * 9
nums.sort(reverse=True)
dp = [i for i in range(2 * n + 1)]
for num in nums:
for j1 in range(n + 1):
dp[j1+num] = min(dp[j1+num], dp[j1] + 1)
print(dp[n])
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
6a2b5689eeaab249fbbcd16268bfeaf37add46d9 | a5a2abaf5c7a681ebea71b4034d7b12dbd750455 | /examens/migrations/0002_auto_20160210_0540.py | 4a24c8b6dac1ce2a87efbeacc069d098d652c98a | [
"BSD-3-Clause"
] | permissive | matinfo/dezede | e8be34a5b92f8e793a96396f7ec4ec880e7817ff | 829ba8c251a0301741460e6695438be52d04a2fc | refs/heads/master | 2020-03-15T11:25:56.786137 | 2018-04-23T13:47:20 | 2018-04-23T13:47:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,213 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
LEVELS_DATA = (
(1, (6107, 10442, 10531)),
(2, (2253, 12468, 12469)),
(3, (10603, 8167, 10447)),
(4, (8280, 15117)),
(5, (3412, 14)),
(6, (2256,)),
)
LEVELS_HELPS = {
1: """
<p>
L’exercice consiste à transcrire un ensemble de sources
de manière diplomatique.
Il comporte six étapes à la difficulté croissante.
Chaque étape est validée lorsque le texte saisi
correspond exactement au texte contenu dans la source.
</p>
<p>
Pour ce type de transcription, il est important de respecter
le texte de la source : graphie fautive, style (capitales,
petites capitales, etc.), abréviations, ponctuation.
Deux exceptions sont admises :
</p>
<ul>
<li>
l’accentuation doit être rétablie suivant l’usage moderne
(y compris sur les majuscules) ;
</li>
<li>
la justification ne doit pas être respectée :
vous devez aligner le texte à gauche.
</li>
</ul>
""",
2: """
<p>
Mêmes règles que pour la première étape.
On insiste cette fois-ci sur le respect des styles
(capitales, petites capitales, italique, gras, exposant).
</p>
""",
3: """
<p>
Dans une transcription diplomatique, l’usage est de respecter
les graphies fautives. Dans ce cas, le mot erroné doit être suivi
de la locution latine « sic » en italique et entre crochets carrés.
Par exemple : « Beethowen [<em>sic</em>] ».
</p>
""",
4: """<p>Combinaison des règles précédentes.</p>""",
5: """
<p>
Combinaison des règles précédentes sur une transcription plus longue.
</p>
<p>
Certaines fautes apparentes pour un lecteur d’aujourd’hui sont en fait
des usages d’orthographe de l’époque.
Par exemple, on écrivait indifféremment « accents » ou « accens »
pour le pluriel d’« accent ».
</p>
<p>Conservez l’orthographe des noms propres.</p>
""",
6: """
<p>
Utilisez les outils de tableau de l’éditeur de texte
pour obtenir un tableau sans bordure.
Ne pas inclure les points servant de guides dans le tableau.
</p>
""",
}
def add_levels(apps, schema_editor):
Level = apps.get_model('examens.Level')
LevelSource = apps.get_model('examens.LevelSource')
Source = apps.get_model('libretto.Source')
level_sources = []
for level_number, source_ids in LEVELS_DATA:
level = Level.objects.create(
number=level_number, help_message=LEVELS_HELPS[level_number])
for pk in source_ids:
try:
source = Source.objects.get(pk=pk)
except Source.DoesNotExist:
continue
level_sources.append(LevelSource(level=level, source=source))
LevelSource.objects.bulk_create(level_sources)
class Migration(migrations.Migration):
dependencies = [
('examens', '0001_initial'),
]
operations = [
migrations.RunPython(add_levels),
]
| [
"[email protected]"
] | |
6b31c5782ba2db81a6a2b0b105aa3a0552dcb4ad | 0e4519d3a94157a419e56576875aec1da906f578 | /Python_200Q/051_/Q059.py | 110df8a421ca7cff330c0a2f0054d5279bd7f11d | [] | no_license | ivorymood/TIL | 0de3b92861e345375e87d01654d1fddf940621cd | 1f09e8b1f4df7c205c68eefd9ab02d17a85d140a | refs/heads/master | 2021-02-23T17:30:50.406370 | 2020-10-02T06:43:25 | 2020-10-02T06:43:25 | 245,388,390 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 251 | py | import time
count = 1
try:
while True:
print(count)
count += 1
time.sleep(0.5)
# Ctrl + C가 입력되면 발생되는 오류
except KeyboardInterrupt:
print('사용자에 의해 프로그램이 중단되었습니다') | [
"[email protected]"
] | |
091ab45ff559b57ac0a45909cf64482b20180975 | 24131940f40e1c71f3a7c0fa3368d09053feb036 | /loop.py | df565bf92ba800b40f0a3161a25380e40aab5804 | [] | no_license | binshadpb/expertzlab_python | de9f5f417201ae034dcdaa0cf9cccd0543c733f9 | b7d29a9f8d356bc9b060dffa3aa8418b454e546e | refs/heads/master | 2023-01-20T13:38:32.766810 | 2020-11-29T14:40:11 | 2020-11-29T14:40:11 | 314,594,318 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 955 | py | #prim number program using whilw loop
# number=int(input("enter the number"))
# i=2
# a=1
# while i<number:
# if number%i==0:
# a=0
# i+=1
#
#
# if a==0:
# print("Its not a prime number")
# else:
# print("its a prime number")
#program numbers divisible by 5 or 7 below 100 using while lopp
# n=100
# i=1
# a=1
# while i<n:
# if ((i%5==0) or (i%7==0)):
# a=0
#
# print(i)
# i+=1
#for lopp programs(for loop executed only in collection (indexing))
# l=[10,50,"hello",20,"world",100]
#
# for i in l:
# print(i)
# print("*****")
#for loop program to count odd numbers and even numbers in a list
# l=[1,2,3,4,5,6,7,8,9,10,11,12,13]
# odd=0
# even=0
# for i in l:
# # print(i)
# if i%2==0:
# even+=1
# else:
#
# odd+=1
#
# print("odd numbers",odd)
# print("even numbers",even)
#range function implementation
print(list(range(10)))
for i in range(10,50,5):
print(i) | [
"[email protected]"
] | |
e78b99366d88cbdb16defac1ca2282fdf9ecf490 | 82f7c00aa14c95032fb6e6ff1029823404246b83 | /apps/statistics/rstats.py | a55468334938caefa6725db99cec04117e861e29 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | gillbates/NewsBlur | 621feaa090cdc2fe9dcfcae4af7de3f40b69ba00 | 0eb2ccf4ebe59ff27d6ed822cc406a427cf3bf6a | refs/heads/master | 2020-12-30T17:32:03.999893 | 2013-07-01T00:12:41 | 2013-07-01T00:12:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,566 | py | import redis
import datetime
import re
from collections import defaultdict
from django.conf import settings
class RStats:
STATS_TYPE = {
'page_load': 'PLT',
'feed_fetch': 'FFH',
}
@classmethod
def stats_type(cls, name):
return cls.STATS_TYPE[name]
@classmethod
def add(cls, name, duration=None):
r = redis.Redis(connection_pool=settings.REDIS_STATISTICS_POOL)
pipe = r.pipeline()
minute = round_time(round_to=60)
key = "%s:%s" % (cls.stats_type(name), minute.strftime('%s'))
pipe.incr("%s:s" % key)
if duration:
pipe.incrbyfloat("%s:a" % key, duration)
pipe.expireat("%s:a" % key, (minute + datetime.timedelta(days=2)).strftime("%s"))
pipe.expireat("%s:s" % key, (minute + datetime.timedelta(days=2)).strftime("%s"))
pipe.execute()
@classmethod
def clean_path(cls, path):
if not path:
return
if path.startswith('/reader/feed/'):
path = '/reader/feed/'
elif path.startswith('/social/stories'):
path = '/social/stories/'
elif path.startswith('/reader/river_stories'):
path = '/reader/river_stories/'
elif path.startswith('/social/river_stories'):
path = '/social/river_stories/'
elif path.startswith('/reader/page/'):
path = '/reader/page/'
elif path.startswith('/api/check_share_on_site'):
path = '/api/check_share_on_site/'
return path
@classmethod
def count(cls, name, hours=24):
r = redis.Redis(connection_pool=settings.REDIS_STATISTICS_POOL)
stats_type = cls.stats_type(name)
now = datetime.datetime.now()
pipe = r.pipeline()
for minutes_ago in range(60*hours):
dt_min_ago = now - datetime.timedelta(minutes=minutes_ago)
minute = round_time(dt=dt_min_ago, round_to=60)
key = "%s:%s" % (stats_type, minute.strftime('%s'))
pipe.get("%s:s" % key)
values = pipe.execute()
total = sum(int(v) for v in values if v)
return total
@classmethod
def sample(cls, sample=1000, pool=None):
if not pool:
pool = settings.REDIS_STORY_HASH_POOL
r = redis.Redis(connection_pool=pool)
keys = set()
errors = set()
prefixes = defaultdict(set)
prefixes_ttls = defaultdict(lambda: defaultdict(int))
prefix_re = re.compile(r"(\w+):(.*)")
p = r.pipeline()
[p.randomkey() for _ in range(sample)]
keys = set(p.execute())
p = r.pipeline()
[p.ttl(key) for key in keys]
ttls = p.execute()
for k, key in enumerate(keys):
match = prefix_re.match(key)
if not match:
errors.add(key)
continue
prefix, rest = match.groups()
prefixes[prefix].add(rest)
ttl = ttls[k]
if ttl < 60*60: # 1 hour
prefixes_ttls[prefix]['1h'] += 1
elif ttl < 60*60*12:
prefixes_ttls[prefix]['12h'] += 1
elif ttl < 60*60*24:
prefixes_ttls[prefix]['1d'] += 1
elif ttl < 60*60*168:
prefixes_ttls[prefix]['1w'] += 1
elif ttl < 60*60*336:
prefixes_ttls[prefix]['2w'] += 1
else:
prefixes_ttls[prefix]['2w+'] += 1
keys_count = len(keys)
print " ---> %s total keys" % keys_count
for prefix, rest in prefixes.items():
total_expiring = sum([k for k in dict(prefixes_ttls[prefix]).values()])
print " ---> %4s: (%.4s%%) %s keys (%s expiring: %s)" % (prefix, 100. * (len(rest) / float(keys_count)), len(rest), total_expiring, dict(prefixes_ttls[prefix]))
print " ---> %s errors: %s" % (len(errors), errors)
def round_time(dt=None, round_to=60):
"""Round a datetime object to any time laps in seconds
dt : datetime.datetime object, default now.
round_to : Closest number of seconds to round to, default 1 minute.
Author: Thierry Husson 2012 - Use it as you want but don't blame me.
"""
if dt == None : dt = datetime.datetime.now()
seconds = (dt - dt.min).seconds
rounding = (seconds+round_to/2) // round_to * round_to
return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)
| [
"[email protected]"
] | |
eaaa3e518f566d4c9e4174b3e550e3ef6e0e9d55 | 85caf3d66dfbf8fb30c064ed629966fc18bb7a26 | /alert_service_45.py | 1c727a3f142188f155dedc0203b305e41ff7ff4e | [] | no_license | karandoshi98/CowinVaccineAlerts | e63f3e6946032bdbd02826b561df7e3c7a9348e0 | 074b3161eeb32f353f255fc98e979936980f45f4 | refs/heads/main | 2023-04-26T12:40:19.922137 | 2021-05-20T16:12:02 | 2021-05-20T16:12:02 | 368,974,452 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,968 | py | # Importing libraries
import app
import requests
import json
import time
from datetime import datetime, date
import smtplib
date_str = str(date.today())
y = date_str[:4]
m = date_str[5:7]
d = str(int(date_str[8:10]) + 1)
DATE = d+"-"+m+"-"+y
MY_EMAIL = "[email protected]"
MY_PASS = 'krds1998'
# Palghar = str(394)
# Mumbai = str(395)
# Thane = str(392)
#url_district = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict?district_id="+Palghar+"&date="+DATE
# with requests.session() as state_session:
# headers = {
# 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
# response = state_session.get("https://cdn-api.co-vin.in/api/v2/admin/location/states", headers=headers)
# print(response.json())
# with requests.session() as dist_session:
# headers = {
# 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
# response = dist_session.get("https://cdn-api.co-vin.in/api/v2/admin/location/districts/21", headers=headers)
# print(response.json())
# with requests.session() as appointment_dist_session:
# headers = {
# 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
# response = appointment_dist_session.get(url_district, headers=headers)
# response = response.json()
while True:
cur = open("user_details_45.json", "r")
try:
user_details = json.loads(cur.read())
except Exception as e:
print(e)
user_details = {}
cur.close()
print(user_details)
for PINCODE in user_details:
print(PINCODE)
mail_to = []
mail_to = user_details[PINCODE]
url_pincode = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByPin?pincode=" + PINCODE + "&date=" + DATE
with requests.session() as appointment_pin_session:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
response = appointment_pin_session.get(url_pincode, headers=headers)
response = response.json()
print(response)
if response['sessions'] == []:
print("No slots available at this moment")
for center in response['sessions']:
# print(center['fee_type'])
# print(center['fee'])
# print(center['min_age_limit'])
# print(center['available_capacity'])
# print(center['available_capacity_dose1'])
# print(center['available_capacity_dose2'])
# print(center['vaccine'])
# print(center['slots'])
if center['min_age_limit'] == 45 and center['available_capacity'] != 0:
message_string = f"Subject: {date_str}'s Vaccine Alert'!! \nVaccine available at-\n{center['name']} for the age above {center['min_age_limit']} \n\nSlots available- {center['available_capacity']}\nSlots for 1st Dose - {center['available_capacity_dose1']}\nSlots for 2nd Dose - {center['available_capacity_dose2']} \n\nAddress: {center['address']}\nhttps://www.cowin.gov.in/home"
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(MY_EMAIL, MY_PASS)
connection.sendmail(
from_addr=MY_EMAIL,
to_addrs=mail_to,
msg=message_string
)
print("Mail sent to "+str(mail_to)+" for pincode "+str(PINCODE)+" for age above 45")
else:
print("No slots available for above 45")
time.sleep(60)
| [
"[email protected]"
] | |
eb442f39adcfd2574853c91485fa1346cffc836e | d286282c96ed1740a4afa266b290d26a6017fa42 | /src/MakeSample.py | 299e4b74ec3b094f93cb60f044888c0c86543179 | [] | no_license | n-narisawa/GraphSLAM | c438c8322aba835a61f2b3fa9592fbbe797ff4ea | 9276f882d67e2e0b67e175687fc4fc0dfe6e7f25 | refs/heads/master | 2020-06-12T11:01:20.581522 | 2019-07-12T04:40:17 | 2019-07-12T04:40:17 | 194,278,227 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,027 | py | import numpy as np
from numpy.linalg import norm
from numpy.random import normal
import matplotlib.pyplot as plt
import os
A = 30
B = 20
RANGE = 20
TIMEFRAME = 1000
NFEATURE = 100
epsilon = 1e-6
def ellipse():
theta = np.linspace(0, 2*np.pi, TIMEFRAME+1)
x = A * np.cos(theta)
y = B * np.sin(theta)
tan = np.arctan2(B**2*x, -A**2*y)
tan[0] = 0
return np.vstack((x, y, tan))
def line():
x = np.zeros(TIMEFRAME+1)
y = np.linspace(0, 50, TIMEFRAME+1)
tan = np.arctan2(B ** 2 * x, -A ** 2 * y)
tan[0] = 0
return np.vstack((x, y, tan))
def landmark():
# lmx = np.random.randint(-A-10, A+10, NFEATURE)
# lmy = np.random.randint(-B-10, B+10, NFEATURE)
lmx = np.random.randint(A-10, A+10, NFEATURE)*np.cos(np.random.randint(0,2*np.pi,NFEATURE))
lmy = np.random.randint(B-10, B+10, NFEATURE)*np.cos(np.random.randint(0,2*np.pi,NFEATURE))
# lmx = np.random.randint(-10, 10, NFEATURE)
# lmy = np.random.randint(-10, 50+10, NFEATURE)
return np.vstack((lmx, lmy))
def main():
dirname = "../data/sample{}".format(len(os.listdir("../data/")))
os.mkdir(dirname)
inputdata = os.path.join(dirname, "input.txt")
truedata = os.path.join(dirname, "truedata.txt")
xnpy = os.path.join(dirname, "xTrue.npy")
lmnpy = os.path.join(dirname, "lmTrue.npy")
fig = os.path.join(dirname, "truedata.png")
x = ellipse()
# x = line()
dx = np.diff(x)
dx[2,:] = (dx[2,:] + np.pi)%(2*np.pi) - np.pi
lm = landmark()
lmdict = dict()
t1 = 0
t2 = 1
with open(inputdata, "w") as f_ob, open(truedata, "w") as f_tr:
for t in range(TIMEFRAME):
c = 0
edge_tr = rotation_matrix(-x[2,t]) @ dx[:2,t]
edge_ob = edge_tr + normal(0, 0.3, 2)
tan_ob = dx[2,t] + normal(0, np.deg2rad(1.0))
f_tr.write("EDGE_SE2 {} {} {} {} {} 0 0 0 0 0 0\n".format(t1, t2, edge_tr[0], edge_tr[1], dx[2,t]))
f_ob.write("EDGE_SE2 {} {} {} {} {} 0 0 0 0 0 0\n".format(t1, t2, edge_ob[0], edge_ob[1], tan_ob))
for j in range(NFEATURE):
if norm(x[:2,t+1] - lm[:,j]) < RANGE:
if j not in lmdict.keys():
c += 1
lmdict[j] = t2 + c
edge_tr = rotation_matrix(-x[2,t+1]) @ (lm[:,j] - x[:2,t+1])
edge_ob = edge_tr + normal(0, 0.3, 2)
f_tr.write("EDGE_SE2_XY {} {} {} {} 0 0 0 0 0 0\n".format(t2, lmdict[j], edge_tr[0], edge_tr[1]))
f_ob.write("EDGE_SE2_XY {} {} {} {} 0 0 0 0 0 0\n".format(t2, lmdict[j], edge_ob[0], edge_ob[1]))
t1 = t2
t2 += 1 + c
np.save(xnpy, x)
np.save(lmnpy, lm)
plt.plot(x[0,:], x[1,:])
plt.scatter(lm[0,:], lm[1,:])
plt.savefig(fig)
plt.show()
def rotation_matrix(theta):
return np.array([[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)]])
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
c357a3066761f697e7adc957d4e50bcf31ced98d | 4fbfcff9c498c597766655cee4867b13b0bc2c16 | /Python/MiniProjects/Others/CardShuffle.py | 9d575c04aefcd78c19c2a850b783378aa8ade3e4 | [] | no_license | seniroberts/Expressions | e0541636cc5b4f5666d26ca3cb3e38c8294986b9 | dee95389555afef2caa71c16fcef33aaf0f8631a | refs/heads/master | 2022-12-19T21:54:58.703454 | 2020-10-09T08:09:44 | 2020-10-09T08:09:44 | 294,386,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 849 | py | import random
card_deck = ["a", "b", "c", "d", "e", "f"]
def shuffleCards(card_deck):
numberofCards = len(card_deck)
for i in range(0, numberofCards - 1):
randon_number = random.randint(0, numberofCards-1)
temp = card_deck[i]
card_deck[i] = card_deck[randon_number]
card_deck[randon_number] = temp
return card_deck # To return the shuffled list
# use the below to return individual cards
for i in range(0, numberofCards):
print(card_deck[i])
# print(shuffleCards(card_deck))
nums = [10, 2, 13, 4, 51, 6, 17]
def sortList(nums):
for i in range(0, len(nums)):
for j in range(i + 1, (len(nums))):
if nums[i] > nums[j]:
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
return nums
print(sortList(nums))
| [
"[email protected]"
] | |
8cc839ce2eb3f1d63aae16b0a5a37c6d5b8669aa | f4434c85e3814b6347f8f8099c081ed4af5678a5 | /sdk/identity/azure-identity/tests/test_authn_client.py | 3dac71b924c722a3ccaee3a40a4d6d8bfffbdf1c | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] | permissive | yunhaoling/azure-sdk-for-python | 5da12a174a37672ac6ed8e3c1f863cb77010a506 | c4eb0ca1aadb76ad892114230473034830116362 | refs/heads/master | 2022-06-11T01:17:39.636461 | 2020-12-08T17:42:08 | 2020-12-08T17:42:08 | 177,675,796 | 1 | 0 | MIT | 2020-03-31T20:35:17 | 2019-03-25T22:43:40 | Python | UTF-8 | Python | false | false | 9,973 | py | # ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""These tests use the synchronous AuthnClient as a driver to test functionality
of the sans I/O AuthnClientBase shared with AsyncAuthnClient."""
import json
import time
try:
from unittest.mock import Mock, patch
except ImportError: # python < 3.3
from mock import Mock, patch # type: ignore
from azure.core.credentials import AccessToken
from azure.identity._authn_client import AuthnClient
from azure.identity._constants import EnvironmentVariables, DEFAULT_REFRESH_OFFSET, DEFAULT_TOKEN_REFRESH_RETRY_DELAY
import pytest
from six.moves.urllib_parse import urlparse
from helpers import mock_response
def test_deserialization_expires_integers():
now = 6
expires_in = 59 - now
expires_on = now + expires_in
access_token = "***"
expected_access_token = AccessToken(access_token, expires_on)
scope = "scope"
# response with expires_on only
token_payload = {"access_token": access_token, "expires_on": expires_on, "token_type": "Bearer", "resource": scope}
mock_send = Mock(return_value=mock_response(json_payload=token_payload))
token = AuthnClient(endpoint="http://foo", transport=Mock(send=mock_send)).request_token(scope)
assert token == expected_access_token
# response with expires_in as well
token_payload = {
"access_token": access_token,
"expires_in": expires_in,
"token_type": "Bearer",
"ext_expires_in": expires_in,
}
with patch(AuthnClient.__module__ + ".time.time") as mock_time:
mock_time.return_value = now
mock_send = Mock(return_value=mock_response(json_payload=token_payload))
token = AuthnClient(endpoint="http://foo", transport=Mock(send=mock_send)).request_token(scope)
assert token == expected_access_token
def test_deserialization_app_service_msi():
now = 6
expires_in = 59 - now
expires_on = now + expires_in
access_token = "***"
expected_access_token = AccessToken(access_token, expires_on)
scope = "scope"
# response with expires_on only and it's a datetime string (App Service MSI, Linux)
token_payload = {
"access_token": access_token,
"expires_on": "01/01/1970 00:00:{} +00:00".format(now + expires_in),
"token_type": "Bearer",
"resource": scope,
}
mock_send = Mock(return_value=mock_response(json_payload=token_payload))
token = AuthnClient(endpoint="http://foo", transport=Mock(send=mock_send)).request_token(scope)
assert token == expected_access_token
def test_deserialization_expires_strings():
now = 6
expires_in = 59 - now
expires_on = now + expires_in
access_token = "***"
expected_access_token = AccessToken(access_token, expires_on)
scope = "scope"
# response with string expires_in and expires_on (IMDS, Cloud Shell)
token_payload = {
"access_token": access_token,
"expires_in": str(expires_in),
"ext_expires_in": str(expires_in),
"expires_on": str(expires_on),
"token_type": "Bearer",
"resource": scope,
}
mock_send = Mock(return_value=mock_response(json_payload=token_payload))
token = AuthnClient(endpoint="http://foo", transport=Mock(send=mock_send)).request_token(scope)
assert token == expected_access_token
def test_caching_when_only_expires_in_set():
"""the cache should function when auth responses don't include an explicit expires_on"""
access_token = "token"
now = 42
expires_in = 1800
expires_on = now + expires_in
expected_token = AccessToken(access_token, expires_on)
mock_send = Mock(
return_value=mock_response(
json_payload={"access_token": access_token, "expires_in": expires_in, "token_type": "Bearer"}
)
)
client = AuthnClient(endpoint="http://foo", transport=Mock(send=mock_send))
with patch("azure.identity._authn_client.time.time") as mock_time:
mock_time.return_value = 42
token = client.request_token(["scope"])
assert token.token == expected_token.token
assert token.expires_on == expected_token.expires_on
cached_token = client.get_cached_token(["scope"])
assert cached_token == expected_token
def test_expires_in_strings():
expected_token = "token"
mock_send = Mock(
return_value=mock_response(
json_payload={
"access_token": expected_token,
"expires_in": "42",
"ext_expires_in": "42",
"token_type": "Bearer",
}
)
)
now = int(time.time())
with patch("azure.identity._authn_client.time.time") as mock_time:
mock_time.return_value = now
token = AuthnClient(endpoint="http://foo", transport=Mock(send=mock_send)).request_token("scope")
assert token.token == expected_token
assert token.expires_on == now + 42
def test_cache_expiry():
access_token = "token"
now = 42
expires_in = 1800
expires_on = now + expires_in
expected_token = AccessToken(access_token, expires_on)
token_payload = {"access_token": access_token, "expires_in": expires_in, "token_type": "Bearer"}
mock_send = Mock(return_value=mock_response(json_payload=token_payload))
client = AuthnClient(endpoint="http://foo", transport=Mock(send=mock_send))
with patch("azure.identity._authn_client.time.time") as mock_time:
# populate the cache with a valid token
mock_time.return_value = now
token = client.request_token("scope")
assert token.token == expected_token.token
assert token.expires_on == expected_token.expires_on
cached_token = client.get_cached_token("scope")
assert cached_token == expected_token
# advance time past the cached token's expires_on
mock_time.return_value = expires_on + 3600
cached_token = client.get_cached_token("scope")
assert not cached_token
# request a new token
new_token = "new token"
token_payload["access_token"] = new_token
token = client.request_token("scope")
assert token.token == new_token
# it should be cached
cached_token = client.get_cached_token("scope")
assert cached_token.token == new_token
def test_cache_scopes():
scope_a = "scope_a"
scope_b = "scope_b"
scope_ab = scope_a + " " + scope_b
expected_tokens = {
scope_a: {"access_token": scope_a, "expires_in": 1 << 31, "ext_expires_in": 1 << 31, "token_type": "Bearer"},
scope_b: {"access_token": scope_b, "expires_in": 1 << 31, "ext_expires_in": 1 << 31, "token_type": "Bearer"},
scope_ab: {"access_token": scope_ab, "expires_in": 1 << 31, "ext_expires_in": 1 << 31, "token_type": "Bearer"},
}
def mock_send(request, **kwargs):
token = expected_tokens[request.data["resource"]]
return mock_response(json_payload=token)
client = AuthnClient(endpoint="http://foo", transport=Mock(send=mock_send))
# if the cache has a token for a & b, it should hit for a, b, a & b
token = client.request_token([scope_a, scope_b], form_data={"resource": scope_ab})
assert token.token == scope_ab
for scope in (scope_a, scope_b):
assert client.get_cached_token([scope]).token == scope_ab
assert client.get_cached_token([scope_a, scope_b]).token == scope_ab
# if the cache has only tokens for a and b alone, a & b should miss
client = AuthnClient(endpoint="http://foo", transport=Mock(send=mock_send))
for scope in (scope_a, scope_b):
token = client.request_token([scope], form_data={"resource": scope})
assert token.token == scope
assert client.get_cached_token([scope]).token == scope
assert not client.get_cached_token([scope_a, scope_b])
@pytest.mark.parametrize("authority", ("localhost", "https://localhost"))
def test_request_url(authority):
tenant_id = "expected-tenant"
parsed_authority = urlparse(authority)
expected_netloc = parsed_authority.netloc or authority # "localhost" parses to netloc "", path "localhost"
def validate_url(url):
actual = urlparse(url)
assert actual.scheme == "https"
assert actual.netloc == expected_netloc
assert actual.path.startswith("/" + tenant_id)
def mock_send(request, **kwargs):
validate_url(request.url)
return mock_response(json_payload={"token_type": "Bearer", "expires_in": 42, "access_token": "***"})
client = AuthnClient(tenant=tenant_id, transport=Mock(send=mock_send), authority=authority)
client.request_token(("scope",))
request = client.get_refresh_token_grant_request({"secret": "***"}, "scope")
validate_url(request.url)
# authority can be configured via environment variable
with patch.dict("os.environ", {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}, clear=True):
client = AuthnClient(tenant=tenant_id, transport=Mock(send=mock_send))
client.request_token(("scope",))
request = client.get_refresh_token_grant_request({"secret": "***"}, "scope")
validate_url(request.url)
def test_should_refresh():
client = AuthnClient(endpoint="http://foo")
now = int(time.time())
# do not need refresh
token = AccessToken("token", now + DEFAULT_REFRESH_OFFSET + 1)
should_refresh = client.should_refresh(token)
assert not should_refresh
# need refresh
token = AccessToken("token", now + DEFAULT_REFRESH_OFFSET - 1)
should_refresh = client.should_refresh(token)
assert should_refresh
# not exceed cool down time, do not refresh
token = AccessToken("token", now + DEFAULT_REFRESH_OFFSET - 1)
client._last_refresh_time = now - DEFAULT_TOKEN_REFRESH_RETRY_DELAY + 1
should_refresh = client.should_refresh(token)
assert not should_refresh
| [
"[email protected]"
] | |
65a4c58bbd2f6b1e6f6ce5534a14c31b02315230 | 28a72c59685f018611d3af9092fb36ee7d01b375 | /maps/recommend.py | 60b7c7e7527ad13dd380dcb28836bf0a1d587d5b | [] | no_license | mollygoss/cs61a | 86cd612787807a0c4938fae894140abb1e93fbba | 403530da63adfafa0d5cf8df77d5af5fb5ae72c4 | refs/heads/master | 2020-04-14T13:50:24.742596 | 2019-01-02T20:13:12 | 2019-01-02T20:13:12 | 163,880,105 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,046 | py | """A Yelp-powered Restaurant Recommendation Program"""
from abstractions import *
from data import ALL_RESTAURANTS, CATEGORIES, USER_FILES, load_user_file
from ucb import main, trace, interact
from utils import distance, mean, zip, enumerate, sample
from visualize import draw_map
##################################
# Phase 2: Unsupervised Learning #
##################################
def find_closest(location, centroids):
"""Return the centroid in centroids that is closest to location. If
multiple centroids are equally close, return the first one.
>>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
[2.0, 3.0]
"""
# BEGIN Question 3
"""distances = []
for centroid in centroids:
distances.append((centroid, distance(location, centroid))
return min(distances, key=lambda tup: tup[1])"""
return min(centroids, key= lambda c: distance(location, c))
# END Question 3
def group_by_first(pairs):
"""Return a list of pairs that relates each unique key in the [key, value]
pairs to a list of all values that appear paired with that key.
Arguments:
pairs -- a sequence of pairs
>>> example = [ [1, 2], [3, 2], [2, 4], [1, 3], [3, 1], [1, 2] ]
>>> group_by_first(example)
[[2, 3, 2], [2, 1], [4]]
"""
keys = []
for key, _ in pairs:
if key not in keys:
keys.append(key)
return [[y for x, y in pairs if x == key] for key in keys]
def group_by_centroid(restaurants, centroids):
"""Return a list of clusters, where each cluster contains all restaurants
nearest to a corresponding centroid in centroids. Each item in
restaurants should appear once in the result, along with the other
restaurants closest to the same centroid.
"""
# BEGIN Question 4
listoclusters = [[find_closest(restaurant_location(x), centroids),x] for x in restaurants]
return group_by_first(listoclusters)
# END Question 4
def find_centroid(cluster):
"""Return the centroid of the locations of the restaurants in cluster."""
# BEGIN Question 5
centroid = [mean([restaurant_location(x)[0] for x in cluster]), mean([restaurant_location(x)[1] for x in cluster])]
return centroid
# END Question 5
def k_means(restaurants, k, max_updates=100):
"""Use k-means to group restaurants by location into k clusters."""
assert len(restaurants) >= k, 'Not enough restaurants to cluster'
old_centroids, n = [], 0
# Select initial centroids randomly by choosing k different restaurants
centroids = [restaurant_location(r) for r in sample(restaurants, k)]
while old_centroids != centroids and n < max_updates:
old_centroids = centroids
# BEGIN Question 6
cluster = group_by_centroid(restaurants, centroids)
centroids = [find_centroid(x) for x in cluster]
# END Question 6
n += 1
return centroids
def find_predictor(user, restaurants, feature_fn):
"""Return a rating predictor (a function from restaurants to ratings),
for a user by performing least-squares linear regression using feature_fn
on the items in restaurants. Also, return the R^2 value of this model.
Arguments:
user -- A user
restaurants -- A sequence of restaurants
feature_fn -- A function that takes a restaurant and returns a number
"""
reviews_by_user = {review_restaurant_name(review): review_rating(review)
for review in user_reviews(user).values()}
xs = [feature_fn(r) for r in restaurants]
ys = [reviews_by_user[restaurant_name(r)] for r in restaurants]
# BEGIN Question 7
def s_xx():
return [(x-mean(xs))**2 for x in xs]
def s_yy():
return [(y-mean(ys))**2 for y in ys]
sxx = sum(s_xx())
syy = sum(s_yy())
newlist = zip([y-mean(ys) for y in ys], [x-mean(xs) for x in xs])
sxy = sum([x*y for y,x in newlist])
b = (sxy/sxx)
a = (mean(ys) - b*mean(xs))
r_squared = ((sxy**2)/(sxx*syy)) # REPLACE THIS LINE WITH YOUR SOLUTION
# END Question 7
def predictor(restaurant):
return b * feature_fn(restaurant) + a
return predictor, r_squared
def best_predictor(user, restaurants, feature_fns):
"""Find the feature within feature_fns that gives the highest R^2 value
for predicting ratings by the user; return a predictor using that feature.
Arguments:
user -- A user
restaurants -- A list of restaurants
feature_fns -- A sequence of functions that each takes a restaurant
"""
reviewed = user_reviewed_restaurants(user, restaurants)
# BEGIN Question 8
highest = max(feature_fns, key=lambda f: find_predictor(user, reviewed, f)[1])
return find_predictor(user, reviewed, highest)[0]
# END Question 8
def rate_all(user, restaurants, feature_fns):
"""Return the predicted ratings of restaurants by user using the best
predictor based a function from feature_fns.
Arguments:
user -- A user
restaurants -- A list of restaurants
feature_fns -- A sequence of feature functions
"""
predictor = best_predictor(user, ALL_RESTAURANTS, feature_fns)
reviewed = user_reviewed_restaurants(user, restaurants)
# BEGIN Question 9
"*** REPLACE THIS LINE ***"
# END Question 9
def search(query, restaurants):
"""Return each restaurant in restaurants that has query as a category.
Arguments:
query -- A string
restaurants -- A sequence of restaurants
"""
# BEGIN Question 10
"*** REPLACE THIS LINE ***"
# END Question 10
def feature_set():
"""Return a sequence of feature functions."""
return [restaurant_mean_rating,
restaurant_price,
restaurant_num_ratings,
lambda r: restaurant_location(r)[0],
lambda r: restaurant_location(r)[1]]
@main
def main(*args):
import argparse
parser = argparse.ArgumentParser(
description='Run Recommendations',
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument('-u', '--user', type=str, choices=USER_FILES,
default='test_user',
metavar='USER',
help='user file, e.g.\n' +
'{{{}}}'.format(','.join(sample(USER_FILES, 3))))
parser.add_argument('-k', '--k', type=int, help='for k-means')
parser.add_argument('-q', '--query', choices=CATEGORIES,
metavar='QUERY',
help='search for restaurants by category e.g.\n'
'{{{}}}'.format(','.join(sample(CATEGORIES, 3))))
parser.add_argument('-p', '--predict', action='store_true',
help='predict ratings for all restaurants')
parser.add_argument('-r', '--restaurants', action='store_true',
help='outputs a list of restaurant names')
args = parser.parse_args()
# Output a list of restaurant names
if args.restaurants:
print('Restaurant names:')
for restaurant in sorted(ALL_RESTAURANTS, key=restaurant_name):
print(repr(restaurant_name(restaurant)))
exit(0)
# Select restaurants using a category query
if args.query:
restaurants = search(args.query, ALL_RESTAURANTS)
else:
restaurants = ALL_RESTAURANTS
# Load a user
assert args.user, 'A --user is required to draw a map'
user = load_user_file('{}.dat'.format(args.user))
# Collect ratings
if args.predict:
ratings = rate_all(user, restaurants, feature_set())
else:
restaurants = user_reviewed_restaurants(user, restaurants)
names = [restaurant_name(r) for r in restaurants]
ratings = {name: user_rating(user, name) for name in names}
# Draw the visualization
if args.k:
centroids = k_means(restaurants, min(args.k, len(restaurants)))
else:
centroids = [restaurant_location(r) for r in restaurants]
draw_map(centroids, restaurants, ratings)
| [
"[email protected]"
] | |
663c05a6f5937328bad2f0c0fd88804f8191ba0d | 38ab2bf049b54c6774d7f11e0cfbb88b5d8d208d | /quadratic/views.py | 4e4d40e5d8fe704677a47a3f0e80804d1af4343b | [] | no_license | Askarb/semester7 | cae25da9e640e8c39af0ceacc5ce2c51d7962daf | 7b55877f5e29ae2fe2fc129d70f84bffa09023c2 | refs/heads/master | 2021-01-16T22:38:13.702003 | 2017-01-24T10:42:34 | 2017-01-24T10:42:34 | 68,733,524 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 939 | py | from django.http import HttpResponse
from django.template import loader
from .forms import QuadraticForm
from univer.settings import STATIC_URL
from .core_quadratic import solve_quadratic
def index(request):
context = {
'form': QuadraticForm(),
'STATIC_URL': STATIC_URL,
'result': 0
}
template = loader.get_template("quadratic.html")
if request.method == "POST":
form = QuadraticForm(request.POST)
if form.is_valid():
a = form.cleaned_data['a']
b = form.cleaned_data['b']
c = form.cleaned_data['c']
context['a'] = a
context['b'] = b
context['c'] = c
context['result'] = 1
context.update(solve_quadratic(a, b, c))
else:
context['result'] = 2
context['comment'] = 'Enter only real or integer!!!'
return HttpResponse(template.render(context, request))
| [
"[email protected]"
] | |
0fe440efb0424338c51082177757617a39c437e7 | 8a081397dae063faa43d1e1dca58b67a44fb1a6c | /add_env_to_service_file.py | b6e686e9c53e39edab4ac444b84b79e9bf2e789b | [] | no_license | altuntasmuhammet/cloud-run-update-env-from-file | 419cd84d638fea06e15823974b226ab4f7352806 | ba92f0c04d877ee83f1d78261f5b19e01e02c676 | refs/heads/main | 2023-05-04T21:58:12.414528 | 2021-05-29T01:00:41 | 2021-05-29T01:00:41 | 371,849,628 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,342 | py | import argparse, sys
# Service file can be obtained
# gcloud run services describe <SERVICE_NAME> --format export > service.yml
parser=argparse.ArgumentParser()
parser.add_argument('--env-file', help='Environment variables file in YAML format', required=True)
parser.add_argument('--service-file', help='Cloud Run service file in YAML format', required=True)
parser.add_argument('--out', help='Environment variables added service file name', required=True)
args=parser.parse_args()
env_file = args.env_file
service_file = args.service_file
output_file = args.out
import yaml
# Read environment data
with open(env_file, 'r') as f:
env_data = yaml.load(f, Loader=yaml.FullLoader)
with open(service_file, 'r') as f:
service_data = yaml.load(f, Loader=yaml.FullLoader)
env_list = []
for key, value in env_data.items():
env_list += [{
"name": key,
'value': value
}]
# Add env
service_data['spec']['template']['spec']['containers'][0]['env'] = env_list
# Change name for avoiding conflict when deploying
service_data['spec']['template']['metadata']['name'] = service_data['spec']['template']['metadata']['name'] + '-with-env'
with open(output_file, 'w') as file:
yaml.dump(service_data, file)
# After obtaining new service file run below command in terminal
# gcloud beta run services replace <out>
| [
"[email protected]"
] | |
93ab51ff87e6e569afdf7b76fa2451e10048db40 | 4166e6d1725791f2a729b2613c3ee535aea34768 | /PSO/local_search.py | da77e5e7dc26b2cbb16c61f11f36a0ac268367c2 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | DataAnalyticsResearchGroup/iRadical | bb8f06e01cff70916b6b3ec1c22cd4123343be55 | 3299217ef9cf035fb10d79e072e273425fc044da | refs/heads/master | 2020-04-01T00:57:01.151829 | 2018-10-12T08:36:59 | 2018-10-12T08:36:59 | 152,677,499 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 763 | py | from fitness import fitness_con
from utility import get_all_degrees, get_neighbors, decode_input, convert_to_binary
def LocalSearch(x, candidate, args):
x = decode_input(x, args)
x = list(x)
lenx= len(x)
gmat = args['gmat']
best_fit_local = fitness_con(x, args)
for i in range(lenx):
local_neighbors = get_neighbors(x[i], gmat)
for itm in local_neighbors:
xx = x[:i]+ [itm] + x[i+1:]
if len(set(xx)) < lenx:
continue
new_fit = fitness_con(xx, args)
if new_fit < best_fit_local:
best_fit_local = new_fit
x = xx
return x, best_fit_local | [
"[email protected]"
] | |
aa9e60059acab84935c4078cc238226f830dd1fa | a364542004257ee19fb90ffdec7d2cd0ede662eb | /slicexyz.py | 06ceccfba74a558bbe4c674db99251b75c87ac2f | [] | no_license | eselinger/quick-scripts | db0dfb59bd63bc9916bba7e3292ed113f4f689d0 | b0337c4717834a464eb3cf041764db86d5aff8c3 | refs/heads/master | 2020-12-28T17:31:11.431572 | 2016-12-06T06:46:01 | 2016-12-06T06:46:01 | 68,584,955 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,186 | py | #!/usr/bin/python
import sys
def main():
infile = sys.argv[1]
atoms = int(sys.argv[2]) #number of atoms to be stretched. MAKE SURE THESE ARE AT BOTTOM OF .xyz FILE
readin = open(infile,'r')
readout = open('cut01_'+infile, 'w')
numat = int(readin.readline())
readout.write(str(numat) + '\n')
readout.write(readin.readline())
#read all coordinates into an array
coordinates = readin.readlines()
coordinates = [[element for element in line.split()] for line in coordinates[:]]
readin.close()
#using only MMCT unit coordinates
mmct = coordinates[numat-atoms:numat]
a = range(atoms)
for i in xrange(atoms):
a[i] = mmct[i][3]
#find highest coordinate
maxz = float(max(a))
print maxz
b = range(4)
newnumat = 0
for i in xrange(numat): #only keep atoms with z-coordinate lower than maxz (from mmct)
if float(coordinates[i][3]) <= maxz:
for j in xrange(4):
b[j] = coordinates[i][j]
for element in b: readout.write(str(element) + ' ')
readout.write('\n')
newnumat = newnumat+1
print newnumat
readout.close()
main()
| [
"[email protected]"
] | |
dd724adaee147b231c761e78851a4b8b5eaabc35 | fd0f25debda5eb51b8d404e78661752bf6eb1e5f | /python3.6.5/Django/2xkt/xxkt/manage.py | 86334f2d371a27ef6b471235db2c4ad1705b54f4 | [] | no_license | fblrainbow/Python | 53f5be4de065dbde2809f69de41fa276107b176a | 525604e756e1107183ae8fcc4d6dd611ea0f34ef | refs/heads/master | 2021-01-20T14:03:11.263929 | 2019-01-06T15:19:33 | 2019-01-06T15:19:33 | 90,551,373 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 551 | py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxkt.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| [
"[email protected]"
] | |
6e7b93ea109d344e4ca0462d6ed03ec20057b1d6 | 045665406e1c8fc74d7e3fd468497f8dc143d717 | /main/migrations/0003_auto_20181211_2310.py | 968c0beff0b819403f16c05cb0b991423de5ccc2 | [] | no_license | ninjascare/Creative_Freedom | 2f0a9df5cb6c379ca0d17db3e6a2f1dcdace99d8 | 74868a01e7ef9aa1506aceda6f2b6de0235019c9 | refs/heads/master | 2020-04-10T23:43:07.438354 | 2019-02-28T23:34:58 | 2019-02-28T23:34:58 | 161,362,224 | 1 | 1 | null | 2018-12-18T22:32:19 | 2018-12-11T16:27:14 | JavaScript | UTF-8 | Python | false | false | 369 | py | # Generated by Django 2.1.4 on 2018-12-11 23:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20181211_2304'),
]
operations = [
migrations.RenameField(
model_name='comment',
old_name='created_At',
new_name='created_at',
),
]
| [
"[email protected]"
] | |
946262f86b97e05896d2f09c9f70dba55baa0988 | 668a4b6b4ce8155042ed55e05dd62ec78c99851b | /爬虫/py_useragent.py | 099051eb1af591db5ab39dfc99d7376be82e143c | [] | no_license | lxjlovewcx/source_code | 46b7255f0b05f32a219fc3a2f405811ae8986053 | 14310e136fb5f83fe1063ae0f9e60445ef5b300a | refs/heads/master | 2021-10-20T17:09:22.595583 | 2019-03-01T05:24:53 | 2019-03-01T05:24:53 | 157,014,785 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,059 | py | '''
Created on 2018年8月18日
@author: lixue
'''
'''
useragent 用户代理
-useragent:用户代理,简称UA,属于heads的一部分,服务器通过UA来判断用户的身份。
-常见的UA值,使用的时候可以直接复制粘贴,也可以用浏览器访问的时候抓包
设置UA可以通过以下两种方式:
1:使用headers
2:使用add_header方法
'''
from urllib import request,error
import json
if __name__ == '__main__':
try:
url = "http://fanyi.baidu.com/sug"
headers = {}
headers['User-Agent'] = '1.0) Gecko/20100101'
req = request.Request(url = url,headers=headers)
res = request.urlopen(req)
json_res = res.read().decode()
json_res = json.loads(json_res)
print(json_res)
req = req.add_handler("User-Agent","1.0) Gecko/20100101")
except error.HTTPError as h:
print("HTTPError :{0}".format(h))
except error.URLError as e:
print("URLError : {0}".format(e))
except Exception as E:
print(E)
| [
"[email protected]"
] | |
5762a635e14df7cc68f81066c7674a663954dd82 | 3f479528a34b2df9e9a001a3537761b259a613eb | /queue/__init__.py | b5ef5a5cec99448a8a93a9fa0b079254ad08d4aa | [] | no_license | gitu/soob | 84e1cee0b7fbc085d6986bd6e66652508330e9f8 | c9fc9d8f42151eac382287bae8cb4263ad41c525 | refs/heads/master | 2021-01-21T12:23:01.282583 | 2014-01-14T15:04:41 | 2014-01-14T15:04:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 55 | py | from LedsCommandQueue import *
from PrintQueue import * | [
"[email protected]"
] | |
c38cba0ee016be6d548d916f969186d04162763b | 5d8338ceea6798aa61d96d19eea007d30083c1aa | /TrainingRBC.py | 6d8ce9f6afc15a552968e9f7ed3da941f19f5354 | [] | no_license | aot3qx/RBC_DeepNet | 22f527c7a70f5fb84015a4efe24b215541732d1e | 8a3f31e1ac23489848b04c962045b8599de04217 | refs/heads/main | 2023-07-22T19:31:51.277411 | 2021-08-27T16:03:20 | 2021-08-27T16:03:20 | 375,060,237 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,412 | py | import tensorflow as tf
import re
import numpy as np
import os as os
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as img
from datetime import datetime
import sys
def train_test_split(image_array,label_array,number_images_per_class,k_fold,seed,first_run,number_of_classes):
number_images_per_class=int(number_images_per_class)
k_fold=float(k_fold)
first_run=int(first_run)
seed=int(seed)
number_of_classes=int(number_of_classes)
holdout_number_of_images = int(np.ceil(k_fold * number_images_per_class))
if first_run==1:
seed_int=np.random.random_integers(0,10000000)
seed_construct=np.random.seed(seed_int)
test_images=[]
test_labels=[]
print("For test runs, your seed is: "+ str(seed_int))
for i in range(0, number_of_classes):
indices = np.where(label_array == i)
random_array=np.random.choice(a=len(indices[0]),size=int(holdout_number_of_images),replace=False)
random_holdout_indices=[]
for num in random_array:
random_holdout_indices.append(indices[0][num])
for index in random_holdout_indices:
test_images.append(np.array(image_array[index],dtype='float32'))
test_labels.append(np.array(label_array[index]))
image_array=np.delete(image_array,random_holdout_indices,axis=0)
label_array=np.delete(label_array,random_holdout_indices,axis=0)
return image_array,label_array,np.array(test_images),np.array(test_labels)
else:
seed_construct = np.random.seed(seed)
test_images = []
test_labels = []
print("Using seed integer of: "+ str(seed))
for i in range(0, number_of_classes):
indices = np.where(label_array == i)
random_array=np.random.choice(a=len(indices[0]),size=int(holdout_number_of_images),replace=False)
random_holdout_indices=[]
for num in random_array:
random_holdout_indices.append(indices[0][num])
for index in random_holdout_indices:
test_images.append(np.array(image_array[index],dtype='float32'))
test_labels.append(np.array(label_array[index]))
image_array=np.delete(image_array,random_holdout_indices,axis=0)
label_array=np.delete(label_array,random_holdout_indices,axis=0)
return image_array,label_array,np.array(test_images),np.array(test_labels)
def read_multiple(mypath,label_vec):
#--Reading in images--#
image_array=[]
label_name_array=[]
label_vec=label_vec.split(',')
for image_path in os.listdir(mypath):
if image_path.endswith(".jpg"):
image_array.append(np.array(img.imread(fname=mypath+"\\"+image_path)))
for individual in label_vec:
image_label=re.search(individual,image_path)
if image_label:
label_name_array.append(image_label.group())
image_array_scaled=[]
for image in image_array:
image_scaled=image/255
image_array_scaled.append(image_scaled)
label_array_duplicates_removed=dict.fromkeys(label_name_array)
i=0
for key in label_array_duplicates_removed.keys():
label_array_duplicates_removed[key]=i
i=i+1
i=0
for i in range(0,len(label_name_array)):
label_name_array[i]=label_array_duplicates_removed[label_name_array[i]]
image_array_scaled=np.array(image_array_scaled)
label_array=np.array(label_name_array)
print("Image array dimensions: "+ str(np.shape(image_array_scaled)))
print("Label array dimensions: "+ str(np.shape(label_array)))
print("These dimensions should match. If not, the parser did not find equivalent amount of images + labels")
return image_array_scaled,label_array
def reshape(image_array,shape):
#--Reshaping images to 55*55, setting up DataSet tensor--#
dataset_with_channel=image_array.reshape((-1,shape,shape,1))
number_of_images, height, width, channels=dataset_with_channel.shape #defining dimensions
return number_of_images,height,width,channels,dataset_with_channel
def convolutional_layer(X,filters,kernel_size):
#--Defining random kernels for each convolutional layer--#
conv=tf.layers.conv2d(X,filters=filters
,kernel_size=kernel_size,strides=[1,1],padding="SAME")
return tf.nn.elu(conv)
def avg_layer(X):
avg_pool=tf.nn.max_pool(X,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
return avg_pool
test_override=input("Are you working solely with test images? 1 for yes, 0 for no: ")
if test_override=="1":
directory = input("Please enter a path: ")
label_vec = input("Enter subject names as comma-delimited list: ")
number_of_classes = input("Enter number of classes: ")
first_run = input("Is this the first run (i.e. training run)?"
"Enter 1 for yes, 0 for no. A seed will be generated that should be used for subsequent"
"test runs. Remember this seed: ")
else:
directory = input("Please enter a path: ")
label_vec = input("Enter subject names as comma-delimited list: ")
number_of_classes = input("Enter number of classes: ")
number_of_images_per_class=input("Enter number of images per class: ")
k_fold = input("Enter ratio of holdout set to train set (if odd, will take ceil): ")
first_run = input("Is this the first run (i.e. training run)?"
"Enter 1 for yes, 0 for no/test run. A seed will be generated that should be used for subsequent"
"test runs. Remember this seed: ")
if test_override=="1":
trained_model_name = input("Enter trained model name (.ckpt file): ")
elif (first_run!="1") and (test_override!="1"):
seed=input("Enter seed: ")
trained_model_name=input("Enter trained model name (.ckpt file): ")
else:
seed=0
model_name=input("Enter model name to be saved to folder (will be saved as .ckpt file): ")
if test_override=="1":
image_array,label_array=read_multiple(mypath=directory,label_vec=label_vec)
print("X_test shape is: " + str(image_array.shape))
print("Y_test shape is: "+ str(label_array.shape))
else:
image_array, label_array = read_multiple(mypath=directory, label_vec=label_vec)
X_train, y_train, X_test, y_test = train_test_split(image_array=image_array, label_array=label_array,
number_images_per_class=number_of_images_per_class,
k_fold=k_fold, seed=seed, first_run=first_run,
number_of_classes=number_of_classes)
print("X_train shape is: " + str(X_train.shape))
print("Y_train shape is: " + str(y_train.shape))
print("X_test shape is: " + str(X_test.shape))
print("Y_test shape is: " + str(y_test.shape))
if (X_train.shape[0] != y_train.shape[0]) or (X_test.shape[0] != y_test.shape[0]):
print(
"First dimension of X train does not match with y train, or first dimension of X test does not match y test."
"Exiting...make sure that file names in folder are unique for each class to avoid duplicates.")
sys.exit("Error. See above message.")
if first_run=="1" and test_override!="1":
number_of_images,height,width,channels,dataset_with_channel=reshape(X_train,shape=60)
print("Dataset shape is: " + str(dataset_with_channel.shape))
elif first_run!="1" and test_override!="1":
number_of_images, height, width, channels, dataset_with_channel = reshape(X_test, shape=60)
print("Dataset shape is: " + str(dataset_with_channel.shape))
elif test_override=="1":
number_of_images, height, width, channels, dataset_with_channel = reshape(image_array, shape=60)
print("Dataset shape is: " + str(dataset_with_channel.shape))
else:
print("Unclear input")
sys.exit("Clean up input")
n_outputs=number_of_classes
print("Dataset shape:"+str(dataset_with_channel.shape))
# Defining placeholder nodes, convolutional/pooling nodes, etc.
X=tf.compat.v1.placeholder(dtype='float32',shape=(None,height,width,channels))
y=tf.compat.v1.placeholder(dtype='int32',shape=(None))
with tf.name_scope("convolutional_nn"):
conv_layer_1=convolutional_layer(X,filters=32,kernel_size=5)
pool_layer_1=avg_layer(conv_layer_1)
conv_layer_2=convolutional_layer(pool_layer_1,filters=64,kernel_size=3)
pool_layer_2=avg_layer(conv_layer_2)
conv_layer_3=convolutional_layer(pool_layer_2,filters=128,kernel_size=2)
pool_layer_3=avg_layer(conv_layer_3)
hidden_1_input=tf.layers.flatten(pool_layer_3)
with tf.name_scope("fully_connected_layer"):
hidden_1=tf.layers.dense(hidden_1_input,200,activation=tf.nn.elu,name="hidden1")
hidden_2=tf.layers.dense(hidden_1,100,activation=tf.nn.elu,name="hidden2")
logits=tf.layers.dense(hidden_2,units=n_outputs,name="logits")
softmax=tf.nn.softmax(logits=logits)
with tf.name_scope("loss"):
cross_entropy=tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y,logits=logits)
loss=tf.reduce_mean(cross_entropy,name="loss")
learning_rate=.1
with tf.name_scope("training"):
optimizer=tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
training_operation=optimizer.minimize(loss=loss)
with tf.name_scope("evaluation"):
number_correct=tf.nn.in_top_k(logits,y,1)
accuracy=tf.reduce_mean(tf.cast(number_correct,tf.float32))
acc_summary=tf.summary.scalar('Accuracy',accuracy)
softmax_summary=tf.summary.tensor_summary('Softmax',softmax)
loss_summary=tf.summary.scalar('Loss',loss)
now=datetime.utcnow().strftime("Year_%Y_Month_%m_Day_%d_Time_%H%M%S")
root_logdir="tf_logs"
logdirectory="{}/run-{}/".format(root_logdir,now)
filewriter=tf.summary.FileWriter(logdir=logdirectory,graph=tf.get_default_graph())
print_logits=tf.print(logits)
print_labels=tf.print(y)
if first_run=="1":
number_epochs=int(input("Enter epoch number: "))
init = tf.global_variables_initializer()
saver=tf.train.Saver()
with tf.Session() as sess:
if first_run=="1":
#train block
init.run()
accuracy_vec=[]
epoch_vec=[]
conv_layer_output=sess.run(conv_layer_1,feed_dict={X:dataset_with_channel})
pool_layer_output=sess.run(pool_layer_1,feed_dict={conv_layer_1:conv_layer_output})
for epoch in range(number_epochs):
print(epoch)
sess.run(training_operation,feed_dict={X:dataset_with_channel,y:y_train})
loss_train=loss.eval(feed_dict={X:dataset_with_channel,y:y_train})
loss_string=loss_summary.eval(feed_dict={X:dataset_with_channel,y:y_train})
filewriter.add_summary(loss_string,epoch)
accuracy_vec.append(loss_train)
epoch_vec.append(epoch)
print(loss_train)
saver.save(sess,"./"+model_name+".ckpt")
else:
saver.restore(sess,"./"+trained_model_name+".ckpt")
softmax_eval = softmax.eval(feed_dict={X: dataset_with_channel})
print(softmax_eval)
if first_run=="1":
print(accuracy_vec) | [
"[email protected]"
] | |
615598e77a7b6267f4a4deecc9c45a50885c5ed7 | be3a563eef50b64fa81fd5d7f25f3173e7e4d126 | /base_web_apps/java/tests/basic_web_test.py | ac371168efa4dbaf0108fa8741c47600745c37ee | [] | no_license | KoalaTea/capstone-security-unit-tests | cc54b2b1fce109826635eda22c2e318231030117 | 249d17648b0909aa2337ef73ea13f6082880252d | refs/heads/master | 2022-12-09T23:54:44.126132 | 2018-03-31T22:44:45 | 2018-03-31T22:44:45 | 126,236,282 | 0 | 0 | null | 2022-12-08T00:51:09 | 2018-03-21T20:24:58 | Python | UTF-8 | Python | false | false | 340 | py | import unittest
import requests
class BasicWebTest(unittest.TestCase):
def setUp(self):
self.client = requests
self.url = "http://127.0.0.1:8080"
def test_index(self):
resp = self.client.get(self.url+'/index')
self.assertEqual(resp.status_code, 200)
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
] | |
9f0d153807bb442e2f36ecc5930db564c9560e68 | d991df05cabd89bbebdff8882ebae599ab362172 | /menu.py | 79603ffda974e152b079209d04bab921c5e9bd27 | [] | no_license | vikash232/Arth_task9.1_audio | 0af13e3752aba2f9bad672ca24254d60777c7dae | 3ec5e668ded5447cdf2b03f31d13ffe4523f985c | refs/heads/main | 2023-01-23T08:21:17.195860 | 2020-11-20T15:54:40 | 2020-11-20T15:54:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,066 | py | import os
import getpass
import speech_recognition as sr
password = getpass.getpass("Password : ")
if password != "menu":
print("Wrong Password")
exit()
else:
while True:
print("\n")
os.system("tput setaf 1")
print("\t\t\t\t\t\t\tWELCOME TO MAIN MENU")
print("\t\t\t\t\t\t\t--------------------")
os.system("tput setaf 7")
print("""
Press 1 : To run Linux Operations
Press 2 : To run Docker Opearations
Press 3 : To run AWS Opearations
Press 4 : To run Hadoop Operations
Press 5 : To exit
""")
r = sr.Recognizer()
with sr.Microphone() as source:
print("Start Speaking")
audio = r.listen(source)
print("Audio Recorded")
ch = r.recognize_google(audio)
if (("linux" in ch) or ("Linux" in ch) or ("linux-operation" in ch) and (("run" in ch) or ("execute" in ch))):
os.system("python3 linux-operation.py")
elif (("docker" in ch) or ("Docker" in ch) or ("docker-operation" in ch) and (("run" in ch) or ("execute" in ch))):
os.system("python3 docker.py")
elif (("aws" in ch) or ("AWS" in ch) or ("aws-operation" in ch) and (("run" in ch) or ("execute" in ch))):
os.system("python3 aws-operation.py")
elif (("hadoop" in ch) or ("Hadoop" in ch) or ("hadoop-operation" in ch) and (("run" in ch) or ("execute" in ch))):
os.system("python3 hadoop.py")
elif (("exit" in ch) or ("return" in ch) and (("main menu" in ch) or ("menu" in ch))):
os.system("exit")
break
else:
print("Invalid Option")
input("Enter to run more main menu...")
os.system("clear")
| [
"[email protected]"
] | |
812eea57b1d0fb6ef70530615cc468dc5bbecced | 5668d8e64a17f11f573f59bccca532c3a26b9780 | /2-3 Months/non-tutorial projects/battleship.py | 00d994b138d636ae28c248badd0e8efebe074345 | [] | no_license | nzsnapshot/MyTimeLine | 9b02141ead11ec660a37cb8752f0025f285443ab | 5d22aa8d9eb043eea06fcb8f3f615a2f2453da56 | refs/heads/master | 2021-03-10T20:44:41.422805 | 2020-03-11T08:53:46 | 2020-03-11T08:53:46 | 246,484,336 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,354 | py | import random
boat_lengths = [2,3,4,5]
game_board = [0 for x in range(0,100)]
for boat_len in boat_lengths:
position_found = False
vertical = random.randint(0,1)
if vertical == 0:
while not position_found:
test_position = random.randint(0,99)
position_found = True
if len(game_board) <= test_position+boat_len:
position_found = False
else:
for i in range(0,boat_len):
if game_board[test_position+i] != 0:
position_found = False
if test_position%10+i >= 10:
position_found = False
for z in range(0,boat_len):
game_board[test_position+z] = boat_len
elif vertical == 1:
while not position_found:
test_position = random.randint(0,99)
position_found = True
if len(game_board) <= test_position+boat_len*10:
position_found = False
else:
for i in range(0,boat_len):
if game_board[test_position+i*10] != 0:
position_found = False
if test_position+i*10 >= 100:
position_found = False
for z in range(0,boat_len):
game_board[test_position+z*10] = boat_len
with open('battleship board.txt', 'w') as map_file:
for y in range(0,10):
for x in range(0,10):
map_file.write(str(game_board[x+y*10]))
map_file.write('\n')
#------boat coordinates for testing-------
#e.g. (vertical,horizontal)
#Destroyer(2hits) = (1,1) and (1,2)
#Cruiser(3hits) = (7,2),(7,3), and (7,4)
#Battleship(4hits) = (0,6),(0,7),(0,8), and (0,9)
#Carrier(5hits) = (2,6),(3,6)(4,6)(5,6), and (6,6)
# ----------functions--------------------------------
def drawBoard(gB):
# this function receives a list of lists
# the list of lists must be a 10x10 structure
# it then uses this to draw an index row and column
# and the board itself...
print('----------------------------------------------')
print(' 0 1 2 3 4 5 6 7 8 9')
for i in range(0, 10, 1):
print(i, ' ', end='')
for j in range(0, 10, 1):
s = ' ' + str(gB[i][j])
print(s, end='')
print()
print('----------------------------------------------')
return
# -----------background setup (preparing data)-------
# 1 import map data
# open the board file for reading
inFile = open('battleship board.txt', 'r')
map = [] # a list of lists
for templine in inFile:
newtempline = templine.strip('\n')
templist = list(newtempline)
map.append(templist)
# must convert these strings to ints
for x in range(0, 10, 1):
for y in range(0, 10, 1):
map[x][y] = int(map[x][y])
gameboard = []
for i in range(0, 10, 1):
gameboard.append(['_', '_', '_', '_', '_', '_', '_', '_', '_', '_'])
drawBoard(gameboard)
# ----------startup conditions for game--------------
notAllHit = True
destroyer = 0 # 2
cruiser = 0 # 3
battleship = 0 # 4
carrier = 0 # 5
destroyerCheck = True
cruiserCheck = True
battleshipCheck = True
carrierCheck = True
# -------------the game------------------------------
while notAllHit:
print('----------------------------------------------')
row = int(input('Enter a vertical integer to fire at (0-9):'))
column = int(input('Enter a horizontal integer to fire at(0-9):'))
############# Below is the try and except statements.
############# try and except allows you to handle errors and give a different outcome
############# This way the user does not get interrupted or the programme stops
try:
if gameboard[row][column] == 'X' or gameboard[row][column] == '.':
print('You already fired at these coordinates, try again.')
print('----------------------------------------------')
else:
if map[row][column] == 0:
print('MISS')
gameboard[row][column] = '.'
drawBoard(gameboard)
else:
print('HIT')
gameboard[row][column] = 'X'
hitBoatType = map[row][column]
#map[row][column] = 0
drawBoard(gameboard)
if map[row][column] == 2:
destroyer += 1
if destroyer == 2:
if destroyerCheck == True:
print('You sunk the Destroyer!')
destroyerCheck = False
if map[row][column] == 3:
cruiser += 1
if cruiser == 3:
if cruiserCheck == True:
print('You sunk the Cruiser!')
cruiserCheck = False
if map[row][column] == 4:
battleship += 1
if battleship == 4:
if battleshipCheck == True:
print('You sunk the Battleship!')
battleshipCheck = False
if map[row][column] == 5:
carrier += 1
if carrier == 5:
if carrierCheck == True:
print('You sunk the Carrier!')
carrierCheck = False
except IndexError:
error = print('Please enter a valid input between 0-9:')
if destroyerCheck == False and cruiserCheck == False and battleshipCheck == False and carrierCheck == False:
notAllHit = False
print('All boats sunk.')
print('You Win!') | [
"[email protected]"
] | |
d5da12321e8dcfa61681d4fe39243fb11987c243 | f55315672696a099c1a25f484efe7c1d3c260d5f | /Co-integration/TradingStrategy.py | 2fc6d6cd1ce3950a88c9577dfe14a05983051e7f | [] | no_license | anchalsri82/Python | cdb64e30b1bfb156be35d4a71ca8428b6feb3112 | b9d35fe1d6a512de7daa80789f3720583ce8645d | refs/heads/master | 2020-12-03T03:50:16.793792 | 2017-07-22T18:22:53 | 2017-07-22T18:22:53 | 95,779,465 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,178 | py | import pandas as pd
# Import statsmodels equivalents to validate results
from statsmodels.tsa.api import VAR
from statsmodels.regression.linear_model import OLS
from statsmodels.tsa.tsatools import (lagmat, add_trend)
from statsmodels.tsa.stattools import adfuller
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.pylab as pylab
# Verfify methods:
instrument1 = pd.read_csv("D:/Projects/Python/trunk/Co-integration/MarketData/C.csv", index_col=0, parse_dates=True, dayfirst=True)
instrument1['Returns'] = np.log(instrument1['Adj Close'].astype(np.float)/instrument1['Adj Close'].shift(1).astype(np.float))
instrument1=instrument1[1:]
instrument2 = pd.read_csv("D:/Projects/Python/trunk/Co-integration/MarketData/BAC.csv", index_col=0, parse_dates=True, dayfirst=True)
instrument2['Returns'] = np.log(instrument2['Adj Close'].astype(np.float)/instrument2['Adj Close'].shift(1).astype(np.float))
instrument2=instrument2[1:]
returns1 = instrument1['Returns'].values
returns2 = instrument2['Returns'].values
Y1_t = instrument1['Adj Close'].values
Y2_t = instrument2['Adj Close'].values
dY1_t = pd.Series(Y1_t, name='Y1_t').diff().dropna()
dY2_t = pd.Series(Y2_t, name='Y2_t').diff().dropna()
## ADF
data = pd.concat([instrument1['Returns'], instrument2['Returns']], axis=1, keys=['Returns1', 'Returns2'])
Yt = np.vstack((Y1_t, Y2_t))
Yr = np.vstack((returns1, returns2))
dY = np.vstack((dY1_t, dY2_t))
maxlags = int(round(12*(len(Yr)/100.)**(1/4.)))
## Optimal Legs
maxlagOptimumVectorAR = GetOptimalLag(Yr, maxlags, modelType='VectorAR')
#maxlagOptimumADFuller = GetOptimalLag(Y=Yr, maxlags=maxlags, modelType='ADFuller')
#resultADFuller = GetADFuller(Y=Yr, maxlags= maxlagOptimumVectorAR['bestlagaic'])
model = VAR(data)
results = model.fit(0, method='ols', ic='aic', trend='c',verbose=True)
results.summary()
#resultADFullerYt = GetADFuller(Yt, 1)
#resultADFullerYt['adfstat']
#maxlagOptimumADFullerdY = GetOptimalLag(dY, maxlags, modelType='ADFuller')
#resultADFullerdY = GetADFuller(dY, maxlagOptimumADFullerdY['bestlagaic'])
# ENGLE-GRANGER STEP 1
Y2_t_d = np.vstack((np.ones(len(Y2_t)), Y2_t))
resultGetOLS = GetOLS(Y=Y1_t, X=Y2_t_d)
a_hat = resultGetOLS['beta_hat'][0,0]
beta2_hat = resultGetOLS['beta_hat'][0,1]
et_hat = Y1_t - np.dot(beta2_hat, Y2_t) - a_hat
# ENGLE-GRANGER STEP 2
result_et_hat_adf = GetADFuller(Y=et_hat, maxlags=1, regression='nc')
print("ADF stat : %f" % result_et_hat_adf['adfstat'])
sm_result_et_hat_adf = adfuller(et_hat, maxlag=1, regression='nc', autolag=None, regresults=True)
# ===== SPREAD PLOTS =====
from matplotlib import gridspec
plt.figure(1, figsize=(15, 20))
# gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
gs = gridspec.GridSpec(3, 1, height_ratios=[1, 0.5, 0.5])
# === SPREAD TIME SERIES ===
plt.subplot(gs[0])
plt.title('Cointegrating spread $\hat{e}_t$ (Brent & Gasoil)')
e_t_hat.plot()
plt.axhline(e_t_hat.mean(), color='red', linestyle='--') # Add the mean
plt.legend(['$\hat{e}_t$', 'mean={0:0.2g}'.format(e_t_hat.mean())], loc='lower right')
plt.xlabel('')
# === SPREAD HISTOGRAM ===
plt.subplot(gs[1])
from scipy import stats
ax = sns.distplot(e_t_hat, bins=20, kde=False, fit=stats.norm);
plt.title('Distribution of Cointegrating Spread for Brent and Gasoil')
# Get the fitted parameters used by sns
(mu, sigma) = stats.norm.fit(e_t_hat)
print "mu={0}, sigma={1}".format(mu, sigma)
# Legend and labels
plt.legend(["normal dist. fit ($\mu \sim${0}, $\sigma=${1:.2f})".format(0, sigma),
"$\hat{e}_t$"
])
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('')
# # Cross-check this is indeed the case - should be overlaid over black curve
# x_dummy = np.linspace(stats.norm.ppf(0.01), stats.norm.ppf(0.99), 100)
# ax.plot(x_dummy, stats.norm.pdf(x_dummy, mu, sigma))
# plt.legend(["normal dist. fit ($\mu=${0:.2g}, $\sigma=${1:.2f})".format(mu, sigma),
# "cross-check"])
# === SPREAD PACF ===
from statsmodels.graphics.tsaplots import plot_pacf
ax = plt.subplot(gs[2])
plot_pacf(e_t_hat, lags=50, alpha=0.01, ax=ax)
plt.title('')
plt.xlabel('Lags')
plt.ylabel('PACF')
# plt.text(x=40.5, y=0.85, s='PACF', size='xx-large')
# ===== GOODNESS OF FIT OF SPREAD TO NORM ======
# Note: do not use scipy's kstest,
# see http://stackoverflow.com/questions/7903977/implementing-a-kolmogorov-smirnov-test-in-python-scipy
import statsmodels.api as sm
# Lilliefors test http://en.wikipedia.org/wiki/Lilliefors_test
print 'Lilliefors:', sm.stats.lillifors(e_t_hat)
# Most Monte Carlo studies show that the Anderson-Darling test is more powerful
# than the Kolmogorov-Smirnov test. It is available in scipy.stats with critical values,
# and in statsmodels with approximate p-values:
print 'Anderson-Darling:', sm.stats.normal_ad(e_t_hat)
# ===== STEP 2: ADF TEST ON SPREAD =====
# Test spread for stationarity with ADF assuming maxlag=1, no constant and no trend
my_res_adf = my_adfuller(e_t_hat, maxlag=3, regression='nc')
# Validate result with statsmodels equivalent
sm_res_adf = adfuller(e_t_hat, maxlag=3, regression='nc', autolag=None, regresults=True)
print sm_res_adf
print my_res_adf['adfstat']
print "%0.4f" % my_res_adf['adfstat']
# ===== STABILITY CHECK =====
print key, np.abs(my_res_adf['roots'])
print "passes stability check: {0}".format(is_stable(my_res_adf['roots']))
from statsmodels.regression.linear_model import OLS
Y = y.diff()[1:] # must remove first element from array which is nan
X = pd.concat([x.diff()[1:], e_t_hat.shift(1)[1:]], axis=1)
X_c = add_constant(X)
sm_res_ecm = OLS(Y, X).fit() # fit without constant
sm_res_ecm_c = OLS(Y, X_c).fit() # fit without constant
sm_res_ecm_c.summary2()
sm_res_ecm.summary2()
# ====== FIT TO OU PROCESS ======
# My implementations
from analysis import my_AR # AR(p) model
# Import statsmodels equivalents to validate results
from statsmodels.tsa.ar_model import AR
# Run AR(1) model with constant term with e_t_hat as endogenous variable
my_res_ar = my_AR(endog=e_t_hat, maxlag=1, trend='c')
sm_res_ar = AR(np.array(e_t_hat)).fit(maxlag=3, trend='c', method='cmle')
# Stability Check
print 'is AR({0}) model stable: {1}'.format(sm_res_ar.k_ar, is_stable(sm_res_ar.roots))
print 'is AR({0}) model stable: {1}'.format(my_res_ar['maxlag'], is_stable(my_res_ar['roots']))
# Cross-checks
print "\
AR({12}).fit.params={0} \n MY_AR({13}) params={1} \n\
AR({12}).fit.llf={2} \n MY_AR({13}) llf={3} \n\
AR({12}).fit.nobs={4} \n MY_AR({13}) nobs={5} \n\
AR({12}).fit.cov_params(scale=ols_scale)={6} \n MY_AR({13}) cov_params={7} \n\
AR({12}).fit.bse={8} \n MY_AR({13}) bse={9} \n\
AR({12}).fit.tvalues={10} \n MY_AR({13}) tvalue={11} \n\
AR({12}).fit.k_ar={12} \n MY_AR({13}) maxlag={13} \n\
".format(
sm_res_ar.params, my_res_ar['params'],
sm_res_ar.llf, np.array(my_res_ar['llf']),
sm_res_ar.nobs, my_res_ar['nobs'],
sm_res_ar.cov_params(scale=my_res_ar['ols_scale']), my_res_ar['cov_params'],
sm_res_ar.bse, my_res_ar['bse'],
sm_res_ar.tvalues, my_res_ar['tvalue'],
sm_res_ar.k_ar, my_res_ar['maxlag']
)
tau = 1. / 252. # ok for daily frequency data
# AR(1)
my_C = my_res_ar['params'][0]
my_B = my_res_ar['params'][1]
my_theta = - np.log(my_B) / tau
my_mu_e = my_C / (1. - my_B)
my_sigma_ou = np.sqrt((2 * my_theta / (1 - np.exp(-2 * my_theta * tau))) * my_res_ar['sigma'])
my_sigma_e = my_sigma_ou / np.sqrt(2 * my_theta)
my_halflife = np.log(2) / my_theta
print ' AR({8}): my_C={0}, my_B={1}, tau={2}, my_theta={3}, my_mu_e={4}, my_sigma_ou={5}, my_sigma_e={6}, my_halflife={7:.4f}'.format(my_C,
my_B,
tau,
my_theta,
my_mu_e,
my_sigma_ou,
my_sigma_e,
my_halflife,
my_res_ar['maxlag'])
# AR(3)
sm_C = sm_res_ar.params[0]
sm_B = sm_res_ar.params[1]
sm_theta = - np.log(sm_B) / tau
sm_mu_e = sm_C / (1. - sm_B)
sm_sigma_ou = np.sqrt((2 * sm_theta / (1 - np.exp(-2 * sm_theta * tau))) * sm_res_ar.sigma2)
sm_sigma_e = sm_sigma_ou / np.sqrt(2 * sm_theta)
sm_halflife = np.log(2) / sm_theta
print ' AR({8}): sm_C={0}, sm_B={1}, tau={2}, sm_theta={3}, sm_mu_e={4}, sm_sigma_ou={5}, sm_sigma_e={6}, sm_halflife={7:.4f}'.format(
sm_C,
sm_B,
tau,
sm_theta,
sm_mu_e,
sm_sigma_ou,
sm_sigma_e,
sm_halflife,
sm_res_ar.k_ar)
# Equivalent to AR(1) model above but expressed using differences
from statsmodels.regression.linear_model import OLS
Y_e = e_t_hat.diff()[1:] # de_t
X_e = e_t_hat.shift(1)[1:] # e_t-1
X_e = add_constant(X_e)
r = OLS(Y_e, X_e).fit()
X_e = X_e.iloc[:, 1] # remove the constant now that we're done
r.summary2()
# PLOTTING
e_t_hat.plot(label='$\hat{e}_t$', figsize=(15, 7))
# plt.plot(e_t_hat, label='$\hat{e}_t$')
# Trading bounds
plt.title('Trading bounds for Cointegrated Spread (Brent & Gasoil)')
plt.axhline(0, color='grey', linestyle='-') # axis line
plt.axhline(my_mu_e, color='green', linestyle=':', label='AR(1) OU $\mu_e \pm \sigma_{eq}$')
plt.axhline(sm_mu_e, color='red', linestyle='--', label='AR(3) OU $\mu_e \pm \sigma_{eq}$')
plt.axhline(my_sigma_e, color='green', linestyle=':')
plt.axhline(-my_sigma_e, color='green', linestyle=':')
plt.axhline(sm_sigma_e, color='red', linestyle='--')
plt.axhline(-sm_sigma_e, color='red', linestyle='--')
plt.legend(loc='lower right')
# ======== BETA HEDGING ========
# === In-sample fit ===
from statsmodels.regression.linear_model import OLS
Y_is = df_is['gasoil'].diff()[1:] # must remove first element from array which is nan
X_is = df_is['brent'].diff()[1:]
X_is_c = add_constant(X_is)
# res_bh = OLS(Y_is, X_is).fit() # fit without constant
res_bh_c = OLS(Y_is, X_is_c).fit() # fit without constant
res_bh_c.summary2()
# === In-sample testing ===
print (Y_is - res_bh_c.params[1]*X_is).mean() # long gasoil, short brent
print (Y_is).mean() # long gasoil only
# === Out-of-sample testing ===
Y_os = df_os['gasoil'].diff()[1:]
X_os = df_os['brent'].diff()[1:]
print (Y_os - res_bh_c.params[1]*X_os).mean() # long gasoil, short brent
print (Y_os).mean() # long gasoil only
normalised_e_t_hat = static_zscore(e_t_hat, mean=sm_mu_e, sigma=sm_sigma_e)
normalised_e_t_hat.plot()
plt.axhline(1.0, color='red', linestyle='--')
plt.axhline(-1.0, color='green', linestyle='--')
plt.legend(['z-score $\hat{e}_t$', '+1', '-1'], loc='lower right')
plt.axhline(0, color='grey')
# ==== GENERATE P&L DATAFRAME FOR A GIVEN SPREAD
def get_pnl_df(spread, mean, sigma):
"""
Note the input spread must be zscore-normalised
"""
spread_norm = (spread - mean) / sigma # normalise as z-score
df_pnl_is = pd.DataFrame(index=spread.index)
df_pnl_is['e_t_hat'] = spread
df_pnl_is['e_t_hat_norm'] = spread_norm
# df_pnl_is['diff'] = df_pnl_is['e_t_hat'].diff()
df_pnl_is['pos'] = np.nan
# Go long the spread when it is below -1 as expectation is it will rise
df_pnl_is.loc[df_pnl_is['e_t_hat_norm'] <= -1.0, 'pos'] = 1
# Go short the spread when it is above +1 as expectation is it will fall
df_pnl_is.loc[df_pnl_is['e_t_hat_norm'] >= 1.0, 'pos'] = -1
# Exit positions when close to zero
df_pnl_is.loc[(df_pnl_is['e_t_hat_norm'] < 0.1) & (df_pnl_is['e_t_hat_norm'] > -0.1), 'pos'] = 0
# # forward fill NaN's with previous value
df_pnl_is['pos'] = df_pnl_is['pos'].fillna(method='pad')
# Returns must be calculated in unnormalised spread
df_pnl_is['chg'] = df_pnl_is['e_t_hat'].diff().shift(-1) # adopting Boris convention with shift(-1) (must shift after taking diff)
# PnL
df_pnl_is['pnl'] = df_pnl_is['pos'] * df_pnl_is['chg']
df_pnl_is['pnl_cum'] = df_pnl_is['pnl'].cumsum()
return df_pnl_is
df_pnl_is = get_pnl_df(e_t_hat, mean=sm_mu_e, sigma=sm_sigma_e)
df_pnl_is.tail()
df_pnl_is.loc[df_pnl_is['pnl'].isnull(), 'pnl']
%run my_pyfolio.py
plot_drawdown_periods(df_pnl_is['pnl'], top=5)
# ======== OUT-OF-SAMPLE TESTING ========
# Construct the out-of-sample spread
e_t_hat_os = df_os['gasoil'] - c_hat - beta2_hat*df_os['brent']
# Normalise to OU bounds
normalised_e_t_hat_os = static_zscore(e_t_hat_os, mean=sm_mu_e, sigma=sm_sigma_e)
normalised_e_t_hat_os.plot()
plt.axhline(1.0, color='red', linestyle='--')
plt.axhline(-1.0, color='green', linestyle='--')
plt.legend(['z-score $\hat{e}_t$', '+1', '-1'], loc='upper right')
plt.axhline(0, color='grey')
df_pnl_os = get_pnl_df(e_t_hat_os, mean=sm_mu_e, sigma=sm_sigma_e)
df_pnl_os.tail()
df_pnl_is[:-1]['pnl_cum'][-1]
%run my_pyfolio.py
df_pnl_is.index[-1]
df_temp = df_pnl_is[:-1]['pnl_cum'] # remove nan on last row
k = df_temp[-1] # last non-nan row of in-sample pnl
df_temp.plot()
plot_drawdown_periods(df_pnl_os['pnl'], k=k, top=5)
plt.axvline(df_temp.index[-1], color='black', linestyle='--')
plt.legend(['in-sample', 'out-of-sample', 'boundary'], loc='upper left')
# Monte carlo
np.random.seed(2000)
d_t = 1
M = 500
mu = 12
sigma = 0.25
Y_t1 = np.zeros((M + 1))
Y_t2 = np.zeros((M + 1))
Y_t1[0] = -75.0
Y_t2[0] = 70.0
theta_1 = 0.004
theta_2 = 0.02
for i in range(1, M + 1):
Y_t1[i] = Y_t1[i-1] + theta_1 * (mu - Y_t1[i-1]) * d_t + sigma * math.sqrt(d_t) * np.random.normal(0, 1)
Y_t2[i] = Y_t2[i-1] + theta_2 * (mu - Y_t2[i-1]) * d_t + sigma * math.sqrt(d_t) * np.random.normal(0, 1)
Y_t = np.vstack((Y_t1,Y_t2))
print(Y_t)
Y_t1 = pd.Series(Y_t1, name='Y_t')
_ = Y_t1.plot()
_ = Y_t1.diff().plot()
# _ = plt.ylabel('Series Value')
_ = plt.xlabel('Time')
_ = plt.legend(['Random walk with drift', 'Stationary Difference'], loc='upper left')
| [
"[email protected]"
] | |
a030475f8a6a0ee5dc27f85bde609489b981399a | 7e34099853f87cbfd0ee69d8894d10eaf8e1df94 | /implementations/group6/src/send_email_is_added.py | 70510b4dd1001292167313512f55410b2e98d056 | [] | no_license | Matias-Bernal/dose2014 | cc1b973de8ba592ba82b2c8c8efd7749bcd3a033 | 139376fb884523cf5e0ccd7e9fed152555641a35 | refs/heads/master | 2016-09-06T03:51:44.566674 | 2014-12-24T14:49:10 | 2014-12-24T14:49:10 | 32,119,587 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 809 | py | import email
import smtplib
import sys
#receives the user email to which send the email
if len(sys.argv) >= 4:
#print 'Argument List:', str(sys.argv)
user_logged = sys.argv[1]
user_invited = sys.argv[2]
project_name= sys.argv[3]
msg = email.message_from_string('Dear user,\n\n You was joined to the project "%s" from "%s". \n\nFrom right now you have access to it.\n\nThis is an automatically generated email, please do not reply to it. ' %(project_name,user_logged))
msg['From'] = "[email protected]"
msg['To'] = user_invited
msg['Subject'] = "[No reply] - Added to projet"
s = smtplib.SMTP("smtp.live.com",587)
s.ehlo()
s.starttls()
s.ehlo()
s.login('[email protected]', 'groupMilan2')
s.sendmail("[email protected]", user_invited, msg.as_string())
s.quit()
| [
"annamaria.nestorov@f6206239-57e0-e8d1-037d-e0d2c07dc7bc"
] | annamaria.nestorov@f6206239-57e0-e8d1-037d-e0d2c07dc7bc |
097c70d581f0a7f277b93936c01ba8b93b14019d | b664bbc0f09ef88761c27aa212a7b0f649768a24 | /ip138/cmdline.py | 920a3f7ae3cbd7ae57e80b5f7878909635206858 | [
"MIT"
] | permissive | niulinlnc/ip138 | 89811d173659106c48a38bd2a29b7c24dd1bef71 | 828962168a1f68517bd1e3258621f7a4dbfa2c7b | refs/heads/master | 2020-09-28T03:06:05.387439 | 2019-06-12T06:09:11 | 2019-06-12T06:09:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,078 | py | # coding: utf-8
from __future__ import print_function
import sys
from optparse import OptionParser
try:
from itertools import ifilter as filter
except ImportError:
pass
from ip138.logger import logger
from ip138 import __version__
try:
if sys.version_info < (3, 0, 0):
import codecs
import locale
sys.stdout = codecs.getwriter(
locale.getpreferredencoding())(sys.stdout)
sys.stderr = codecs.getwriter(
locale.getpreferredencoding())(sys.stderr)
except NameError:
# python3
pass
def banner():
logger.info(u'''ip138 IP 地理信息查询 ver %s''' % __version__)
def cmd_parser():
parser = OptionParser()
parser.add_option('--ip', type='string', dest='ip',
action='store', help='ip address')
try:
sys.argv = list(map(lambda x: unicode(
x.decode(sys.stdin.encoding)), sys.argv))
except (NameError, TypeError):
pass
except UnicodeDecodeError:
exit(0)
args, _ = parser.parse_args(sys.argv[1:])
return args
| [
"[email protected]"
] | |
9c39907cb189fd01a905f1183f03c509c54c9867 | c89e4099f801cb4e71b732f74ba2237883de0b16 | /spider/concurrent/concur_threads_insts.py | 0dbe75f7f91c002521ecda1898366e1fa47d83e3 | [
"BSD-2-Clause"
] | permissive | JiyangZhang/PSpider | 3abc14792875e306d4a0207f1cd872834c35335c | 2151bbdd028acfa5794acab6c87988dc4bf485d3 | refs/heads/master | 2021-08-19T01:31:22.975247 | 2017-11-24T10:03:10 | 2017-11-24T10:38:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,792 | py | # _*_ coding: utf-8 _*_
"""
concur_threads_insts.py by xianhu
"""
import time
import logging
from .concur_abase import TPEnum, BaseThread
# ===============================================================================================================================
def work_fetch(self):
"""
procedure of fetching, auto running, and return False if you need stop thread
"""
# ----1----
priority, url, keys, deep, repeat = self._pool.get_a_task(TPEnum.URL_FETCH)
# ----2----
fetch_result, content = self._worker.working(priority, url, keys, deep, repeat)
# ----3----
if fetch_result == 1:
self._pool.update_number_dict(TPEnum.URL_FETCH_SUCC, +1)
self._pool.add_a_task(TPEnum.HTM_PARSE, (priority, url, keys, deep, content))
elif fetch_result == 0:
self._pool.add_a_task(TPEnum.URL_FETCH, (priority+1, url, keys, deep, repeat+1))
else:
self._pool.update_number_dict(TPEnum.URL_FETCH_FAIL, +1)
# ----4----
self._pool.finish_a_task(TPEnum.URL_FETCH)
# ----5----
while (self._pool.get_number_dict(TPEnum.HTM_NOT_PARSE) > 500) or (self._pool.get_number_dict(TPEnum.ITEM_NOT_SAVE) > 500):
logging.debug("%s[%s] sleep 5 seconds because of too many 'HTM_NOT_PARSE' or 'ITEM_NOT_SAVE'...", self.__class__.__name__, self.getName())
time.sleep(5)
return False if fetch_result == -2 else True
FetchThread = type("FetchThread", (BaseThread,), dict(working=work_fetch))
# ===============================================================================================================================
def work_parse(self):
"""
procedure of parsing, auto running, and only return True
"""
# ----1----
priority, url, keys, deep, content = self._pool.get_a_task(TPEnum.HTM_PARSE)
# ----2----
parse_result, url_list, save_list = self._worker.working(priority, url, keys, deep, content)
# ----3----
if parse_result > 0:
self._pool.update_number_dict(TPEnum.HTM_PARSE_SUCC, +1)
for _url, _keys, _priority in url_list:
self._pool.add_a_task(TPEnum.URL_FETCH, (_priority, _url, _keys, deep+1, 0))
for item in save_list:
self._pool.add_a_task(TPEnum.ITEM_SAVE, (url, keys, item))
else:
self._pool.update_number_dict(TPEnum.HTM_PARSE_FAIL, +1)
# ----4----
self._pool.finish_a_task(TPEnum.HTM_PARSE)
return True
ParseThread = type("ParseThread", (BaseThread,), dict(working=work_parse))
# ===============================================================================================================================
def work_save(self):
"""
procedure of saving, auto running, and only return True
"""
# ----1----
url, keys, item = self._pool.get_a_task(TPEnum.ITEM_SAVE)
# ----2----
save_result = self._worker.working(url, keys, item)
# ----3----
if save_result:
self._pool.update_number_dict(TPEnum.ITEM_SAVE_SUCC, +1)
else:
self._pool.update_number_dict(TPEnum.ITEM_SAVE_FAIL, +1)
# ----4----
self._pool.finish_a_task(TPEnum.ITEM_SAVE)
return True
SaveThread = type("SaveThread", (BaseThread,), dict(working=work_save))
# ===============================================================================================================================
def init_monitor_thread(self, name, pool, sleep_time=5):
"""
constructor of MonitorThread
"""
BaseThread.__init__(self, name, None, pool)
self._sleep_time = sleep_time # sleeping time in every loop
self._init_time = time.time() # initial time of this spider
self._last_fetch_num = 0 # fetch number in last time
self._last_parse_num = 0 # parse number in last time
self._last_save_num = 0 # save number in last time
return
def work_monitor(self):
"""
monitor the pool, auto running, and return False if you need stop thread
"""
time.sleep(self._sleep_time)
info = "%s status: running_tasks=%s;" % (self._pool.__class__.__name__, self._pool.get_number_dict(TPEnum.TASKS_RUNNING))
cur_not_fetch = self._pool.get_number_dict(TPEnum.URL_NOT_FETCH)
cur_fetch_succ = self._pool.get_number_dict(TPEnum.URL_FETCH_SUCC)
cur_fetch_fail = self._pool.get_number_dict(TPEnum.URL_FETCH_FAIL)
cur_fetch_all = cur_fetch_succ + cur_fetch_fail
info += " fetch:[NOT=%d, SUCC=%d, FAIL=%d, %d/(%ds)];" % (cur_not_fetch, cur_fetch_succ, cur_fetch_fail, cur_fetch_all-self._last_fetch_num, self._sleep_time)
self._last_fetch_num = cur_fetch_all
cur_not_parse = self._pool.get_number_dict(TPEnum.HTM_NOT_PARSE)
cur_parse_succ = self._pool.get_number_dict(TPEnum.HTM_PARSE_SUCC)
cur_parse_fail = self._pool.get_number_dict(TPEnum.HTM_PARSE_FAIL)
cur_parse_all = cur_parse_succ + cur_parse_fail
info += " parse:[NOT=%d, SUCC=%d, FAIL=%d, %d/(%ds)];" % (cur_not_parse, cur_parse_succ, cur_parse_fail, cur_parse_all-self._last_parse_num, self._sleep_time)
self._last_parse_num = cur_parse_all
cur_not_save = self._pool.get_number_dict(TPEnum.ITEM_NOT_SAVE)
cur_save_succ = self._pool.get_number_dict(TPEnum.ITEM_SAVE_SUCC)
cur_save_fail = self._pool.get_number_dict(TPEnum.ITEM_SAVE_FAIL)
cur_save_all = cur_save_succ + cur_save_fail
info += " save:[NOT=%d, SUCC=%d, FAIL=%d, %d/(%ds)];" % (cur_not_save, cur_save_succ, cur_save_fail, cur_save_all-self._last_save_num, self._sleep_time)
self._last_save_num = cur_save_all
info += " total_seconds=%d" % (time.time() - self._init_time)
logging.warning(info)
return False if self._pool.get_monitor_stop_flag() else True
MonitorThread = type("MonitorThread", (BaseThread,), dict(__init__=init_monitor_thread, working=work_monitor))
| [
"[email protected]"
] | |
e59f782592089a4da3e002b48c1a670053397139 | 9e926b19df2f4f10c3f070530700a39c7282aad9 | /media.py | 483fd3ba5bd17c1056f877cc920a7ebc9c3a2ea8 | [
"MIT"
] | permissive | saitec/Movie-Trailers | 8dd011ceab19d5d6f7970cb5e18f775dc3104b1d | dab0b519bbdaf41fce6eb4944081084d51bb9d04 | refs/heads/master | 2021-01-10T04:34:41.223419 | 2016-04-08T19:09:49 | 2016-04-08T19:09:49 | 55,802,362 | 0 | 0 | null | 2016-04-08T19:09:49 | 2016-04-08T18:53:12 | Python | UTF-8 | Python | false | false | 533 | py | __author__ = 'Sai'
class Movie():
"""Creates movie object that maps movie with various attributes.
A factory for creating movie objects that is subsequently used
by fresh_tomatoes.html to display movie, its attributes, and media.
"""
def __init__(self, title, storyline, poster_image, trailer_video):
self.title = title
self.storyline = storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_video
| [
"[email protected]"
] | |
8ab301dd273e72218c63933931cb30d0cf77700c | 9d5dd1489fdd0a49ed1a273ba33a3712fd6984de | /gui.py | 99a875ee51af63eada7836310ff9edc1e7848f77 | [] | no_license | xgfelicia/Line-sticker-downloader | cdc7f8c3381dff0eb323f3450ee78104926f54b8 | 08d6dd733ae56cce08c201d0b08a204e0d737881 | refs/heads/master | 2021-01-14T09:53:26.550228 | 2016-12-05T19:15:16 | 2016-12-05T19:15:16 | 59,918,359 | 0 | 0 | null | 2016-12-05T17:43:50 | 2016-05-28T23:23:40 | Python | UTF-8 | Python | false | false | 443 | py | from tkinter import *
root = Tk()
root.configure(background = "#fff")
root.geometry("500x500")
title = Label(root, text = "Line Sticker Downloader", bg = "#fff",
font = (None, 20))
inputText = Label(root, text = "Enter the sticker pack ID: ", font = (None, 12))
inputUser = Entry(root, bd = 2)
title.pack(anchor = CENTER)
inputText.pack(side = LEFT, anchor = 'n')
inputUser.pack(side = RIGHT, anchor = 'n')
root.mainloop()
| [
"[email protected]"
] | |
04b4d7465d1daa21646925bc05298466c4b22db1 | 8853c0d2d714f698bbdadfe6c9ad3af67af74018 | /Python/demo0009.py | 9c1cf93254ef4072976fe0e146057c34b86f2953 | [] | no_license | zywz2333/111 | a89d95d699f0cfb1ed5dd565af73f3fab462c146 | 3b05d4f023588fbc8d24477b8cf00732a0a6a5b6 | refs/heads/master | 2020-07-14T18:59:42.446699 | 2019-08-30T11:57:44 | 2019-08-30T11:57:44 | 205,379,178 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 134 | py | f = open("./名字.txt", encoding='utf-8')
for user in f:
if user.startswith("吴") and user.endswith("彬"):
print(user) | [
"[email protected]"
] | |
73d482f093d60af110dad51de738c055a98d4ee8 | da39bac16d679acf630539eaf3fcb7d9bfd4266c | /pruebas_estudio/ahorcado.py | 261e54e6620b46343bce3b59d925c85ae73ba361 | [] | no_license | JhonveraDev/python_test | 1c2a7cb938d433d8449186e3918421de620fb76b | b24305bb7f5241161ebebab5b5f2296f622e41e0 | refs/heads/master | 2022-12-19T17:25:29.745898 | 2020-10-05T20:32:06 | 2020-10-05T20:32:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,067 | py | import random
IMAGES = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
WORDS= [
'lavadora',
'gobierno',
'sofa',
'diputado',
'teclado'
]
def random_word():
indice = random.randint(0, len(WORDS)-1)
return WORDS[indice]
def display_board(hidden_word,tries):
print(IMAGES[tries])
print('')
print(hidden_word)
print('---*---')
def run():
word=random_word()
hidden_word=['-'] *len(word)
tries=0
while True:
display_board(hidden_word,tries)
curret_letter = str(input("Escoge una Letra: "))
if __name__ == '__main__':
print("Entrada de juego")
run()
| [
"[email protected]"
] | |
90b1b2935f90ce882628d4ff106a146a7efaf433 | 85e96c5af2a85a21d8c8ce7f48c458ecb9c1560d | /sigfeat/feature/common.py | 2709789552bc21551c853a823441dd71e87e7f96 | [
"BSD-3-Clause"
] | permissive | SiggiGue/sigfeat | 0758cbe8bdefcb657f641239dad6256100ac59a3 | 86bb94200dcd4b33c21de1abc01814bf85f97b38 | refs/heads/master | 2021-01-10T15:39:37.379959 | 2019-08-21T15:28:53 | 2019-08-21T15:28:53 | 43,051,564 | 9 | 5 | null | null | null | null | UTF-8 | Python | false | false | 2,658 | py | import numpy as np
from scipy.signal import get_window
from scipy.stats import gmean
from ..base import Feature
from ..base import HiddenFeature
from ..base import Parameter
class Index(Feature):
"""Index of source."""
def process(self, data, result):
return data[1]
class WindowedSignal(HiddenFeature):
"""WindowedSignal Feature provides a windowed block from source.
Parameters
----------
window : str
Name of window to be used (supports all from scipy.signal.get_window).
Default is 'hann'.
size : int
Size of the window.
periodic : bool
Periodic True (e.g. for ffts) or symmetric False.
"""
window = Parameter(default='hann')
size = Parameter()
periodic = Parameter(default=True)
def on_start(self, source, *args, **kwargs):
if not self.size:
self.size = source.blocksize
win = get_window(
window=self.window,
Nx=self.size,
fftbins=self.periodic)
self.channels = source.channels
if self.channels > 1:
win = np.tile(win, (self.channels, 1)).T
self.w = win
def process(self, data, result):
if self.window == 'rect':
return data[0]
return self.w * data[0]
def centroid(index, values, axis):
return np.sum(index * values, axis=axis) / np.sum(values, axis=axis)
def flatness(values, axis):
return gmean(values, axis=axis) / np.mean(values, axis=axis)
def flux(values1, values2, axis):
def _abs_max_ratio(s):
return s / np.max(s, axis=axis)
d = _abs_max_ratio(values2) - _abs_max_ratio(values1)
return 0.5 * np.sum(d + np.abs(d), axis=axis)
def rolloff(absvalues, samplerate, kappa=0.85):
cumspec = np.cumsum(absvalues)
rolloffindex = np.argmax(cumspec > kappa*cumspec[-1])
frequency = rolloffindex * 0.5 * samplerate / len(absvalues)
return frequency
def crest_factor(signal):
return np.max(np.abs(signal)) / np.sqrt(np.mean(signal*signal))
def zero_crossing_count(signal):
return np.round(0.5 * np.sum(np.abs(np.diff(np.sign(signal)))))
def moments(signal):
mu = np.mean(signal)
sigma = signal - mu
framecount = len(signal)
# moments:
ss = sigma*sigma
mu_variance = np.mean(ss)
sss = ss * sigma
mu_skewness = np.mean(sss)
mu_kurtosis = np.mean(sss * sigma)
# standardize the moments:
mu_kurtosis = mu_kurtosis / (mu_variance * mu_variance)
mu_skewness = mu_skewness / np.sqrt(mu_variance)**3
mu_variance = mu_variance * framecount / (framecount - 1)
return mu, mu_variance, mu_skewness, mu_kurtosis
| [
"[email protected]"
] | |
6a229e3a74854188654dfdce1ffadf178b5c94d4 | 4391b3ecfe3add85093cc72aca825a1f28236a28 | /deprecated/scripts/test_baddata.py | d155266411ba13b51d2c84a236408b0c4403f06f | [] | no_license | UWKepler/uwpyKepler | dd1d831db1ad8db495134fdf58fba1becf0b38f9 | c6a65f3082854ff0b1f228b46fb6e2080ead24b8 | refs/heads/master | 2021-01-01T16:51:08.348073 | 2012-12-04T00:34:14 | 2012-12-04T00:34:14 | 2,013,217 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 986 | py | import sys
import uwpyKepler as kep
import numpy as num
import pylab
import MySQLdb
#KeplerID = sys.argv[1]
KeplerID = 8478994
#KeplerID = 11295426
#KeplerID = 10341831
db = MySQLdb.connect(host='tddb.astro.washington.edu', user='tddb', passwd='tddb', db='Kepler')
cursor = db.cursor()
foo = 'select * from source where (KEPLERID = %s)' % (KeplerID)
cursor.execute(foo)
results = cursor.fetchall()
# reading time, corrected flux and flux errors
time = num.ma.array([x[2] for x in results])
f1 = num.ma.array([x[5] for x in results])
e1 = num.ma.array([x[6] for x in results])
f2 = num.ma.array([x[7] for x in results])
e2 = num.ma.array([x[8] for x in results])
btime = num.where(time <= 0)
bcf = num.where(f2 <= 0)
bcerr = num.where(e2 <= 0)
good = num.where( (f2 > 0) & (e2 > 0))
print time[btime]
print f2[bcf]
print e2[bcerr]
print btime
print bcf
print bcerr
pylab.plot(time[good],f2[good]-num.median(f2),'b.')
pylab.plot(time[bcf],f2[bcf],'r.')
pylab.show()
| [
"[email protected]"
] | |
6b888afa8081076650b26ddc72d066c50f07c958 | 98b19dae95ea913b90a2eb298b646bce375470a6 | /gov/gov/settings.py | dcab7394e42926cdb055687d1ec70a870b2dab44 | [] | no_license | ZHENGYUANING/ENCP | 88eb6aef3db7e8c639c06b05dc3676565f546916 | 18a00f5ff3e978c9176d6068c95aebcb6685f32b | refs/heads/master | 2020-03-26T03:12:25.509718 | 2018-08-12T06:54:11 | 2018-08-12T06:54:11 | 144,444,384 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,250 | py | # -*- coding: utf-8 -*-
# Scrapy settings for gov project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'gov'
SPIDER_MODULES = ['gov.spiders']
NEWSPIDER_MODULE = 'gov.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'gov (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'
# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'gov.middlewares.GovSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'gov.middlewares.GovDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'gov.pipelines.GovPipeline': 300,
# 'gov.pipelines.JsonPipeline':301,
# 'gov.pipelines.CsvPipeline':302,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
| [
"[email protected]"
] | |
055f9ee55777f37d7d21551a10ed5e0c2a1a9a9a | fd36c2d26d1a39ad084d4ab86cfca2b4cc59e4ca | /run_server.py | 19d0ea76e5957e428be98164f3b126425323977d | [] | no_license | mitchelljustin/PoliticansWritePHComments | dffadcc4fd0c1bf860c37b72e326896c253e6819 | 367b942b5a7c62e01dcac149f8589f31b3b8c71a | refs/heads/master | 2021-05-31T02:29:44.715090 | 2016-03-03T03:43:23 | 2016-03-03T03:43:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 141 | py | from os import environ
from app import app
debug = (environ.get('DEBUG', 'true') == 'true')
app.run(debug=debug, port=8001, host='0.0.0.0')
| [
"[email protected]"
] | |
2692affb62ec83ac4b2975758a8639d73502b62b | 05bdb29b7dbdbc3fd160ab1b06bff2cf8b62f81a | /installRadiant/xlib/xData.py | 5ebe0ef69d424f2b685cd20b27748af8ceb7d951 | [] | no_license | shawnyan888/wikee | 6e9420a4bd828b9fc2aab55d7c6d6a0256196bb7 | b2181cbba1b8600a044cfcfeb519de85755b14a3 | refs/heads/master | 2020-03-18T15:34:10.440524 | 2018-05-28T03:56:28 | 2018-05-28T03:56:28 | 134,915,388 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,337 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import sys
import collections
__author__ = 'Shawn Yan'
__date__ = '16:09 2018/5/25'
ON_WIN = sys.platform.startswith("win")
# Radiant Release Path
rel_path_win = "//192.168.48.104/home/rel"
rel_path_lin = "/home/rel"
REL_PATH = rel_path_win if ON_WIN else rel_path_lin
# Radiant Install Path
lscc_path_win = "d:/radiant_auto"
lscc_path_lin = "/lsh/sw/qa/qadata/radiant/lin"
LSCC_PATH = lscc_path_win if ON_WIN else lscc_path_lin
# install file package logo dictionary
PACKAGE_LOGOS = collections.OrderedDict([
("base", [re.compile("Radiant_x64")]),
("epic", [re.compile("Ctrl_Pack_EPIC")]),
("jedi", [re.compile("Ctrl_Pack_JEDI")]),
("power", [re.compile("PowerEstimator")]),
("program_security", [re.compile("Radiant_Programmer_Security")]),
("program", [re.compile("Radiant_Programmer")]),
("reveal", [re.compile("Radiant_Reveal")]),
("security", [re.compile("Radiant_Security")]),
])
DEFAULT_PACKS = ["base", "jedi", "epic"]
EMAIL = "[email protected]"
success_win = """[root]
path = {0}
[check]
path00 = {0}/ispfpga/bin/nt64/map.exe
path01 = {0}/bin/nt64/pnmain.exe
"""
success_lin = """[root]
path = {0}
[check]
path00 = {0}/ispfpga/bin/lin/map
path01 = {0}/bin/lin/pnmain
"""
SUCCESS_INI = success_win if ON_WIN else success_lin
| [
"[email protected]"
] | |
9b9fa54cd5bf6db34b1d4797b25707c6e44eef12 | 05c19a66688fc35e1d5d57a3c5101c267366aecd | /class_example_one_public.py | e6d073a3a42563d2a5866b56aa90257ad65c5242 | [] | no_license | andrewjwant/warning_public_repo | eafb0790e120bbf1759ac03b99ba018738b96ba9 | f499a20c26a91300ba6971ae34aa79f2174dad64 | refs/heads/master | 2020-05-19T09:39:00.611103 | 2014-12-23T20:02:24 | 2014-12-23T20:02:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,636 | py | from numpy import loadtxt, where
from error_log_file import log_file
%pwd "Insert pathname here"
class FileObject(object):
def __init__(self,
name,
content=None):
self.name = name
self.content = content
def add_content(self):
if self.content is None:
array_to_import = raw_input("Insert {0} filepath here: ".format(self.name))
if array_to_import.endswith(".csv"):
self.content = loadtxt(array_to_import,
dtype="S32",
delimiter=","
)
else:
log_file("{0} file not found".format(self.name))
else:
log_file("{0} file already has content".format(self.name))
class SampleObject(object):
def __init__(self,
bc=None,
d=None,
sn=None,
p_time_d_h_m=None,
p_datetime=None
):
self.bc = bc
self.d = d
self.sn = sn
self.p_time_d_h_m = p_time_d_h_m
self.p_datetime
def add_d(self):
pass
def add_sn(self):
pass
def add_p_time_d_h_m(self):
pass
def add_p_datetime(self):
pass
file_list = [
]
file_dictionary = {}
for item in file_list:
file_dictionary[item] = FileObject(item)
print file_dictionary.keys()
file_dictionary["file"].add_content()
| [
"[email protected]"
] | |
92b79cde823f26c042ca7d307980db5644353457 | 26997a040bc3b9dbc7a1a2ad427c50f474a1d2e5 | /ProLite.py | 0d95ce36b1486cd6cc6662df4d1d944387c09932 | [] | no_license | flyingclimber/LegalTally | 5af8fc2e283e445d5a0cfa91f57f86cc8247e8db | 63aff26656c4a32bfbfc93d54dc4fada6bd4dbf9 | refs/heads/master | 2021-01-15T21:09:55.019532 | 2012-05-13T23:50:38 | 2012-05-13T23:50:38 | 4,037,224 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,361 | py | '''Class library for ProLite signs'''
#Colors
class ProLite:
colors = dict({
'DIM_RED':'<CA>',
'RED':'<CB>',
'BRIGHT_RED':'<CC>',
'ORANGE':'<CD>',
'BRIGHT_ORANGE' : '<CE>',
'LIGHT_YELLOW' : '<CF>',
'YELLOW' : '<CG>',
'BRIGHT_YELLOW' : '<CH>',
'LIME' : '<CI>',
'DIM_LIME' : '<CJ>',
'BRIGHT_LIME' : '<CK>',
'BRIGHT_GREEN' : '<CL>',
'GREEN' : '<CM>',
'DIM_GREEN' : '<CN>',
'YELLOW_GREEN_RED' : '<CO>',
'RAINBOW_DEFAULT' : '<CP>',
'RED_GREEN_3D' : '<CQ>',
'RED_YELLOW_3D' : '<CR>',
'GREEN_RED_3D' : '<CS>',
'GREEN_YELLOW_3D' : '<CT>',
'GREEN_ON_RED' : '<CU>',
'RED_ON_GREEN' : '<CV>',
'ORANGE_ON_GREEN_3D' : '<CW>',
'LIME_ON_RED_3D' : '<CX>',
'GREEN_ON_RED_3D' : '<CY>',
'RED_ON_GREEN_3D' : '<CZ>'})
#Character Size/Format - There are eight character sizes or formats
formats = dict({
'NORMAL_DEFAULT' : '<SA>',
'BOLD_WIDE' : '<SB>',
'ITALIC' : '<SC>',
'BOLD_ITALIC_WIDE' : '<SD>',
'FLASHING_NORMAL' : '<SE>',
'FLASHING_BOLD_WIDE' : '<SF>',
'FLASHING_ITALIC' : '<SG>',
'FLASHING_BOLD_ITALIC_WIDE' : '<SH>'})
#Functions - These are the available functions for displaying the text
functions = dict({
'RANDOM_COLOUR_AND_EFFECT' : '<FA>',
'OPEN_FROM_THE_CENTER' : '<FB>',
'HIDE_THE_TEXT' : '<FC>',
'APPEAR' : '<FD>',
'SCROLLING_COLOURS' : '<FE>',
'CLOSE_RIGHT_TO_LEFT' : '<FF>',
'CLOSE_LEFT_TO_RIGHT' : '<FG>',
'CLOSE_TOWARD_CENTER' : '<FH>',
'SCROLL_UP_FROM_THE_BOTTOM' : '<FI>',
'SCROLL_DOWN_FROM_THE_TOP' : '<FJ>',
'TWO_LAYERS_SLIDE_TOGETHER' : '<FK>',
'FALLING_DOTS_FORM_TEXT' : '<FL>',
'PAC_MAN_GRAPHIC' : '<FM>',
'CREATURES' : '<FN>',
'BEEP_THE_SIGN_BEEPS' : '<FO>',
'PAUSE_SHORT_DELAY' : '<FP>',
'SLEEP_BLANK_SCREEN' : '<FQ>',
'RANDOM_DOTS_FORM_TEXT' : '<FR>',
'ROLL_MESSAGE_LEFT_TO_RIGHT' : '<FS>',
'SHOW_TIME_AND_DATE_NO_FORMATTING_CHOICES' : '<FT>',
'TEXT_COLOUR_CHANGES_EACH_TIME' : '<FU>',
'THANK_YOU_IN_CURSIVE' : '<FV>',
'WELCOME_IN_CURSIVE' : '<FW>',
'SPEED_1' : '<FX>',
'SPEED_2' : '<FY>',
'SPEED_3' : '<FZ>'})
#PAGES
PAGE_1 = '<PA>'
#UNIT
UNIT = '<ID01>'
| [
"[email protected]"
] | |
91475bb7b2a80a9a0e351fb6cf1a0503131fe2c0 | efea24c51375e6a5a79f7224a768b4677f35585e | /sistemaInventarioApi/migrations/0013_remove_usuario_cedula.py | e4d83b82c4aad54d492a8a078ce315a6f58414b5 | [] | no_license | ORLINHNDZ/sistemaInventarioApi | da1bca1c8f2d716e2f9d759d514466196a36e4ad | 9011ffbed1223d894fe0e15b66a555ff2ccf6cc9 | refs/heads/main | 2023-04-14T02:39:15.046578 | 2021-04-27T21:57:31 | 2021-04-27T21:57:31 | 315,148,057 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 342 | py | # Generated by Django 3.1.2 on 2020-12-10 23:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sistemaInventarioApi', '0012_auto_20201207_1316'),
]
operations = [
migrations.RemoveField(
model_name='usuario',
name='cedula',
),
]
| [
"[email protected]"
] | |
d25711699363e9206514c4e7ad370e6cdfa6d6cc | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_049/ch10_2019_02_25_13_33_57_478412.py | 82ad6cf6556fc264702c4e9a127a1e2a0506b9ad | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 52 | py | def libras_para_kg(x):
y=x*0.453592
return y | [
"[email protected]"
] | |
8929025ad037980637683b391c705635384815bd | 114f9e0fc3671a653639f3946f97a2a343b42d1b | /latlong_assignment/settings.py | 6205b4def9fa1ba2f79d0cf9cb3b03b8f5275b9c | [
"MIT"
] | permissive | sivasankar-dev/latlong-django | 3db530419f30199790138e8bcf0ac55c1b119d0b | ca1093ced3955b89f8512f5a3b3ad5f39efec4ee | refs/heads/main | 2023-04-13T18:31:15.690597 | 2021-04-27T18:40:20 | 2021-04-27T18:40:20 | 360,786,820 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,573 | py | """
Django settings for latlong_assignment project.
Generated by 'django-admin startproject' using Django 2.2.17.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, "static")
API_KEY = "SYHvyRGc8Jn73R692npkQknPgpWAimkJ"
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1_2vyop42_19i#pzszxdj#_ckh0h16=&)#^487x$f7)$7+=b)w'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'geolocations_app',
'import_export'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'latlong_assignment.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'latlong_assignment.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [STATIC_DIR,]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
FILE_UPLOAD_HANDLERS = ["django.core.files.uploadhandler.MemoryFileUploadHandler",
"django.core.files.uploadhandler.TemporaryFileUploadHandler"]
| [
"[email protected]"
] | |
d2d2f55bf58acf2c7b0638ee9c3f974eddcc7f15 | 1f41b828fb652795482cdeaac1a877e2f19c252a | /maya_tools_backup/chRig/python/chModules/jointBasePsd/ui/part1_driverInfo.py | f84898d94a6be94c7c1a4dcd28d3858e67aa209f | [] | no_license | jonntd/mayadev-1 | e315efe582ea433dcf18d7f1e900920f5590b293 | f76aeecb592df766d05a4e10fa2c2496f0310ca4 | refs/heads/master | 2021-05-02T07:16:17.941007 | 2018-02-05T03:55:12 | 2018-02-05T03:55:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,678 | py | import maya.cmds as cmds
import uifunctions as uifnc
import globalInfo
import math
from functools import partial
class MovedDriverList:
def __init__(self, width, targetUI, minValue=0.1 ):
self._width = width-25
self._minValue = minValue
self._updateTargetUi = targetUI
def driverScrollAddPopupCmd(self, *args ):
try: cmds.deleteUI( self.popupUi, menu=1 )
except: pass
self.popupUi = cmds.popupMenu( p=self._updateTargetUi )
def removeSelCmd( *args ):
si = cmds.textScrollList( self._updateTargetUi, q=1, si=1 )
cmds.textScrollList( self._updateTargetUi, e=1, ri=si )
def removeAllCmd( *args ):
cmds.textScrollList( self._updateTargetUi, e=1, ra=1 )
#cmds.deleteUI( self.popupUi, menu=1 )
cmds.menuItem( l='Remove All', c=removeAllCmd )
def addConnectDriver(self, str1, *args ):
driverName = str1.split( ':' )[0]
strList = cmds.textScrollList( self._updateTargetUi, q=1, ai=1 )
if not strList: strList = []
for strTarget in strList:
targetDriverName = strTarget.split( ':' )[0]
if driverName == targetDriverName:
cmds.textScrollList( self._updateTargetUi, e=1, ri=strTarget )
cmds.textScrollList( self._updateTargetUi, e=1, a=str1 )
def add(self, driverName, angleValues=[] ):
if not angleValues:
angleValues = [0,0,0]
defaultBgc = [ .1, .1, .1 ]
onBgc = [ .9, .9, .2 ]
enList = [0,0,0]
bgcList = [None,None,None]
for i in range( 3 ):
if math.fabs( angleValues[i] ) >= self._minValue:
bgcList[i] = onBgc
enList[i] = 1
else:
bgcList[i] = defaultBgc
enList[i] = 0
widthList = uifnc.setWidthByPerList( [70,15,15,15] , self._width )
cmds.rowColumnLayout( nc=4, cw=[(1,widthList[0]),(2,widthList[1]),(3,widthList[2]),(4,widthList[3])] )
cmds.text( l= driverName+' : ', al='right' )
cmds.floatField( precision=2, v=angleValues[0], bgc= bgcList[0] )
cmds.popupMenu(); cmds.menuItem( l='Add Driver', c= partial( self.addConnectDriver, driverName+' | angle0 : %3.2f' %angleValues[0] ) )
cmds.floatField( precision=2, v=angleValues[1], bgc= bgcList[1] )
cmds.popupMenu(); cmds.menuItem( l='Add Driver', c= partial( self.addConnectDriver, driverName+' | angle1 : %3.2f' %angleValues[1] ) )
cmds.floatField( precision=2, v=angleValues[2], bgc= bgcList[2] )
cmds.popupMenu(); cmds.menuItem( l='Add Driver', c= partial( self.addConnectDriver, driverName+' | angle2 : %3.2f' %angleValues[2] ) )
self.driverScrollAddPopupCmd()
cmds.setParent( '..' )
class Cmd:
def __init__(self, width ):
globalInfo.driverInfoInst = self
def updateCmd( self, *args ):
rootName = globalInfo.rootDriver
minValue = 0.1
movedDriverCheck = cmds.checkBox( self._movedDriverCheck, q=1, v=1 )
children = cmds.listRelatives( rootName, c=1, ad=1, f=1 )
angleDriverList = []
for child in children:
hists = cmds.listHistory( child )
for hist in hists:
if cmds.nodeType( hist ) == 'angleDriver':
if not hist in angleDriverList:
angleDriverList.append( hist )
showDrivers = []
for driver in angleDriverList:
if movedDriverCheck:
angle1, angle2, angle3 = cmds.getAttr( driver+'.outDriver' )[0]
if math.fabs( angle1 ) > minValue or math.fabs( angle2 ) > minValue or math.fabs( angle3 ) > minValue:
showDrivers.append( driver )
else:
showDrivers.append( driver )
childUis = cmds.scrollLayout( self._driverListLay, q=1, ca=1 )
if childUis:
for childUi in childUis:
cmds.deleteUI( childUi )
cmds.setParent( self._driverListLay )
for driver in showDrivers:
values = cmds.getAttr( driver+'.outDriver' )[0]
self._movedDriverInst.add( driver, values )
self._movedDrivers = showDrivers
self.reWriteValueCmd()
def reWriteValueCmd( self ):
items = cmds.textScrollList( self._driverScrollList, q=1, ai=1 )
if not items: items = []
for item in items:
driverName, other = item.split( ' | angle' )
angleIndex, angleValue = other.split( ' : ' )
angleValue = cmds.getAttr( driverName+'.outDriver%s' % angleIndex )
reItem = driverName+' | angle'+angleIndex+' : %3.2f' % angleValue
cmds.textScrollList( self._driverScrollList, e=1, ri=item )
if angleValue > 0.1:
cmds.textScrollList( self._driverScrollList, e=1, a=reItem )
class Add( Cmd ):
def __init__(self, width ):
self._emptyWidth = 10
self._width = width - self._emptyWidth*2 - 4
self._height = 140
sepList = [ 65, 50 ]
self._mainWidthList = uifnc.setWidthByPerList( sepList, self._width )
sepList = [ 70, 30 ]
self._optionWidthList = uifnc.setWidthByPerList( sepList, self._mainWidthList[0]-20 )
Cmd.__init__( self, self._mainWidthList[0] )
self._rowColumns = []
self.core()
def core(self):
column1 = cmds.rowColumnLayout( nc= 3, cw=[(1,self._emptyWidth),
(2,self._width),
(3,self._emptyWidth)])
uifnc.setSpace()
cmds.text( l='Driver LIST' )
uifnc.setSpace()
cmds.setParent( '..' )
uifnc.setSpace( 5 )
column2 = cmds.rowColumnLayout( nc=4, cw=[(1,self._emptyWidth),
(2,self._mainWidthList[0]),
(3,self._mainWidthList[1]),
(4,self._emptyWidth) ] )
uifnc.setSpace()
column3 = cmds.rowColumnLayout( nc=1, cw=[(1,self._mainWidthList[0])])
self._driverListLay = cmds.scrollLayout( h=self._height-30 )
cmds.setParent( '..' )
uifnc.setSpace( 5 )
column4 = cmds.rowColumnLayout( nc= 4, cw=[(1,self._emptyWidth),
(2,self._optionWidthList[0]),
(3,self._optionWidthList[1]),
(4,self._emptyWidth)] )
uifnc.setSpace()
self._movedDriverCheck = cmds.checkBox( l='Show Only Moved Drivers', cc= self.updateCmd )
cmds.button( l='Refresh', c= self.updateCmd )
uifnc.setSpace()
cmds.setParent( '..' )
cmds.setParent( '..' )
self._driverScrollList = cmds.textScrollList( h= self._height )
self._movedDriverInst = MovedDriverList( self._mainWidthList[0], self._driverScrollList )
uifnc.setSpace()
cmds.setParent( '..' )
self._rowColumns = [ column1, column2, column3, column4 ] | [
"[email protected]"
] | |
17bfe12b73f8151f90bbe524f3e7eec78405670d | e00d41c9f4045b6c6f36c0494f92cad2bec771e2 | /hardware/disk/jfsutils/actions.py | 04137c15c4fe42097f20e21c0e2fb42b734f7ec0 | [] | no_license | pisilinux/main | c40093a5ec9275c771eb5fb47a323e308440efef | bfe45a2e84ea43608e77fb9ffad1bf9850048f02 | refs/heads/master | 2023-08-19T00:17:14.685830 | 2023-08-18T20:06:02 | 2023-08-18T20:06:02 | 37,426,721 | 94 | 295 | null | 2023-09-14T08:22:22 | 2015-06-14T19:38:36 | Python | UTF-8 | Python | false | false | 810 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 3.
# See the file https://www.gnu.org/licenses/gpl-3.0.txt
from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
from pisi.actionsapi import get
def setup():
autotools.configure("--sbindir=/usr/sbin")
def build():
autotools.make()
def install():
autotools.rawInstall("DESTDIR=%s" % get.installDIR())
for bin in "mkfs", "fsck":
pisitools.remove("/usr/sbin/%s.jfs" % bin)
pisitools.dosym("jfs_%s" % bin, "/usr/sbin/%s.jfs" % bin)
manfile = "/%s/man8/%s.jfs.8" % (get.manDIR(), bin)
pisitools.remove(manfile)
pisitools.dosym("jfs_%s.8" % bin, manfile)
pisitools.dodoc("ChangeLog", "AUTHORS", "NEWS", "README*", "COPYING")
| [
"[email protected]"
] | |
5134901473eeb9233f87e142e6334a82d18c9d2e | 307653196b0a90f98d53aec2b1974ecd61dbad39 | /zabbix/core/maintenance.py | ca8e570624db3cdedd29deedd3ce06a68498480f | [] | no_license | dhyaniarun1993/automation_scripts | b2138987da58b27f86953ca82245af738564a6d8 | 09521d1e264982a244c4e33ab969b6e754f659cb | refs/heads/master | 2021-08-28T12:12:36.580484 | 2017-12-12T07:18:30 | 2017-12-12T07:18:30 | 112,226,652 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,073 | py | '''
created by Arun Dhyani
'''
import requests
import json
import sys
URL = 'http://localhost/zabbix/api_jsonrpc.php'
HEADERS = {'content-type': 'application/json'}
def createTimePeriodObject(start_time, start_date=None, period=3600, timeperiod_type=0, day=None, dayofweek=None, every=None, month=None):
'''
function to create time period object
'''
obj = {
"timeperiod_type": timeperiod_type,
"start_time": start_time,
"period": period
}
if start_date:
obj['start_date'] = start_date
if day:
obj['day'] = day
if dayofweek:
obj['dayofweek'] = dayofweek
if every:
obj['every'] = every
if month:
obj['month'] = month
return obj
def appendcreateTimePeriodObjectList(start_time, start_date=None, period=3600, timeperiod_type=0, day=None, dayofweek=None, every=None, month=None, tpObjList=None):
'''
function to create list of time period object or append time period object to provided list
'''
if tpObjList:
objList = tpObjList
else:
objList = []
obj = createTimePeriodObject(start_time, start_date=start_date, period=period, timeperiod_type=timeperiod_type, day=day, dayofweek=dayofweek, every=every, month=month)
objList.append(obj)
return objList
def createMaintenance(name, timeperiodObjList, authToken, maintenanceType=0, active_since=None, active_till=None, groupids=None, hostids=None, url=URL, headers=HEADERS):
'''
function to create maintenance
'''
if groupids or hostids:
payload = {
"jsonrpc": "2.0",
"method": "maintenance.create",
"params": {
"name": name,
"maintenance_type": maintenanceType,
"timeperiods": timeperiodObjList
},
"auth": authToken,
"id": 1
}
if active_since:
payload['params']['active_since'] = active_since
if active_till:
payload['params']['active_till'] = active_till
if groupids:
payload['params']['groupids'] = groupids
if hostids:
payload['params']['hostids'] = hostids
print payload
result = requests.post(url, data=json.dumps(payload), headers=headers).json()
print result
if result.has_key('error'):
return False, result['error']['message']
else:
return True, result['result']
else:
message = 'Please provide groupids or hostids for maintenance'
return False, message
def updateMaintenanceUsingId(maintenanceId, authToken, timeperiodObjList=None, hostids=None, groupids=None, active_since=None, active_till=None, url=URL, headers=HEADERS):
'''
function to update maintenance
'''
payload = {
"jsonrpc": "2.0",
"method": "maintenance.update",
"params": {
"maintenanceid": maintenanceId,
},
"auth": authToken,
"id": 1
}
if groupids:
payload['params']['groupids'] = groupids
if hostids:
payload['params']['hostids'] = hostids
if timeperiodObjList:
payload['params']['timeperiods'] = timeperiodObjList
if active_since:
payload['params']['active_since'] = active_since
if active_till:
payload['params']['active_till'] = active_till
print payload
result = requests.post(url, data=json.dumps(payload), headers=headers).json()
if result.has_key('error'):
print result
return False, result['error']['message']
else:
return True, result['result']
def getMaintenanceUsingName(name, authToken, url=URL, headers=HEADERS):
payload = {
"jsonrpc": "2.0",
"method": "maintenance.get",
"params": {
"filter": {
"name": [
name
]
}
},
"auth": authToken,
"id": 1
}
result = requests.post(url, data=json.dumps(payload), headers=headers).json()
if result.has_key('error'):
return False, result['error']['message']
else:
return True, result['result']
def deleteMaintenanceUsingId(maintenanceId, authToken, url=URL, headers=HEADERS):
payload = {
"jsonrpc": "2.0",
"method": "maintenance.delete",
"params": [
maintenanceId
],
"auth": authToken,
"id": 1
}
result = requests.post(url, data=json.dumps(payload), headers=HEADERS).json()
if result.has_key('error'):
return False, result['error']['message']
else:
return True, result['result']
| [
"[email protected]"
] | |
77e9fa8f8cf6dd5234cee2db266d3fdaeb7f6bbf | 7c5f1aeda72966c9080aa2b0bafa83c3360d7de0 | /link_prediction/link_prediction_neo4j.py | 1b99fd0cb60e00e9ef9871d278dbe91e64573dc6 | [] | no_license | jpalaskas/GraphAnalysis | 88c3d3386ccf3bffa8c0e9855f83b6726f40caa1 | 541a817da4c336012df41eef813444efb043602c | refs/heads/master | 2022-12-03T10:10:36.938929 | 2020-08-22T08:34:32 | 2020-08-22T08:34:32 | 284,316,179 | 0 | 0 | null | 2020-08-01T18:25:36 | 2020-08-01T18:25:35 | null | UTF-8 | Python | false | false | 5,368 | py | from py2neo import Graph
import json
import pandas as pd
from pandas import DataFrame
import sys
import matplotlib.pyplot as plt
def best_users(graph):
best_in = graph.run('MATCH (u:User)<-[r]-() RETURN u.id, count(r) as count').to_data_frame()
best_out = graph.run('MATCH (u:User)-[r]->() RETURN u.id, count(r) as count').to_data_frame()
best_out_degree = [user for user in best_out.nlargest(100, ['count'])['u.id']]
best_in_degree = [user for user in best_in.nlargest(100, ['count'])['u.id']]
worst_in_degree = [user for user in best_in.nsmallest(100, ['count'])['u.id']]
worst_out_degree = [user for user in best_out.nsmallest(100, ['count'])['u.id']]
print()
return best_in, best_out
def adamic_adar_alg(rel_type, graph):
if rel_type != '':
sc_per_type = graph.run(
'MATCH (p1:User) MATCH (p2:User) RETURN algo.linkprediction.adamicAdar(p1, p2, {relationshipQuery: "%s"}) AS score,p1.id,p2.id'% rel_type,
rel_type=rel_type)
return sc_per_type.to_data_frame()
else:
sc_per_user = graph.run(
'MATCH (p1:User) MATCH (p2:User) RETURN algo.linkprediction.adamicAdar(p1, p2) AS score').to_data_frame()
return sc_per_user
def common_neighbors(rel_type, graph):
if rel_type != '':
sc_common_per_type = graph.run('MATCH (p1:User) MATCH (p2:User) RETURN algo.linkprediction.commonNeighbors(p1, p2, {relationshipQuery: "%s"}) AS score LIMIT 10'% rel_type, rel_type=rel_type)
return sc_common_per_type.to_data_frame()
else:
sc_common_per_user = graph.run(
'MATCH (p1:User) MATCH (p2:User) RETURN algo.linkprediction.commonNeighbors(p1, p2) AS score LIMIT 10').to_data_frame()
return sc_common_per_user
def linkprediction_preferectialAttachment(rel_type, graph):
if rel_type != '':
sc_preferential_per_type = graph.run(
'MATCH (p1:User) MATCH (p2:User) RETURN algo.linkprediction.preferentialAttachment(p1, p2, {relationshipQuery: "%s"}) AS score'% rel_type, rel_type=rel_type).to_data_frame()
return sc_preferential_per_type.to_data_frame()
else:
sc_preferential_per_user = graph.run('MATCH (p1:User) MATCH (p2:User) RETURN algo.linkprediction.preferentialAttachment(p1, p2) AS score').to_data_frame()
return sc_preferential_per_user
def resourceAllocation(rel_type, graph):
if rel_type != '':
sc_resourceAllocation_per_type = graph.run('''
MATCH (p1:Person {name: 'Michael'})
MATCH (p2:Person {name: 'Karin'})
RETURN algo.linkprediction.resourceAllocation(p1, p2, {relationshipQuery: "s"}) AS score '''% rel_type, rel_type=rel_type).to_data_frame()
return sc_resourceAllocation_per_type
else:
sc_resourceAllocation_per_user = graph.run('''
MATCH (p1:User)
MATCH (p2:User)
RETURN algo.linkprediction.resourceAllocation(p1, p2) AS score ''').to_data_frame()
return sc_resourceAllocation_per_user
def linkpred_sameCommunity(rel_type, graph):
if rel_type != '':
sc_sameCommunity_per_type = graph.run('''
MATCH (p1:User)
MATCH (p2:User)
RETURN algo.linkprediction.sameCommunity(p1, p2) AS score
'''% rel_type, rel_type=rel_type).to_data_frame()
return sc_sameCommunity_per_type
else:
sc_sameCommunity_per_user = graph.run('''
MATCH (p1:User)
MATCH (p2:User)
RETURN algo.linkprediction.sameCommunity(p1, p2) AS score''').to_data_frame()
return sc_sameCommunity_per_user
def total_neighbors(rel_type, graph):
if rel_type != '':
sc_totalNeighbors_per_type = graph.run('''
MATCH (p1:Person {name: 'Michael'})
MATCH (p2:Person {name: 'Karin'})
RETURN algo.linkprediction.totalNeighbors(p1, p2, {relationshipQuery: "%s"}) AS score'''% rel_type, rel_type=rel_type).to_data_frame()
return sc_totalNeighbors_per_type
else:
sc_totalNeighboors_per_user = graph.run('''
MATCH (p1:User)
MATCH (p2:User)
RETURN algo.linkprediction.totalNeighbors(p1, p2) AS score
''').to_data_frame()
return sc_totalNeighboors_per_user
def main():
graph = Graph('127.0.0.1', password='leomamao971')
best_users(graph)
print("Read from database")
common_neighbors('TRADES', graph)
common_neighbors('ATTACKS', graph)
common_neighbors('messages', graph)
common_neighbors('', graph)
adamic_adar_alg('TRADES', graph)
adamic_adar_alg('ATTACKS', graph)
adamic_adar_alg('messages', graph)
adamic_adar_alg('', graph)
linkprediction_preferectialAttachment('TRADES', graph)
linkprediction_preferectialAttachment('ATTACKS', graph)
linkprediction_preferectialAttachment('messages', graph)
linkprediction_preferectialAttachment('', graph)
resourceAllocation('TRADES', graph)
resourceAllocation('ATTACKS', graph)
resourceAllocation('messages', graph)
resourceAllocation('', graph)
linkpred_sameCommunity('TRADES', graph)
linkpred_sameCommunity('ATTACKS', graph)
linkpred_sameCommunity('messages', graph)
linkpred_sameCommunity('', graph)
total_neighbors('TRADES', graph)
total_neighbors('ATTACKS', graph)
total_neighbors('messages', graph)
total_neighbors('', graph)
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
3e043eafd697d0bda7dcd78559589164ec7a7da4 | 574b04d5942e33a580f93c0256670d8368d2c49e | /videoDetection/dataset_creation/dataset_generation/dataset_gen.py | 4882be0c7f8f05685e7730f9a8029eaa807c9d88 | [
"MIT"
] | permissive | Rubik90/TFM_AG | c9ac96f279a8583b9bbdd20c4917cf320a5a1057 | 5e836245d0704122f2a0d47413e93bf53d966ca0 | refs/heads/main | 2023-05-04T14:30:56.446322 | 2021-04-01T12:35:35 | 2021-04-01T12:35:35 | 336,585,569 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,073 | py | import os
import sys
import shutil
import glob
from PIL import Image
if "--videos_path" in sys.argv:
videos_path = sys.argv[sys.argv.index("--videos_path") + 1]
else:
print("ERROR: No value specified for the frames path")
sys.exit()
if "--annotations_path" in sys.argv:
annotations_path = sys.argv[sys.argv.index("--annotations_path") + 1]
else:
print("ERROR: No value specified for the annotations path")
sys.exit()
if "--dataset_path" in sys.argv:
dataset_path = sys.argv[sys.argv.index("--dataset_path") + 1]
else:
print("ERROR: No value specified for the destination path where the dataset will be created")
sys.exit()
videos = os.listdir(videos_path)
videos.sort()
annotations = os.listdir(annotations_path)
annotations.sort()
emotions = ['Neutral', 'Anger', 'Disgust',
'Fear', 'Happiness', 'Sadness', 'Surprise']
if(os.path.isdir(dataset_path)):
shutil.rmtree(dataset_path)
os.mkdir(dataset_path)
for emotion in emotions:
path = f'{dataset_path}/{emotion}'
if(os.path.isdir(path)):
shutil.rmtree(path)
os.mkdir(path)
print('Generating the dataset, please wait...\n')
for video in videos:
for annotation in annotations:
video_id = video[:-8]
annotation_id = annotation[:-4]
if (video_id == annotation_id):
print(f'Currently processing video \'{video_id}\'')
# Get the annotations
with open(annotations_path + annotation, 'r') as ann:
lines = ann.readlines()
# Get the frames
frames = os.listdir(videos_path + video)
frames.sort()
for i in range(1, len(frames) - 1):
annotation_value = int(lines[i])
print("", end=f"\rProgress: [{i + 1}/{len(frames) - 1}]")
if (annotation_value >= 0 and annotation_value <= 6): # Skip untagged frames
shutil.copy2(f'{videos_path}/{video}/{frames[i]}', f'{dataset_path}/{emotions[int(lines[i])]}')
print("\n")
print("")
| [
"[email protected]"
] | |
4cd959feba76f04559dbece78f61eac0cd436715 | 1efe68b3c5178a8054e499120066671363cc300d | /17/17.py | 5b32b1fa6405e4b59bd8546e01f1aba5d2a63d13 | [
"MIT"
] | permissive | fxbk/AoC2020 | 0c9f688bd1b38fec840a0a834216c51897b93865 | 52dca0a0d8e4960821ee3b363313b6f806c5cfa0 | refs/heads/main | 2023-02-07T08:51:00.948648 | 2020-12-28T12:32:18 | 2020-12-28T12:32:18 | 318,993,552 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,916 | py | import copy
import itertools
from tqdm import tqdm
file = open('input.txt', 'r')
input = file.read()
input = input.split('\n')
active = []
for y, row in enumerate(input):
for x, c in enumerate(row):
if c == '#':
active.append((x, y, 0))
def get_number_of_active_neighbors(active_list, x, y, z):
number_of_active_neighbors = 0
neighbors = list(itertools.product([-1, 0, 1], [-1, 0, 1], [-1, 0, 1]))
del neighbors[neighbors.index((0, 0, 0))]
for neighbor in neighbors:
x_idx = x + neighbor[0]
y_idx = y + neighbor[1]
z_idx = z + neighbor[2]
if (x_idx, y_idx, z_idx) in active_list:
number_of_active_neighbors += 1
return number_of_active_neighbors
x_max = len(input[0])
y_max = len(input)
z_max = 0
for cycle in range(1, 7):
out = copy.deepcopy(active)
for z in range(-cycle, cycle + 1):
for y in range(-cycle, y_max + cycle + 1):
for x in range(-cycle, x_max + cycle + 1):
numb_neigbbors = get_number_of_active_neighbors(active, x, y, z)
if (x, y, z) in active and numb_neigbbors not in [2, 3]:
del out[out.index((x, y, z))]
elif (x, y, z) not in active and numb_neigbbors == 3:
out.append((x, y, z))
active = out
print(f'Solution part 1: {len(out)}')
# Part 2
active = []
for y, row in enumerate(input):
for x, c in enumerate(row):
if c == '#':
active.append((x, y, 0, 0))
def get_number_of_active_neighbors_part2(active_list, x, y, z, w):
number_of_active_neighbors = 0
neighbors = list(itertools.product([-1, 0, 1], [-1, 0, 1], [-1, 0, 1], [-1, 0, 1]))
del neighbors[neighbors.index((0, 0, 0, 0))]
for neighbor in neighbors:
x_idx = x + neighbor[0]
y_idx = y + neighbor[1]
z_idx = z + neighbor[2]
w_idx = w + neighbor[3]
if (x_idx, y_idx, z_idx, w_idx) in active_list:
number_of_active_neighbors += 1
return number_of_active_neighbors
x_max = len(input[0])
y_max = len(input)
# TODO Adjust range in order to cure the curse of dimensionality i.e. delete row, column if no point active there
for cycle in tqdm(range(1, 7), 'Cycles: '):
out = copy.deepcopy(active)
for w in tqdm(range(-cycle, cycle + 1), 'W Dimension'):
for z in range(-cycle, cycle + 1):
for y in range(-cycle, y_max + cycle + 1):
for x in range(-cycle, x_max + cycle + 1):
numb_neigbbors = get_number_of_active_neighbors_part2(active, x, y, z, w)
if (x, y, z, w) in active and numb_neigbbors not in [2, 3]:
del out[out.index((x, y, z, w))]
elif (x, y, z, w) not in active and numb_neigbbors == 3:
out.append((x, y, z, w))
active = out
print(f'Solution part 2: {len(out)}')
| [
"[email protected]"
] | |
036b49dc3e04b13b6a60801e493266459786b344 | 5ddec5c9fc664340de68cce69037d553478226d5 | /python/AirConOff.py | dede34f710b8548e9dcd6268796171fdf59e22d3 | [
"Apache-2.0"
] | permissive | dobachi/PythonECHONETLiteExample | 4f17086dc9df835bdb59123738f5a8a1165c3116 | ea243d8f084772a83c76a1e3cabd2be9d20cc072 | refs/heads/main | 2023-08-24T09:22:24.510430 | 2021-10-02T15:59:30 | 2021-10-02T15:59:30 | 411,939,682 | 0 | 0 | Apache-2.0 | 2021-09-30T05:58:50 | 2021-09-30T05:52:07 | null | UTF-8 | Python | false | false | 2,861 | py | #!/usr/bin/env python
# https://yomon.hatenablog.com/entry/2020/09/sharp_aircon_echonet_lite を
# 参考に試してみる例
import socket
import sys
def create_command():
# ---------------------------------------------------
# 3.2.1 ECHONET Lite ヘッダ(EHD)
# ---------------------------------------------------
# 3.2.1.1 ECHONET Lite ヘッダ 1(EHD1)
EHD1 = "10" # ECHONET Lite規格
# 3.2.1.2 ECHONET Lite ヘッダ 2(EHD2)
EHD2 = "81" # 形式1(規定電文形式)
# 3.2.2 Transaction ID(TID)
TID = "0001" # IDなのでこの検証ではどの値でもOK
# フレームのヘッダ-を構成
EHD = EHD1 + EHD2 + TID
# ---------------------------------------------------
# 3.2.1 ECHONET Lite データ(EDATA)
# ---------------------------------------------------
# 3.2.4 ECHONETオブジェクト
# EOJ = ECHONET Lite オブジェクト
# SEOJ = 送信元ECHONET Lite オブジェクト
SEOJ_CLS_GROUP = "05" # 管理・操作関連クラスグループ
SEOJ_CLS_CODE = "ff" # コントローラー
SEOJ_CLS_INSTANCE = "01" # インスタンス番号
SEOJ = SEOJ_CLS_GROUP + SEOJ_CLS_CODE + SEOJ_CLS_INSTANCE
# DEOJ = 送信先ECHONET Lite オブジェクト
DEOJ_CLS_GROUP = "01" # 空調関連機器クラスグループ
DEOJ_CLS_CODE = "30" # 家庭用エアコンクラス
DEOJ_CLS_INSTANCE = "01" # All Instanses
DEOJ = DEOJ_CLS_GROUP + DEOJ_CLS_CODE + DEOJ_CLS_INSTANCE
# 3.2.5 ECHONET Lite サービス(ESV)
ESV = "60" # プロパティ値書き込み要求 (Set)
###############
# APPENDIX ECHONET機器オブジェクト詳細規定
# - 空調関連機器クラスグループ
# - 家庭用エアコンクラス規定
# を確認
# 3.2.6 処理プロパティカウンタ
OPC = "01" # 1件
# プロパティ(今回は電源の操作なので1件だけ)
EPC1 = "80" # 動作状態
PDC1 = "01" # Setなので1Byte指定
EDT1 = "31" # Offつまり0x31を指定
PROP1 = EPC1 + PDC1 + EDT1
# フレームのデータ部分であるEDATAを構成
EDATA = SEOJ + DEOJ + ESV + OPC + PROP1
echonet_command = EHD + EDATA
return echonet_command
def send(host, echonet_command):
echonet_port = 3610
#aircon_ip = "192.168.1.10" # 224.0.23.0のアドレスを使うとマルチキャストもできます
# 要求送信用ソケットでコマンド送信
send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
send_sock.sendto(bytes.fromhex(echonet_command), (host, echonet_port))
send_sock.close()
if __name__ == '__main__':
args = sys.argv
echonet_command = create_command()
send(args[1], echonet_command); | [
"[email protected]"
] | |
4adb49be9ca1bb4ee2cc1405b6663fb0901635ad | 20e122159c1e877b87c55e09bf7239da9e893f6d | /CSE230/programming assignments/pa6/pa6_solution/vector.py | d8be81d69efdd0ecf03078bb9013d4cad86bac27 | [] | no_license | e3u3/UCSDCourse | 87fe4621e34cab962be94542bd8167e63585638e | ce89a23526482453275077aa5aa1eecc8829139b | refs/heads/master | 2020-06-08T11:04:27.317484 | 2019-06-21T17:03:30 | 2019-06-21T17:03:30 | 193,217,763 | 1 | 1 | null | 2019-06-22T09:48:51 | 2019-06-22T09:48:51 | null | UTF-8 | Python | false | false | 3,092 | py | from misc import Failure
class Vector(object):
def __init__(self, args):
"""
constructor
Input: int means the length of the vector or a list of values to assign to the vetor
Out: vector
"""
if (isinstance(args,int) or isinstance(args,long)):
if (args < 0):
raise ValueError("Vector length must greater than 0.")
self.vec = [0.0] * args
elif (isinstance(args, list)):
self.vec = list(args)
else:
raise TypeError("The type is expecting is an Integer or a list but given with {}".format(type(args)))
def __repr__(self):
""" repr is the string represention of the class, it returns
Vector(contents of the list)"""
return "Vector(" + repr(self.vec) + ")"
def __len__(self):
"""
compute the length of vector
"""
return len(self.vec)
def __iter__(self):
""" Returns an iterator for the vector """
for item in self.vec:
yield(item)
def __add__(self,second):
"""
This function override the function object.__add__() to implement binary operation of addition.
"""
return Vector(([x + y for x, y in zip(list(self), list(second))]))
def __iadd__(self, second):
self.vec = Vector(([x + y for x, y in zip(list(self), list(second))]))
return self.vec
def __radd__(self,second):
return Vector(([x + y for x, y in zip(list(self), list(second))]))
def dot(self, second):
"""
This function is the implemention of dot product of vector
"""
return sum([ x * y for x, y in zip(self, second)])
def __getitem__ (self, index):
"""
this function get corresponding elems
"""
return self.vec[index]
def __setitem__ (self, x, y):
temp = len(self.vec)
self.vec[x] = y
if ( temp != len(self.vec)):
raise ValueError(" Can not change length of vector")
def __eq__(self, second):
if not isinstance(second, Vector):
return False
allequal = ([ x == y for x, y in zip(self, second)])
if False in allequal:
return False
else:
return True
def __ne__(self, other):
return not self.__eq__(other)
def __ge__(self, second):
if self.__gt__(second):
return True
selfSorted = sorted(self, reverse = True)
secondSorted= sorted(second, reverse = True)
if selfSorted.__eq__(secondSorted):
return True
return False
def __gt__(self, second):
if not isinstance(second,Vector):
return (self > other)
selfSorted = sorted(self, reverse = True)
secondSorted= sorted(second, reverse = True)
for x, y in zip(selfSorted, secondSorted):
if x > y:
return True
elif x < y:
return False
return False
def __lt__(self, second):
return not self.__ge__(second)
def __le__(self, second):
return not self.__gt__(second)
| [
"[email protected]"
] | |
36ca3c04dd363c14bcc23be5a628b5e7e6829b54 | d554b1aa8b70fddf81da8988b4aaa43788fede88 | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4131/codes/1593_1801.py | 68aa91038cf015d360afa193c96d8336c1eea4bb | [] | no_license | JosephLevinthal/Research-projects | a3bc3ca3b09faad16f5cce5949a2279cf14742ba | 60d5fd6eb864a5181f4321e7a992812f3c2139f9 | refs/heads/master | 2022-07-31T06:43:02.686109 | 2020-05-23T00:24:26 | 2020-05-23T00:24:26 | 266,199,309 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 74 | py | x1= input("nome")
x2= int(input(" nrf "))
print(("Abra " + x1 + " ") * x2) | [
"[email protected]"
] | |
04ce0850226367c30af7a2f3c7517bed18065b12 | 07763d43e0074ee19d550b02419e71b576b6dbec | /tuples_samples.py | d4de359b78c77d6d7eea0bb419af05a1b02f80c9 | [] | no_license | balasubramanianramesh/Python_Training | a93ee368ec364485bec36b095018a62628799381 | 96b4ef0c06993407d12b411ded2de3b5a770ecaa | refs/heads/master | 2021-01-11T16:02:01.792651 | 2017-01-25T09:08:27 | 2017-01-25T09:08:27 | 79,989,295 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 855 | py | tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = ( 0, 1, 2, 3, 4, 5, 6, 7 );
tup3 = "a", "b", "c", "d";
tup1 = (); ##Empty tuple
tup1 = (50,); ## To write a tuple containing a single value you have to include a comma, even though there is only one value
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]
print "tup2[3:]: ", tup2[3:] # tup2[3::]
print "tup2[::2]: ", tup2[::2]
print "tup2[::-2]: ", tup2[::-2]
print "tup2[::1]: ", tup2[::1]
print "tup2[2]: ", tup2[2]
print "tup2[-2]: ", tup2[-2]
tup4 = tup1 + tup2 + tup3;
print tup4
print len(tup4)
print 10 in tup4
print 'a' in tup4
print "tup2 : ",tup2
print "tup4 : ",tup4
print tup2 in tup4 ## cann't able to check the tuples values
print 'compare tup2 with tup4', cmp( tup2, tup4 )
print 'compare tup4 with tup2', cmp( tup4, tup2 )
#del tup4 ## del tup4[2] ## will not work
#print tup4 | [
"[email protected]"
] | |
532ef36c34decb44e73a5e1b81beb7a67c57cc0a | f3b233e5053e28fa95c549017bd75a30456eb50c | /ptp1b_input/L83/83-79_MD_NVT_rerun/set_1.py | e52dbdc3dbc2b5c4afd43f06c240d855b04ecbb2 | [] | no_license | AnguseZhang/Input_TI | ddf2ed40ff1c0aa24eea3275b83d4d405b50b820 | 50ada0833890be9e261c967d00948f998313cb60 | refs/heads/master | 2021-05-25T15:02:38.858785 | 2020-02-18T16:57:04 | 2020-02-18T16:57:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 741 | py | import os
dir = '/mnt/scratch/songlin3/run/ptp1b/L83/MD_NVT_rerun/ti_one-step/83_79/'
filesdir = dir + 'files/'
temp_prodin = filesdir + 'temp_prod_1.in'
temp_pbs = filesdir + 'temp_1.pbs'
lambd = [ 0.00922, 0.04794, 0.11505, 0.20634, 0.31608, 0.43738, 0.56262, 0.68392, 0.79366, 0.88495, 0.95206, 0.99078]
for j in lambd:
os.chdir("%6.5f" %(j))
workdir = dir + "%6.5f" %(j) + '/'
#prodin
prodin = workdir + "%6.5f_prod_1.in" %(j)
os.system("cp %s %s" %(temp_prodin, prodin))
os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, prodin))
#PBS
pbs = workdir + "%6.5f_1.pbs" %(j)
os.system("cp %s %s" %(temp_pbs, pbs))
os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, pbs))
#submit pbs
#os.system("qsub %s" %(pbs))
os.chdir(dir)
| [
"[email protected]"
] | |
584d4619db06c8d1462cb07e7215ad04c548557e | 31681488e69da3c7e00b0eda28e5cb720ef2299c | /liteiclink/serwb/packet.py | e8fc035b1b096ded56e1cea8560fc1819ccb2679 | [
"BSD-2-Clause"
] | permissive | zsipos/liteiclink | 4e9bdf6a819f490461cb33d0837247041203071d | 864cd831f3475dffd1c92d6d4a1b86608680bcf2 | refs/heads/master | 2021-07-08T07:43:10.897604 | 2020-01-28T09:40:17 | 2020-01-28T09:40:17 | 245,119,569 | 0 | 0 | NOASSERTION | 2020-03-05T09:25:16 | 2020-03-05T09:25:15 | null | UTF-8 | Python | false | false | 4,839 | py | # This file is Copyright (c) 2017-2019 Florent Kermarrec <[email protected]>
# License: BSD
from math import ceil
from migen import *
from migen.genlib.misc import WaitTimer
from litex.gen import *
from litex.soc.interconnect import stream
class HeaderField:
def __init__(self, byte, offset, width):
self.byte = byte
self.offset = offset
self.width = width
class Header:
def __init__(self, fields, length, swap_field_bytes=True):
self.fields = fields
self.length = length
self.swap_field_bytes = swap_field_bytes
def get_layout(self):
layout = []
for k, v in sorted(self.fields.items()):
layout.append((k, v.width))
return layout
def get_field(self, obj, name, width):
if "_lsb" in name:
field = getattr(obj, name.replace("_lsb", ""))[:width]
elif "_msb" in name:
field = getattr(obj, name.replace("_msb", ""))[width:2*width]
else:
field = getattr(obj, name)
if len(field) != width:
raise ValueError("Width mismatch on " + name + " field")
return field
def encode(self, obj, signal):
r = []
for k, v in sorted(self.fields.items()):
start = v.byte*8 + v.offset
end = start + v.width
field = self.get_field(obj, k, v.width)
if self.swap_field_bytes:
field = reverse_bytes(field)
r.append(signal[start:end].eq(field))
return r
def decode(self, signal, obj):
r = []
for k, v in sorted(self.fields.items()):
start = v.byte*8 + v.offset
end = start + v.width
field = self.get_field(obj, k, v.width)
if self.swap_field_bytes:
r.append(field.eq(reverse_bytes(signal[start:end])))
else:
r.append(field.eq(signal[start:end]))
return r
def phy_description(dw):
layout = [("data", dw)]
return stream.EndpointDescription(layout)
def user_description(dw):
layout = [
("data", 32),
("length", 32)
]
return stream.EndpointDescription(layout)
class Packetizer(Module):
def __init__(self):
self.sink = sink = stream.Endpoint(user_description(32))
self.source = source = stream.Endpoint(phy_description(32))
# # #
# Packet description
# - preamble : 4 bytes
# - length : 4 bytes
# - payload
fsm = FSM(reset_state="PREAMBLE")
self.submodules += fsm
fsm.act("PREAMBLE",
If(sink.valid,
source.valid.eq(1),
source.data.eq(0x5aa55aa5),
If(source.ready,
NextState("LENGTH")
)
)
)
fsm.act("LENGTH",
source.valid.eq(1),
source.data.eq(sink.length),
If(source.ready,
NextState("DATA")
)
)
fsm.act("DATA",
source.valid.eq(sink.valid),
source.data.eq(sink.data),
sink.ready.eq(source.ready),
If(source.ready & sink.last,
NextState("PREAMBLE")
)
)
class Depacketizer(Module):
def __init__(self, clk_freq, timeout=10):
self.sink = sink = stream.Endpoint(phy_description(32))
self.source = source = stream.Endpoint(user_description(32))
# # #
count = Signal(len(source.length))
length = Signal(len(source.length))
# Packet description
# - preamble : 4 bytes
# - length : 4 bytes
# - payload
fsm = FSM(reset_state="PREAMBLE")
self.submodules += fsm
timer = WaitTimer(clk_freq*timeout)
self.submodules += timer
fsm.act("PREAMBLE",
sink.ready.eq(1),
If(sink.valid &
(sink.data == 0x5aa55aa5),
NextState("LENGTH")
)
)
fsm.act("LENGTH",
sink.ready.eq(1),
If(sink.valid,
NextValue(count, 0),
NextValue(length, sink.data),
NextState("DATA")
),
timer.wait.eq(1)
)
fsm.act("DATA",
source.valid.eq(sink.valid),
source.last.eq(count == (length[2:] - 1)),
source.length.eq(length),
source.data.eq(sink.data),
sink.ready.eq(source.ready),
If(timer.done,
NextState("PREAMBLE")
).Elif(source.valid & source.ready,
NextValue(count, count + 1),
If(source.last,
NextState("PREAMBLE")
)
),
timer.wait.eq(1)
)
| [
"[email protected]"
] | |
545bebbae87cb9883640029d8b20937e0fc6f49c | c924c06d2b658924a0e0fabe7fcbf27ad98cc149 | /COLOSSEUM/backend/migrations/0004_game_server_response.py | 83461480f224dbbcc5fd35062c584d8774e0ba69 | [] | no_license | ColosseumGroup/ColosseumII | 49b85c7d00aa16c62d700fc194db679fd34a978c | 36fde3cc947bf68034aeb4b84aa10e561b5be52a | refs/heads/master | 2018-12-05T17:59:26.728207 | 2018-08-13T02:18:39 | 2018-08-13T02:18:39 | 119,014,472 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 387 | py | # Generated by Django 2.1 on 2018-08-12 03:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0003_game_max_player_num'),
]
operations = [
migrations.AddField(
model_name='game',
name='server_response',
field=models.TextField(default=''),
),
]
| [
"[email protected]"
] | |
632910dc19509552a058895affb69cb8bfc155ce | 8bb0dea2174658ad305ce37d38bc0375e4765977 | /cards/management/commands/jsonimport.py | 8c487cf8cbe691b9d37eb6764b1c5e634ccc3f33 | [
"MIT"
] | permissive | axm1820/cards-against-django | e256622d6f12a608f68c617953f79c82a7ae2bfa | dabc508474b028e9de400b27736590613b8396d8 | refs/heads/master | 2020-12-03T10:30:10.394144 | 2014-08-15T01:24:08 | 2014-08-15T01:24:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,693 | py | import sys
from optparse import make_option
# json support, TODO consider http://pypi.python.org/pypi/omnijson
try:
# Python 2.6+
import json
except ImportError:
# from http://code.google.com/p/simplejson
import simplejson as json
dump_json = json.dumps
load_json = json.loads
from django.core.management.base import BaseCommand, CommandError
from cards.models import dict2db
class Command(BaseCommand):
args = 'json_filename'
help = dict2db.__doc__
option_list = BaseCommand.option_list + (
make_option('--replace_existing',
action='store_true',
dest='replace_existing',
default=False,
help='Allow replacement (delete then add) of existing cardsets'),
)
def handle(self, *args, **options):
try:
filename = args[0]
if filename == '-':
filename = None
except IndexError:
filename = None
verbosity = int(options['verbosity'])
replace_existing = options['replace_existing']
if verbosity >= 1:
if filename:
self.stdout.write('Using %r' % filename)
else:
self.stdout.write('Using STDIN')
if filename:
f = open(filename, 'rb')
else:
f = sys.stdin
raw_str = f.read()
if filename:
f.close()
d = load_json(raw_str)
results = dict2db(d, verbosity, replace_existing)
for cardset_name, b_count, w_count in results:
if verbosity >= 1:
print '%s total# %d question# %d answer# %d' % (cardset_name, b_count + w_count, b_count, w_count)
| [
"[email protected]"
] | |
29fe4042cd2cbd2f2ca9d31a58cf53afd5ba5298 | 4368c51ce45504e2cc17ea8772eeb94c13e1c34a | /utils/meta_utils.py | 2c8068279495081ff5d67c14a8d980c40f3f982b | [] | no_license | Shuai-Xie/metaASM | 1eddc02846ee3fc05198883277357f9735dbaeb0 | c6a7b8fe3ecbca2bdc874e3b0dad6dd8f8c1c4cd | refs/heads/master | 2021-03-18T17:57:12.952618 | 2020-04-03T14:20:12 | 2020-04-03T14:20:12 | 247,087,294 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,664 | py | import torch
import numpy as np
import random
from datasets import CIFAR
from datasets.dataset_utils import get_cls_img_idxs_dict
from datasets.transforms import transform_train
from utils.asm_utils import detect_unlabel_imgs, get_select_fn
"""
sort each cls samples by criterion
"""
@torch.no_grad()
def sort_cls_samples(model, label_dataset, num_classes, criterion='lc'):
# 每类图片 idxs
cls_img_idxs = get_cls_img_idxs_dict(label_dataset.targets, num_classes)
y_pred_prob = detect_unlabel_imgs(model, label_dataset.data, num_classes, bs=100) # [N,10] prob vector
sort_cls_idxs_dict = {}
assert criterion in ['rs', 'lc', 'ms', 'en'], 'no such criterion'
select_fn = get_select_fn(criterion)
for cls_idx, img_idxs in cls_img_idxs.items():
img_idxs = np.array(img_idxs)
cls_probs = y_pred_prob[img_idxs] # [n,10]
# sorted idxs in list
_, sort_cls_idxs = select_fn(cls_probs, n_samples=len(cls_probs)) # sort total
# recover to total label idx
sort_cls_idxs_dict[cls_idx] = img_idxs[sort_cls_idxs]
return sort_cls_idxs_dict
def check_sample_targets(cls_idxs_dict, targets):
for cls, img_idxs in cls_idxs_dict.items():
print('class:', cls, [targets[i] for i in img_idxs])
"""
build meta dataset by different sampling methods
"""
def build_meta_dataset(label_dataset, idx_to_meta):
random.shuffle(idx_to_meta) # 原本 samples 按 cls 顺序排列
meta_dataset = CIFAR(
data=np.take(label_dataset.data, idx_to_meta, axis=0),
targets=np.take(label_dataset.targets, idx_to_meta, axis=0),
transform=transform_train
)
return meta_dataset
# random sample
def random_sample_meta_dataset(label_dataset, num_meta, num_classes):
img_idxs = list(range(len(label_dataset.targets)))
random.shuffle(img_idxs)
idx_to_meta = img_idxs[:int(num_meta * num_classes)]
return build_meta_dataset(label_dataset, idx_to_meta)
def random_sample_equal_cls(label_dataset, cls_img_idxs_dict, num_meta):
idx_to_meta = []
for cls, img_idxs in cls_img_idxs_dict.items():
idx_to_meta.extend(random.sample(img_idxs, num_meta))
return build_meta_dataset(label_dataset, idx_to_meta)
# random sample in a systematic way, loyal to original data distribution
# cover all hard-level samples
def random_system_sample_meta_dataset(label_dataset, sort_cls_idxs_dict, num_meta, mid=None): # 等距抽样
idx_to_meta = []
for cls, img_idxs in sort_cls_idxs_dict.items(): # 能处理各类 样本数量不同, list 不等长
step = len(img_idxs) // num_meta
mid = mid % step if mid else random.randint(0, step) # 指定每个系统内 要取的元素位置
idx_to_meta.extend([img_idxs[min(i * step + mid, len(img_idxs) - 1)]
for i in range(num_meta)]) # 等间隔
return build_meta_dataset(label_dataset, idx_to_meta)
# sample top hard samples on label_dataset
# 不带随机后,选出的样本固定了...
def sample_top_hard_meta_dataset(label_dataset, sort_cls_idxs_dict, num_meta):
idx_to_meta = []
for cls, img_idxs in sort_cls_idxs_dict.items(): # 各类按难度降序排列
idx_to_meta.extend(img_idxs[:num_meta])
return build_meta_dataset(label_dataset, idx_to_meta)
# sample top easy samples on label_dataset
def sample_top_easy_meta_dataset(label_dataset, sort_cls_idxs_dict, num_meta):
idx_to_meta = []
for cls, img_idxs in sort_cls_idxs_dict.items(): # 各类按难度降序排列
idx_to_meta.extend(img_idxs[-num_meta:])
return build_meta_dataset(label_dataset, idx_to_meta)
| [
"[email protected]"
] | |
f3ad2d30d023ac96ee324cece587c787ec28b6ad | 93652e0f73558ffa24059647324f79ba043ba241 | /topi/tests/python/test_topi_clip.py | 041565433bccd162ef55c48cb1e6cd6f106a8200 | [
"Apache-2.0"
] | permissive | souptc/tvm | 830b1444435b6bda267df305538a783eb687d473 | a8574e7bb814997cb3920a72035071899635b753 | refs/heads/master | 2020-03-25T12:42:20.686770 | 2018-08-06T21:07:38 | 2018-08-06T21:07:38 | 143,789,191 | 1 | 0 | Apache-2.0 | 2018-08-06T22:18:20 | 2018-08-06T22:18:19 | null | UTF-8 | Python | false | false | 1,458 | py | """Test code for clip operator"""
import numpy as np
import tvm
import topi
from topi.util import get_const_tuple
from tvm.contrib.pickle_memoize import memoize
def verify_clip(N, a_min, a_max, dtype):
A = tvm.placeholder((N, N), dtype=dtype, name='A')
B = topi.clip(A, a_min, a_max)
s = tvm.create_schedule([B.op])
# use memoize to pickle the test data for next time use
@memoize("topi.tests.test_topi_clip")
def get_ref_data():
a_np = np.random.uniform(a_min*2, a_max*2, size=(N, N)).astype(dtype)
b_np = np.clip(a_np, a_min, a_max)
return a_np, b_np
a_np, b_np = get_ref_data()
def check_device(device):
ctx = tvm.context(device, 0)
if not ctx.exist:
print("Skip because %s is not enabled" % device)
return
print("Running on target: %s" % device)
with tvm.target.create(device):
s = topi.generic.schedule_injective(B)
a = tvm.nd.array(a_np, ctx)
b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=dtype), ctx)
f = tvm.build(s, [A, B], device, name="clip")
f(a, b)
np.testing.assert_allclose(b.asnumpy(), b_np, rtol=1e-5)
for device in ['llvm', 'opencl']:
check_device(device)
def test_clip():
verify_clip(1024, -127, 127, 'float32')
verify_clip(1024, -127, 127, 'int16')
verify_clip(1024, -127, 127, 'int8')
if __name__ == "__main__":
test_clip()
| [
"[email protected]"
] | |
0eacc151f4687b9c510af5c578b7c2cc7da03f1f | f9626bbbffad4e4157fc279358e0edd1f997f1d8 | /irl/maxent.py | 945969f604bee43554f1c2fb036aeeac012e3c91 | [] | no_license | markalence/MaxEntIRL | 5b58a0272d06cd595c0ad5229be2164168067018 | 00e45c59de70ef9171496152e2cc1d13be5959f5 | refs/heads/master | 2023-01-10T20:32:42.767135 | 2020-11-17T22:07:09 | 2020-11-17T22:07:09 | 308,770,725 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,470 | py | """
Implements maximum entropy inverse reinforcement learning (Ziebart et al., 2008)
Matthew Alger, 2015
[email protected]
"""
from itertools import product
import numpy as np
import numpy.random as rn
from . import value_iteration
import json
def irl(feature_matrix, n_actions, discount, transition_probability,
trajectories, epochs, learning_rate):
"""
Find the reward function for the given trajectories.
feature_matrix: Matrix with the nth row representing the nth state. NumPy
array with shape (N, D) where N is the number of states and D is the
dimensionality of the state.
n_actions: Number of actions A. int.
discount: Discount factor of the MDP. float.
transition_probability: NumPy array mapping (state_i, action, state_k) to
the probability of transitioning from state_i to state_k under action.
Shape (N, A, N).
trajectories: 3D array of state/action pairs. States are ints, actions
are ints. NumPy array with shape (T, L, 2) where T is the number of
trajectories and L is the trajectory length.
epochs: Number of gradient descent steps. int.
learning_rate: Gradient descent learning rate. float.
-> Reward vector with shape (N,).
"""
n_states, d_states = feature_matrix.shape
# Initialise weights.
alpha = rn.uniform(size=(d_states,))
# Calculate the feature expectations \tilde{phi}.
feature_expectations = find_feature_expectations(feature_matrix,
trajectories)
# Gradient descent on alpha.
for i in range(epochs):
print(f'EPOCH {i}')
r = feature_matrix.dot(alpha)
expected_svf = find_expected_svf(n_states, r, n_actions, discount,
transition_probability, trajectories)
grad = feature_expectations - feature_matrix.T.dot(expected_svf)
alpha += learning_rate * grad
return feature_matrix.dot(alpha).reshape((n_states,))
def find_svf(n_states, trajectories):
"""
Find the state visitation frequency from trajectories.
n_states: Number of states. int.
trajectories: 3D array of state/action pairs. States are ints, actions
are ints. NumPy array with shape (T, L, 2) where T is the number of
trajectories and L is the trajectory length.
-> State visitation frequencies vector with shape (N,).
"""
svf = np.zeros(n_states)
for trajectory in trajectories:
for state, _, _ in trajectory:
svf[state] += 1
svf /= trajectories.shape[0]
return svf
def find_feature_expectations(feature_matrix, trajectories):
"""
Find the feature expectations for the given trajectories. This is the
average path feature vector.
feature_matrix: Matrix with the nth row representing the nth state. NumPy
array with shape (N, D) where N is the number of states and D is the
dimensionality of the state.
trajectories: 3D array of state/action pairs. States are ints, actions
are ints. NumPy array with shape (T, L, 2) where T is the number of
trajectories and L is the trajectory length.
-> Feature expectations vector with shape (D,).
"""
feature_expectations = np.zeros(feature_matrix.shape[1])
for trajectory in trajectories:
for state, _, _ in trajectory:
feature_expectations += feature_matrix[state]
feature_expectations /= trajectories.shape[0]
return feature_expectations
def find_expected_svf(n_states, r, n_actions, discount,
transition_probability, trajectories):
"""
Find the expected state visitation frequencies using algorithm 1 from
Ziebart et al. 2008.
n_states: Number of states N. int.
alpha: Reward. NumPy array with shape (N,).
n_actions: Number of actions A. int.
discount: Discount factor of the MDP. float.
transition_probability: NumPy array mapping (state_i, action, state_k) to
the probability of transitioning from state_i to state_k under action.
Shape (N, A, N).
trajectories: 3D array of state/action pairs. States are ints, actions
are ints. NumPy array with shape (T, L, 2) where T is the number of
trajectories and L is the trajectory length.
-> Expected state visitation frequencies vector with shape (N,).
"""
n_trajectories = trajectories.shape[0]
trajectory_length = trajectories.shape[1]
# policy = find_policy(n_states, r, n_actions, discount,
# transition_probability)
policy = value_iteration.find_policy(n_states, n_actions,
transition_probability, r, discount)
with open('policies.txt', 'w') as policies:
policies.write(json.dumps(policy, default=lambda x: list(x), indent=4))
with open('rewards.txt', 'w') as rewards:
rewards.write(json.dumps(r, default=lambda x: list(x), indent=4))
start_state_count = np.zeros(n_states)
for trajectory in trajectories:
start_state_count[trajectory[0, 0]] += 1
p_start_state = start_state_count / n_trajectories
expected_svf = np.tile(p_start_state, (trajectory_length, 1)).T
for t in range(1, trajectory_length):
print(t)
expected_svf[:, t] = 0
for i, j, k in product(range(n_states), range(n_actions), range(n_states)):
expected_svf[k, t] += (expected_svf[i, t - 1] *
policy[i, j] * # Stochastic policy
transition_probability[i, j, k])
return expected_svf.sum(axis=1)
def softmax(x1, x2):
"""
Soft-maximum calculation, from algorithm 9.2 in Ziebart's PhD thesis.
x1: float.
x2: float.
-> softmax(x1, x2)
"""
max_x = max(x1, x2)
min_x = min(x1, x2)
return max_x + np.log(1 + np.exp(min_x - max_x))
def find_policy(n_states, r, n_actions, discount,
transition_probability):
"""
Find a policy with linear value iteration. Based on the code accompanying
the Levine et al. GPIRL paper and on Ziebart's PhD thesis (algorithm 9.1).
n_states: Number of states N. int.
r: Reward. NumPy array with shape (N,).
n_actions: Number of actions A. int.
discount: Discount factor of the MDP. float.
transition_probability: NumPy array mapping (state_i, action, state_k) to
the probability of transitioning from state_i to state_k under action.
Shape (N, A, N).
-> NumPy array of states and the probability of taking each action in that
state, with shape (N, A).
"""
# V = value_iteration.value(n_states, transition_probability, r, discount)
# NumPy's dot really dislikes using inf, so I'm making everything finite
# using nan_to_num.
V = np.nan_to_num(np.ones((n_states, 1)) * float("-inf"))
diff = np.ones((n_states,))
while (diff > 1e-4).all(): # Iterate until convergence.
new_V = r.copy()
for j in range(n_actions):
for i in range(n_states):
new_V[i] = softmax(new_V[i], r[i] + discount *
np.sum(transition_probability[i, j, k] * V[k]
for k in range(n_states)))
# # This seems to diverge, so we z-score it (engineering hack).
new_V = (new_V - new_V.mean()) / new_V.std()
diff = abs(V - new_V)
V = new_V
# We really want Q, not V, so grab that using equation 9.2 from the thesis.
Q = np.zeros((n_states, n_actions))
for i in range(n_states):
for j in range(n_actions):
p = np.array([transition_probability[i, j, k]
for k in range(n_states)])
Q[i, j] = p.dot(r + discount * V)
# Softmax by row to interpret these values as probabilities.
Q -= Q.max(axis=1).reshape((n_states, 1)) # For numerical stability.
Q = np.exp(Q) / np.exp(Q).sum(axis=1).reshape((n_states, 1))
return Q
def expected_value_difference(n_states, n_actions, transition_probability,
reward, discount, p_start_state, optimal_value, true_reward):
"""
Calculate the expected value difference, which is a proxy to how good a
recovered reward function is.
n_states: Number of states. int.
n_actions: Number of actions. int.
transition_probability: NumPy array mapping (state_i, action, state_k) to
the probability of transitioning from state_i to state_k under action.
Shape (N, A, N).
reward: Reward vector mapping state int to reward. Shape (N,).
discount: Discount factor. float.
p_start_state: Probability vector with the ith component as the probability
that the ith state is the start state. Shape (N,).
optimal_value: Value vector for the ground reward with optimal policy.
The ith component is the value of the ith state. Shape (N,).
true_reward: True reward vector. Shape (N,).
-> Expected value difference. float.
"""
policy = value_iteration.find_policy(n_states, n_actions,
transition_probability, reward, discount)
value = value_iteration.value(policy.argmax(axis=1), n_states,
transition_probability, true_reward, discount)
evd = optimal_value.dot(p_start_state) - value.dot(p_start_state)
return evd
| [
"[email protected]"
] | |
eda754ab5842624ac525d528542a4e12b3812987 | 82dddaf5cde354bc6d96fdf0ef2516abf2960cb4 | /zom/bonbon/migrations/0003_remove_res_link.py | caaf4f16351c0795ac0d78ece628613590113a9f | [
"MIT"
] | permissive | Neha-Prabhu/Zomato-clone | 9f623d215c6e89528d129507f8cd27067c93d128 | 4d57f784c6de91780a171fe4e2853ccb20c8e8ca | refs/heads/master | 2022-07-17T01:01:01.372469 | 2020-05-13T19:45:23 | 2020-05-13T19:45:23 | 263,724,693 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 322 | py | # Generated by Django 2.2.4 on 2019-10-12 18:57
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bonbon', '0002_auto_20191012_2320'),
]
operations = [
migrations.RemoveField(
model_name='res',
name='link',
),
]
| [
"[email protected]"
] | |
8ad0f2dc3caaa8c82153abee8dbfd4ae141503a1 | 9321d3460ffbbb6cd7917b2bac77ce8321e04737 | /contributions/Legacy/JPlus/Old/EDMFunctions with infiltration not working.py | 0e4abdb725c1f2e288370fefe3c7374edd491e9d | [
"MIT"
] | permissive | muehleisen/CEAforArcGIS | b820d837cd5373b95851b4e5dda609d69f054b97 | b6aeca5a9d70835381625a9162d5695714e1a02b | refs/heads/master | 2021-01-11T21:24:18.482264 | 2017-01-06T05:28:48 | 2017-01-06T05:28:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 73,097 | py | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# ####MODULES
# <codecell>
from __future__ import division
import arcpy
from arcpy import sa
import sys,os
import pandas as pd
import datetime
import jdcal
import numpy as np
import math
import sympy as sp
import scipy
import scipy.optimize
sys.path.append("C:\console\sandbox")
from pyGDsandbox.dataIO import df2dbf, dbf2df
arcpy.env.overwriteOutput = True
arcpy.CheckOutExtension("spatial")
arcpy.CheckOutExtension("3D")
# <markdowncell>
# ##RADIATION MODEL
# <markdowncell>
# ###1. Calculation of hourly radiation in a day
# <codecell>
def CalcRadiation(day, CQ_name, DEMfinal, Observers, T_G_day, latitude, locationtemp1):
# Local Variables
Latitude = str(latitude)
skySize = '3000'
dayInterval = '1'
hourInterval = '1'
calcDirections = '32'
zenithDivisions = '1500'
azimuthDivisions = '160'
diffuseProp = str(T_G_day.loc[day-1,'diff'])
transmittivity = str(T_G_day.loc[day-1,'ttr'])
heightoffset = '5'
global_radiation = locationtemp1+'\\'+CQ_name+'\\'+'radiation'+'\\'+'Day_'+str(day)+'.shp'
timeConfig = 'WithinDay '+str(day)+', 0, 24'
#Run the extension of arcgis
arcpy.gp.PointsSolarRadiation_sa(DEMfinal, Observers, global_radiation, heightoffset,
Latitude, skySize, timeConfig, dayInterval, hourInterval, "INTERVAL", "1", "FROM_DEM",
calcDirections, zenithDivisions, azimuthDivisions, "STANDARD_OVERCAST_SKY",
diffuseProp, transmittivity, "#", "#", "#")
return arcpy.GetMessages()
# <markdowncell>
# 1.1 Sub-function to calculate radiation non-sunshinehours
# <codecell>
def calc_radiationday(day, CQ_name, T_G_day, locationtemp1):
radiation_sunnyhours = dbf2df(locationtemp1+'\\'+CQ_name+'\\'+'radiation'+'\\'+'Day_'+str(day)+'.dbf')
#Obtain the number of points modeled to do the iterations
radiation_sunnyhours['ID'] = 0
counter = radiation_sunnyhours.ID.count()
value = counter+1
radiation_sunnyhours['ID'] = range(1, value)
# Table with empty values with the same range as the points.
Table = pd.DataFrame.copy(radiation_sunnyhours)
Names = ['T0','T1','T2','T3','T4','T5','T6','T7','T8','T9','T10','T11','T12','T13','T14','T15','T16','T17','T18','T19','T20','T21','T22','T23']
for Name in Names:
Table[Name]= 0
#Counter of Columns in the Initial Table
Counter = radiation_sunnyhours.count(1)
Value = Counter[0]-1
#Condition to take into account daysavingtime in Switzerland as the radiation data in ArcGIS is calculated for 2013.
if 90 <= day <300:
D = 1
else:
D = 0
# Calculation of Sunrise time
Sunrise_time = T_G_day.loc[day-1,'sunrise']
# Calculation of table
for time in range(Value):
Hour = int(Sunrise_time)+ int(time)
Table['T'+str(Hour)] = radiation_sunnyhours['T'+str(time)]
#rename the table for every T to get in 1 to 8760 hours.
if day == 1:
name = 1
else:
name = int(day-1)*24+1
Table.rename(columns={'T0':'T'+str(name),'T1':'T'+str(name+1),'T2':'T'+str(name+2),'T3':'T'+str(name+3),'T4':'T'+str(name+4),
'T5':'T'+str(name+5),'T6':'T'+str(name+6),'T7':'T'+str(name+7),'T8':'T'+str(name+8),'T9':'T'+str(name+9),
'T10':'T'+str(name+10),'T11':'T'+str(name+11),'T12':'T'+str(name+12),'T13':'T'+str(name+13),'T14':'T'+str(name+14),
'T15':'T'+str(name+15),'T16':'T'+str(name+16),'T17':'T'+str(name+17),'T18':'T'+str(name+18),'T19':'T'+str(name+19),
'T20':'T'+str(name+20),'T21':'T'+str(name+21),'T22':'T'+str(name+22),'T23':'T'+str(name+23),'ID':'ID'},inplace=True)
return Table.copy()
# <markdowncell>
# ###2. Burn buildings into DEM
# <codecell>
def Burn(Buildings,DEM,DEMfinal,locationtemp1, locationtemp2, database, DEM_extent = '676682, 218586, 684612, 229286'):
#Create a raster with all the buildings
Outraster = locationtemp1+'\\'+'AllRaster'
arcpy.env.extent = DEM_extent #These coordinates are extracted from the environment settings/once the DEM raster is selected directly in ArcGIS,
arcpy.FeatureToRaster_conversion(Buildings,'height',Outraster,'0.5') #creating raster of the footprints of the buildings
#Clear non values and add all the Buildings to the DEM
OutNullRas = sa.IsNull(Outraster) # identify noData Locations
Output = sa.Con(OutNullRas == 1,0,Outraster)
RadiationDEM = sa.Raster(DEM) + Output
RadiationDEM.save(DEMfinal)
return arcpy.GetMessages()
# <markdowncell>
# ###3. Calculate Boundaries - Factor Height and Factor Shade
# <codecell>
def CalcBoundaries (Simple_CQ,locationtemp1, locationtemp2, DataFactorsCentroids, DataFactorsBoundaries):
#local variables
NearTable = locationtemp1+'\\'+'NearTable.dbf'
CQLines = locationtemp2+'\\'+'\CQLines'
CQVertices = locationtemp2+'\\'+'CQVertices'
CQSegments = locationtemp2+'\\'+'CQSegment'
CQSegments_centroid = locationtemp2+'\\'+'CQSegmentCentro'
centroidsTable_name = 'CentroidCQdata.dbf'
centroidsTable = locationtemp1+'\\'+centroidsTable_name
Overlaptable = locationtemp1+'\\'+'overlapingTable.csv'
#Create points in the centroid of segment line and table with near features:
# indentifying for each segment of line of building A the segment of line of building B in common.
arcpy.FeatureToLine_management(Simple_CQ,CQLines)
arcpy.FeatureVerticesToPoints_management(Simple_CQ,CQVertices,'ALL')
arcpy.SplitLineAtPoint_management(CQLines,CQVertices,CQSegments,'2 METERS')
arcpy.FeatureVerticesToPoints_management(CQSegments,CQSegments_centroid,'MID')
arcpy.GenerateNearTable_analysis(CQSegments_centroid,CQSegments_centroid,NearTable,"1 Meters","NO_LOCATION","NO_ANGLE","CLOSEST","0")
#Import the table with NearMatches
NearMatches = dbf2df(NearTable)
# Import the table with attributes of the centroids of the Segments
arcpy.TableToTable_conversion(CQSegments_centroid, locationtemp1, centroidsTable_name)
DataCentroids = dbf2df(centroidsTable, cols={'Name','height','ORIG_FID'})
# CreateJoin to Assign a Factor to every Centroid of the lines,
FirstJoin = pd.merge(NearMatches,DataCentroids,left_on='IN_FID', right_on='ORIG_FID')
SecondaryJoin = pd.merge(FirstJoin,DataCentroids,left_on='NEAR_FID', right_on='ORIG_FID')
# delete matches within the same polygon Name (it can happen that lines are too close one to the other)
# also delete matches with a distance of more than 20 cm making room for mistakes during the simplicfication of buildings but avoiding deleten boundaries
rows = SecondaryJoin.IN_FID.count()
for row in range(rows):
if SecondaryJoin.loc[row,'Name_x'] == SecondaryJoin.loc[row,'Name_y'] or SecondaryJoin.loc[row,'NEAR_DIST'] > 0.2:
SecondaryJoin = SecondaryJoin.drop(row)
SecondaryJoin.reset_index(inplace=True)
#FactorShade = 0 if the line exist in a building totally covered by another one, and Freeheight is equal to the height of the line
# that is not obstructed by the other building
rows = SecondaryJoin.IN_FID.count()
SecondaryJoin['FactorShade']=0
SecondaryJoin['Freeheight']=0
for row in range(rows):
if SecondaryJoin.loc[row,'height_x'] <= SecondaryJoin.loc[row,'height_y']:
SecondaryJoin.loc[row,'FactorShade'] = 0
SecondaryJoin.loc[row,'Freeheight'] = 0
elif SecondaryJoin.loc[row,'height_x'] > SecondaryJoin.loc[row,'height_y'] and SecondaryJoin.loc[row,'height_x']-1 <= SecondaryJoin.loc[row,'height_y']:
SecondaryJoin.loc[row,'FactorShade'] = 0
else:
SecondaryJoin.loc[row,'FactorShade'] = 1
SecondaryJoin.loc[row,'Freeheight'] = abs(SecondaryJoin.loc[row,'height_y']- SecondaryJoin.loc[row,'height_x'])
#Create and export Secondary Join with results, it will be Useful for the function CalcObservers
SecondaryJoin.to_csv(DataFactorsBoundaries,index=False)
#Update table Datacentroids with the Fields Freeheight and Factor Shade. for those buildings without
#shading boundaries these factors are equal to 1 and the field 'height' respectively.
DataCentroids['FactorShade'] = 1
DataCentroids['Freeheight'] = DataCentroids['height']
Results = DataCentroids.merge(SecondaryJoin, left_on='ORIG_FID', right_on='ORIG_FID_x', how='outer')
Results.FactorShade_y.fillna(Results['FactorShade_x'],inplace=True)
Results.Freeheight_y.fillna(Results['Freeheight_x'],inplace=True)
Results.rename(columns={'FactorShade_y':'FactorShade','Freeheight_y':'Freeheight'},inplace=True)
FinalDataCentroids = pd.DataFrame(Results,columns={'ORIG_FID','height','FactorShade','Freeheight'})
FinalDataCentroids.to_csv(DataFactorsCentroids,index=False)
return arcpy.GetMessages()
# <markdowncell>
# ###4. Calculate observation points
# <codecell>
def CalcObservers(Simple_CQ,Observers, DataFactorsBoundaries, locationtemporal2):
#local variables
Buffer_CQ = locationtemporal2+'\\'+'BufferCQ'
temporal_lines = locationtemporal2+'\\'+'lines'
Points = locationtemporal2+'\\'+'Points'
AggregatedBuffer = locationtemporal2+'\\'+'BufferAggregated'
temporal_lines3 = locationtemporal2+'\\'+'lines3'
Points3 = locationtemporal2+'\\'+'Points3'
Points3Updated = locationtemporal2+'\\'+'Points3Updated'
EraseObservers = locationtemporal2+'\\'+'eraseobservers'
Observers0 = locationtemporal2+'\\'+'observers0'
NonoverlappingBuildings = locationtemporal2+'\\'+'Non_overlap'
templines = locationtemporal2+'\\'+'templines'
templines2 = locationtemporal2+'\\'+'templines2'
Buffer_CQ0 = locationtemporal2+'\\'+'Buffer_CQ0'
Buffer_CQ = locationtemporal2+'\\'+'Buffer_CQ'
Buffer_CQ1 = locationtemporal2+'\\'+'Buffer_CQ1'
Simple_CQcopy = locationtemporal2+'\\'+'Simple_CQcopy'
#First increase the boundaries in 2m of each surface in the community to
#analyze- this will avoid that the observers overlap the buildings and Simplify
#the community vertices to only create 1 point per surface
arcpy.CopyFeatures_management(Simple_CQ,Simple_CQcopy)
#Make Square-like buffers
arcpy.PolygonToLine_management(Simple_CQcopy,templines,"IGNORE_NEIGHBORS")
arcpy.SplitLine_management(templines,templines2)
arcpy.Buffer_analysis(templines2,Buffer_CQ0,"0.75 Meters","FULL","FLAT","NONE","#")
arcpy.Append_management(Simple_CQcopy,Buffer_CQ0,"NO_TEST")
arcpy.Dissolve_management(Buffer_CQ0,Buffer_CQ1,"Name","#","SINGLE_PART","DISSOLVE_LINES")
arcpy.SimplifyBuilding_cartography(Buffer_CQ1,Buffer_CQ,simplification_tolerance=8, minimum_area=None)
#arcpy.Buffer_analysis(Simple_CQ,Buffer_CQ,buffer_distance_or_field=1, line_end_type='FLAT') # buffer with a flat finishing
#arcpy.Generalize_edit(Buffer_CQ,"2 METERS")
#Transform all polygons of the simplified areas to observation points
arcpy.SplitLine_management(Buffer_CQ,temporal_lines)
arcpy.FeatureVerticesToPoints_management(temporal_lines,Points,'MID') # Second the transformation of Lines to a mid point
#Join all the polygons to get extra vertices, make lines and then get points.
#these points should be added to the original observation points
arcpy.AggregatePolygons_cartography(Buffer_CQ,AggregatedBuffer,"0.5 Meters","0 SquareMeters","0 SquareMeters","ORTHOGONAL") # agregate polygons
arcpy.SplitLine_management(AggregatedBuffer,temporal_lines3) #make lines
arcpy.FeatureVerticesToPoints_management(temporal_lines3,Points3,'MID')# create extra points
# add information to Points3 about their buildings
arcpy.SpatialJoin_analysis(Points3,Buffer_CQ,Points3Updated,"JOIN_ONE_TO_ONE","KEEP_ALL",match_option="CLOSEST",search_radius="5 METERS")
arcpy.Erase_analysis(Points3Updated,Points,EraseObservers,"2 Meters")# erase overlaping points
arcpy.Merge_management([Points,EraseObservers],Observers0)# erase overlaping points
# Eliminate Observation points above roofs of the highest surfaces(a trick to make the
#Import Overlaptable from function CalcBoundaries containing the data about buildings overlaping, eliminate duplicades, chose only those ones no overlaped and reindex
DataNear = pd.read_csv(DataFactorsBoundaries)
CleanDataNear = DataNear[DataNear['FactorShade'] == 1]
CleanDataNear.drop_duplicates(cols='Name_x',inplace=True)
CleanDataNear.reset_index(inplace=True)
rows = CleanDataNear.Name_x.count()
for row in range(rows):
Field = "Name" # select field where the name exists to iterate
Value = CleanDataNear.loc[row,'Name_x'] # set the value or name of the City quarter
Where_clausule = ''''''+'"'+Field+'"'+"="+"\'"+str(Value)+"\'"+'''''' # strange writing to introduce in ArcGIS
if row == 0:
arcpy.MakeFeatureLayer_management(Simple_CQ, 'Simple_lyr')
arcpy.SelectLayerByAttribute_management('Simple_lyr',"NEW_SELECTION",Where_clausule)
else:
arcpy.SelectLayerByAttribute_management('Simple_lyr',"ADD_TO_SELECTION",Where_clausule)
arcpy.CopyFeatures_management('simple_lyr', NonoverlappingBuildings)
arcpy.ErasePoint_edit(Observers0,NonoverlappingBuildings,"INSIDE")
arcpy.CopyFeatures_management(Observers0,Observers)#copy features to reset the OBJECTID
return arcpy.GetMessages()
# <markdowncell>
# ###5. Radiation results to surfaces
# <codecell>
def CalcRadiationSurfaces(Observers, Radiationyearfinal, DataFactorsCentroids, DataradiationLocation, locationtemp1, locationtemp2):
# local variables
CQSegments_centroid = locationtemp2+'\\'+'CQSegmentCentro'
Outjoin = locationtemp2+'\\'+'Join'
CQSegments = locationtemp2+'\\'+'CQSegment'
OutTable = 'CentroidsIDobserv.dbf'
# Create Join of features Observers and CQ_sementscentroids to
# assign Names and IDS of observers (field TARGET_FID) to the centroids of the lines of the buildings,
# then create a table to import as a Dataframe
arcpy.SpatialJoin_analysis(CQSegments_centroid,Observers,Outjoin,"JOIN_ONE_TO_ONE","KEEP_ALL",match_option="CLOSEST",search_radius="10 METERS")
arcpy.JoinField_management(Outjoin,'OBJECTID',CQSegments, 'OBJECTID') # add the lenghts of the Lines to the File
arcpy.TableToTable_conversion(Outjoin, locationtemp1, OutTable)
Centroids_ID_observers = dbf2df(locationtemp1+'\\'+OutTable, cols={'Name_12','height','ORIG_FID','Shape_Leng'})
Centroids_ID_observers.rename(columns={'Name_12':'Name'},inplace=True)
#Create a Join of the Centroid_ID_observers and Datacentroids in the Second Chapter to get values of surfaces Shaded.
Datacentroids = pd.read_csv(DataFactorsCentroids)
DataCentroidsFull = pd.merge(Centroids_ID_observers,Datacentroids,left_index=True,right_index=True)
#Read again the radiation table and merge values with the Centroid_ID_observers under the field ID in Radiationtable and 'ORIG_ID' in Centroids...
Radiationtable = pd.read_csv(DataradiationLocation,index_col='Unnamed: 0')
DataRadiation = pd.merge(DataCentroidsFull,Radiationtable, left_on='ORIG_FID_x',right_on='ID')
DataRadiation.to_csv(Radiationyearfinal,index=False)
return arcpy.GetMessages()
# <markdowncell>
# ##DETERMINISTIC ENERGY MODEL
# <markdowncell>
# ###1. Thermal properties and geometry of buildings
# <codecell>
def CalcProperties(CQ, CQproperties, RadiationFile,locationtemp1):
#Local Variables
OutTable = 'CQshape3.dbf'
# Set of estimated constants
Z = 3 # height of basement for every building in m
Bf = 0.7 # It calculates the coefficient of reduction in transmittance for surfaces in contact with the ground according to values of SIA 380/1
# Set of constants according to EN 13790
his = 3.45 #heat transfer coefficient between air and the surfacein W/(m2K)
hms = 9.1 # Heat transfer coeddicient between nodes m and s in W/m2K
# Set of estimated constants
#Import RadiationFile and Properties of the shapefiles
rf = pd.read_csv(RadiationFile)
arcpy.TableToTable_conversion(CQ, locationtemp1, OutTable)
CQShape_properties = dbf2df(locationtemp1+'\\'+OutTable)
#Areas above ground #get the area of each wall in the buildings
rf['Awall'] = rf['Shape_Leng']*rf['Freeheight']*rf['FactorShade']
Awalls0 = pd.pivot_table(rf,rows='Name',values='Awall',aggfunc=np.sum); Awalls = pd.DataFrame(Awalls0) #get the area of walls in the whole buildings
Areas = pd.merge(Awalls,CQproperties, left_index=True,right_on='Name')
Areas['Aw'] = Areas['Awall']*Areas['fwindow']*Areas['PFloor'] # Finally get the Area of windows
Areas['Aop_sup'] = Areas['Awall']*Areas['PFloor'] #....and Opaque areas PFloor represents a factor according to the amount of floors heated
#Areas bellow ground
AllProperties = pd.merge(Areas,CQShape_properties,on='Name')# Join both properties files (Shape and areas)
AllProperties['Aop_bel'] = Z*AllProperties['Shape_Leng']+AllProperties['Shape_Area'] # Opague areas in m2 below ground including floor
AllProperties['Atot'] = AllProperties['Aop_sup']+AllProperties['Aop_bel']+AllProperties['Shape_Area'] # Total area of the building envelope m2, it is considered the roof to be flat
AllProperties['Af'] = AllProperties['Shape_Area']*AllProperties['Floors_y']*AllProperties['Hs_y']# conditioned area
AllProperties['Aef'] = AllProperties['Shape_Area']*AllProperties['Floors_y']*AllProperties['Es']# conditioned area only those for electricity
AllProperties['Am'] = AllProperties.Construction.apply(lambda x:AmFunction(x))*AllProperties['Af'] # Effective mass area in m2
#Steady-state Thermal transmittance coefficients and Internal heat Capacity
AllProperties ['Htr_w'] = AllProperties['Aw']*AllProperties['Uwindow'] # Thermal transmission coefficient for windows and glazing. in W/K
AllProperties ['HD'] = AllProperties['Aop_sup']*AllProperties['Uwall']+AllProperties['Shape_Area']*AllProperties['Uroof'] # Direct Thermal transmission coefficient to the external environment in W/K
AllProperties ['Hg'] = Bf*AllProperties ['Aop_bel']*AllProperties['Ubasement'] # stady-state Thermal transmission coeffcient to the ground. in W/K
AllProperties ['Htr_op'] = AllProperties ['Hg']+ AllProperties ['HD']
AllProperties ['Htr_ms'] = hms*AllProperties ['Am'] # Coupling conduntance 1 in W/K
AllProperties ['Htr_em'] = 1/(1/AllProperties['Htr_op']-1/ AllProperties['Htr_ms']) # Coupling conduntance 2 in W/K
AllProperties ['Htr_is'] = his*AllProperties ['Atot']
AllProperties['Cm'] = AllProperties.Construction.apply(lambda x:CmFunction(x))*AllProperties['Af'] # Internal heat capacity in J/K
# Year Category of building
AllProperties['YearCat'] = AllProperties.apply(lambda x: YearCategoryFunction(x['Year_y'], x['Renovated']), axis=1)
AllProperties.rename(columns={'Hs_y':'Hs','Floors_y':'Floors','PFloor_y':'PFloor','Year_y':'Year','fwindow_y':'fwindow'},inplace=True)
return AllProperties
# <codecell>
def CalcIncidentRadiation(AllProperties, Radiationyearfinal):
#Import Radiation table and compute the Irradiation in W in every building's surface
Radiation_Shading2 = pd.read_csv(Radiationyearfinal)
Columns = 8761
Radiation_Shading2['AreaExposed'] = Radiation_Shading2['Shape_Leng']*Radiation_Shading2['FactorShade']*Radiation_Shading2['Freeheight']
for Column in range(1, Columns):
#transform all the points of solar radiation into Wh
Radiation_Shading2['T'+str(Column)] = Radiation_Shading2['T'+str(Column)]*Radiation_Shading2['AreaExposed']
#Do pivot table to sum up the irradiation in every surface to the building
#and merge the result with the table allProperties
PivotTable3 = pd.pivot_table(Radiation_Shading2,rows='Name',margins='Add all row')
RadiationLoad = pd.DataFrame(PivotTable3)
Solar = AllProperties.merge(RadiationLoad, left_on='Name',right_index=True)
return Solar # total solar radiation in areas exposed to radiation in Watts
# <markdowncell>
# 1.1 Sub-functions of Thermal mass
# <codecell>
def CmFunction (x):
if x == 'Medium':
return 165000
elif x == 'Heavy':
return 300000
elif x == 'Light':
return 110000
else:
return 165000
# <codecell>
def AmFunction (x):
if x == 'Medium':
return 2.5
elif x == 'Heavy':
return 3.2
elif x == 'Light':
return 2.5
else:
return 2.5
# <markdowncell>
# 1.2. Sub- Function Hourly thermal transmission coefficients
# <codecell>
def calc_Htr(Hve, Htr_is, Htr_ms, Htr_w):
Htr_1 = 1/(1/Hve+1/Htr_is)
Htr_2 = Htr_1+Htr_w
Htr_3 = 1/(1/Htr_2+1/Htr_ms)
Coefficients = [Htr_1,Htr_2,Htr_3]
return Coefficients
# <markdowncell>
# ###2. Calculation of thermal and Electrical loads - No processes
# <codecell>
def CalcThermalLoads(i, AllProperties, locationFinal, Solar, Profiles,Profiles_names, Temp, Seasonhours, Servers,Coolingroom):
# Mode is a variable 0 without losses, 1 With losses of distribution enmission and control
#Local Variables
Name = AllProperties.loc[i,'Name']
# Set of constants according to EN 13790
g_gl = 0.9*0.75 # solar energy transmittance assuming a reduction factor of 0.9 and most of the windows to be double glazing (0.75)
pa_ca = 1200 # Air constant J/m3K
F_f = 0.3 # Frame area faction coefficient
Bf = 0.7 # It calculates the coefficient of reduction in transmittance for surfaces in contact with the ground according to values of SIA 380/1
tw = 10 # the temperature of intake of water for hot water
# Set of variables used offently
nf = AllProperties.loc[i,'Floors']
nfpercent = AllProperties.loc[i,'PFloor']
height = AllProperties.loc[i,'height']
Lw = AllProperties.loc[i,'MBG_Width']
Ll = AllProperties.loc[i,'MBG_Length']
Awall = AllProperties.loc[i,'Awall']
footprint = AllProperties.loc[i,'Shape_Area']
Year = AllProperties.loc[i,'Year']
Yearcat = AllProperties.loc[i,'YearCat']
Af = AllProperties.loc[i,'Af']
Aef = AllProperties.loc[i,'Aef']
SystemH = AllProperties.loc[i,'Emission_heating']
SystemC = AllProperties.loc[i,'Emission_cooling']
tsh0 = AllProperties.loc[i,'tsh0']
trh0 = AllProperties.loc[i,'trh0']
tsc0 = AllProperties.loc[i,'tsc0']
trc0 = AllProperties.loc[i,'trc0']
te_min = Temp.te.min()
te_max = Temp.te.max()
# Determination of Profile of occupancy to use
Occupancy0 = calc_Type(Profiles,Profiles_names, AllProperties, i, Servers,Coolingroom)
#Create Labels in data frame to iterate
Columns = ['IH_nd_ac','IC_nd_ac','g_gl','Htr_1','Htr_2','Htr_3','tm_t','tair_ac','top_ac','IHC_nd_ac', 'Asol', 'I_sol','te',
'Eal','Qhsf','Qcsf','Qhs','Qcs','Qwwf','Qww','tair','top','tsc','trc','tsh','trh','Qhs_em_ls','Qcs_em_ls',
'Qhs_d_ls','Qcs_d_ls','Qww_dh_ls','Qww_d_ls','tamb','Qcs_dis_em_ls','Qhs_dis_em_ls',
'Eaux_hs', 'Eaux_cs', 'Eaux_ww']
for Label in Columns:
Occupancy0 [Label] = 0
if Af >0:
#Assign temperature data to the table
Occupancy0['te'] = Temp['te']
# Determination of Hourly Thermal transmission coefficient due to Ventilation in W/K
# without infiltration - this value is calculated later on
Occupancy0['Hve'] = pa_ca*(Occupancy0['Ve']* Af/3600)
#Calculation of hot water use At 60 degrees and 45 degress for new buildings
if AllProperties.loc[i,'Year'] >= 2020:
twws = 45
else:
twws = 60
Occupancy0['Qww'] = Occupancy0['Mww']*Af*4.184*(twws-tw)*0.277777777777778 # in wattshour.
#Calculation of lossess distribution system for domestic hot water
Occupancy = calc_Qww_dis_ls(nf, nfpercent, Lw, Ll, Year,Af,twws, Bf, AllProperties.loc[i,'Renovated'],
Occupancy0, Seasonhours,footprint,1) #1 when internal loads ar calculated
#addd losses of hotwater system into internal loads for the mass balance
Occupancy['I_int'] = Occupancy['I_int']*Af+ Occupancy['Qww_dh_ls']*0.8# 80% is recoverable or enter to play in the energy balance
#Determination of Heat Flows for internal loads in W
Occupancy['I_ia'] = 0.5*Occupancy['I_int']
# Calculation Shading factor per hour due to operation of external shadings, 1 when I > 300 W/m2
Rf_sh = Calc_Rf_sh(AllProperties.loc[i,'Shading_Po'],AllProperties.loc[i,'Shading_Ty'])
# Calculation of effecive solar area of surfaces in m2, opaque areas are not considered, reduction factor of overhangs is not included. Fov =0
Num_Hours = Occupancy.tamb.count()
for hour in range(Num_Hours):
Occupancy.loc[hour,'g_gl'] = calc_gl(Solar.loc[i,'T'+str(hour+1)]/AllProperties.loc[i,'Awall'], g_gl,Rf_sh)
# Calculation of solar efective area per hour in m2
Occupancy.loc[hour,'Asol'] = Occupancy.loc[hour,'g_gl']*(1-F_f)*AllProperties.loc[i,'Aw']
# Calculation of Solar gains in each facade in W it is neglected the extraflow of radiation from the surface to the exterior Fr_k*Ir_k = 0 as well as gains in opaque surfaces
Occupancy.loc[hour,'I_sol'] = Occupancy.loc[hour,'Asol']*(Solar.loc[i,'T'+str(hour+1)]/AllProperties.loc[i,'Awall'])#-Fr*AllProperties.loc[i,'Aw_N']*AllProperties.loc[i,'Uwindow']*delta_t_er*hr*Rse
# Determination of Hourly thermal transmission coefficients for Determination of operation air temperatures in W/K
Coefficients = calc_Htr(Occupancy.loc[hour,'Hve'], AllProperties.loc[i,'Htr_is'], AllProperties.loc[i,'Htr_ms'], AllProperties.loc[i,'Htr_w'])
Occupancy.loc[hour,'Htr_1'] = Coefficients[0]
Occupancy.loc[hour,'Htr_2'] = Coefficients[1]
Occupancy.loc[hour,'Htr_3'] = Coefficients[2]
# Determination of Heat Flows for internal heat sources
Occupancy['I_m'] = (AllProperties.loc[i,'Am']/AllProperties.loc[i,'Atot'])*(Occupancy['I_ia']+Occupancy['I_sol'])
Occupancy['I_st'] = (1-(AllProperties.loc[i,'Am']/AllProperties.loc[i,'Atot'])-(AllProperties.loc[i,'Htr_w']/(9.1*AllProperties.loc[i,'Atot'])))*(Occupancy['I_ia']+Occupancy['I_sol'])
# Seed for calculation
# factors of Losses due to emission of systems vector hot or cold water for heating and cooling
tHC_corr = [0,0]
tHC_corr = calc_Qem_ls(str(SystemH),str(SystemC))
tHset_corr = tHC_corr[0]
tCset_corr = tHC_corr[1]
Occupancy.loc[0,'tm_t'] = Occupancy.loc[0,'te']
for j in range(1,Num_Hours): #mode = 0
# first calculation without Losses to get real operation and air temperatures
Losses = 0
tm_t0 = Occupancy.loc[j-1,'tm_t']
te_t = Occupancy.loc[j,'te']
tintH_set = Occupancy.loc[j,'tintH_set']
tintC_set = Occupancy.loc[j,'tintC_set']
Htr_em = AllProperties.loc[i,'Htr_em']
Htr_ms = AllProperties.loc[i,'Htr_ms']
Htr_is = AllProperties.loc[i,'Htr_is']
Htr_1 = Occupancy.loc[j,'Htr_1']
Htr_2 = Occupancy.loc[j,'Htr_2']
Htr_3 = Occupancy.loc[j,'Htr_3']
Hve = Occupancy.loc[j,'Hve']
Htr_w = AllProperties.loc[i,'Htr_w']
I_st = Occupancy.loc[j,'I_st']
I_ia = Occupancy.loc[j,'I_ia']
I_m = Occupancy.loc[j,'I_m']
Cm = AllProperties.loc[i,'Cm']
Results0 = calc_TL(str(SystemH),str(SystemC), te_min, te_max, tm_t0, te_t, tintH_set, tintC_set, Htr_em, Htr_ms, Htr_is, Htr_1,
Htr_2, Htr_3, I_st, Hve, Htr_w, I_ia, I_m, Cm, Af, Losses, tHset_corr,
tCset_corr)
#Occupancy.loc[j,'tm_t'] = Results0[0]
Occupancy.loc[j,'tair'] = Results0[1] # temperature of inside air
#Occupancy.loc[j,'top'] = Results0[2] # temperature of operation
#Occupancy.loc[j,'Qhs'] = Results0[3] # net heating load
#Occupancy.loc[j,'Qcs'] = Results0[4] # net cooling load
#NOW CONSIDERING INFILTRATION
Temp0 = calc_infiltration(Temp,Occupancy,Awall, Yearcat,height,nfpercent)
Occupancy['Hve'] = pa_ca*(Occupancy['Ve']* Af/3600+ Temp0['Ve_inf'])
Num_Hours = Occupancy.tamb.count()
for hour in range(Num_Hours):
Coefficients = calc_Htr(Occupancy.loc[hour,'Hve'], AllProperties.loc[i,'Htr_is'], AllProperties.loc[i,'Htr_ms'], AllProperties.loc[i,'Htr_w'])
Occupancy.loc[hour,'Htr_1'] = Coefficients[0]
Occupancy.loc[hour,'Htr_2'] = Coefficients[1]
Occupancy.loc[hour,'Htr_3'] = Coefficients[2]
# Determination of Heat Flows for internal heat sources
Occupancy['I_m'] = (AllProperties.loc[i,'Am']/AllProperties.loc[i,'Atot'])*(Occupancy['I_ia']+Occupancy['I_sol'])
Occupancy['I_st'] = (1-(AllProperties.loc[i,'Am']/AllProperties.loc[i,'Atot'])-(AllProperties.loc[i,'Htr_w']/(9.1*AllProperties.loc[i,'Atot'])))*(Occupancy['I_ia']+Occupancy['I_sol'])
for j in range(1,Num_Hours):
# Determination of net thermal loads and temperatures including emission losses
Losses = 0
#tm_t0 = Occupancy.loc[j-1,'tm_t']
#te_t = Occupancy.loc[j,'te']
#tintH_set = Occupancy.loc[j,'tintH_set']
#tintC_set = Occupancy.loc[j,'tintC_set']
#Htr_em = AllProperties.loc[i,'Htr_em']
#Htr_ms = AllProperties.loc[i,'Htr_ms']
#Htr_is = AllProperties.loc[i,'Htr_is']
Htr_1 = Occupancy.loc[j,'Htr_1']
Htr_2 = Occupancy.loc[j,'Htr_2']
Htr_3 = Occupancy.loc[j,'Htr_3']
Hve = Occupancy.loc[j,'Hve']
#Htr_w = AllProperties.loc[i,'Htr_w']
I_st = Occupancy.loc[j,'I_st']
I_ia = Occupancy.loc[j,'I_ia']
I_m = Occupancy.loc[j,'I_m']
#Cm = AllProperties.loc[i,'Cm']
Results0 = calc_TL(str(SystemH),str(SystemC), te_min, te_max, tm_t0, te_t, tintH_set, tintC_set, Htr_em, Htr_ms, Htr_is, Htr_1,
Htr_2, Htr_3, I_st, Hve, Htr_w, I_ia, I_m, Cm, Af, Losses, tHset_corr,
tCset_corr)
Occupancy.loc[j,'tm_t'] = Results0[0]
Occupancy.loc[j,'tair'] = Results0[1] # temperature of inside air
Occupancy.loc[j,'top'] = Results0[2] # temperature of operation
Occupancy.loc[j,'Qhs'] = Results0[3] # net heating load
Occupancy.loc[j,'Qcs'] = Results0[4] # net cooling load
Losses = 1
Results1 = calc_TL(str(SystemH),str(SystemC), te_min, te_max, tm_t0, te_t, tintH_set, tintC_set, Htr_em, Htr_ms, Htr_is, Htr_1,
Htr_2, Htr_3, I_st, Hve, Htr_w, I_ia, I_m, Cm, Af, Losses, tHset_corr,tCset_corr)
Occupancy.loc[j,'Qhs_em_ls'] = Results1[3]- Occupancy.loc[j,'Qhs'] # losses emission and control
Occupancy.loc[j,'Qcs_em_ls'] = Results1[4]- Occupancy.loc[j,'Qcs'] #losses emission and control
#Calculation of the emission factor of the distribution system
Emissionfactor = calc_em_t(str(SystemH),str(SystemC))
nh = Emissionfactor[4]
# sum of final energy up to the generation first time
Occupancy['Qhsf'] = Occupancy['Qhs']
Occupancy['Qcsf'] = -Occupancy['Qcs']
Occupancy['Qwwf'] = Occupancy['Qww']
Occupancy.to_csv(r'C:\ArcGIS\Toerase0.csv')
#Qc MUST BE POSITIVE
#Calculation temperatures of the distribution system during time
Results2 = calc_temperatures(str(SystemH),str(SystemC),Occupancy,Temp0,tsh0,trh0,tsc0,trc0,nh,nf,Af)
Occupancy2 = Results2[0]
#Calculation of lossess distribution system for space heating space cooling
Occupancy3 = calc_Qdis_ls(str(SystemH),str(SystemC), nf,nfpercent,Lw,Ll,Year,Af,twws, Bf, AllProperties.loc[i,'Renovated'],
Occupancy2, Seasonhours,footprint)
#Calculation of lossess distribution system for domestic hot water
Occupancy4 = calc_Qww_dis_ls(nf, nfpercent, Lw, Ll, Year,Af,twws, Bf, AllProperties.loc[i,'Renovated'],
Occupancy3, Seasonhours,footprint,0)#0 when real loads are calculated
Occupancy4.to_csv(r'C:\ArcGIS\Toerase.csv')
Occupancy4['Qww_dis_ls'] = Occupancy4['Qww_d_ls']+ Occupancy4['Qww_dh_ls']
Occupancy4['Qcs_dis_em_ls'] = -(Occupancy4['Qcs_em_ls']+ Occupancy4['Qcs_d_ls'])
Occupancy4['Qhs_dis_em_ls'] = Occupancy4['Qhs_em_ls']+ Occupancy4['Qhs_d_ls']
# sum of final energy up to the generation
Occupancy4['Qhsf'] = Occupancy4['Qhs']+Occupancy4['Qhs_dis_em_ls']#it is already taking into account contributon of heating system.
Occupancy4['Qcsf'] = -Occupancy4['Qcs']+Occupancy4['Qcs_dis_em_ls']
Occupancy4['Qwwf'] = Occupancy4['Qww'] + Occupancy4['Qww_dis_ls']
Occupancy4.to_csv(r'C:\ArcGIS\Toerase2.csv')
#Calculation temperatures of the distribution system during time second time
Results3 = calc_temperatures(str(SystemH),str(SystemC),Occupancy4,Temp0,tsh0,trh0,tsc0,trc0,nh,nf,Af)
Occupancy5 = Results3[0]
Qhs0 = Results3[1]/1000
Qcs0 = Results3[2]/1000
mwh0 = Results3[3]/4190
mwc0 = Results3[4]/4190
tsh0 = Results3[5]
trh0 = Results3[6]
tsc0 = Results3[7]
trc0 = Results3[8]
Occupancy5.to_csv(r'C:\ArcGIS\Toerase3.csv')
for j in range(1,Num_Hours):
if Seasonhours[0] < j < Seasonhours[1]:
Occupancy4.loc[j,'Qhs'] = 0
Occupancy4.loc[j,'Qhsf'] = 0
Occupancy4.loc[j,'Qhs_em_ls'] = 0
Occupancy4.loc[j,'Qhs_d_ls'] = 0
Occupancy4.loc[j,'tsh'] = 0
Occupancy4.loc[j,'trh'] = 0
elif 0 <= j <= Seasonhours[0] or Seasonhours[1] <= j <= 8759:
Occupancy4.loc[j,'Qcs'] = 0
Occupancy4.loc[j,'Qcsf'] = 0
Occupancy4.loc[j,'Qcs_em_ls'] = 0
Occupancy4.loc[j,'Qcs_d_ls'] = 0
Occupancy4.loc[j,'tsc'] = 0
Occupancy4.loc[j,'trc'] = 0
#calculation of energy for pumping of all the systems (no air-conditioning
Occupancy6 = calc_Aux_hscs(nf,nfpercent,Lw,Ll,footprint,Year,Qhs0,tsh0,trh0,Occupancy5,Qcs0,tsc0,trc0,
str(SystemH),str(SystemC),twws,tw)
#Calculation of Electrical demand
if SystemC == 'Air conditioning' or SystemC == 'Ceiling cooling':
for j in range(Num_Hours): #mode = 0
if Seasonhours[0] < j < Seasonhours[1]: #cooling season air conditioning 15 may -15sept
Occupancy6.loc[j,'Eal'] = (Occupancy6.loc[j,'Ealf_ve'] + Occupancy6.loc[j,'Ealf_nove'])*AllProperties.loc[i,'Aef']
else:
Occupancy6.loc[j,'Eal'] = (Occupancy6.loc[j,'Ealf_nove'])*Aef
if SystemH == 'Air conditioning':
for j in range(Num_Hours): #mode = 0
if 0 <= j <= Seasonhours[0]: #heating season air conditioning 15 may -15sept
Occupancy6.loc[j,'Eal'] = (Occupancy6.loc[j,'Ealf_ve'] + Occupancy6.loc[j,'Ealf_nove'])*AllProperties.loc[i,'Aef']
elif Seasonhours[1] <= j <= 8759: #cooling season air conditioning 15 may -15sept
Occupancy6.loc[j,'Eal'] = (Occupancy6.loc[j,'Ealf_ve'] + Occupancy6.loc[j,'Ealf_nove'])*AllProperties.loc[i,'Aef']
else:
Occupancy6.loc[j,'Eal'] = (Occupancy6.loc[j,'Ealf_nove'])*AllProperties.loc[i,'Aef']
else:
Occupancy0['Eal'] = Occupancy0['Ealf_nove']*Aef
Occupancy6 = Occupancy0
Qhs0 = 0
Qcs0 = 0
Occupancy6['Eaux'] = Occupancy6['Eaux_hs'] + Occupancy6['Eaux_cs'] + Occupancy6['Eaux_ww']
Occupancy6['Ealf'] = Occupancy6['Eal'] + Occupancy6['Eaux']
Occupancy6['NAME'] = AllProperties.loc[i,'Name']
# Calculate Occupancy
Occupancy6['Occupancy'] = Occupancy6['People']*Af
# Results
Result_TL = pd.DataFrame(Occupancy6,columns = ['DATE','NAME','Qhs_dis_em_ls','Qcs_dis_em_ls','Qww_dis_ls','Qhs','Qcs','Qww','Qhsf','Qcsf','Qwwf','Ealf','Eaux',
'I_sol','I_int','tsh','trh','tsc','trc','tair','top','te','Occupancy'])
Totals_TL = pd.DataFrame(Result_TL.sum()).T/1000000 #in MWh
GT = {'Name':[AllProperties.loc[i,'Name']],'Qhs_dis_em_ls':Totals_TL.Qhs_dis_em_ls,'Qhsf':Totals_TL.Qhsf,'Qcs_dis_em_ls':Totals_TL.Qcs_dis_em_ls,'Qcsf':Totals_TL.Qcsf,
'Qhs':Totals_TL.Qhs,'Qcs':Totals_TL.Qcs,'Qww':Totals_TL.Qww,'Qww_dis_ls':Totals_TL.Qww_dis_ls,'Qwwf':Totals_TL.Qwwf,
'Ealf':Totals_TL.Ealf,'Eaux':Totals_TL.Eaux,'Occupancy':Totals_TL.Occupancy,'tsh0':tsh0,'trh0':trh0,'tsc0':tsc0,'trc0':trc0,'Qhs0':Qhs0,'Qcs0':Qcs0,'mwh0':mwh0,'mwc0':mwc0,'Af':Af}
Grandtotal = pd.DataFrame(GT)
# EXPORT RESULTS
Result_TL.to_csv(locationFinal+'\\'+Name+'.csv',index=False)
Grandtotal.to_csv(locationFinal+'\\'+Name+'T'+'.csv')
return Grandtotal
# <codecell>
def calc_infiltration(Temp,Occupancy,Awall,Yearcat,height,nfpercent):
if Yearcat <= 5: # all renovated buildings plus those from 2000 on are considered tight
K1 = 0.1
K2 = 0.011
K3 = 0.034
elif 2 < Yearcat <= 4: # these categories are considered medium
K1 = 0.1
K2 = 0.017
K3 = 0.049
else: # up to 1970 and not renovated are poorly
K1 = 0.1
K2 = 0.023
K3 = 0.007
Temp['Wind_net'] = 0.21*Temp['Wind']*height**0.33 # city center conditions urban
Temp['Ve_inf'] = 0#(K1 + K2*abs(Temp['te'] - Occupancy['tair'])+K3*Temp['Wind_net'])*Awall*nfpercent*3/3600
return Temp.copy()
# <markdowncell>
# Calc temperatures distribution system
# <codecell>
def calc_temperatures(SystemH,SystemC,DATA,Temp0,tsh0,trh0,tsc0,trc0,nh,Af,Floors):
# FOR HEATING SYSTEMS FOLLOW THIS
if SystemH == 'No':
Qhsmax = 0
else:
Qh0 = Qhsmax = DATA['Qhsf'].max()
tair0 = DATA['tintH_set'].max()
if SystemH == 'Air conditioning':
HVAC = calc_HVAC(DATA,Temp0,tsh0,trh0,Qh0,tair0,nh)
RESULT = HVAC[0]
elif SystemH == 'Radiator':
rad = calc_RAD(DATA,tsh0,trh0,Qh0,tair0,nh)
RESULT = rad[0]
mwh0 = rad[1]/4190
elif SystemH == 'Floor heating':
fH = calc_TABSH(DATA,Qh0,tair0,Af,Floors)
RESULT = fh[0]
mwh0 = fh[1]/4190
tsh0 = rad[2] # this values are designed for the conditions of the building
trh0 = rad[3] # this values are designed for the conditions of the building
if SystemC == 'No':
Qcsmax = 0
else:
Qc0 = Qcsmax = DATA['Qcsf'].max()
tair0 = DATA['tintC_set'].min()
if SystemC == 'Ceiling cooling': # it is considered it has a ventilation system to regulate moisture.
fc = calc_TABSC(DATA, Qc0,tair0,Af)
RESULT = fc[0]
mwc0 = fc[1]/4190
tsc0 = fc[2]
trc0 = fc[3]
return RESULT.copy(),Qhsmax,Qcsmax, mwh0, mwc0, tsh0, trh0, tsc0, trc0
# <markdowncell>
# 2.1 Sub-function temperature radiator systems
# <codecell>
def calc_RAD(DATA,tsh0,trh0,Qh0,tair0,nh):
tair0 = tair0 + 273
tsh0 = tsh0 + 273
trh0 = trh0 + 273
mCw0 = Qh0/(tsh0-trh0)
LMRT = (tsh0-trh0)/scipy.log((tsh0-tair0)/(trh0-tair0))
k1 = 1/mCw0
def fh(x):
Eq = mCw0*k2-Qh0*(k2/(scipy.log((x+k2-tair)/(x-tair))*LMRT))**(nh+1)
return Eq
rows = DATA.Qhsf.count()
for row in range(rows):
if DATA.loc[row,'Qhsf'] != 0 and (DATA.loc[row,'tair'] == (tair0-273) or DATA.loc[row,'tair'] == 16): # in case hotel or residential
k2 = DATA.loc[row,'Qhsf']*k1
tair = DATA.loc[row,'tair']+ 273
result = scipy.optimize.newton(fh, trh0, maxiter=100,tol=0.01) - 273
DATA.loc[row,'trh'] = result.real
DATA.loc[row,'tsh'] = DATA.loc[row,'trh'] + k2
return DATA.copy(), mCw0, tsh0, trh0
# <markdowncell>
# 2.1 Sub-function temperature Floor activated slabs
# <codecell>
def calc_TABSH(DATA, Qh0,tair0,Floors,Af):
tair0 = tair0 + 273
tmean_max = tair0 + 10 # according ot EN 1264, simplifying to +9 k inernal surfaces and 15 perimeter and batroom
nh = 0.025
q0 = Qh0/Af
S0 = 5 #drop of temperature of supplied water at nominal conditions
U0 = q0/(tmean_max-tair0)
deltaH0 = (Qh0/(U0*Af))
if S0/deltaH0 <= 0.5: #temperature drop of water should be in this range
deltaV0 = deltaH0 + S0/2
else:
deltaV0 = deltaH0 + S0/2+(S0**2/(12*deltaH0))
tsh0 = deltaV0 + tair0
trh0 = tsh0 - S0
tsh0 = tsh0 + 273
trh0 = trh0 + 273
mCw0 = q0*Af/(tsh0-trh0)
LMRT = (tsh0-trh0)/scipy.log((tsh0-tair0)/(trh0-tair0))
qh0 = 8.92*(tmean_max-tair0)**1.1
kH0 = qh0*Af/(LMRT**(1+n))
k1 = 1/mCw0
def fh(x):
Eq = mCw0*k2-kH0*(k2/(scipy.log((x+k2-tair)/(x-tair))))**(1+n)
return Eq
rows = DATA.Qhsf.count()
DATA['surface']=0
for row in range(rows):
if DATA.loc[row,'Qhsf'] != 0 (DATA.loc[row,'tair'] == (tair0-273) or DATA.loc[row,'tair'] == 16):
Q = DATA.loc[row,'Qhsf']
q =Q/Af
k2 = Q*k1
tair = DATA.loc[row,'tair'] + 273
result = scipy.optimize.newton(fh, trh0, maxiter=100,tol=0.01) - 273
DATA.loc[row,'trh'] = result.real
DATA.loc[row,'tsh'] = DATA.loc[row,'trh'] + k2
DATA.loc[row,'surface'] = (q/U0)**(1/1.1)+ DATA.loc[row,'tair']
#FLOW CONSIDERING LOSSES Floor slab prototype
# no significative losses are considered
# !!!!!!!!!this text is just in case if in the future it will be used!!!!!
#sins = 0.07
#Ru = sins/0.15+0.17+0.1
#R0 = 0.1+0.0093+0.045/1 # su = 0.045 it is the tickness of the slab
# CONSTANT FLOW CONDITIONS
#tu = 13 # temperature in the basement
#if Floors ==1:
# mCw0 = Af*q0/(S0)*(1+R0/Ru+(tair-tu)/(q0*Ru))
#else:
# Af1 = Af/Floors
# mCw0 = Af1*q0/(S0)*(1+R0/Ru+(tair-tu)/(Qh0*Ru/Af1))+((Af-Af1)*q0/(S0*4190)*(1+R0/Ru))
tsh0 = DATA.loc[row,'tsh'].max()
trh0 = DATA.loc[row,'trh'].max()
return DATA.copy(), mCw0, tsh0, trh0
# <markdowncell>
# 2.1 Subfunction temperature and flow TABS Cooling
# <codecell>
def calc_TABSC(DATA, Qc0,tair0, Af):
tair0 = tair0 + 273
qc0 = Qc0/(Af*0.5) # 50% of the area available for heat exchange = to size of panels
tmean_min = dewP = 18
deltaC_N = 8 # estimated difference of temperature room and panel at nominal conditions
Sc0 = 2.5 # rise of temperature of supplied water at nominal conditions
delta_in_des = deltaC_N + Sc0/2
U0 = qc0/deltaC_N
tsc0 = tair0 - 273 - delta_in_des
if tsc0 <= dewP:
tsc0 = dewP - 1
trc0 = tsc0 + Sc0
tsc0 = tsc0 + 273
trc0 = trc0 + 273
tmean_min = (tsc0+trc0)/2 # for design conditions difference room and cooling medium
mCw0 = Qc0/(trc0-tsc0)
LMRT = (trc0-tsc0)/scipy.log((tsc0-tair0)/(trc0-tair0))
kC0 = Qc0/(LMRT)
k1 = 1/mCw0
def fc(x):
Eq = mCw0*k2-kC0*(k2/(scipy.log((x-k2-tair)/(x-tair))))
return Eq
rows = DATA.Qcsf.count()
DATA['surfaceC']=0
for row in range(rows):
if DATA.loc[row,'Qcsf'] != 0 and (DATA.loc[row,'tair'] == (tair0-273) or DATA.loc[row,'tair'] == 30):# in a hotel
Q = DATA.loc[row,'Qcsf']
q = Q/(Af*0.5)
k2 = Q*k1
tair = DATA.loc[row,'tair'] + 273
DATA.loc[row,'trc'] = scipy.optimize.newton(fc, trc0, maxiter=100,tol=0.01) - 273
DATA.loc[row,'tsc'] = DATA.loc[row,'trc'] - k2
DATA.loc[row,'surfaceC'] = DATA.loc[row,'tair'] - (q/U0)
#FLOW CONSIDERING LOSSES Floor slab prototype
# no significative losses are considered
tsc0 = (tsc0-273)
trc0 = (trc0-273)
return DATA.copy(), mCw0, tsc0, trc0
# <markdowncell>
# 2.1 Sub-function temperature Air conditioning
# <codecell>
def calc_HVAC(Temp,DATA,tsh0,trh0,Qh0,tair0,nh):
#Claculate net ventilation required taking into account losses and efficiency of ventilation system
#assumptions
# ev = 1
#nrec_teta = 0.75
#Cctr = 0.8
#Cdu_lea =
#Ci_lea = Cdu_lea*CAHU_lea
#CRCA =
# DATA['Ve_req'] = (DATA['Ve']+Temp0['Ve_inf'])*Cctr*Ci_lea*CRCA/ev
return 0
# <markdowncell>
# 2.1. Sub-Function Hourly thermal load
# <codecell>
def calc_TL(SystemH, SystemC, te_min, te_max, tm_t0, te_t, tintH_set, tintC_set, Htr_em, Htr_ms, Htr_is, Htr_1, Htr_2, Htr_3, I_st, Hve, Htr_w, I_ia, I_m, Cm, Af, Losses, tHset_corr,tCset_corr):
# assumptions
# the installed capacities are assumed to be gigantic, it is assumed that the building can
# generate heat and cold at anytime
IC = 500
IH = 500
if Losses == 1:
#Losses due to emission and control of systems
tintH_set = tintH_set + tHset_corr
tintC_set = tintC_set + tCset_corr
# Case 1 IHC_nd = 0
IHC_nd = 0
IC_nd_ac = 0
IH_nd_ac = 0
Im_tot = I_m + Htr_em * te_t + Htr_3*(I_st + Htr_w*te_t + Htr_1*(((I_ia + IHC_nd)/Hve)+ te_t))/Htr_2
tm_t = (tm_t0 *((Cm/3600)-0.5*(Htr_3+ Htr_em))+ Im_tot)/((Cm/3600)+0.5*(Htr_3+Htr_em))
tm = (tm_t+tm_t0)/2
if SystemH =='Floor heating' or SystemC =='Floor cooling':#by norm 29 max temperature of operation,
t_TABS = 29 - (29-15)*(te_t-te_min)/(te_max-te_min)
I_TABS = Af/0.08*(t_TABS-tm)
Im_tot = Im_tot+I_TABS
tm_t = (tm_t0 *((Cm/3600)-0.5*(Htr_3+ Htr_em))+ Im_tot)/((Cm/3600)+0.5*(Htr_3+Htr_em))
tm = (tm_t+tm_t0)/2
ts = (Htr_ms * tm + I_st + Htr_w*te_t + Htr_1*(te_t+(I_ia+IHC_nd)/Hve))/(Htr_ms+Htr_w+Htr_1)
tair0 = (Htr_is*ts + Hve*te_t + I_ia + IHC_nd)/(Htr_is+Hve)
top0 = 0.31*tair0+0.69*ts
if (tintH_set <= tair0) and (tair0<=tintC_set):
tair_ac = tair0
top_ac = top0
IHC_nd_ac = 0
IH_nd_ac = IHC_nd_ac
IC_nd_ac = IHC_nd_ac
else:
if tair0 > tintC_set:
tair_set = tintC_set
else:
tair_set = tintH_set
# Case 2 IHC_nd = 10 * Af
IHC_nd = IHC_nd_10 = 10*Af
Im_tot = I_m + Htr_em * te_t + Htr_3*(I_st + Htr_w*te_t + Htr_1*(((I_ia + IHC_nd)/Hve)+ te_t))/Htr_2
tm_t = (tm_t0 *((Cm/3600)-0.5*(Htr_3+ Htr_em))+ Im_tot)/((Cm/3600)+0.5*(Htr_3+Htr_em))
tm = (tm_t+tm_t0)/2
if SystemH =='Floor heating' or SystemC =='Floor cooling':#by norm 29 max temperature of operation,
t_TABS = 29 - (29-15)*(te_t-te_min)/(te_max-te_min)
I_TABS = Af/0.08*(t_TABS-tm)
Im_tot = Im_tot+I_TABS
tm_t = (tm_t0 *((Cm/3600)-0.5*(Htr_3+ Htr_em))+ Im_tot)/((Cm/3600)+0.5*(Htr_3+Htr_em))
tm = (tm_t+tm_t0)/2
ts = (Htr_ms * tm + I_st + Htr_w*te_t + Htr_1*(te_t+(I_ia+IHC_nd)/Hve))/(Htr_ms+Htr_w+Htr_1)
tair10 = (Htr_is*ts + Hve*te_t + I_ia + IHC_nd)/(Htr_is+Hve)
top10 = 0.3*tair10+0.7*ts
IHC_nd_un = IHC_nd_10*(tair_set - tair0)/(tair10-tair0)
IC_max = -IC*Af
IH_max = IH*Af
if IC_max < IHC_nd_un < IH_max:
tair_ac = tair_set
top_ac = 0.31*tair_ac+0.69*ts
IHC_nd_ac = IHC_nd_un
else:
if IHC_nd_un > 0:
IHC_nd_ac = IH_max
else:
IHC_nd_ac = IC_max
# Case 3 when the maximum power is exceeded
Im_tot = I_m + Htr_em * te_t + Htr_3*(I_st + Htr_w*te_t + Htr_1*(((I_ia + IHC_nd_ac)/Hve)+ te_t))/Htr_2
tm_t = (tm_t0 *((Cm/3600)-0.5*(Htr_3+ Htr_em))+ Im_tot)/((Cm/3600)+0.5*(Htr_3+Htr_em))
tm = (tm_t+tm_t0)/2
if SystemH =='Floor heating' or SystemC =='Floor cooling':#by norm 29 max temperature of operation,
t_TABS = 29 - (29-15)*(te_t-te_min)/(te_max-te_min)
I_TABS = Af/0.08*(t_TABS-tm)
Im_tot = Im_tot+I_TABS
tm_t = (tm_t0 *((Cm/3600)-0.5*(Htr_3+ Htr_em))+ Im_tot)/((Cm/3600)+0.5*(Htr_3+Htr_em))
tm = (tm_t+tm_t0)/2
ts = (Htr_ms * tm + I_st + Htr_w*te_t + Htr_1*(te_t+(I_ia+IHC_nd_ac)/Hve))/(Htr_ms+Htr_w+Htr_1)
tair_ac = (Htr_is*ts + Hve*te_t + I_ia + IHC_nd)/(Htr_is+Hve)
top_ac = 0.31*tair_ac+0.69*ts
# Results
if IHC_nd_ac > 0:
IH_nd_ac = IHC_nd_ac
else:
IC_nd_ac = IHC_nd_ac
Results = [tm_t, tair_ac ,top_ac, IH_nd_ac, IC_nd_ac]
return list(Results)
# <markdowncell>
# 2.1. Sub-Function Shading Factors of movebale parts
# <codecell>
#It calculates the rediction factor of shading due to type of shading
def Calc_Rf_sh (ShadingPosition,ShadingType):
#0 for not #1 for Louvres, 2 for Rollo, 3 for Venetian blinds, 4 for Courtain, 5 for Solar control glass
d ={'Type':[0, 1, 2, 3, 4,5],'ValueIN':[1, 0.2,0.2,0.3,0.77,0.1],'ValueOUT':[1, 0.08,0.08,0.15,0.57,0.1]}
ValuesRf_Table = pd.DataFrame(d)
rows = ValuesRf_Table.Type.count()
for row in range(rows):
if ShadingType == ValuesRf_Table.loc[row,'Type'] and ShadingPosition == 1: #1 is exterior
return ValuesRf_Table.loc[row,'ValueOUT']
elif ShadingType == ValuesRf_Table.loc[row,'Type'] and ShadingPosition == 0: #0 is intetiror
return ValuesRf_Table.loc[row,'ValueIN']
# <codecell>
def calc_gl(radiation, g_gl,Rf_sh):
if radiation > 300: #in w/m2
return g_gl*Rf_sh
else:
return g_gl
# <markdowncell>
# 2.2. Sub-Function equivalent profile of Occupancy
# <codecell>
def calc_Type(Profiles, Profiles_names, AllProperties, i, Servers, Coolingroom):
profiles_num = len(Profiles)
if Servers == 0:
Profiles[1] = Profiles[0]
if Coolingroom == 0:
Profiles[10] = Profiles[15]
Profiles[0].Ve = AllProperties.loc[i,Profiles_names[0]] * Profiles[0].Ve
Profiles[0].I_int = AllProperties.loc[i,Profiles_names[0]] * Profiles[0].I_int
Profiles[0].tintH_set = AllProperties.loc[i,Profiles_names[0]] * Profiles[0].tintH_set
Profiles[0].tintC_set = AllProperties.loc[i,Profiles_names[0]] * Profiles[0].tintC_set
Profiles[0].Mww = AllProperties.loc[i,Profiles_names[0]] * Profiles[0].Mww
Profiles[0].Mw = AllProperties.loc[i,Profiles_names[0]] * Profiles[0].Mw
Profiles[0].Ealf_ve = AllProperties.loc[i,Profiles_names[0]] * Profiles[0].Ealf_ve
Profiles[0].Ealf_nove = AllProperties.loc[i,Profiles_names[0]] * Profiles[0].Ealf_nove
Profiles[0].People = AllProperties.loc[i,Profiles_names[0]] * Profiles[0].People
for num in range(1,profiles_num):
Profiles[0].Ve = Profiles[0].Ve + AllProperties.loc[i,Profiles_names[num]]*Profiles[num].Ve
Profiles[0].I_int = Profiles[0].I_int + AllProperties.loc[i,Profiles_names[num]] * Profiles[num].I_int
Profiles[0].tintH_set = Profiles[0].tintH_set + AllProperties.loc[i,Profiles_names[num]] * Profiles[num].tintH_set
Profiles[0].tintC_set = Profiles[0].tintC_set + AllProperties.loc[i,Profiles_names[num]] * Profiles[num].tintC_set
Profiles[0].Mww = Profiles[0].Mww + AllProperties.loc[i,Profiles_names[num]] * Profiles[num].Mww
Profiles[0].Mw = Profiles[0].Mw + AllProperties.loc[i,Profiles_names[num]] * Profiles[num].Mw
Profiles[0].Ealf_ve = Profiles[0].Ealf_ve + AllProperties.loc[i,Profiles_names[num]] * Profiles[num].Ealf_ve
Profiles[0].Ealf_nove = Profiles[0].Ealf_nove + AllProperties.loc[i,Profiles_names[num]] * Profiles[num].Ealf_nove
Profiles[0].People = Profiles[0].People + AllProperties.loc[i,Profiles_names[num]] * Profiles[num].People
return Profiles[0].copy()
# <markdowncell>
# 2.3 Sub-Function calculation of thermal losses of emission systems differet to air conditioning
# <codecell>
def calc_Qem_ls(SystemH,SystemC):
tHC_corr = [0,0]
# values extracted from SIA 2044 - national standard replacing values suggested in EN 15243
if SystemH == 'Ceiling heating' or 'Radiator':
tHC_corr[0] = 0.5 + 1.2
elif SystemH == 'Floor heating':
tHC_corr[0] = 0 + 1.2
elif SystemH == 'Air conditioning': # no emission losses but emissions for ventilation
tHC_corr[0] = 0.5 + 1 #regulation is not taking into account here
else:
tHC_corr[0] = 0.5 + 1.2
if SystemC == 'Ceiling cooling':
tHC_corr[1] = 0 - 1.8
elif SystemC == 'Floor cooling':
tHC_corr[1] = - 0.4 - 1.8
elif SystemC == 'Air conditioning': # no emission losses but emissions for ventilation
tHC_corr[1] = 0 - 1 #regulation is not taking into account here
else:
tHC_corr[1] = 0 + - 1.2
return list(tHC_corr)
# <markdowncell>
# 2.1. Sub-Function losses heating system distribution
# <codecell>
def calc_Qdis_ls(SystemH,SystemC,nf,nfpercent, Lw,Ll,year,Af,twws, Bf, Renovated, Occupancy,Seasonhours,footprint):
# Local variables
D = 20 #in mm the diameter of the pipe to calculate losses
tws = 32 # t at the spurs according to EN 1516 3-2
# Ifdentification of linera trasmissivity coefficeitn dependent on dimensions and year of construction of building W/(m.K)
if year >= 1995 or Renovated == 'Yes':
Y = [0.2,0.3,0.3]
elif 1985 <= year < 1995 and Renovated == 'No':
Y = [0.3,0.4,0.4]
else:
Y = [0.4,0.4,0.4]
fforma = Calc_form(Lw,Ll,footprint)
# Identification of equivalent lenghts
hf = 3*(nf-1) # standard height of every floor -1 for the distribution system
Lv = (2*Ll+0.0325*Ll*Lw+6)*fforma
Lvww_c = (2*Ll+0.0125*Ll*Lw)*fforma
Lvww_dis = (Ll+0.0625*Ll*Lw)*fforma
Lsww_c = (0.075*Ll*Lw*nf*nfpercent*hf)*fforma
Lsww_dis = (0.038*Ll*Lw*nf*nfpercent*hf)*fforma
Lslww_dis = (0.05*Ll*Lw*nf*nfpercent)*fforma
# Calculate tamb in basement according to EN
hours = Occupancy.tamb.count()
for hour in range(hours):
if Seasonhours[0] < hour < Seasonhours[1]: # cooling season
Occupancy.loc[hour,'tamb'] = Occupancy.loc[hour,'tintC_set'] - Bf*(Occupancy.loc[hour,'tintC_set']-Occupancy.loc[hour,'te'])
elif 0 <= hour <= Seasonhours[0] or Seasonhours[1] <= hour <= 8759:
Occupancy.loc[hour,'tamb'] = Occupancy.loc[hour,'tintH_set'] - Bf*(Occupancy.loc[hour,'tintH_set']-Occupancy.loc[hour,'te'])
# Calculation of losses only nonrecoverable losses are considered for the calculation, # those of the distribution in the basement for space heating and cooling system
# This part applies the method described by SIA 2044
if SystemH != 'No':
if Occupancy['Qhs'].max()!=0:
Occupancy['Qhs_d_ls'] = ((Occupancy['tsh']+Occupancy['trh'])/2-Occupancy['tamb'])*(Occupancy['Qhs']/Occupancy['Qhs'].max())*(Lv*Y[0])
else:
Occupancy['Qhs_d_ls'] = 0
if SystemC != 'No':
if Occupancy['Qcs'].min()!=0:
Occupancy['Qcs_d_ls'] = ((Occupancy['tsc']+Occupancy['trc'])/2-Occupancy['tamb'])*(Occupancy['Qcs']/Occupancy['Qcs'].min())*(Lv*Y[0])
else:
Occupancy['Qcs_d_ls']=0
# Calculation of lossesof the distribution and cirulation loop of the hotwater system in the basement.
Occupancy['Qww_d_ls'] = (twws-Occupancy['tamb'])*Y[0]*(Lvww_c+Lvww_dis)*(Occupancy['Mww']*Af)/(12*60) #velocity of flow of 12 l/min
# Physical approach, losses Inside the conditioned space
hours = Occupancy.tamb.count()
for hour in range(hours):
if Seasonhours[0] < hour < Seasonhours[1]: # cooling season
Occupancy.loc[hour,'tamb'] = Occupancy['tintC_set'].min()
else:
Occupancy.loc[hour,'tamb'] = Occupancy['tintH_set'].max()
Occupancy['Qww_dh_ls'] = ((twws-Occupancy['tamb'])*Y[1]*(Lsww_c+Lsww_dis)*((Occupancy['Mww']*Af)/1000)+
(tws-Occupancy['tamb'])*Y[1]*(Lslww_dis)*((Occupancy['Mww']*Af)/1000))
return Occupancy.copy()
# <codecell>
def calc_Qww_dis_ls(nf,nfpercent,Lw,Ll,year,Af,twws, Bf, Renovated, Occupancy,Seasonhours,footprint,calcintload):
# Local variables
D = 20 #in mm the diameter of the pipe to calculate losses
tws = 32 # t at the spurs according to EN 1516 3-2
# Ifdentification of linera trasmissivity coefficeitn dependent on dimensions and year of construction of building W/(m.K)
if year >= 1995 or Renovated == 'Yes':
Y = [0.2,0.3,0.3]
elif 1985 <= year < 1995 and Renovated == 'No':
Y = [0.3,0.4,0.4]
else:
Y = [0.4,0.4,0.4]
fforma = Calc_form(Lw,Ll,footprint)
# Identification of equivalent lenghts
hf = 3*(nf-1) # standard height of every floor
Lsww_c = 0.075*Ll*Lw*nf*nfpercent*hf*fforma
Lsww_dis = 0.038*Ll*Lw*nf*nfpercent*hf*fforma
Lslww_dis = (0.05*Ll*Lw*nf*nfpercent)*fforma
# Calculate tamb in basement according to EN
if calcintload == 1:
hours = Occupancy.tamb.count()
for hour in range(hours):
if Seasonhours[0] < hour < Seasonhours[1]: # cooling season
Occupancy.loc[hour,'tamb'] = Occupancy['tintC_set'].min()
else:
Occupancy.loc[hour,'tamb'] = Occupancy['tintH_set'].max()
else:
Occupancy['tamb'] = Occupancy['tair']
Occupancy['Qww_dh_ls'] = ((twws-Occupancy['tamb'])*Y[1]*(Lsww_c+Lsww_dis)*((Occupancy['Mww']*Af)/1000)+
(tws-Occupancy['tamb'])*Y[1]*(Lslww_dis)*((Occupancy['Mww']*Af)/1000))
return Occupancy.copy()
# <codecell>
#a factor taking into account that Ll and lw are measured from an aproximated rectangular surface
def Calc_form(Lw,Ll,footprint):
factor = footprint/(Lw*Ll)
return factor
# <codecell>
def calc_Aux_hscs(nf,nfpercent,Lw,Ll,footprint,Year,Qhs0,tsh0,trh0,data,Qcs0,tsc0,trc0,SystemH,SystemC,twws,tw):
# accoridng to SIA 2044
# Identification of equivalent lenghts
hf = 3
fforma = Calc_form(Lw,Ll,footprint)
# constants
deltaP_l = 0.1
fsr = 0.3
cp = 1000*4.186
#variable depending on new or old building. 2000 as time line
if Year >= 2000:
b =1
else:
b =1.2
# for heating system
#the power of the pump in Watts
if SystemH != 'Air conditioning' or SystemH != 'No':
fctr = 1.05
qV_des = Qhs0*1000/((tsh0-trh0)*cp)
Imax = 2*(Ll+Lw/2+hf+(nf*nfpercent)+10)*fforma
deltaP_des = Imax*deltaP_l*(1+fsr)
Phy_des = 0.2278*deltaP_des*qV_des
feff = (1.25*(200/Phy_des)**0.5)*fctr*b
Ppu_dis = Phy_des*feff
#the power of the pump in Watts
hours = data.tamb.count()
for hour in range(hours):
if data.loc[hour,'Qhsf'] > 0:
if data.loc[hour,'Qhsf']/Qhs0 > 0.67:
Ppu_dis_hy_i = Phy_des
feff = (1.25*(200/Ppu_dis_hy_i)**0.5)*fctr*b
data.loc[hour,'Eaux_hs'] = Ppu_dis_hy_i*feff
else:
Ppu_dis_hy_i = 0.0367*Phy_des
feff = (1.25*(200/Ppu_dis_hy_i)**0.5)*fctr*b
data.loc[hour,'Eaux_hs'] = Ppu_dis_hy_i*feff
else:
data.loc[hour,'Eaux_hs']=0
# for Cooling system
#the power of the pump in Watts
if SystemH != 'Air conditioning' or SystemH != 'No':
fctr = 1.10
qV_des = Qcs0/((trc0-tsc0)*cp)
Imax = 2*(Ll+Lw/2+hf+(nf*nfpercent)+10)*fforma
deltaP_des = Imax*deltaP_l*(1+fsr)
Phy_des = 0.2778*deltaP_des*qV_des
feff = (1.25*(200/Phy_des)**0.5)*fctr*b
Ppu_dis = Phy_des*feff
#the power of the pump in Watts
hours = data.tamb.count()
for hour in range(hours):
if data.loc[hour,'Qcsf'] > 0:
if data.loc[hour,'Qcsf']/(Qcs0*1000) > 0.67:
Ppu_dis_hy_i = Phy_des
feff = (1.25*(200/Ppu_dis_hy_i)**0.5)*fctr*b
data.loc[hour,'Eaux_cs'] = Ppu_dis_hy_i*feff
else:
Ppu_dis_hy_i = 0.0367*Phy_des
feff = (1.25*(200/Ppu_dis_hy_i)**0.5)*fctr*b
data.loc[hour,'Eaux_cs'] = Ppu_dis_hy_i*feff
else:
data.loc[hour,'Eaux_cs']=0
# for domestichotwater
#the power of the pump in Watts
qV_des = data['Qwwf'].max()/((twws-tw)*cp)
Imax = 2*(Ll+2.5+hf+(nf*nfpercent))*fforma
deltaP_des = Imax*deltaP_l*(1+fsr)
Phy_des = 0.2778*deltaP_des*qV_des
feff = (1.25*(200/Phy_des)**0.5)*fctr*b
Ppu_dis = Phy_des*feff
#the power of the pump in Watts
hours = data.tamb.count()
for hour in range(hours):
if data.loc[hour,'Qwwf']>0:
if data.loc[hour,'Qwwf']/data['Qwwf'].max() > 0.67:
Ppu_dis_hy_i = Phy_des
feff = (1.25*(200/Ppu_dis_hy_i)**0.5)*b
data.loc[hour,'Eaux_ww'] = Ppu_dis_hy_i*feff
else:
Ppu_dis_hy_i = 0.0367*Phy_des
feff = (1.25*(200/Ppu_dis_hy_i)**0.5)*b
data.loc[hour,'Eaux_ww'] = Ppu_dis_hy_i*feff
return data.copy()
# <markdowncell>
# 2.1. Sub-Function calculation of nominal temperatures of system
# <codecell>
def calc_em_t(SystemH,SystemC):
# References: 70 supply 50 return radiatior system #several authors
# Floor cooling/ceiling cooling 18 -22 /thermofloor.co.uk
# Floor heating /ceiling heating EN 1264-3
# Emission factors extracted from SIA 384/2,1984
#Default values
nh =0.3
tsh0 = 70
trh0 = 50
tsc0 = 7
trc0 = 12
# Create tables with information of nominal temperatures
h={'Type':['Ceiling heating', 'Radiator', 'Floor heating', 'Air conditioning'],'tsnominal':[35,70,35,60],
'trnominal':[25,50,25,50],'EmissionFactor':[0.22,0.33,0.24,0.3]}
Heating = pd.DataFrame(h)
c ={'Type':['Ceiling cooling','Floor cooling', 'Air conditioning'],'tsnominal':[15,15,7],
'trnominal':[20,20,12]}
Cooling = pd.DataFrame(c)
# Calculate the nominal temperatures and emission factors based on the type of system.
# for heating systems
rows = Heating.Type.count()
for row in range(rows):
if SystemH == Heating.loc[row,'Type']:
tsh0 = Heating.loc[row,'tsnominal']
trh0 = Heating.loc[row,'trnominal']
nh = Heating.loc[row,'EmissionFactor']
#for cooling sytems
rows = Cooling.Type.count()
for row in range(rows):
if SystemC == Cooling.loc[row,'Type']:
tsc0 = Cooling.loc[row,'tsnominal']
trc0 = Cooling.loc[row,'trnominal']
return tsh0,trh0,tsc0,trc0,nh
# <markdowncell>
# ##STATISTICAL ENERGY MODEL
# <codecell>
def Querystatistics(CQ, CQ_name, Model, locationtemp1,locationFinal):
#Create the table or database of the CQ to generate the values
OutTable = 'Database.dbf'
arcpy.TableToTable_conversion(CQ, locationtemp1, OutTable)
Database0 = dbf2df(locationtemp1+'\\'+OutTable)
#THE FIRST PART RELATED TO THE BUILDING PROPERTIES
#Assing main use of the building To assign systems of heating or cooling in a building basis.
Database = MainUse(Database0)
# assign the year of each category and create a new code
Database['YearCat'] = Database.apply(lambda x: YearCategoryFunction(x['Year'], x['Renovated']), axis=1)
Database['CODE'] = Database.Type + Database.YearCat
# Create join with the model
Joineddata = pd.merge(Database, Model, left_on='CODE', right_on='Code')
Joineddata.rename(columns={'Hs_x':'Hs'},inplace=True)
# EXPORT PROPERTIES
Joineddata.to_excel('c:\ArcGIS\EDMdata\Statistical'+'\\'+CQ_name+'\\'+'Properties.xls',
sheet_name='Values',index=False,cols={'Name','tsh0','trh0','tsc0','trc0','Hs','Es','PFloor','Year','fwindow',
'Floors','Construction','Emission_heating','Emission_cooling',
'Uwall','Uroof','Ubasement','Uwindow'})
#EXPORT PROPERTIES RELATED TO PROCESEES AND EQUIPMENT
Counter = Joineddata.INDUS.count()
Joineddata['E4'] = Joineddata['SRFlag'] = Joineddata['CRFlag'] = Joineddata['ICEFlag'] = 0
for row in range(Counter):
if Joineddata.loc[row,'INDUS'] >0:
Joineddata.loc[row,'E4'] = 1
if Joineddata.loc[row,'SR'] >0:
Joineddata.loc[row,'SRFlag'] = 1
if Joineddata.loc[row,'ICE'] >0:
Joineddata.loc[row,'ICEFlag'] = 1
if Joineddata.loc[row,'CR'] >0:
Joineddata.loc[row,'CRFlag'] = 1
Joineddata.to_excel('c:\ArcGIS\EDMdata\Statistical'+'\\'+CQ_name+'\\'+'Equipment.xls',
sheet_name='Values',index=False,cols={'Name','CRFlag','SRFlag','ICEFlag',
'E4'})
#THE OTHER PART RELATED TO THE ENERGY VALUES'
DatabaseUnpivoted = pd.melt(Database, id_vars=('Name','Shape_Area','YearCat','Hs','Floors'))
DatabaseUnpivoted['CODE'] = DatabaseUnpivoted.variable + DatabaseUnpivoted.YearCat
#Now both Database with the new codification is merged or joined to the values of the Statistical model
DatabaseModelMerge = pd.merge(DatabaseUnpivoted, Model, left_on='CODE', right_on='Code')
#Now the values are created. as all the intensity values are described in MJ/m2.
##they are transformed into MWh, Heated space is assumed as an overall 90% of the gross area according to the standard SIA,
##unless it is known (Siemens buildings and surroundings, Obtained during visual inspection a report of the area Grafenau)
counter = DatabaseModelMerge.value.count()
for r in range (counter):
if DatabaseModelMerge.loc[r,'Hs_x']>0:
DatabaseModelMerge.loc[r,'Hs_y'] = DatabaseModelMerge.loc[r,'Hs_x']
DatabaseModelMerge['Qhsf'] = DatabaseModelMerge.value * DatabaseModelMerge.Shape_Area * DatabaseModelMerge.Floors * DatabaseModelMerge.Hs_y* DatabaseModelMerge.qhsf_kWhm2/1000
DatabaseModelMerge['Qhpf'] = DatabaseModelMerge.value * DatabaseModelMerge.Shape_Area * DatabaseModelMerge.Floors * DatabaseModelMerge.Hs_y* DatabaseModelMerge.qhpf_kWhm2/1000
DatabaseModelMerge['Qwwf'] = DatabaseModelMerge.value * DatabaseModelMerge.Shape_Area * DatabaseModelMerge.Floors * DatabaseModelMerge.Hs_y* DatabaseModelMerge.qwwf_kWhm2/1000
DatabaseModelMerge['Qcsf'] = DatabaseModelMerge.value * DatabaseModelMerge.Shape_Area * DatabaseModelMerge.Floors * DatabaseModelMerge.Hs_y* DatabaseModelMerge.qcsf_kWhm2/1000
DatabaseModelMerge['Qcdataf'] = DatabaseModelMerge.value * DatabaseModelMerge.Shape_Area * DatabaseModelMerge.Floors * DatabaseModelMerge.Hs_y* DatabaseModelMerge.qcdataf_kWhm2/1000
DatabaseModelMerge['Qcicef'] = DatabaseModelMerge.value * DatabaseModelMerge.Shape_Area * DatabaseModelMerge.Floors * DatabaseModelMerge.Hs_y* DatabaseModelMerge.qcicef_kWhm2/1000
DatabaseModelMerge['Qcpf'] = DatabaseModelMerge.value * DatabaseModelMerge.Shape_Area * DatabaseModelMerge.Floors * DatabaseModelMerge.Hs_y* DatabaseModelMerge.qcpf_kWhm2/1000
DatabaseModelMerge['Ealf'] = DatabaseModelMerge.value * DatabaseModelMerge.Shape_Area * DatabaseModelMerge.Floors * DatabaseModelMerge.Hs_y* DatabaseModelMerge.Ealf_kWhm2/1000
DatabaseModelMerge['Edataf'] = DatabaseModelMerge.value * DatabaseModelMerge.Shape_Area * DatabaseModelMerge.Floors * DatabaseModelMerge.Hs_y* DatabaseModelMerge.Edataf_kWhm2/1000
DatabaseModelMerge['Epf'] = DatabaseModelMerge.value * DatabaseModelMerge.Shape_Area * DatabaseModelMerge.Floors * DatabaseModelMerge.Es* DatabaseModelMerge.Epf_kWhm2/1000
DatabaseModelMerge['Ecaf'] = 0 #compressed air is 0 for all except siemens where data is measured.
# Pivoting the new table and summing rows all in MWh
Qhsf = pd.pivot_table(DatabaseModelMerge, values='Qhsf', rows='Name', cols='CODE', aggfunc='sum', margins='add all rows')
Qhpf = pd.pivot_table(DatabaseModelMerge, values='Qhpf', rows='Name', cols='CODE', aggfunc='sum', margins='add all rows')
Qwwf = pd.pivot_table(DatabaseModelMerge, values='Qwwf', rows='Name', cols='CODE', aggfunc='sum', margins='add all rows')
Qcsf = pd.pivot_table(DatabaseModelMerge, values='Qcsf', rows='Name', cols='CODE', aggfunc='sum', margins='add all rows')
Qcdataf = pd.pivot_table(DatabaseModelMerge, values='Qcdataf', rows='Name', cols='CODE', aggfunc='sum', margins='add all rows')
Qcicef = pd.pivot_table(DatabaseModelMerge, values='Qcicef', rows='Name', cols='CODE', aggfunc='sum', margins='add all rows')
Qcpf = pd.pivot_table(DatabaseModelMerge, values='Qcpf', rows='Name', cols='CODE', aggfunc='sum', margins='add all rows')
Ealf = pd.pivot_table(DatabaseModelMerge, values = 'Ealf', rows='Name', cols='CODE', aggfunc='sum', margins='add all rows')
Edataf = pd.pivot_table(DatabaseModelMerge, values='Edataf', rows='Name', cols='CODE', aggfunc='sum', margins='add all rows')
Epf = pd.pivot_table(DatabaseModelMerge, values='Epf', rows='Name', cols='CODE', aggfunc='sum', margins='add all rows')
Ecaf = pd.pivot_table(DatabaseModelMerge, values='Ecaf', rows='Name', cols='CODE', aggfunc='sum', margins='add all rows')
Total = pd.DataFrame({'Qhsf': Qhsf['All'],'Qhpf': Qhpf['All'],'Qwwf': Qwwf['All'],'Qcsf': Qcsf['All'],'Qcpf': Qcpf['All'],
'Ealf': Ealf['All'],'Epf': Epf['All'],'Edataf': Edataf['All'],'Qcdataf': Qcdataf['All'],
'Ecaf': Ecaf['All'],'Qcicef': Qcicef['All'] })
# reset index
Total['Name'] = Total.index
counter = Total.Qhsf.count()
Total.index = range(counter)
Total.to_csv(locationFinal+'\\'+CQ_name+'\\'+'Loads.csv', index=False)
return Total
# <markdowncell>
# This function estimates the main type of ocupation in the building. as a result those values such as coefficients of trasnmittance, temperatures of operation and type of emission systems are selected in a mayority basis.
# <codecell>
def MainUse(Database0):
uses = ['ADMIN','SR','INDUS','REST','RESTS','DEPO','COM','MDU','SDU','EDU','CR','HEALTH','SPORT',
'SWIM','PUBLIC','SUPER','ICE','HOT']
Database0['Type'] = 'MDU'
n_buildings = Database0.ADMIN.count()
n_uses = len(uses)
for r in range (n_uses):
for row in range(n_buildings):
if Database0.loc[row, uses[r]]>=0.5:
Database0.loc[row, 'Type']= uses[r]
return Database0.copy()
# <markdowncell>
# Sub-function: assign As the values in the statistical model are codified according to a secuence of 1, 2, 3, 4 and 5, a function has to be define to codify in the same therms the Database, a new filed (YearCAt) is assigned to the Database
# <codecell>
def YearCategoryFunction(x,y):
if x <= 1920:
#Database['Qh'] = Database.ADMIN.value * Model.
result = '1'
elif x > 1920 and x <= 1970:
result = '2'
elif x > 1970 and x <= 1980:
result = '3'
elif x > 1980 and x <= 2000:
result = '4'
elif x > 2000 and x <= 2020:
result = '5'
elif x > 2020:
result = '6'
if x <= 1920 and y=='Yes':
result = '7'
elif 1920 < x <= 1970 and y=='Yes':
result = '8'
elif 1970 < x <= 1980 and y=='Yes':
result = '9'
elif 1980 < x <= 2000 and y=='Yes':
result = '10'
return result
| [
"[email protected]"
] | |
fd2d35e5d2c521e1cecac452695ef706d4c2c8f4 | d60a3e90a556f0a3401b4353608da2aac5f7540b | /patch_dispatch.py | 913599474cc1e1498e97b006aab071d810d30fff | [] | no_license | egorzhdan/swift-windows-helper | 4ab8c31bfefee6659f79421800f38aea7e6d0a85 | dd9999ef02f180c8b11524c665f458d1ade2d158 | refs/heads/master | 2023-03-10T21:42:22.161709 | 2021-02-20T14:19:49 | 2021-02-20T14:19:49 | 309,090,363 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 434 | py | import sys
import shutil
sdk_path = sys.argv[1] # C:\Library\Developer\Platforms\Windows.platform\Developer\SDKs\Windows.sdk
include_dir = sdk_path + "\\usr\\include"
dir_names = [
"Block",
"dispatch",
"os",
]
for dir_name in dir_names:
current_dir = sdk_path + "\\usr\\lib\\swift\\" + dir_name
print("Moving", current_dir, "to", include_dir)
shutil.move(current_dir, include_dir)
print()
print("Done!")
| [
"[email protected]"
] | |
56e24c6bedffbf4b9570c232138492920f42e23f | cab59201f865b223ecaf51de7a56e7876ec0b52f | /xpath.py | 904e7f786ba6a29b88257f0aba7bb90b51a53bcc | [] | no_license | Dao-zhi/GoogleScholarGUI | e45128a18dfec823c6239f6338d053aeeef29420 | 4ef8efc265f3b56603f6bd72c596478a60e8fe76 | refs/heads/master | 2023-04-15T11:00:01.728444 | 2023-04-11T15:24:10 | 2023-04-11T15:24:10 | 296,362,335 | 50 | 10 | null | null | null | null | UTF-8 | Python | false | false | 3,871 | py | from lxml import etree
text = '''
<div>
<ul>
<li class="item-0"><a href="https://ask.hellobi.com/link1.html">first item</a></li>
<li class="item-1"><a href="https://ask.hellobi.com/link2.html">second item</a></li>
<li class="item-inactive"><a href="https://ask.hellobi.com/link3.html">third item</a></li>
<li class="item-1"><a href="https://ask.hellobi.com/link4.html">fourth item</a></li>
<li class="item-0"><a href="https://ask.hellobi.com/link5.html">fifth item</a>
<li class="li li-first"><a href="https://ask.hellobi.com/link.html">sixth item</a></li>
<li class="li li-first" name="item"><a href="https://ask.hellobi.com/link.html">seventh item</a></li>
</ul>
</div>
'''
html = etree.HTML(text)
result = etree.tostring(html)
print('-----解析节果-----')
# print(result.decode('utf-8')) # 输出解析后的节果
# 从文件中解析html
# html = etree.parse('./test.html', etree.HTMLParser())
# result = etree.tostring(html)
# print(result.decode('utf-8')) # 输出解析后的节果
# 所有节点
print('-----所有节点-----')
result = html.xpath('//*')
print(result)
# 所有li节点
print('-----所有li节点-----')
result = html.xpath('//li')
print(result)
print(result[0])
# 子节点
print('-----子节点-----')
result = html.xpath('//li/a') # li 节点的所有直接 a 子节点
print(result)
result = html.xpath('//ul//a') # ul 节点下的所有子孙 a 节点
print(result)
# 父节点
print('-----父节点-----')
result = html.xpath('//a[@href="https://ask.hellobi.com/link4.html"]/../@class')
print(result)
result = html.xpath('//a[@href="https://ask.hellobi.com/link4.html"]/parent::*/@class')
print(result)
# 属性匹配
print('-----属性匹配-----')
result = html.xpath('//li[@class="item-0"]')
print(result)
# 文本获取
print('-----文本获取-----')
result = html.xpath('//li[@class="item-0"]/text()')
print(result)
result = html.xpath('//li[@class="item-0"]/a/text()')
print(result)
result = html.xpath('//li[@class="item-0"]//text()')
print(result)
# 属性获取
print('-----属性获取-----')
result = html.xpath('//li/a/@href')
print(result)
# 属性多值匹配
print('-----属性多值匹配-----')
result = html.xpath('//li[@class="li"]/a/text()') # 无法匹配
print(result)
result = html.xpath('//li[contains(@class, "li")]/a/text()')
print(result)
# 多属性匹配
print('-----多属性匹配-----')
result = html.xpath('//li[contains(@class, "li") and @name="item"]/a/text()') # class=li并且name=item
print(result)
# 按序选择
print('-----按序选择-----')
result = html.xpath('//li[1]/a/text()') # 第一个
print(result)
result = html.xpath('//li[last()]/a/text()') # 最后一个
print(result)
result = html.xpath('//li[position()<3]/a/text()') # 前两个
print(result)
result = html.xpath('//li[last()-2]/a/text()') # 倒数第三个
print(result)
# 节点轴选择
print('-----节点轴选择-----')
result = html.xpath('//li[1]/ancestor::*') # 所有祖先节点
print(result)
result = html.xpath('//li[1]/ancestor::div') # 所有祖先节点中的div
print(result)
result = html.xpath('//li[1]/attribute::*') # 所有属性
print(result)
result = html.xpath('//li[1]/child::a[@href="https://ask.hellobi.com/link1.html"]') # 子节点中href为...的节点
print(result)
result = html.xpath('//li[1]/descendant::span') # 所有孙子节点中的span
print(result)
result = html.xpath('//li[1]/following::*[2]') # 当前节点之后的所有节点,这里我们虽然使用的是 * 匹配,但又加了索引选择,所以只获取了第二个后续节点。
print(result)
result = html.xpath('//li[1]/following-sibling::*') # 当前节点之后的所有同级节点,这里我们使用的是 * 匹配,所以获取了所有后续同级节点
print(result) | [
"[email protected]"
] | |
5f537c70f9cd6b0a19616b71a25a215de60024f5 | e070e662194c12e8441f62e92cad8528b81b12a5 | /djd-prog2/noite/aula6/teste_retangulo_for.py | 5451392e572992ca3a801263bbdc7e89df81f727 | [] | no_license | antoniorcn/fatec-2019-1s | 0297c4a3d8b5ac4ff8d1f97edc5859202827e721 | 9f5e2e12b894de08b43db3c83a9c4d08cd6de14e | refs/heads/master | 2020-04-22T23:02:45.763837 | 2019-06-03T15:58:19 | 2019-06-03T15:58:19 | 170,727,501 | 5 | 10 | null | null | null | null | UTF-8 | Python | false | false | 98 | py | for linha in range(0, 4):
for coluna in range(0, 5):
print("*", end="")
print("")
| [
"[email protected]"
] | |
51841a19a264faf973ced18a9e1cf35247bbda79 | 46681c3220e9279aa111167b8c5cb1d5a01aa2ad | /Flappy_bird/Keyboard version/bird.py | 42864d03d56d0b71d092fa85b1ccdd36e9f9c875 | [] | no_license | J-Z-Z/Pygame-Samples | c74e59f170c975e530fad60ac4f024095393b82d | 9e8ca3ec1c1c2eb9747aa4108168a0809863aa95 | refs/heads/master | 2022-07-07T02:00:53.583274 | 2020-05-12T15:38:50 | 2020-05-12T15:38:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,264 | py | import pygame
class Bird():
def __init__(self,g_settings,screen):
'''初始化 并设置其初始位置'''
self.screen = screen
self.g_settings = g_settings
#加载主体图像并获取其外接矩形
self.image = pygame.image.load('images/bird.png')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
#将主体放在屏幕的中央部中央的位置
self.rect.centerx = self.screen_rect.centerx
self.rect.bottom = 0.5 * self.screen_rect.bottom
self.center = float(self.rect.centerx)
self.birdy = float(self.rect.y)
#移动标识 用于持续移动
self.moving = False
def update(self):
'''自动更新主体位置'''
if self.rect.y < (self.screen_rect.bottom - 30):
self.birdy += 10
self.rect.centerx = self.center
self.rect.y = self.birdy
def move(self):
'''根据标识符来改变主体的移动状态'''
if self.moving and 0 < self.rect.y < (self.screen_rect.bottom):
self.birdy -= 20
self.rect.y = self.birdy
def blitme(self):
'''指定位置绘制主体'''
self.screen.blit(self.image,self.rect) | [
"[email protected]"
] | |
156246262492d16dbce1e7855ed7bfc5704e2fc2 | 20d7e33c26d6a26cfca5b7dd4c769e5a8e4fae5b | /app_info.py | 210d25de849c52df1fb1412b5c5b79aca9f4d870 | [
"MIT"
] | permissive | sokcheng/Kitsuchan-NG | 02fc23cb2bc1c3e41226e3895cd32d0f23eec542 | 3a456ad06814181d13d4aabefc151756c55444f4 | refs/heads/master | 2021-01-21T17:38:14.271366 | 2017-05-21T15:16:45 | 2017-05-21T15:16:45 | 91,972,929 | 1 | 0 | null | 2017-05-21T16:51:46 | 2017-05-21T16:51:46 | null | UTF-8 | Python | false | false | 634 | py | #!/usr/bin/env python3
"""Contains application information.
Yes, it's slightly bad practice to put this in a Python file."""
NAME = "Kitsuchan-NG"
URL = "https://github.com/n303p4/Kitsuchan-NG"
DESCRIPTION = (f"This is a running instance of [{NAME}]({URL}), a modular Discord bot. Originally "
"designed with anime images and basic utility in mind, it has become a fairly "
f"flexible bot with decent extensibility. {NAME} surely isn't finished yet; please "
"report any bugs you observe!")
VERSION = (0, 6, 0, "ap", "Fennec")
VERSION_STRING = "{0}.{1}.{2}{3} \"{4}\"".format(*VERSION)
| [
"[email protected]"
] | |
b497b5eab779e045244040b84540a3b1de211872 | d47a1652db00123911c7f7ef41c26b094eaa5bf4 | /statsmodels/datasets/statecrime/data.py | 66f2cdd37551eebf7472fbeaa8e995767e5f885b | [
"BSD-3-Clause"
] | permissive | harpone/statsmodels | 7779642f9f224966df515b24e3a95801884092ac | 07576e42b29bf8a46511b316381624461499f8f6 | refs/heads/master | 2020-12-26T00:45:38.269093 | 2014-02-25T02:57:35 | 2014-02-25T02:57:35 | 17,170,955 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,985 | py | #! /usr/bin/env python
"""Statewide Crime Data"""
__docformat__ = 'restructuredtext'
COPYRIGHT = """Public domain."""
TITLE = """Statewide Crime Data 2009"""
SOURCE = """
All data is for 2009 and was obtained from the American Statistical Abstracts except as indicated below.
"""
DESCRSHORT = """State crime data 2009"""
DESCRLONG = DESCRSHORT
#suggested notes
NOTE = """
Number of observations: 51
Number of variables: 8
Variable name definitions:
state
All 50 states plus DC.
violent
Rate of violent crimes / 100,000 population. Includes murder, forcible
rape, robbery, and aggravated assault. Numbers for Illinois and Minnesota
do not include forcible rapes. Footnote included with the American
Statistical Abstract table reads:
"The data collection methodology for the offense of forcible
rape used by the Illinois and the Minnesota state Uniform Crime Reporting
(UCR) Programs (with the exception of Rockford, Illinois, and Minneapolis
and St. Paul, Minnesota) does not comply with national UCR guidelines.
Consequently, their state figures for forcible rape and violent crime (of
which forcible rape is a part) are not published in this table."
murder
Rate of murders / 100,000 population.
hs_grad
Precent of population having graduated from high school or higher.
poverty
% of individuals below the poverty line
white
Percent of population that is one race - white only. From 2009 American
Community Survey
single
Calculated from 2009 1-year American Community Survey obtained obtained
from Census. Variable is Male householder, no wife present, family
household combined with Female household, no husband prsent, family
household, divided by the total number of Family households.
urban
% of population in Urbanized Areas as of 2010 Census. Urbanized Areas are
area of 50,000 or more people."""
import numpy as np
from statsmodels.datasets import utils as du
from os.path import dirname, abspath
def load():
"""
Load the statecrime data and return a Dataset class instance.
Returns
-------
Dataset instance:
See DATASET_PROPOSAL.txt for more information.
"""
data = _get_data()
##### SET THE INDICES #####
#NOTE: None for exog_idx is the complement of endog_idx
return du.process_recarray(data, endog_idx=2, exog_idx=[7, 4, 3, 5],
dtype=float)
def load_pandas():
data = _get_data()
##### SET THE INDICES #####
#NOTE: None for exog_idx is the complement of endog_idx
return du.process_recarray_pandas(data, endog_idx=2, exog_idx=[7,4,3,5],
dtype=float, index_idx=0)
def _get_data():
filepath = dirname(abspath(__file__))
##### EDIT THE FOLLOWING TO POINT TO DatasetName.csv #####
data = np.recfromtxt(open(filepath + '/statecrime.csv', 'rb'),
delimiter=",", names=True, dtype=None)
return data
| [
"[email protected]"
] | |
1b44227170fdcac65c26a440e7d2e2b2a47ec25c | e8900be618c45fdd4ded96a7f4f73d98175b0d58 | /lifesaver/load_list.py | c0897b11c8bd4a9ec30ca2deb3fcbbbdec7c5025 | [
"MIT"
] | permissive | lun-4/lifesaver | badf56aa0dfd744c49fb50a2611cbf201bd8ba0e | e8c4b492490d678db80258f69fce6dc4769fd1d7 | refs/heads/master | 2022-11-23T08:29:25.297035 | 2020-06-14T04:00:30 | 2020-06-14T04:00:30 | 228,510,471 | 0 | 0 | NOASSERTION | 2019-12-17T01:51:50 | 2019-12-17T01:51:49 | null | UTF-8 | Python | false | false | 2,422 | py | # encoding: utf-8
import importlib
import logging
import typing
from collections import UserList
from pathlib import Path
FORBIDDEN_EXTENSIONS = {
".pyc",
".log",
".ini",
".DS_Store",
".db",
".mypy_cache",
".tmp",
}
FORBIDDEN_NAMES = {"__pycache__"}
def transform_path(path: typing.Union[Path, str]) -> str:
return str(path).replace("/", ".").replace(".py", "")
def filter_path(path: typing.Union[Path, str]) -> bool:
"""Return whether a path is appropriate for extension loading."""
string_path = str(path)
if any(string_path.endswith(ext) for ext in FORBIDDEN_EXTENSIONS):
return False
if string_path in FORBIDDEN_NAMES:
return False
return True
class LoadList(UserList):
"""A class that encompasses behavior related to discovering extensions and loading them."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.log = logging.getLogger(__name__)
def build(self, exts_path: Path):
if not exts_path.is_dir():
self.log.warning(
"Cannot build load list: %s is not a directory.", exts_path
)
return
# Build a list of extensions to load.
paths = [
transform_path(path) for path in exts_path.iterdir() if filter_path(path)
]
def ext_filter(path: str) -> bool:
try:
module = importlib.import_module(path)
return hasattr(module, "setup")
except Exception:
# Failed to import, extension might be bugged.
# If this extension was previously included, retain it in the
# load list because it might be fixed and reloaded later.
#
# Otherwise, discard.
previously_included = path in self.data
if not previously_included:
self.log.exception("Excluding %s from the load list:", path)
else:
self.log.warning(
(
"%s has failed to load, but it will be retained in "
"the load list because it was previously included."
),
path,
)
return previously_included
self.data = list(filter(ext_filter, paths))
| [
"[email protected]"
] | |
213840862cac4a5e0577be766248cd201e560514 | be6b4181de09a50ccbd7caea58dbdbcbf90602be | /numba/servicelib/threadlocal.py | 2ad13112109b26cdbb93c40202dffb8edc1a6bf4 | [
"BSD-2-Clause"
] | permissive | pombreda/numba | 6490c73fcc0ec5d93afac298da2f1068c0b5ce73 | 25326b024881f45650d45bea54fb39a7dad65a7b | refs/heads/master | 2021-01-15T10:37:08.119031 | 2014-11-06T22:32:48 | 2014-11-06T22:32:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 910 | py | """
Implements:
- Threadlocal stack
"""
from __future__ import print_function, absolute_import, division
import threading
class TLStack(object):
def __init__(self):
self.local = threading.local()
@property
def stack(self):
try:
# Retrieve thread local stack
return self.local.stack
except AttributeError:
# Initialize stack for the thread
self.local.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop()
@property
def top(self):
return self.stack[-1]
@property
def is_empty(self):
return not self.stack
def __bool__(self):
return not self.is_empty
def __nonzero__(self):
return self.__bool__()
def __len__(self):
return len(self.stack)
def clear(self):
self.__init__()
| [
"[email protected]"
] | |
f97b3364c92a623168bf5bf6a376bc641629e379 | 52a784d003dea763794b526d0e8b5763d0a01fd9 | /app.py | 56a4a65b9d0a3a5707e7909854b8fa6b3510ae61 | [] | no_license | jdaltuvec/flask-pets | 9d9306583fb2d8892325d4fcebe9858bfae0ff40 | 8d0216fed907501a4ff89387bef68109f0041ab5 | refs/heads/master | 2023-05-11T06:21:11.722624 | 2020-02-15T19:47:43 | 2020-02-15T19:47:43 | 240,777,885 | 0 | 0 | null | 2023-05-02T18:42:41 | 2020-02-15T19:45:03 | Python | UTF-8 | Python | false | false | 3,429 | py | from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
import datetime
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///pets.sqlite"
db = SQLAlchemy(app)
class DictMixIn:
def to_dict(self):
return {
column.name: getattr(self, column.name)
if not isinstance(getattr(self, column.name), datetime.datetime)
else getattr(self, column.name).isoformat()
for column in self.__table__.columns
}
class Pet(db.Model, DictMixIn):
__tablename__ = "pet"
id = db.Column(db.Integer(), primary_key=True)
date = db.Column(db.Date())
age = db.Column(db.Integer())
name = db.Column(db.String())
type = db.Column(db.String())
color = db.Column(db.String())
@app.before_first_request
def init_app():
db.create_all()
db.session.add(Pet(date=datetime.datetime.utcnow() - datetime.timedelta(days=7), name="Sample Pet 1", age=12, type="fish", color="green"))
db.session.add(Pet(date=datetime.datetime.utcnow() - datetime.timedelta(days=7), name="Sample Pet 2", age=13, type="dog", color="green"))
db.session.add(Pet(date=datetime.datetime.utcnow() - datetime.timedelta(days=3), name="Sample Pet 3", age=14, type="cat", color="green"))
db.session.add(Pet(date=datetime.datetime.utcnow(), name="felix", age=14, type="cat", color="green"))
db.session.add(Pet(date=datetime.datetime.utcnow(), name="felix", age=14, type="dog", color="green"))
db.session.commit()
@app.route("/")
def home():
return "Welcome to Pet Lister!"
@app.route("/all_pets")
def show_all():
pets = Pet.query.all()
return jsonify([pet.to_dict() for pet in pets])
@app.route("/pet_page/<pet_id>")
def pet_page(pet_id):
try:
pet = Pet.query.filter(Pet.id == int(pet_id)).first()
return pet.to_dict()
except Exception as e:
return jsonify({"status": "failure", "error": str(e)})
return "Pet not found!", 404
@app.route("/add_pet", methods=["POST"])
def collect():
try:
data = request.json
db.session.add(
Pet(
date=datetime.datetime.utcnow(),
name=data["name"],
age=int(data["age"]),
type=data["type"],
color=data["color"],
)
)
db.session.commit()
return {"status": "sucess"}
except Exception as e:
return jsonify({"status": "failure", "error": str(e)})
@app.route("/search_type")
def search_type():
request_type = request.args.get("type")
request_name = request.args.get("name")
request_start = request.args.get("start")
request_end = request.args.get("end")
try:
base_cmd = Pet.query
if request_type:
base_cmd = base_cmd.filter(Pet.type == request_type)
if request_name:
base_cmd = base_cmd.filter(Pet.name == request_name)
if request_start:
base_cmd = base_cmd.filter(Pet.date >= datetime.datetime.strptime(request_start, "%Y-%m-%d"))
if request_end:
base_cmd = base_cmd.filter(Pet.date <= datetime.datetime.strptime(request_end, "%Y-%m-%d"))
data = base_cmd.all()
return jsonify([pet.to_dict() for pet in data])
except Exception as e:
return jsonify({"status": "failure", "error": str(e)})
if __name__ == "__main__":
app.run(debug=True) | [
"[email protected]"
] | |
f7ddf93e9bfb05edb2d6891fb7ebf3d1b70e760a | 17d32eb5d4c4f89811f1420ef712eb9d6c758352 | /config.py | c1d5ee6759fdf1f2a906d8e6338ad007a2f18ce5 | [] | no_license | bolv88/Auction | f5b16077473bb63074c7684907f6dd56035f0e58 | 4a5a7f2cf02aa6d9728b152edbd6f500e2b89d46 | refs/heads/master | 2021-03-19T07:10:15.014586 | 2012-07-25T14:42:44 | 2012-07-25T14:42:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 53 | py | userdb = {"user":"",
"pw":"",
"db":"",
"host":""}
| [
"[email protected]"
] | |
01b0ccd6b3a54eeed8c167ac4172f697c5a180f8 | c7fb558508ed66254ad4553000327e244633a71b | /Python/python_stacks/django_test/surprise/surprise/settings.py | 8c6137b331c35953423b8d51660aba1d89396262 | [] | no_license | jrhodesy4/DojoAssignments | e64e33d5b96df65b54f7defe38959dbc69ce5285 | 57a5f82ee343ae1fd755564d7ec30998e301dc02 | refs/heads/master | 2021-01-22T23:29:35.068913 | 2017-04-24T23:21:50 | 2017-04-24T23:21:50 | 85,645,354 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,125 | py | """
Django settings for surprise project.
Generated by 'django-admin startproject' using Django 1.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!3#5t(m@^rmgfuqo#h7x8-_1p#f68m8wxsm(gks+oad8n0^()m'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'apps.surprise_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'surprise.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'surprise.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.